Skip to content
Back to Blog
Security11 min read

Ransomware Attack Prevention: 9 Server Defenses That Work

Lock down your server with access controls, file-system restrictions, and network segmentation that stop ransomware before the encryption stage starts.

Written by Abdul AbrorTechnical Hosting Support Engineer
Ransomware Attack Prevention: 9 Server Defenses That Work
On this page

Ransomware actors target hosting environments because one compromised account can cascade into dozens of encrypted customer sites. The encryption stage is usually the final step—by then, the attacker already has persistent access, privilege escalation paths, and backdoors planted. Prevention means stopping that chain before it reaches the payload.

I've worked support tickets where a single weak FTP password led to full server encryption within hours. The pattern is predictable: initial access through exposed services, lateral movement via shared credentials, privilege escalation through misconfigured sudo or kernel exploits, then mass file encryption. Nine hardening layers can break that pattern.

1. Harden SSH access and disable password auth

SSH is the most targeted entry point. Password authentication invites brute-force attacks around the clock.

Disable it completely:

sudo nano /etc/ssh/sshd_config

Set these directives:

PasswordAuthentication no
PermitRootLogin prohibit-password
PubkeyAuthentication yes
Port 2222

Changing the default port cuts down on automated scans. Restart SSH:

sudo systemctl restart sshd

Use key-based authentication only. Generate an ed25519 key pair on your local machine:

ssh-keygen -t ed25519 -C "[email protected]"
ssh-copy-id -p 2222 user@your-server-ip

Test the key login before closing your existing session. Install fail2ban to block repeated failed attempts:

sudo apt install fail2ban
sudo systemctl enable fail2ban

Default fail2ban rules handle SSH brute-force out of the box.

2. Enforce least-privilege user permissions

Ransomware needs write access to encrypt files. Limit which users can write where.

Never run application processes as root. Create dedicated service accounts with minimal permissions:

sudo useradd -r -s /bin/false appuser
sudo chown -R appuser:appuser /var/www/html/app

Set directory permissions to 755 for directories and 644 for files by default. Only the owning user writes; group and others read only:

find /var/www/html -type d -exec chmod 755 {} \;
find /var/www/html -type f -exec chmod 644 {} \;

For shared hosting environments, use separate Linux users per account. cPanel does this automatically, but custom setups often skip it. Isolate users with chmod 711 on home directories so other users can't browse in:

sudo chmod 711 /home/*

Review sudo rules. Many servers grant overly broad sudo access:

sudo visudo

Remove NOPASSWD entries unless absolutely required. An attacker who compromises a sudo-enabled account can escalate immediately.

3. Use immutable backups stored offline

Ransomware often hunts for backup directories and encrypts those first. If your backups live on mounted network shares or the same filesystem, they're vulnerable.

Store backups off-server entirely—object storage with versioning enabled, tape, or a dedicated backup appliance not accessible from the production network. For cloud backups, use bucket versioning and object lock:

In AWS S3, enable object lock in compliance mode with a retention period. In Backblaze B2 or Wasabi, enable versioning and lifecycle rules to retain deleted versions for at least thirty days.

On the server, push backups via a one-way sync. The backup destination should never be mounted read-write during normal operation:

rclone sync /var/backups remote:bucket-name --transfers 4

Schedule this in cron with restricted credentials that can only write, not delete. Use append-only or immutable flags where supported.

For local emergency snapshots, use filesystem snapshots (LVM or ZFS) that are harder to overwrite from userspace. Create a daily LVM snapshot:

sudo lvcreate -L 10G -s -n snap-$(date +%F) /dev/vg0/root

These snapshots sit below the file layer and won't be touched by a user-level encryption process.

4. Segment the network and firewall everything

Lateral movement is how ransomware spreads from one compromised host to others. Segment your environment so a breach on one server doesn't grant access to the rest.

Use iptables or ufw to block all inbound traffic except what you explicitly allow:

sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow 2222/tcp
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable

For multi-server setups, place application servers behind a load balancer or reverse proxy and block direct public access. Database servers should only accept connections from application servers, never from the public internet:

sudo ufw allow from 192.168.1.10 to any port 3306

If you run containers, use network policies to isolate workloads. In Kubernetes, apply default-deny network policies and whitelist only required communication paths.

Review listening services:

sudo ss -tlnp

Close anything you don't recognize or need. Disable unused services:

sudo systemctl disable cups
sudo systemctl stop cups

Every open port is a potential entry point.

So what if your firewall is tight but application vulnerabilities remain?

5. Patch the OS and all software on a schedule

Unpatched vulnerabilities are the second most common entry point after weak credentials. Privilege escalation exploits in the kernel or common utilities let attackers go from limited shell access to root in seconds.

Enable automatic security updates on Debian and Ubuntu:

sudo apt install unattended-upgrades
sudo dpkg-reconfigure -plow unattended-upgrades

Edit /etc/apt/apt.conf.d/50unattended-upgrades to include security repos only if you want to avoid surprise feature updates.

On RHEL and CentOS, use dnf-automatic:

sudo dnf install dnf-automatic
sudo systemctl enable --now dnf-automatic.timer

For application software (PHP, Node.js, Python packages, WordPress plugins), set a weekly review process. Subscribe to security mailing lists for the stacks you run. I check WordPress.org security announcements and GitHub security advisories for any custom code dependencies.

Test updates in a staging environment first if you can. But don't let testing delay critical patches for months—a known remote code execution bug is worse than a broken plugin.

6. Monitor file integrity and catch tampering early

Ransomware drops executables, modifies cron jobs, and alters configuration files before it starts encrypting user data. File integrity monitoring (FIM) alerts you to these changes.

Install AIDE (Advanced Intrusion Detection Environment):

sudo apt install aide
sudo aideinit
sudo cp /var/lib/aide/aide.db.new /var/lib/aide/aide.db

Run a daily check:

sudo aide --check

Schedule it in cron and send the output to email or a logging system:

0 2 * * * /usr/bin/aide --check | mail -s "AIDE Report" [email protected]

Configure AIDE to watch critical directories:

/etc p+i+n+u+g+s+b+m+c+md5+sha256
/bin p+i+n+u+g+s+b+m+c+md5+sha256
/sbin p+i+n+u+g+s+b+m+c+md5+sha256
/usr/bin p+i+n+u+g+s+b+m+c+md5+sha256
/var/www p+i+n+u+g+s+b+m+c+md5+sha256

Any change to binaries or config files triggers an alert. Investigate immediately—legitimate updates are infrequent and you'll know when you applied them.

For higher volume environments, ship logs to a centralized SIEM. Graylog or Wazuh can ingest AIDE reports and correlate them with other security events.

7. Restrict and audit administrative actions

Even trusted administrators can be phished or have their credentials stolen. Log all privileged commands and review them.

Enable process accounting with auditd:

sudo apt install auditd
sudo systemctl enable auditd

Add rules to track executions and file access:

sudo auditctl -w /etc/passwd -p wa -k passwd_changes
sudo auditctl -w /usr/bin/sudo -p x -k sudo_exec
sudo auditctl -w /var/www -p wa -k web_changes

Make rules persistent by adding them to /etc/audit/rules.d/audit.rules. Search the audit log:

sudo ausearch -k passwd_changes

For sudo, log full command lines. Edit /etc/sudoers:

Defaults log_output
Defaults!/usr/bin/sudoreplay !log_output

Sudo sessions are now recorded in /var/log/sudo-io/. Replay a session:

sudo sudoreplay <session-id>

In a support ticket I handled, the audit log showed a compromised WordPress admin account running wget to pull down a cryptominer. That command would never appear in normal operations. Logs caught it before the miner executed.

8. Disable or isolate risky services like email and FTP

Ransomware spreads through email attachments and credentials harvested from cleartext protocols. Turn off what you don't need.

If you must run FTP, switch to SFTP (SSH file transfer) or FTPS (FTP over TLS). Disable plain FTP entirely:

sudo systemctl disable vsftpd
sudo systemctl stop vsftpd

For cPanel servers, enforce FTPS in WHM:

  • WHM → Service Configuration → FTP Server Configuration → TLS Encryption → Require TLS

Better yet, push users toward SFTP. It uses SSH keys and the same hardened authentication you already set up.

If you run a mail server, disable open relay, enforce authentication, and enable SPF, DKIM, and DMARC to reduce spoofed messages. Limit the damage if an account is compromised:

postconf -e "smtpd_recipient_restrictions = permit_sasl_authenticated, reject_unauth_destination"
postconf -e "message_size_limit = 10485760"

Rate-limit outbound mail per user:

postconf -e "smtpd_client_message_rate_limit = 100"

This won't stop ransomware directly but it limits the blast radius when attackers use your server for spam or phishing campaigns to deliver malware.

9. Run endpoint detection or a host-based IPS

Traditional antivirus misses most modern ransomware because the binaries are polymorphic and change on every build. Behavior-based detection watches for suspicious patterns instead.

For Linux servers, ClamAV provides basic scanning:

sudo apt install clamav clamav-daemon
sudo freshclam
sudo systemctl enable clamav-freshclam

Run periodic scans:

clamscan -r -i /var/www /home

ClamAV catches known malware but won't stop zero-day ransomware. Pair it with a host-based intrusion prevention system (HIPS) like Wazuh or OSSEC. These monitor system calls, file changes, and process behavior to detect anomalies:

  • Rapid file modifications across many directories
  • Execution of unsigned binaries in temp directories
  • Privilege escalation attempts
  • Network connections to known malicious IPs

Wazuh integrates with AIDE, auditd, and firewall logs to correlate events. Configure alerts for high-risk patterns and send them to Slack or email for immediate response.

Commercial EDR tools (CrowdStrike, SentinelOne, Microsoft Defender for Endpoint) offer better detection rates if budget allows. They use machine learning models trained on ransomware behavior and can kill processes before encryption starts.

Testing and drills

Paper defenses fail in practice. Test your ransomware response at least twice a year.

Run a tabletop exercise: walk through what happens if a server gets compromised. Who gets notified? How do you isolate the infected host? Where are the backups and how long does restore take?

Test backup restoration for real. Spin up a temporary server and restore from your immutable backup. Time how long it takes. I've seen teams discover their backup scripts were silently failing for months—only a real restore attempt revealed it.

Use a safe test payload to validate monitoring. Drop a harmless executable in /tmp and run it. Did your FIM catch it? Did auditd log the execution? Did your EDR alert?

Patch the gaps you find.

Lock it down before the attack starts

Ransomware prevention is a checklist, not a single fix. Harden access points, enforce least privilege, isolate backups, monitor for tampering, and segment the network. Each layer stops a different stage of the attack chain.

The encryption stage is the loud finale—by then the attacker has been inside for hours or days. The earlier you catch them, the less damage they can do. Test your defenses, patch aggressively, and drill your response plan.

Your backups are your last line. Make sure they actually work.

FAQ

Will fail2ban stop ransomware?

It stops brute-force login attempts, which is one entry vector. It won't stop phishing, application exploits, or supply-chain attacks. Treat it as one layer, not a complete defense.

How often should I rotate SSH keys?

Rotate immediately if an admin leaves or a key might be compromised. For routine rotation, every six to twelve months is reasonable. Focus more on protecting the private keys (passphrases, hardware tokens) than on rotation frequency.

Can ransomware spread through Docker containers?

Yes, if the container has write access to host volumes or if the container runtime itself is compromised. Run containers as non-root users, use read-only volumes where possible, and apply the same network segmentation principles.

Should I pay the ransom?

No. Payment funds future attacks and there's no guarantee you'll get a working decryption key. Law enforcement and security researchers advise against it. Focus on prevention and reliable backups so you never face that decision.