Take a breath. You are not the first person this has happened to, and your server can be recovered. This guide walks you through every step — from containing the breach to preventing it from happening again.
Do NOT panic-shutdown your server. Powering off destroys volatile evidence in memory — running processes, active network connections, and attacker sessions. You need this data to understand what happened and prevent reinfection.
Your first priority is stopping the attacker from doing more damage — without destroying evidence. Isolation means cutting off the attacker's access while keeping the server running so you can investigate.
# Option A: Block all traffic except your current SSH session
$ iptables -A INPUT -s YOUR_IP -j ACCEPT
$ iptables -A OUTPUT -d YOUR_IP -j ACCEPT
$ iptables -P INPUT DROP
$ iptables -P OUTPUT DROP
$ iptables -P FORWARD DROP
# Option B: Use your hosting provider's firewall panel
# DigitalOcean, Hetzner, AWS, Vultr — all have network-level firewalls
# Block all inbound/outbound except SSH from your IP
# Option C: If you suspect the attacker has a live reverse shell
# Block all outbound traffic FIRST to kill C2 connections
$ iptables -P OUTPUT DROP
$ iptables -A OUTPUT -d YOUR_IP -j ACCEPT
$ iptables -A OUTPUT -j LOG --log-prefix "BLOCKED_OUTBOUND: "
Important: Replace YOUR_IP with your actual public IP address. If you lock yourself out, use your provider's console (VNC/KVM) to regain access. Most providers offer out-of-band console access that does not depend on SSH.
If your server is actively sending spam, participating in a DDoS attack, or mining cryptocurrency, your hosting provider may suspend it before you can act. Containment shows them you are responding — contact their abuse team proactively to avoid suspension.
Before you start cleaning anything, capture the current state. You will need this evidence to understand the attack vector, determine what data was accessed, and prevent the same breach from happening again.
# Save running processes with full command lines
$ ps auxwwf > /root/incident/processes.txt
# Save all network connections (active + listening)
$ ss -tunap > /root/incident/network.txt
$ netstat -tulnp >> /root/incident/network.txt 2>/dev/null
# Save all open files (find malware file handles)
$ lsof +L1 > /root/incident/deleted_files.txt 2>/dev/null
# Save login history
$ last -a > /root/incident/logins.txt
$ lastlog > /root/incident/lastlog.txt
$ cat /var/log/auth.log > /root/incident/auth.log 2>/dev/null
$ journalctl -u sshd --since "7 days ago" > /root/incident/sshd.log 2>/dev/null
# Save all cron jobs for every user
$ for user in $(cut -f1 -d: /etc/passwd); do echo "=== $user ==="; crontab -l -u $user 2>/dev/null; done > /root/incident/crons.txt
# Save list of recently modified files
$ find / -mtime -7 -type f -not -path "/proc/*" -not -path "/sys/*" 2>/dev/null > /root/incident/recent_files.txt
Create the evidence directory first: mkdir -p /root/incident. If possible, copy these files off the compromised server to a clean location. An attacker with root access could tamper with local files.
Understanding the entry point is critical. If you skip this step and just clean up, the attacker will come back through the same door. These are the most common attack vectors for Linux servers, ranked by frequency.
Outdated plugins, unpatched CMS versions, and file upload vulnerabilities are the number one entry point. Attackers use automated scanners that test thousands of known CVEs against every website they find.
Check: grep POST /var/log/nginx/access.log | grep -i "upload\|wp-\|admin"
Weak passwords on SSH, especially on servers with password authentication enabled and no rate limiting. A new VPS receives its first SSH attack within 22 minutes of being provisioned.
Check: grep "Accepted password\|Accepted publickey" /var/log/auth.log | tail -20
MongoDB, Redis, Elasticsearch, and Docker APIs exposed to the internet without authentication. Attackers scan for these continuously — a misconfigured Redis instance can be compromised in under a minute.
Check: ss -tlnp | grep -E "3306|5432|6379|27017|2375"
Known kernel exploits, privilege escalation CVEs, and library vulnerabilities. Once an attacker gets unprivileged access through any vector, unpatched CVEs let them escalate to root.
Check: apt list --upgradable 2>/dev/null | head -20
Database passwords in .env files accessible via web server, exposed .git directories with config files, and unprotected backup archives containing credentials.
Check: curl -s http://yoursite.com/.env | head -5
Check your web server access logs for the hours and days before the breach. Look for unusual POST requests to upload endpoints, 200 responses to paths that should return 404, and access to PHP files in unexpected directories. The SSH attack blocking guide covers brute force entry points in detail.
Attackers rarely stop at one thing. A single compromised WordPress plugin can lead to web shells, cryptominers, spam relays, and backdoor accounts — all on the same server. Check everything.
# Check for new user accounts (compare against known users)
$ cat /etc/passwd | grep -v nologin | grep -v false
# Check for unauthorized SSH keys
$ find / -name authorized_keys -exec cat {} \; 2>/dev/null
# Check for processes running from /tmp, /dev/shm, or hidden dirs
$ ls -la /tmp /dev/shm /var/tmp 2>/dev/null
$ find /tmp /dev/shm /var/tmp -type f -executable 2>/dev/null
# Check for modified system binaries
$ dpkg -V 2>/dev/null || rpm -Va 2>/dev/null
# Check for rootkit indicators
$ cat /etc/ld.so.preload 2>/dev/null
$ ps aux | wc -l
$ ls /proc | grep -E '^[0-9]+$' | wc -l
# A large discrepancy between these two counts suggests hidden processes
# Check outbound connections to unknown IPs
$ ss -tunap | grep ESTAB
Rootkit warning: If /etc/ld.so.preload contains entries, or the process count from ps differs significantly from /proc, you likely have a kernel-level rootkit. In this case, do not trust any command output on the compromised server. The safest path is a full wipe and reinstall from a clean backup.
Manual investigation catches the obvious infections. A proper malware scan catches the hidden ones — obfuscated web shells, renamed binaries, and persistence mechanisms that manual checks miss. See the complete Linux malware removal guide for detailed scanning instructions.
$ sudo apt update && sudo apt install clamav -y
$ sudo systemctl stop clamav-freshclam && sudo freshclam
$ sudo clamscan -ri /var/www /tmp /home /dev/shm --log=/root/incident/clamav.log
$ grep FOUND /root/incident/clamav.log
$ curl -fsSL https://defensia.cloud/install.sh | sudo bash
# Scans automatically on first run — results in dashboard within minutes
# 64,000+ hash signatures + 684 dynamic patterns
# Detects web shells, cryptominers, rootkit indicators, backdoors
ClamAV was designed for email gateway scanning and misses many PHP web shells, obfuscated backdoors, and modern server-targeted malware. Defensia's scanner was built specifically for Linux servers with web-focused detection patterns.
Now that you have identified every infection, remove them methodically. Missing even one persistence mechanism means the attacker comes back — often within hours.
Kill all malicious processes — use kill -9 <PID> for each identified malicious process. Check with ps aux after killing to confirm they did not respawn
Remove all malware files — delete web shells, cryptominer binaries, backdoor scripts, and any files identified by your malware scanner
Remove unauthorized cron jobs — check every user's crontab, /etc/cron.d/, /etc/cron.daily/, and /var/spool/cron/
Remove unauthorized systemd services — check /etc/systemd/system/ for unknown unit files, then systemctl daemon-reload
Remove unauthorized SSH keys — audit every authorized_keys file on the system and remove keys you do not recognize
Delete rogue user accounts — remove any accounts created by the attacker: userdel -r <username>
Clean /etc/ld.so.preload — remove any entries and run ldconfig. This file should be empty or not exist
Reinstall modified system packages — apt install --reinstall <package> for any packages flagged by dpkg -V or rpm -Va
Patch the entry point — update the vulnerable software, disable the exposed service, or fix the misconfiguration that allowed the breach
Reboot and verify — restart the server and confirm no malware respawns. Monitor CPU, processes, and network connections for 24 hours
If you found a rootkit: Do not attempt to clean the server. A rootkit means the attacker has kernel-level access and every tool on the system may be compromised. Provision a new server, restore from a pre-breach backup, and harden before reconnecting to the network.
Assume every password, key, and token on the compromised server has been captured. Attackers routinely dump .env files, database credentials, API keys, and SSH keys. If any of those credentials are reused on other servers, those servers are now compromised too.
Generate new key pairs for all administrators. Remove all existing keys from authorized_keys and re-add only verified keys. If you were using password authentication, switch to key-only auth now.
Change every user password on the system. If any passwords were reused on other servers or services, change those too — attackers test stolen credentials across all your infrastructure.
Change MySQL, PostgreSQL, MongoDB, and Redis passwords. Update the connection strings in all application config files (.env, wp-config.php, settings.py).
Rotate Laravel APP_KEY, Django SECRET_KEY, JWT secrets, Stripe/Paddle API keys, AWS credentials, and any other API tokens stored on the server. Attackers dump .env files routinely.
If the attacker had root access, they could have copied your private keys. Revoke and reissue SSL certificates from your certificate authority.
Any OAuth tokens, SMTP credentials, CDN API keys, or monitoring service tokens stored on the server should be rotated immediately.
Cleanup without hardening is just delaying the next breach. Most servers get hacked because of known, preventable vulnerabilities. Here is how to close them permanently. For a comprehensive hardening walkthrough, follow the VPS security checklist.
Defensia installs in 30 seconds and provides real-time SSH brute force blocking, web application firewall, malware scanning, and CVE detection. You get alerted the moment something suspicious happens — not hours or days later.
Enable unattended-upgrades (Debian/Ubuntu) or dnf-automatic (RHEL). Most server compromises exploit known CVEs with available patches. Defensia scans your installed packages against the NVD database and alerts you to critical vulnerabilities.
Switch to key-only SSH authentication. This eliminates brute force attacks entirely — no password means nothing to guess. Edit /etc/ssh/sshd_config and set PasswordAuthentication no.
A WAF detects and blocks SQL injection, XSS, path traversal, and remote code execution before they reach your application. Defensia's WAF reads nginx/Apache access logs and blocks attackers automatically — zero configuration required.
Configure Defensia to scan daily or weekly. Catch new malware within hours of it appearing, not weeks later when your hosting provider sends an abuse notice or Google blacklists your site.
New vulnerabilities are published daily. Defensia checks your installed packages against the NVD, scores them with EPSS (Exploit Prediction Scoring System), and flags CISA Known Exploited Vulnerabilities — the ones actively being used in attacks right now.
Configure Slack, email, Discord, or webhook alerts for critical events: new malware detected, brute force attacks blocked, critical CVE found, server goes offline. Defensia Pro includes all alert channels.
This is the hardest decision in incident response. Here are clear guidelines:
✓Compromise limited to a web shell in an upload directory
✓Single application exploit with known entry point
✓Cryptominer running from /tmp (no rootkit)
✓Unauthorized SSH key added but no system binary changes
✓You can identify and confirm the exact attack vector
✗Rootkit detected (ld.so.preload entries, hidden processes)
✗Modified system binaries (ls, ps, netstat, sshd)
✗Kernel-level compromise or unknown kernel modules
✗You cannot determine how the attacker got in
✗Multiple attack vectors were used simultaneously
✗The server has been compromised for an unknown duration
The steps above take hours and require significant Linux experience. Defensia automates the critical parts — malware detection, brute force blocking, web attack prevention, and vulnerability scanning — with a single 30-second install.
$ curl -fsSL https://defensia.cloud/install.sh | sudo bash
Defensia detects attacks as they happen — not after the damage is done. The real-time dashboard shows every blocked attempt, malware finding, and CVE vulnerability across all your servers in one place.
The most common signs are: unexplained high CPU usage (cryptominers), unknown processes running from /tmp or /dev/shm, unauthorized SSH keys in authorized_keys files, unexpected cron jobs, new user accounts you did not create, modified system binaries, and outbound connections to unknown IP addresses. Run the diagnostic commands in Steps 2-4 above to investigate.
Do NOT shut down the server — you will lose volatile forensic evidence in memory. First, isolate the server from the network (Step 1). Then preserve evidence by saving process lists, network connections, and logs (Step 2). Only then begin investigating and cleaning up.
If you found a rootkit, kernel-level compromise, or cannot determine the initial entry point, a full wipe and reinstall from a known-clean backup is the safest option. If the compromise was limited to a web shell or single application exploit with a known entry point, cleaning is usually sufficient — but you must patch the vulnerability that allowed the breach.
A basic investigation takes 30-60 minutes. Full forensic analysis, cleanup, credential rotation, and hardening typically takes 4-8 hours for a single server. With Defensia installed, the malware scan takes 2-5 minutes and the real-time dashboard shows you exactly what happened and when.
Install automated security monitoring (Defensia installs in 30 seconds), keep all software updated, use SSH key authentication instead of passwords, deploy a web application firewall, run scheduled malware scans, and monitor for CVE vulnerabilities in your installed packages. Most breaches exploit known vulnerabilities with available patches.
Yes. Defensia's malware scanner checks for cryptominers, web shells, rootkit indicators, backdoors, and suspicious executables using 64,000+ hash signatures and 684 dynamic detection patterns. It also monitors SSH access, detects brute force attacks, and alerts you to new threats in real time via the dashboard, Slack, email, or webhook.
NIST SP 800-61 Rev. 2: Computer Security Incident Handling Guide — https://csrc.nist.gov/publications/detail/sp/800-61/rev-2/final
SANS Incident Handler's Handbook — https://www.sans.org/white-papers/33901/
NIST SP 800-83: Guide to Malware Incident Prevention and Handling — https://csrc.nist.gov/publications/detail/sp/800-83/rev-1/final
Verizon 2025 Data Breach Investigations Report — https://www.verizon.com/business/resources/reports/dbir/
Defensia agent telemetry data from 9 production servers (2025-2026)
MalwareBazaar (abuse.ch): https://bazaar.abuse.ch/
Real-time monitoring, automated blocking, malware scanning, and CVE detection. Install in 30 seconds.
Free for 1 server. No credit card required.