Ransomware finds its way into servers through weak credentials, unpatched services, and lateral movement from other compromised machines. Once the encryption starts, recovery becomes expensive and uncertain. The alternative is blocking attackers before they deploy the payload.
I've seen servers locked down in minutes after an intrusion went unnoticed for days. The pattern is predictable: brute-forced SSH, privilege escalation through an old kernel exploit, then .php files rewritten and databases encrypted. Prevention relies on controlling who gets in, limiting what they can reach, and keeping clean backups they cannot touch.
Lock down SSH and remote access
Password authentication over SSH is the easiest entry point. Disable it.
Edit /etc/ssh/sshd_config and set:
PasswordAuthentication no
PubkeyAuthentication yes
PermitRootLogin no
Restart SSH after editing:
sudo systemctl restart sshd
Generate an SSH key pair on your local machine if you haven't already:
ssh-keygen -t ed25519 -C "[email protected]"
Copy the public key to your server:
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@your-server-ip
Test the key-based login before you close your current session. Once confirmed, password attacks become irrelevant.
Change the default SSH port from 22 to something higher if your setup allows it. Automated scanners hit port 22 constantly. Moving to a non-standard port cuts noise and reduces brute-force attempts. Update Port in sshd_config, adjust your firewall rules, and reconnect on the new port.
Install and configure Fail2Ban to block repeated failed login attempts:
sudo apt install fail2ban
sudo systemctl enable fail2ban
sudo systemctl start fail2ban
The default jail configuration watches SSH logs and bans IPs after a few failures. Check active bans with:
sudo fail2ban-client status sshd
For multi-user environments, enforce two-factor authentication with Google Authenticator or a similar PAM module. It adds a second layer even if a private key leaks.
Automate backups and store them offline
Backups only help if ransomware cannot encrypt them. Store copies outside the server's filesystem—offsite storage, a separate cloud bucket, or a physically disconnected drive.
Use rsync or restic to snapshot your critical directories daily. Restic encrypts backups by default and supports multiple backend targets. Install it:
sudo apt install restic
Initialize a repository on a remote server or S3-compatible storage:
restic -r sftp:backup-user@backup-server:/backups init
Run a backup:
restic -r sftp:backup-user@backup-server:/backups backup /var/www /home /etc
Schedule it with cron. Open your crontab:
crontab -e
Add a daily backup at 2 AM:
0 2 * * * /usr/bin/restic -r sftp:backup-user@backup-server:/backups backup /var/www /home /etc --quiet
Keep multiple snapshots using restic's retention policy:
restic -r sftp:backup-user@backup-server:/backups forget --keep-daily 7 --keep-weekly 4 --keep-monthly 6 --prune
Test restoration regularly. Backups you never restore are assumptions, not insurance. Pull a snapshot to a test directory and verify file integrity:
restic -r sftp:backup-user@backup-server:/backups restore latest --target /tmp/restore-test
For database servers, dump databases before the backup runs:
mysqldump --all-databases -u root -p > /var/backups/all-databases.sql
Include /var/backups in your restic path. If you're running cPanel or Plesk, use their built-in backup tools but always replicate those backups to a second location the panel cannot access.
Immutable backups are better. Some S3-compatible providers offer object locking that prevents deletion or modification for a set retention period. Configure it if your storage backend supports it.
Segment your network and isolate services
Ransomware spreads by scanning internal networks and moving laterally. Separate your production web server from your database server, mail server, and control panel.
Use VLANs or private networking if your hosting provider supports it. Otherwise, bind services to localhost and use SSH tunnels or VPN access for administrative connections.
For example, if MySQL runs on the same machine as your web app, bind it to 127.0.0.1 instead of 0.0.0.0. Edit /etc/mysql/mysql.conf.d/mysqld.cnf:
bind-address = 127.0.0.1
Restart MySQL:
sudo systemctl restart mysql
If your database must accept remote connections, restrict them by IP using firewall rules:
sudo ufw allow from 192.168.1.50 to any port 3306
sudo ufw deny 3306
Apply the same logic to Redis, Memcached, and any other service that doesn't need public exposure.
Deploy a firewall on every server, not just the perimeter. Use ufw on Ubuntu or firewalld on CentOS. Default-deny everything, then whitelist only the ports you need:
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow 22/tcp
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable
Check active rules:
sudo ufw status numbered
For multi-server setups, place your database and internal APIs behind a bastion host or VPN. Let the web-facing server reach them over a private subnet, but block direct internet access to those internal services.
So what if your setup is a single VPS with everything on one machine? You can still reduce the blast radius by running services in containers or chroot jails and limiting file-system access with AppArmor or SELinux policies.
Patch your kernel and application stack
Unpatched vulnerabilities are the second-most common entry point I see in post-incident reviews. The pattern is consistent: an exploit for a six-month-old kernel bug or a PHP version that should have been updated months ago.
Enable automatic security updates. On Ubuntu:
sudo apt install unattended-upgrades
sudo dpkg-reconfigure --priority=low unattended-upgrades
Edit /etc/apt/apt.conf.d/50unattended-upgrades to ensure security patches are applied automatically:
Unattended-Upgrade::Allowed-Origins {
"${distro_id}:${distro_codename}-security";
};
On CentOS or RHEL, use dnf-automatic:
sudo dnf install dnf-automatic
sudo systemctl enable --now dnf-automatic.timer
Check for available updates weekly even with automation enabled:
sudo apt update && sudo apt list --upgradable
Reboot after kernel updates. Many security patches require a restart to take effect. Schedule maintenance windows for reboots rather than letting the server run an outdated kernel for months.
For web applications, keep PHP, Node.js, Python, and associated libraries current. Use version managers like nvm or pyenv to simplify upgrades without breaking compatibility. Pin major versions in production, but move forward within minor releases:
nvm install 20
nvm alias default 20
Update Composer, npm, or pip dependencies monthly. Run composer update, npm audit fix, or pip list --outdated and address high-severity issues immediately.
Subscribe to security mailing lists for your distribution and any third-party software you run. When a critical vulnerability drops, patch it the same day if possible.
Monitor logs and watch for anomalies
Attackers probe your server before deploying ransomware. Spotting the reconnaissance phase gives you time to respond.
Centralize logs with rsyslog forwarding or a tool like Loki, Graylog, or the ELK stack if you manage multiple servers. For single-server setups, review /var/log/auth.log and /var/log/syslog daily.
Set up alerts for repeated authentication failures, privilege escalation attempts, and unusual outbound connections. Use logwatch or fail2ban notifications:
sudo apt install logwatch
sudo logwatch --detail high --mailto [email protected] --range today
Schedule it in cron to email you every morning with a summary.
Monitor disk I/O and CPU usage. Ransomware encryption spikes disk writes and CPU load. Install atop or iotop and check for sustained high activity:
sudo apt install atop
sudo atop
Look for processes writing to large numbers of files rapidly. If you spot suspicious activity, isolate the server from the network immediately, investigate the process tree, and check recently modified files:
find /var/www -type f -mmin -60 -ls
Enable auditd to track file access and system calls:
sudo apt install auditd
sudo systemctl enable auditd
sudo systemctl start auditd
Add rules to monitor sensitive directories:
sudo auditctl -w /etc/passwd -p wa -k passwd_changes
sudo auditctl -w /var/www -p wa -k webroot_changes
Query the audit log:
sudo ausearch -k webroot_changes
Integrate your server with an intrusion detection system like OSSEC or Wazuh if you have the capacity to manage it. These tools correlate events, detect rootkits, and alert on known attack patterns.
How often should I test backups?
Monthly at minimum. Full restoration tests quarterly. Verify checksums or run a quick file comparison weekly if you can script it.
Does two-factor authentication slow down server administration?
Slightly, but the tradeoff is worth it. Use SSH agent forwarding and keep your session alive to avoid re-authenticating constantly.
Can ransomware still spread if I use containers?
Yes, if the host is compromised or containers share the same network without isolation. Containers reduce the attack surface but aren't a substitute for hardening.
What should I do if I spot an active encryption process?
Disconnect the server from the network immediately. Kill the process, check for persistence mechanisms in cron or systemd, then restore from a clean backup after identifying the entry point.
Check your backup integrity first
The five steps above work because they address the kill chain from initial access to payload execution. You block entry with SSH hardening and firewalls, limit movement with segmentation, patch the exploits attackers rely on, keep clean backups they can't reach, and catch anomalies before encryption starts.
Hardening is not one-time work. Review your configurations quarterly, rotate SSH keys annually, and audit user accounts for stale credentials. Ransomware evolves, but the fundamentals—access control, patching, backups, monitoring—remain consistent. Implement them now rather than recovering from an incident later.
