Advanced VPS Hardening Guide 2026: Secure Your Server Like a Pro
Advanced VPS security hardening guide covering kernel tuning, intrusion detection, firewall rules, fail2ban, AppArmor, and more. Protect your server from real threats.
Advanced VPS Hardening Guide: Secure Your Server Like a Pro
A basic VPS setup leaves you exposed. Default configs, open ports, and weak authentication are an open invitation. This guide goes beyond the basics — kernel hardening, intrusion detection, automated blocking, and audit logging that actually catches threats.
Already have SSH keys and a firewall? Good. This picks up where beginner guides stop.
What This Guide Covers
What This Guide Covers
| Layer | Tools | Purpose |
|---|---|---|
| Network | UFW, iptables, fail2ban | Block unauthorized access |
| Authentication | SSH hardening, 2FA | Prevent brute force |
| Kernel | sysctl tuning | Reduce attack surface |
| Mandatory Access Control | AppArmor / SELinux | Contain compromised services |
| Intrusion Detection | AIDE, auditd | Detect unauthorized changes |
| Logging | rsyslog, logwatch | Monitor everything |
| Automatic Updates | unattended-upgrades | Patch vulnerabilities |
Prerequisites
- A VPS running Ubuntu 22.04+ or Debian 12+ (most examples work on RHEL/Rocky with minor tweaks)
- SSH key authentication already configured
- Root or sudo access
- Basic familiarity with the Linux command line
Recommended VPS providers for security-conscious users:
| Provider | Why | Starting Price |
|---|---|---|
| Hetzner | EU data centers, GDPR compliant, raw performance | €3.79/mo |
| Hostinger | Affordable KVM with snapshot backups | $4.99/mo |
| Vultr | Bare metal options, DDoS protection included | $6/mo |
| DigitalOcean | VPC networking, managed firewalls | $6/mo |
1. SSH Hardening (Beyond the Basics)
You already have key-based auth. Now lock it down further.
Restrict SSH to Key-Only, Disable Root
sudo nano /etc/ssh/sshd_config
Set these values:
# Authentication
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
AuthenticationMethods publickey
# Limit exposure
MaxAuthTries 3
MaxSessions 3
LoginGraceTime 30
ClientAliveInterval 300
ClientAliveCountMax 2
# Disable unnecessary features
X11Forwarding no
AllowTcpForwarding no
AllowAgentForwarding no
PermitTunnel no
# Use only strong algorithms
KexAlgorithms skedf25519-sha256,skedf25519-sha256@libssh.org,diffie-hellman-group16-sha512
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com
MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com
Change Default SSH Port
Moving SSH off port 22 stops most automated scans:
# Add new port (don't remove 22 yet!)
Port 2222
Port 22
Restart and test with the new port before removing 22:
sudo systemctl restart sshd
ssh -p 2222 user@your-server
Once confirmed, remove Port 22 and restart again.
Add Two-Factor Authentication
sudo apt install libpam-google-authenticator
google-authenticator
Edit PAM config:
sudo nano /etc/pam.d/sshd
Add at the top:
auth required pam_google_authenticator.so
Update sshd_config:
AuthenticationMethods publickey,keyboard-interactive
ChallengeResponseAuthentication yes
Now logins require both your SSH key and a TOTP code.
2. Firewall Configuration with UFW + Rate Limiting
Basic UFW Setup
sudo ufw default deny incoming
sudo ufw default allow outgoing
# Allow SSH (use your custom port)
sudo ufw limit 2222/tcp comment 'SSH rate-limited'
# Allow web traffic
sudo ufw allow 80/tcp comment 'HTTP'
sudo ufw allow 443/tcp comment 'HTTPS'
# Enable
sudo ufw enable
The limit rule automatically rate-limits connections — 6 connections per 30 seconds, then blocks.
Advanced: iptables Rules for DDoS Mitigation
For servers under heavy traffic, add these iptables rules:
# Drop invalid packets
sudo iptables -A INPUT -m conntrack --ctstate INVALID -j DROP
# Block port scanning
sudo iptables -A INPUT -p tcp --tcp-flags ALL NONE -j DROP
sudo iptables -A INPUT -p tcp --tcp-flags ALL ALL -j DROP
# Rate limit new connections (SYN flood protection)
sudo iptables -A INPUT -p tcp --syn -m limit --limit 25/second --limit-burst 50 -j ACCEPT
sudo iptables -A INPUT -p tcp --syn -j DROP
# Limit ICMP (ping flood protection)
sudo iptables -A INPUT -p icmp --icmp-type echo-request -m limit --limit 1/s --limit-burst 4 -j ACCEPT
sudo iptables -A INPUT -p icmp --icmp-type echo-request -j DROP
Save rules to persist across reboots:
sudo apt install iptables-persistent
sudo netfilter-persistent save
3. Fail2Ban: Intelligent Brute Force Protection
Install and Configure
sudo apt install fail2ban
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
Edit /etc/fail2ban/jail.local:
[DEFAULT]
bantime = 3600
findtime = 600
maxretry = 3
banaction = ufw
backend = systemd
# Email notifications (optional)
destemail = you@example.com
action = %(action_mwl)s
[sshd]
enabled = true
port = 2222
maxretry = 3
bantime = 86400
[sshd-ddos]
enabled = true
port = 2222
# Protect nginx
[nginx-http-auth]
enabled = true
filter = nginx-http-auth
logpath = /var/log/nginx/error.log
maxretry = 3
[nginx-botsearch]
enabled = true
filter = nginx-botsearch
logpath = /var/log/nginx/access.log
maxretry = 2
# Protect against repeated 404s (scanners)
[nginx-404]
enabled = true
port = http,https
filter = nginx-404
logpath = /var/log/nginx/access.log
maxretry = 10
findtime = 60
bantime = 3600
Create the nginx-404 filter:
sudo nano /etc/fail2ban/filter.d/nginx-404.conf
[Definition]
failregex = ^<HOST> .* "(GET|POST|HEAD).*" 404
ignoreregex =
Start fail2ban:
sudo systemctl enable fail2ban
sudo systemctl start fail2ban
sudo fail2ban-client status
4. Kernel Hardening with sysctl
These settings reduce your kernel’s attack surface:
sudo nano /etc/sysctl.d/99-hardening.conf
# Disable IP forwarding (unless running Docker/VPN)
net.ipv4.ip_forward = 0
net.ipv6.conf.all.forwarding = 0
# Prevent IP spoofing
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
# Ignore ICMP redirects
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv6.conf.all.accept_redirects = 0
# Don't send ICMP redirects
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0
# Ignore source-routed packets
net.ipv4.conf.all.accept_source_route = 0
net.ipv6.conf.all.accept_source_route = 0
# Enable SYN cookies (SYN flood protection)
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_max_syn_backlog = 2048
net.ipv4.tcp_synack_retries = 2
# Log suspicious packets
net.ipv4.conf.all.log_martians = 1
net.ipv4.conf.default.log_martians = 1
# Disable IPv6 if not needed
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1
# Harden kernel
kernel.randomize_va_space = 2
kernel.kptr_restrict = 2
kernel.dmesg_restrict = 1
kernel.perf_event_paranoid = 3
kernel.yama.ptrace_scope = 2
# Restrict unprivileged user namespaces
kernel.unprivileged_userns_clone = 0
# Filesystem hardening
fs.protected_hardlinks = 1
fs.protected_symlinks = 1
fs.suid_dumpable = 0
Apply immediately:
sudo sysctl --system
Docker users: Keep
net.ipv4.ip_forward = 1if you run containers. Docker needs it for networking.
5. AppArmor: Mandatory Access Control
AppArmor confines programs to a limited set of resources — even if an attacker exploits a vulnerability, they can’t escape the profile.
Enable and Check Status
sudo apt install apparmor apparmor-utils apparmor-profiles apparmor-profiles-extra
sudo aa-status
Enforce Profiles for Key Services
# List available profiles
sudo aa-unconfined
# Put nginx in enforce mode
sudo aa-enforce /etc/apparmor.d/usr.sbin.nginx
# Create a profile for a custom application
sudo aa-genprof /usr/local/bin/myapp
Create Custom Profiles
For apps without existing profiles:
# Start in complain mode (logs violations but doesn't block)
sudo aa-complain /path/to/application
# Run the app normally, exercise all features
# Then review logs and convert to enforce mode
sudo aa-logprof
sudo aa-enforce /path/to/application
6. Intrusion Detection with AIDE
AIDE (Advanced Intrusion Detection Environment) monitors file integrity — it alerts you when system files change unexpectedly.
Install and Initialize
sudo apt install aide
sudo aideinit
sudo cp /var/lib/aide/aide.db.new /var/lib/aide/aide.db
Configure What to Monitor
sudo nano /etc/aide/aide.conf
Add custom rules:
# Monitor critical system directories
/etc p+i+u+g+sha256
/bin p+i+u+g+sha256
/sbin p+i+u+g+sha256
/usr/bin p+i+u+g+sha256
/usr/sbin p+i+u+g+sha256
# Monitor web root
/var/www p+i+u+g+sha256
# Exclude noisy directories
!/var/log
!/var/cache
!/tmp
Automate Daily Checks
sudo crontab -e
Add:
0 5 * * * /usr/bin/aide --check | mail -s "AIDE Report $(hostname)" you@example.com
7. Audit Logging with auditd
Track who does what on your system:
sudo apt install auditd audispd-plugins
Add Audit Rules
sudo nano /etc/audit/rules.d/hardening.rules
# Monitor authentication
-w /etc/pam.d/ -p wa -k auth_changes
-w /etc/shadow -p wa -k shadow_changes
-w /etc/passwd -p wa -k passwd_changes
# Monitor SSH config
-w /etc/ssh/sshd_config -p wa -k sshd_config
# Monitor sudo usage
-w /var/log/auth.log -p wa -k auth_log
-w /etc/sudoers -p wa -k sudoers
# Monitor cron
-w /etc/crontab -p wa -k cron_changes
-w /etc/cron.d/ -p wa -k cron_changes
-w /var/spool/cron/ -p wa -k cron_changes
# Monitor network config
-w /etc/hosts -p wa -k hosts_changes
-w /etc/network/ -p wa -k network_changes
# Monitor kernel modules
-w /sbin/insmod -p x -k kernel_modules
-w /sbin/modprobe -p x -k kernel_modules
-w /sbin/rmmod -p x -k kernel_modules
# Log all commands run by root
-a always,exit -F arch=b64 -F euid=0 -S execve -k root_commands
# Make rules immutable (requires reboot to change)
-e 2
Restart auditd:
sudo systemctl restart auditd
Search audit logs:
# Find all sudo events
sudo ausearch -k sudoers
# Find SSH config changes
sudo ausearch -k sshd_config
8. Automatic Security Updates
Never miss a critical patch:
sudo apt install unattended-upgrades apt-listchanges
sudo dpkg-reconfigure -plow unattended-upgrades
Configure what gets auto-updated:
sudo nano /etc/apt/apt.conf.d/50unattended-upgrades
Unattended-Upgrade::Allowed-Origins {
"${distro_id}:${distro_codename}-security";
"${distro_id}ESMApps:${distro_codename}-apps-security";
};
Unattended-Upgrade::AutoFixInterruptedDpkg "true";
Unattended-Upgrade::Remove-Unused-Dependencies "true";
Unattended-Upgrade::Automatic-Reboot "true";
Unattended-Upgrade::Automatic-Reboot-Time "04:00";
// Email notifications
Unattended-Upgrade::Mail "you@example.com";
Unattended-Upgrade::MailReport "on-change";
9. Secure Shared Memory and /tmp
Prevent shared memory attacks:
sudo nano /etc/fstab
Add:
tmpfs /run/shm tmpfs defaults,noexec,nosuid,nodev 0 0
tmpfs /tmp tmpfs defaults,noexec,nosuid,nodev,size=2G 0 0
Remount:
sudo mount -o remount /run/shm
sudo mount -o remount /tmp
Note:
noexecon/tmpcan break some installers. Temporarily remount with exec when needed:sudo mount -o remount,exec /tmp
10. Log Monitoring with Logwatch
Get daily security summaries:
sudo apt install logwatch
Configure:
sudo nano /etc/logwatch/conf/logwatch.conf
Output = mail
MailTo = you@example.com
Detail = High
Range = yesterday
Service = All
Test it:
sudo logwatch --detail High --mailto you@example.com --range today
Security Checklist
Run through this after hardening:
| Check | Command | Expected |
|---|---|---|
| SSH root disabled | grep PermitRootLogin /etc/ssh/sshd_config | no |
| Password auth off | grep PasswordAuthentication /etc/ssh/sshd_config | no |
| Firewall active | sudo ufw status | active |
| Fail2ban running | sudo fail2ban-client status | Active jails listed |
| AppArmor loaded | sudo aa-status | Profiles in enforce mode |
| AIDE initialized | sudo aide --check | No unexpected changes |
| Auto-updates on | apt-config dump | grep Unattended | "1" |
| Open ports minimal | sudo ss -tlnp | Only expected ports |
| Kernel hardened | sysctl kernel.randomize_va_space | 2 |
Ongoing Maintenance
Hardening isn’t one-and-done. Schedule these:
- Daily: Review fail2ban bans (
sudo fail2ban-client status sshd) - Weekly: Check AIDE reports, review auth logs
- Monthly: Update all packages, review open ports, check for new CVEs
- Quarterly: Audit user accounts, rotate SSH keys, review firewall rules
Best VPS Providers for Security
| Provider | Security Features | Best For |
|---|---|---|
| Hostinger | KVM isolation, DDoS protection, backups | Best value — strong security at low cost |
| Hetzner | EU privacy laws, dedicated firewall, snapshots | Privacy-focused deployments |
| Vultr | DDoS protection, firewall API, bare metal | High-security workloads |
| DigitalOcean | VPC, managed firewalls, monitoring | Team environments |
| Linode | Free DDoS mitigation, Longview monitoring | Monitoring-heavy setups |
Hostinger offers the best balance of security features and price — KVM virtualization ensures full isolation from other tenants, and their automated backup system gives you recovery options if something goes wrong.
Conclusion
A hardened VPS isn’t just about running a firewall. It’s layers: network filtering, authentication controls, kernel restrictions, mandatory access control, file integrity monitoring, and automated patching. Each layer catches what the others miss.
Start with SSH hardening and fail2ban (immediate impact), then add kernel tuning and AppArmor (deeper protection), and finish with AIDE and auditd (detection and forensics).
No server is unhackable. But a properly hardened VPS makes attackers move on to easier targets — and that’s the goal.
Ready to get started?
Get the best VPS hosting deal today. Hostinger offers 4GB RAM VPS starting at just $4.99/mo.
Get Hostinger VPS — $4.99/mo// up to 75% off + free domain included
// related topics
// related guides
$1 VPS Hosting 2026: Cheapest VPS Servers Starting at $1/Month
Looking for $1 VPS hosting? Compare the cheapest VPS providers starting from $1-3/month. Real specs, no hidden fees, honest reviews of budget VPS options.
tutorialCaddy Reverse Proxy Guide 2026: Automatic HTTPS Made Easy
Set up Caddy as a reverse proxy with automatic HTTPS, zero-config SSL, and simple Caddyfile syntax. Complete VPS deployment guide.
tutorialCloudflare Tunnel VPS Guide 2026: Expose Services Without Opening Ports
Set up Cloudflare Tunnel on your VPS to expose web apps securely without opening ports or revealing your server IP. Complete guide with Docker and DNS config.
tutorialCoolify VPS Setup Guide 2026: Self-Hosted Vercel Alternative
Deploy Coolify on your VPS for a self-hosted Vercel/Netlify experience. Complete setup guide with Docker, SSL, and app deployments.
Andrius Putna
I am Andrius Putna. Geek. Since early 2000 in love tinkering with web technologies. Now AI. Bridging business and technology to drive meaningful impact. Combining expertise in customer experience, technology, and business strategy to deliver valuable insights. Father, open-source contributor, investor, 2xIronman, MBA graduate.
// last updated: March 14, 2026. Disclosure: This article may contain affiliate links.