Tutorial 📅 January 2025 📖 8 min read

VPS Got Hacked? Response & Prevention (2025)

VPS hacked? Follow this critical incident response checklist to remove attackers and secure your server against future breaches.

You just noticed suspicious activity on your VPS. Unknown processes running, mysterious users in your system, or your server is sending spam. Your VPS has been compromised.

Don't panic. This guide provides a systematic response plan to minimize damage, remove attackers, and secure your server.

⚠️ Act Fast: The longer attackers have access, the more damage they can do. Follow these steps immediately.

Phase 1: Immediate Containment (First 15 Minutes)

Step 1: Isolate the Server

Prevent the attacker from causing more damage:

# Block all incoming connections (emergency firewall)
sudo iptables -P INPUT DROP
sudo iptables -P FORWARD DROP
sudo iptables -A INPUT -i lo -j ACCEPT  # Allow localhost
sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# Or completely disconnect from network (if you have console access)
sudo ip link set eth0 down
Important: This will kill your current SSH session. Make sure you have console access via your provider's web panel before doing this.

Step 2: Identify Active Threats

Check what's happening right now:

# Check who's logged in
w
who

# Check all running processes
ps aux | less

# Check for suspicious users
cat /etc/passwd | grep /bin/bash

# Check active network connections
sudo ss -tupln
sudo netstat -tupln

Step 3: Kill Suspicious Processes

# Kill process by PID
sudo kill -9 [PID]

# Kill all processes by user (if you find a rogue user)
sudo pkill -u suspicious_username
sudo killall -u suspicious_username

Phase 2: Investigation (Next 30 Minutes)

Check Authentication Logs

# Check recent logins
sudo last | head -20
sudo lastb | head -20  # Failed login attempts

# Check auth logs for break-in attempts
sudo grep -i "accepted" /var/log/auth.log
sudo grep -i "failed" /var/log/auth.log | tail -50

# For CentOS/RHEL:
sudo grep -i "accepted" /var/log/secure

Check for Backdoors and Malware

# Check crontab for malicious scheduled tasks
sudo crontab -l
sudo cat /etc/crontab
sudo ls -la /etc/cron.*

# Check for modified system files
sudo find /bin /usr/bin /sbin /usr/sbin -mtime -7

# Check for listening services
sudo ss -tlnp

# Check startup scripts
sudo ls -la /etc/init.d/
sudo systemctl list-unit-files --type=service

Check for Rootkits

# Install rootkit scanners
sudo apt install rkhunter chkrootkit -y  # Ubuntu/Debian
sudo yum install rkhunter chkrootkit -y  # CentOS

# Scan for rootkits
sudo rkhunter --check
sudo chkrootkit

Phase 3: Remove the Attacker (Next 1-2 Hours)

1. Remove Malicious Users

# List all users
cat /etc/passwd

# Delete suspicious users
sudo userdel -r suspicious_username

# Lock user accounts you're unsure about
sudo passwd -l username

2. Change ALL Passwords

# Change root password
sudo passwd root

# Change your user password
passwd

# Change SSH keys
rm ~/.ssh/authorized_keys
ssh-keygen -t ed25519 -C "new-key@example.com"
# Add new public key to authorized_keys

3. Remove Malicious SSH Keys

# Check all users' authorized_keys
sudo find /home -name "authorized_keys" -exec cat {} \;

# Remove suspicious keys
sudo nano ~/.ssh/authorized_keys
sudo nano /root/.ssh/authorized_keys

4. Remove Malicious Cron Jobs

# Check all cron jobs
sudo crontab -l
for user in $(cut -f1 -d: /etc/passwd); do
  echo "=== $user ==="
  sudo crontab -u $user -l 2>/dev/null
done

# Remove malicious cron entries
sudo crontab -e

5. Find and Remove Malware

# Install malware scanner
sudo apt install clamav clamav-daemon -y

# Update virus definitions
sudo freshclam

# Scan system
sudo clamscan -r -i /home /var/www /tmp

# Find recently modified files
sudo find / -mtime -7 -type f | grep -v "/proc" | grep -v "/sys"

Phase 4: Secure Your Server

1. Update Everything

# Ubuntu/Debian
sudo apt update && sudo apt upgrade -y
sudo apt dist-upgrade -y

# CentOS/RHEL
sudo yum update -y

2. Harden SSH Configuration

Proper SSH configuration prevents unauthorized access. If you encounter issues, see our SSH troubleshooting guide.

sudo nano /etc/ssh/sshd_config

# Recommended settings:
PermitRootLogin no
PasswordAuthentication no  # Use keys only
PubkeyAuthentication yes
Port 2222  # Change from default port 22
MaxAuthTries 3
LoginGraceTime 30
AllowUsers your-username  # Whitelist specific users

sudo systemctl restart sshd
Warning: Test SSH login in a new terminal before closing your current session!

3. Configure Firewall

A properly configured firewall is essential. See our complete VPS security basics guide for comprehensive hardening steps.

# Using UFW (Ubuntu/Debian)
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow 2222/tcp  # Your SSH port
sudo ufw allow 80/tcp    # HTTP
sudo ufw allow 443/tcp   # HTTPS
sudo ufw enable

# Check status
sudo ufw status verbose

4. Install Fail2Ban

# Install
sudo apt install fail2ban -y

# Configure
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
sudo nano /etc/fail2ban/jail.local

# Set these values:
[sshd]
enabled = true
port = 2222  # Your SSH port
maxretry = 3
bantime = 3600
findtime = 600

sudo systemctl enable fail2ban
sudo systemctl start fail2ban

# Check banned IPs
sudo fail2ban-client status sshd

5. Enable Automatic Security Updates

# Ubuntu/Debian
sudo apt install unattended-upgrades -y
sudo dpkg-reconfigure -plow unattended-upgrades

# CentOS/RHEL
sudo yum install yum-cron -y
sudo systemctl enable yum-cron
sudo systemctl start yum-cron

Security Breaches Are Stressful - Prevent Them with VPS Commander

VPS Commander includes built-in security workflows: configure firewalls, set up fail2ban, harden SSH, monitor suspicious activity - all with one click. Plus, you'll have audit logs of all server changes.

Secure Your VPS with VPS Commander

Phase 5: Long-Term Prevention

1. Regular Backups

Regular backups are your safety net. Learn comprehensive VPS backup strategies to protect your data.

# Automate backups with cron
sudo crontab -e

# Daily backup at 2 AM
0 2 * * * tar -czf /backup/$(date +\%Y\%m\%d)-backup.tar.gz /var/www /etc

# Consider using backup services:
# - Automated snapshots from your VPS provider
# - Restic for encrypted backups
# - BorgBackup for deduplicated backups

2. Enable 2FA for SSH

# Install Google Authenticator
sudo apt install libpam-google-authenticator -y

# Run setup
google-authenticator

# Configure PAM
sudo nano /etc/pam.d/sshd
# Add: auth required pam_google_authenticator.so

# Update SSH config
sudo nano /etc/ssh/sshd_config
# Set: ChallengeResponseAuthentication yes

sudo systemctl restart sshd

3. Monitor Your Server

Continuous monitoring helps detect breaches early. Check out our guides on VPS performance monitoring and understanding VPS log files.

# Install monitoring tools
sudo apt install htop iotop nethogs -y

# Set up log monitoring
sudo apt install logwatch -y

# Configure email alerts
sudo nano /etc/aliases
# Add: root: your-email@example.com

sudo newaliases

4. Use Intrusion Detection

# Install AIDE (Advanced Intrusion Detection Environment)
sudo apt install aide -y

# Initialize database
sudo aideinit
sudo mv /var/lib/aide/aide.db.new /var/lib/aide/aide.db

# Run checks
sudo aide --check

When to Rebuild From Scratch

In some cases, it's safer to rebuild your VPS from a clean image:

Rebuild checklist:

  1. Take a snapshot/backup of the compromised server (for forensics)
  2. Deploy a fresh VPS from your provider
  3. Restore only verified data (databases, uploaded files) from backups
  4. Redeploy applications from source control
  5. Apply all security hardening steps above

Post-Incident Checklist

  1. ✅ Server isolated from network
  2. ✅ Malicious processes killed
  3. ✅ Malicious users removed
  4. ✅ All passwords changed
  5. ✅ SSH keys regenerated
  6. ✅ Malicious cron jobs removed
  7. ✅ Malware scanned and removed
  8. ✅ System fully updated
  9. ✅ SSH hardened
  10. ✅ Firewall configured
  11. ✅ Fail2Ban installed
  12. ✅ Automatic updates enabled
  13. ✅ Backup system in place
  14. ✅ Monitoring configured

Prevention is Better Than Cure

Most VPS compromises happen due to:

Conclusion

Recovering from a VPS compromise is stressful, but following this systematic approach will help you regain control and secure your server.

Key takeaways:

  1. Act immediately - isolate the server first
  2. Investigate thoroughly - understand what was compromised
  3. Remove all traces of the attacker
  4. Harden your security before reconnecting to the internet
  5. Consider rebuilding if the compromise is severe
  6. Implement prevention measures to avoid future breaches
Learn from this: Document everything you find during the investigation. This will help you prevent similar attacks in the future and improve your security posture.