Most ransomware gets in through SSH brute-force, unpatched software, or misconfigured services. Once inside, attackers escalate privileges, disable backups, and encrypt everything they can reach. The window between entry and encryption is measured in hours—sometimes minutes.
You can't stop every attack, but you can close the entry points attackers rely on and make privilege escalation expensive enough that automated tools give up. Here are nine server hardening steps I've used to lock down VPS and dedicated servers hosting client sites, cPanel installs, and application stacks.
1. SSH key-only authentication
Password authentication over SSH is the biggest single risk. Brute-force bots hit port 22 constantly, trying common usernames and credential dumps.
Disable password auth entirely. Edit /etc/ssh/sshd_config:
PasswordAuthentication no
PubkeyAuthentication yes
PermitRootLogin prohibit-password
ChallengeResponseAuthentication no
Restart the SSH daemon:
systemctl restart sshd
Before you close your current session, open a second terminal and verify key-based login works. If you lock yourself out, you'll need console access through your hosting panel.
Move SSH off port 22 if you want to cut down log noise, but that's security through obscurity—it won't stop a determined attacker who runs a port scan. The real protection is forcing public-key cryptography.
2. Disable root login completely
Even with key auth, leaving root login enabled means one compromised key gives full system access. Create a non-root user, add it to the sudo group, and lock out root over SSH:
useradd -m -s /bin/bash deploy
usermod -aG sudo deploy
passwd deploy
Copy your SSH key to the new user's authorized_keys, then edit /etc/ssh/sshd_config again:
PermitRootLogin no
Restart sshd and test login as the new user. Use sudo for privileged commands. This adds one more layer an attacker has to break through.
3. Automatic security updates
Unpatched kernel vulnerabilities and service exploits are the second most common entry point I see in post-incident reviews. Staying current is not optional.
On Debian/Ubuntu, enable unattended-upgrades:
apt install unattended-upgrades
dpkg-reconfigure --priority=low unattended-upgrades
Edit /etc/apt/apt.conf.d/50unattended-upgrades to include security updates:
Unattended-Upgrade::Allowed-Origins {
"${distro_id}:${distro_codename}-security";
};
On RHEL/CentOS/AlmaLinux, use dnf-automatic:
dnf install dnf-automatic
systemctl enable --now dnf-automatic.timer
Configure /etc/dnf/automatic.conf to apply security updates:
[commands]
apply_updates = yes
Schedule a monthly manual review of /var/log/unattended-upgrades/ or /var/log/dnf.log to catch any held-back packages that need manual intervention.
4. Fail2ban for brute-force protection
Even with key-only auth, logging failed login attempts and blocking repeat offenders keeps attack surface smaller and reduces log clutter.
Install Fail2ban:
apt install fail2ban # Debian/Ubuntu
dnf install fail2ban # RHEL/Alma
Create /etc/fail2ban/jail.local:
[DEFAULT]
bantime = 3600
findtime = 600
maxretry = 5
[sshd]
enabled = true
port = ssh
logpath = /var/log/auth.log
Start and enable the service:
systemctl enable --now fail2ban
Check banned IPs:
fail2ban-client status sshd
Adjust bantime and maxretry based on your threat model. I usually set a one-hour ban after five failures in ten minutes.
5. Filesystem mount options: noexec on /tmp
Attackers often drop payloads in /tmp because it's world-writable. Mounting /tmp with noexec prevents execution of binaries placed there.
Edit /etc/fstab and add a line for tmpfs:
tmpfs /tmp tmpfs defaults,noexec,nosuid,nodev 0 0
Remount without a reboot:
mount -o remount /tmp
Verify:
mount | grep /tmp
You should see noexec in the options. This won't stop everything—attackers can use interpreters like Python or Perl—but it blocks the simplest exploit chains.
6. Minimal services
Every running service is another potential entry point. Audit what's listening:
ss -tulnp
Disable anything you don't need. On a typical web server, you want SSH, HTTP/HTTPS, and maybe MySQL listening only on localhost. If you see Postfix, cups, avahi-daemon, or other desktop services running on a headless VPS, stop and disable them:
systemctl stop cups
systemctl disable cups
For MySQL or PostgreSQL, bind to 127.0.0.1 unless you're running a separate database server. Edit /etc/mysql/my.cnf or /etc/my.cnf.d/server.cnf:
[mysqld]
bind-address = 127.0.0.1
Restart the service and verify with ss -tulnp | grep mysql. The listen address should be 127.0.0.1, not 0.0.0.0.
7. SELinux or AppArmor in enforcing mode
Mandatory Access Control systems confine processes even when an attacker gains shell access. SELinux (RHEL-based) and AppArmor (Debian/Ubuntu) limit what a compromised web server or database daemon can touch.
Check SELinux status:
getenforce
If it says Permissive or Disabled, edit /etc/selinux/config:
SELINUX=enforcing
Reboot, then check again. You'll see policy denials in /var/log/audit/audit.log. Most modern web stacks have policies already, but custom apps may need tweaking.
On Ubuntu, check AppArmor:
sudo aa-status
Most profiles are in enforce mode by default. If you see important services in complain mode, investigate the logs in /var/log/syslog and either fix the app or create a custom profile.
MAC won't stop an attacker from encrypting files the web server user owns, but it will block lateral movement and privilege escalation.
8. Immutable backups stored off-server
Ransomware isn't solved by prevention alone. You need backups the attacker can't delete or encrypt.
Take daily snapshots with rsync or restic to a separate server or object storage. The key requirement: the backup destination must not be writable from the source server. Use append-only S3 buckets, write-once snapshots, or a pull model where the backup server connects inbound on a schedule.
Example with restic to Backblaze B2:
export RESTIC_REPOSITORY="b2:bucketname:/backups"
export RESTIC_PASSWORD="your-strong-passphrase"
export B2_ACCOUNT_ID="your-account-id"
export B2_ACCOUNT_KEY="your-application-key"
restic backup /var/www /etc /home
restic forget --keep-daily 7 --keep-weekly 4 --prune
Schedule in cron, store credentials in a protected file readable only by root. Test restoration monthly—backups you haven't restored are just expensive log files.
9. File integrity monitoring
Know when critical binaries or config files change. AIDE or Tripwire will alert you if /bin/bash, /etc/shadow, or web application files are modified outside your deployment process.
Install AIDE:
apt install aide
Initialize the database:
aide --init
mv /var/lib/aide/aide.db.new /var/lib/aide/aide.db
Run checks daily via cron:
0 2 * * * /usr/bin/aide --check | mail -s "AIDE report" [email protected]
You'll get an email whenever monitored files change. Tune /etc/aide/aide.conf to ignore log directories and other noisy paths. False positives are common at first, but once the baseline is stable, any unexpected change is worth investigating.
What if an attacker already has a foothold?
These steps close entry points, but if you're hardening a server that's been online for years, check for compromise first. Look for unknown SSH keys in /root/.ssh/authorized_keys and user home directories. Review cron jobs in /etc/cron* and crontab -l for all users. Check listening ports and running processes for anything unfamiliar.
Run rkhunter or chkrootkit for a quick scan, but don't trust them completely—rootkits can hide from detection tools. If you find anything suspicious, treat the server as compromised and either rebuild from a known-good backup or migrate to a fresh instance.
How often should I review these settings?
Every time you provision a new server, and quarterly on existing infrastructure. Configurations drift when you install new software or apply manual fixes under pressure. Schedule a quarterly audit: verify SSH config, check that Fail2ban is running, confirm backups are completing, and review SELinux denials.
Will this stop zero-day exploits?
No. Zero-days by definition have no patch yet. But most ransomware uses known exploits and common attack patterns—automated tools scanning for open SSH with weak passwords, unpatched CMS installs, exposed database ports. Hardening raises the cost of attack enough that opportunistic scans move on to easier targets.
Can I automate this with Ansible or a script?
Yes. Ansible roles exist for SSH hardening, Fail2ban, and backup jobs. Write a playbook once, apply it to every new server, and update it when you refine your baseline. Configuration management turns hardening from a checklist into infrastructure code that's versioned and repeatable.
Test your hardening
Once these steps are in place, verify they work. Try SSH password auth from a test account—it should fail. Drop a shell script in /tmp and try to execute it—should be blocked. Simulate a restore from backup and time how long it takes. Fire a few dozen failed SSH attempts at your server from an external IP and confirm Fail2ban blocks it.
Hardening isn't a one-time project. Threat models change, new vulnerabilities appear, and software updates sometimes reset configurations. But these nine steps form a baseline that blocks the vast majority of automated ransomware tools I've seen hit production servers.
