How to Secure Your VPS: Essential Security Hardening Guide
Comprehensive guide to securing your VPS against common threats. Learn SSH hardening, firewall configuration, fail2ban setup, intrusion detection, and security best practices.
- Dataset size: 1,257 plans across 12 providers. Last checked: 2026-01-28.
- Change log updated: 2026-01-28 ( see updates).
- Latency snapshot: 2026-01-23 ( how tiers work).
- Benchmarks: 60 run(s) (retrieved: 2026-01-23). Benchmark your own VPS .
- Found an issue? Send a correction .
How to Secure Your VPS: Essential Security Hardening Guide
VPS security is not optional—it’s essential. A compromised VPS can lead to data theft, service disruption, and financial loss. The good news is that you can significantly improve your VPS security with some basic hardening steps.
This comprehensive guide will walk you through essential security measures to protect your VPS from common threats.
Understanding VPS Security Threats
Before hardening, understand what you’re protecting against:
Common VPS threats:
- Brute force attacks - Automated attempts to guess passwords
- DDoS attacks - Overwhelming your server with traffic
- Malware injection - Malicious code installation
- Zero-day exploits - Unpatched software vulnerabilities
- Insider threats - Compromised credentials
- Port scanning - Attackers looking for open ports
Attack surfaces:
- SSH access (port 22)
- Web services (ports 80, 443)
- Database ports (3306, 5432)
- Email services (25, 587)
- Unnecessary open ports
Pre-Security Checklist
Before implementing security measures:
- Full backup - Create complete system backup
- Access recovery - Ensure you can regain access if locked out
- Documentation - Record all changes and credentials
- Test environment - Practice on a test VPS first
- Emergency access - Keep alternative access method ready
Part 1: SSH Hardening
SSH (Secure Shell) is the most common attack vector. Secure it first.
Step 1: Disable SSH Password Authentication
Use SSH keys instead of passwords:
# Generate SSH key pair (on your local machine)
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
# Copy public key to VPS
ssh-copy-id username@your-vps-ip
# Test SSH key login
ssh username@your-vps-ip
Disable password authentication:
# Edit SSH config
sudo nano /etc/ssh/sshd_config
# Find and change these lines:
PasswordAuthentication no
PubkeyAuthentication yes
# Optional: Disable root login
PermitRootLogin no
# Optional: Change default SSH port (security through obscurity)
# Port 2222 (change from 22)
# Optional: Limit allowed users
AllowUsers username
# Restart SSH
sudo systemctl restart sshd
# Note: Keep your current session open while testing!
# Open new terminal to verify SSH key login works
Step 2: Configure SSH Timeout
# Edit SSH config
sudo nano /etc/ssh/sshd_config
# Add or modify:
ClientAliveInterval 300
ClientAliveCountMax 2
# Restart SSH
sudo systemctl restart sshd
This disconnects idle sessions after 10 minutes.
Step 3: Limit SSH Access by IP (Optional)
If you have a static IP, restrict SSH access:
# Edit SSH config
sudo nano /etc/ssh/sshd_config
# Add at end:
AllowUsers your_username@your_ip_address
# Restart SSH
sudo systemctl restart sshd
Part 2: Firewall Configuration
Step 1: Install and Configure UFW (Uncomplicated Firewall)
# Install UFW
sudo apt install ufw -y
# Default policies
sudo ufw default deny incoming
sudo ufw default allow outgoing
# Allow SSH (important before enabling!)
sudo ufw allow OpenSSH
# If you changed SSH port:
sudo ufw allow 2222/tcp
# Allow HTTP and HTTPS
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
# Enable firewall
sudo ufw enable
# Check status
sudo ufw status verbose
Step 2: Additional Firewall Rules
# Allow specific services (if needed):
# FTP (21)
sudo ufw allow 21/tcp
# Email (25, 587, 465)
sudo ufw allow 25/tcp
sudo ufw allow 587/tcp
sudo ufw allow 465/tcp
# MySQL (only if remote access needed)
sudo ufw allow from trusted_ip to any port 3306
# PostgreSQL (only if remote access needed)
sudo ufw allow from trusted_ip to any port 5432
# Delete old rules if needed
sudo ufw delete allow 21/tcp
# Reload firewall
sudo ufw reload
Step 3: Advanced Firewall with iptables (Optional)
For more complex rules, use iptables directly:
# Install iptables-persistent
sudo apt install iptables-persistent -y
# View current rules
sudo iptables -L -n -v
# Save current rules
sudo netfilter-persistent save
Part 3: Install and Configure Fail2Ban
Fail2ban monitors log files and bans IPs with too many failed login attempts.
Step 1: Install Fail2Ban
# Install Fail2Ban
sudo apt install fail2ban -y
# Start and enable
sudo systemctl start fail2ban
sudo systemctl enable fail2ban
Step 2: Configure Fail2Ban
# Create local configuration
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
# Edit configuration
sudo nano /etc/fail2ban/jail.local
Add/modify these jails:
[DEFAULT]
# Ban for 1 hour
bantime = 3600
# Ban after 3 failures
maxretry = 3
# Find time window
findtime = 600
# Send email alerts (optional)
destemail = your_email@example.com
sendername = Fail2Ban
action = %(action_mwl)s
[sshd]
enabled = true
port = ssh
logpath = /var/log/auth.log
maxretry = 3
bantime = 3600
[apache]
enabled = true
port = http,https
logpath = /var/log/apache2/error.log
maxretry = 3
bantime = 3600
[nginx-http-auth]
enabled = true
port = http,https
logpath = /var/log/nginx/error.log
maxretry = 3
bantime = 3600
[nginx-noscript]
enabled = true
port = http,https
logpath = /var/log/nginx/access.log
maxretry = 6
bantime = 3600
Restart Fail2Ban:
sudo systemctl restart fail2ban
# Check status
sudo fail2ban-client status
# Check specific jail
sudo fail2ban-client status sshd
Part 4: System Hardening
Step 1: Keep System Updated
# Update package lists
sudo apt update
# Upgrade all packages
sudo apt upgrade -y
# Install unattended-upgrades for automatic security updates
sudo apt install unattended-upgrades apt-listchanges -y
# Configure automatic updates
sudo dpkg-reconfigure -plow unattended-upgrades
# Enable automatic updates
sudo nano /etc/apt/apt.conf.d/50unattended-upgrades
# Add/modify:
Unattended-Upgrade::AutoFixInterruptedDpkg "true";
Unattended-Upgrade::MinimalSteps "true";
Unattended-Upgrade::Remove-Unused-KernelPackages "true";
Unattended-Upgrade::Automatic-Reboot "false";
Unattended-Upgrade::Automatic-Reboot-Time "02:00";
Unattended-Upgrade::MailOnlyOnError "true";
Step 2: Secure Shared Memory
# Edit fstab
sudo nano /etc/fstab
# Add line:
tmpfs /run/shm tmpfs defaults,noexec,nosuid,size=1G 0 0
# Remount without reboot
sudo mount -o remount /run/shm
Step 3: Disable Unused Services
# List all services
sudo systemctl list-unit-files --type=service
# Disable unused services:
sudo systemctl disable service_name
# Common services to disable (if not used):
sudo systemctl disable bluetooth
sudo systemctl disable cups
sudo systemctl disable avahi-daemon
Step 4: Limit Network Protocols
# Disable IPv6 (if not needed)
sudo nano /etc/sysctl.conf
# Add:
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1
# Apply changes
sudo sysctl -p
# Disable unnecessary network protocols
sudo nano /etc/sysctl.conf
# Add:
net.ipv4.tcp_syncookies = 1
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.all.rp_filter = 1
# Apply changes
sudo sysctl -p
Part 5: Application Security
Step 1: Secure Web Server Configuration
For Apache:
# Hide server version
sudo nano /etc/apache2/conf-available/security.conf
# Add/modify:
ServerTokens Prod
ServerSignature Off
TraceEnable Off
# Enable security headers
sudo a2enmod headers
sudo nano /etc/apache2/mods-available/headers.conf
# Add:
Header always set X-Content-Type-Options "nosniff"
Header always set X-Frame-Options "SAMEORIGIN"
Header always set X-XSS-Protection "1; mode=block"
Header always set Referrer-Policy "strict-origin-when-cross-origin"
Header always set Permissions-Policy "geolocation=(), microphone=(), camera=()"
# Restart Apache
sudo systemctl restart apache2
For Nginx:
# Edit main config
sudo nano /etc/nginx/nginx.conf
# Add in http block:
server_tokens off;
# Add security headers
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Permissions-Policy "geolocation=(), microphone=(), camera=()" always;
# Restart Nginx
sudo systemctl restart nginx
Step 2: Secure MySQL/MariaDB
# Run mysql secure installation (if not done)
sudo mysql_secure_installation
# Create MySQL user for applications (avoid root)
sudo mysql -u root -p
CREATE USER 'app_user'@'localhost' IDENTIFIED BY 'StrongPassword';
GRANT SELECT, INSERT, UPDATE, DELETE ON app_database.* TO 'app_user'@'localhost';
FLUSH PRIVILEGES;
EXIT;
# Bind MySQL to localhost (skip-networking)
sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf
# Add:
[mysqld]
bind-address = 127.0.0.1
# Restart MySQL
sudo systemctl restart mysql
Step 3: Install SSL Certificate
# Install Certbot
sudo apt install certbot python3-certbot-nginx -y
# Or for Apache:
# sudo apt install certbot python3-certbot-apache -y
# Obtain certificate
sudo certbot --nginx -d example.com -d www.example.com
# Auto-renewal is configured automatically
sudo certbot renew --dry-run
Part 6: Intrusion Detection and Monitoring
Step 1: Install Rootkit Hunter
# Install rkhunter
sudo apt install rkhunter -y
# Update database
sudo rkhunter --update
# Run scan
sudo rkhunter --check
# Configure email alerts (optional)
sudo nano /etc/rkhunter.conf
# Add:
MAIL-ON-WARNING="your_email@example.com"
MAIL_CMD=mail
Step 2: Install Lynis (Security Auditing)
# Install Lynis
sudo apt install lynis -y
# Run security audit
sudo lynis audit system
# View report
cat /var/log/lynis-report.dat
Step 3: Set Up Log Monitoring
# Install logwatch
sudo apt install logwatch -y
# Configure
sudo nano /etc/cron.daily/00logwatch
# Set email for reports
MailTo = your_email@example.com
# Test
sudo logwatch --detail High --mailto your_email@example.com
Step 4: Real-time Monitoring (Optional)
Install tools:
- htop - Interactive process viewer
- iotop - I/O monitoring
- nethogs - Network bandwidth monitoring
sudo apt install htop iotop nethogs -y
Part 7: Backup and Disaster Recovery
Step 1: Automated Backup Script
# Create backup script
sudo nano /usr/local/bin/vps-backup.sh
#!/bin/bash
DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_DIR="/backup"
CONFIG_FILES="/etc /home /root"
# Create backup directory
mkdir -p $BACKUP_DIR
# Backup system files
tar -czf $BACKUP_DIR/system-config-$DATE.tar.gz $CONFIG_FILES
# Backup MySQL databases
mysqldump --all-databases > $BACKUP_DIR/mysql-all-$DATE.sql
# Backup web files
tar -czf $BACKUP_DIR/web-files-$DATE.tar.gz /var/www/html
# Delete backups older than 7 days
find $BACKUP_DIR -type f -mtime +7 -delete
echo "Backup completed: $DATE"
# Make executable
sudo chmod +x /usr/local/bin/vps-backup.sh
# Add to crontab (daily at 3 AM)
sudo crontab -e
# Add:
0 3 * * * /usr/local/bin/vps-backup.sh >> /var/log/vps-backup.log 2>&1
Step 2: Off-Site Backup (Optional)
Consider using:
- Restic - Encrypted backups to various backends
- Borg - Deduplicating backup program
- rsync - Sync to remote server
- Cloud storage - AWS S3, Backblaze B2, etc.
Part 8: Security Best Practices
Daily Practices
- Monitor system logs
- Check for software updates
- Review active user sessions (
wcommand) - Monitor disk usage (
df -h) - Check running processes (
htop)
Weekly Practices
- Review security bulletins
- Audit user accounts
- Check firewall logs
- Review Fail2Ban bans
- Test backup restoration
Monthly Practices
- Full security audit
- Update all software
- Review SSH keys
- Check SSL certificates
- Review user permissions
- Audit installed packages
Part 9: Incident Response Plan
Prepare for security incidents before they happen:
Create Emergency Response Plan
# Security Incident Response Plan
## 1. Detection
- How to detect: Monitoring alerts, user reports, unusual activity
- Contact: security@example.com
## 2. Containment
- Disconnect from network if needed
- Change all passwords
- Block attacker IP
- Preserve evidence (logs, screenshots)
## 3. Eradication
- Identify vulnerability
- Patch/fix vulnerability
- Remove malware/backdoors
- Verify system clean
## 4. Recovery
- Restore from clean backup
- Update all credentials
- Monitor for recurrence
- Document incident
## 5. Post-Incident
- Review what happened
- Update security measures
- Train team if needed
- Update response plan
Security Checklist
Initial Setup (Day 1)
- SSH hardening completed
- Firewall configured
- Fail2Ban installed
- SSL certificate installed
- System updated
- Backup configured
- Monitoring set up
Ongoing Maintenance
- Updates installed weekly
- Logs reviewed weekly
- Backups tested monthly
- Security audit quarterly
- Incident plan reviewed annually
Troubleshooting
Locked Out of SSH?
If you can’t log in after SSH changes:
-
Use VPS provider console:
- Most providers offer web-based console
- Access directly from their dashboard
-
Check SSH config:
# Via provider console sudo nano /etc/ssh/sshd_config # Ensure PasswordAuthentication is yes temporarily sudo systemctl restart sshd -
Revert to last known good config:
# If you backed up sudo cp /etc/ssh/sshd_config.backup /etc/ssh/sshd_config sudo systemctl restart sshd
Firewall Blocking Access?
# Via provider console
sudo ufw status
# Reset if needed
sudo ufw --force reset
sudo ufw allow ssh
sudo ufw enable
Fail2Ban Blocking You?
# Check if banned
sudo fail2ban-client status sshd
# Unban your IP
sudo fail2ban-client set sshd unbanip your_ip_address
# Or whitelist your IP
sudo nano /etc/fail2ban/jail.local
# Add to [DEFAULT]:
ignoreip = 127.0.0.1/8 your_ip_address
Conclusion
VPS security is an ongoing process, not a one-time setup. By implementing these measures:
You’ve protected against:
- ✅ Brute force attacks (SSH hardening, Fail2Ban)
- ✅ Unauthorized access (firewall, SSH keys)
- ✅ Software vulnerabilities (automatic updates)
- ✅ Common attacks (security headers, SSL)
- ✅ Data loss (automated backups)
Remember:
- Security is a process - Continuously monitor and improve
- Backups are essential - Your last line of defense
- Stay informed - Subscribe to security bulletins
- Test regularly - Verify backups and restoration
- Have a plan - Know what to do when something goes wrong
Need a secure VPS? Use our VPS Finder to find providers with good security features and refund policies.
Additional resources:
Last updated: January 2026 Found this guide helpful? Share it with others to help make the internet more secure!