Order matters here. Unlike other pages on this site, these phases are sequential. Do
Security theatre is labelled. Some steps are common advice that adds friction without meaningfully improving security. Those are marked so you can make an informed decision rather than cargo-culting every recommendation you've ever seen.
access before firewall, firewall before updates. Locking yourself out by setting up the firewall before your SSH key is in place is a rite of passage; this page helps you skip it. Checkboxes persist in your browser for this session.
Security theatre is labelled. Some steps are common advice that adds friction without meaningfully improving security. Those are marked so you can make an informed decision rather than cargo-culting every recommendation you've ever seen.
| # | Step | Phase | Commands | Notes | |
|---|---|---|---|---|---|
| 1 | Create non-root sudo user | access |
adduser deploy
usermod -aG sudo deploy
su - deploy
sudo whoami
# confirm sudo works before proceeding
|
Never run applications as root. Create a named user now (before changing SSH config) so you have a working non-root login before you lock root out. Confirm sudo works in the same session before continuing. | |
| 2 | Verify host key before first connection | access |
# install ssh-init-vm (requires Python 3, OpenSSH client):
curl -fsSL https://raw.githubusercontent.com/JoachimSchipper/ssh-init-vm/main/ssh-init-vm -o ssh-init-vm && chmod +x ssh-init-vm
# at VPS provisioning: inject a temporary host key via cloud-init user-data:
./ssh-init-vm generate-cloud-config > cloud-init.yaml
# pass cloud-init.yaml as user-data when creating the server
# once the server is up, bootstrap the trusted connection:
./ssh-init-vm connect root@<vps-ip>
# real host keys are now in ~/.ssh/known_hosts via OpenSSH key rotation
# temp key material is deleted: metadata service leak is now harmless
|
Prevents MITM on the very first connection. The default "yes to fingerprint" (TOFU) leaves you open to a network attacker rerouting your traffic. Injecting a long-term key via cloud-init is worse: the private key sits at http://169.254.169.254/, readable by any process on the VM and provider systems. ssh-init-vm injects a throwaway temporary key, uses it to bootstrap, retrieves the real host keys via OpenSSH key rotation, then discards the temp material. By the time you log in normally, the temp key is worthless even if an attacker reads it from the metadata service. Requires cloud-init support at the provider: Hetzner, DigitalOcean, Linode, AWS, GCP, Azure all support it. |
|
| 3 | Install your SSH public key | access |
# from your local machine:
ssh-copy-id -i ~/.ssh/id_ed25519.pub deploy@<vps-ip>
# or manually on the server:
mkdir -p ~/.ssh && chmod 700 ~/.ssh
echo "ssh-ed25519 AAAA..." >> ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys
# test key login in a NEW terminal before proceeding
|
Test key-based login in a new terminal before disabling password auth. If you lock yourself out here you still have root access and time to fix it. Use Ed25519: RSA 2048 is legacy, RSA 4096 is slower than Ed25519 with no meaningful security gain. | |
| 4 | Harden sshd_config | access |
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
sudo nano /etc/ssh/sshd_config
# set these values:
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
MaxAuthTries 3
LoginGraceTime 20
AllowUsers deploy
X11Forwarding no
AllowTcpForwarding no
sudo sshd -t
sudo systemctl reload sshd
|
sshd -t validates config before reloading. Never reload without it. Keep your existing session open while testing login in a new terminal. AllowUsers whitelist means even if an attacker creates another user, they can't SSH in. AllowTcpForwarding no prevents your server being used as a tunnel if a key is compromised. |
|
| 5 | Change SSH port theatre | access |
# /etc/ssh/sshd_config
Port 2222
sudo sshd -t && sudo systemctl reload sshd
# update firewall before closing session (step 5)
# add to ~/.ssh/config on client:
Host myvps
HostName <vps-ip>
Port 2222
User deploy
|
Security theatre. Moving SSH off port 22 eliminates noise from unsophisticated scanners but any port scanner running a service probe will find it anyway. Reduces log noise significantly: a legitimate reason to do it. If you do it: update your firewall rule in the same session, or you lock yourself out. | |
| 6 | Configure UFW: default deny | firewall |
sudo apt install -y ufw
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow 22/tcp
# if you changed SSH port above: sudo ufw allow 2222/tcp
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw --force enable
sudo ufw status verbose
|
Enable UFW only after SSH is allowed: in that order. --force skips the interactive prompt, safe in scripts. Add application ports before enabling, not after. UFW is a frontend for iptables; it persists across reboots. Verify the rules look right before closing your current session. |
|
| 7 | Verify firewall from outside | firewall |
# from your local machine or another host, NOT from the VPS itself:
nmap -Pn -sV <vps-ip>
nmap -Pn -p- --min-rate=1000 <vps-ip>
# only your allowed ports should appear as open
# or use a web-based scanner: nmap.online, pentest-tools.com
|
ss -tlnp on the server shows listening sockets. It does not show what's blocked by the firewall. Always verify from an external host. -p- scans all 65535 ports. Anything unexpected appearing here is a finding: stop and investigate before continuing. |
|
| 8 | Full system update | updates |
sudo apt update && sudo apt upgrade -y
sudo apt dist-upgrade -y
sudo apt autoremove -y && sudo apt autoclean
sudo reboot
# reconnect and verify uptime after reboot
uptime && uname -r
|
Do a full update immediately on a fresh server: cloud provider images are often weeks behind. dist-upgrade handles dependency changes that upgrade skips. Reboot now to start on the latest kernel before configuring anything that depends on kernel behaviour (like fail2ban netfilter integration). |
|
| 9 | Enable unattended-upgrades | updates |
sudo apt install -y unattended-upgrades needrestart
sudo dpkg-reconfigure -plow unattended-upgrades
# /etc/apt/apt.conf.d/50unattended-upgrades: key settings:
Unattended-Upgrade::Automatic-Reboot "true";
Unattended-Upgrade::Automatic-Reboot-Time "03:00";
Unattended-Upgrade::Mail "you@example.com";
Unattended-Upgrade::Remove-Unused-Dependencies "true";
sudo unattended-upgrades --dry-run --debug
|
Security patches only by default. It does not upgrade all packages, only those in the -security suite. Automatic-Reboot applies kernel patches without manual intervention; set a maintenance window time. --dry-run confirms what it would do before it runs live. needrestart detects services using outdated libraries after an update. |
|
| 10 | Remove unnecessary packages | updates |
sudo apt purge -y telnet rsh-client rsh-redone-client ftp
sudo apt purge -y xinetd nis yp-tools tftpd atftpd tftpd-hpa
dpkg --list | grep -E "^ii" | awk '{print $2}' | less
sudo systemctl list-units --type=service --state=running
# disable services you don't need:
sudo systemctl disable --now avahi-daemon cups bluetooth
|
Every running service is an attack surface. Review what's running and disable what you don't need. Cloud provider base images are usually lean but it's worth auditing. Legacy protocols like telnet and rsh send credentials in plaintext: remove them even if you're sure you won't use them. | |
| 11 | Install and configure fail2ban | brute-force |
sudo apt install -y fail2ban
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
# /etc/fail2ban/jail.local: key settings:
[DEFAULT]
bantime = 1h
findtime = 10m
maxretry = 5
banaction = ufw
[sshd]
enabled = true
port = ssh
logpath = %(sshd_log)s
sudo systemctl enable --now fail2ban
|
Always edit jail.local, never jail.conf: the latter gets overwritten on upgrades. banaction = ufw integrates with your firewall. Default bantime of 10 minutes is too short; 1 hour is a reasonable minimum. Set findtime shorter than bantime: 10m/1h means 5 failures in 10 minutes triggers a 1-hour ban. |
|
| 12 | Verify fail2ban operation | brute-force |
sudo fail2ban-client status
sudo fail2ban-client status sshd
sudo fail2ban-client get sshd bantime
sudo fail2ban-client set sshd banip <ip>
sudo fail2ban-client set sshd unbanip <ip>
sudo tail -f /var/log/fail2ban.log
|
Confirm the sshd jail is active and the ban count is incrementing. Manual banip/unbanip is the correct way to test the integration or unblock yourself after a lockout. Do not edit iptables/ufw directly while fail2ban is running. tail -f shows live banning activity. |
|
| 13 | Kernel sysctl hardening | hardening |
sudo nano /etc/sysctl.d/99-hardening.conf
# network hardening:
net.ipv4.tcp_syncookies = 1
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.all.accept_redirects = 0
net.ipv6.conf.all.accept_redirects = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.icmp_echo_ignore_broadcasts = 1
# kernel hardening:
kernel.dmesg_restrict = 1
kernel.kptr_restrict = 2
fs.protected_hardlinks = 1
fs.protected_symlinks = 1
sudo sysctl --system
|
SYN cookies protect against SYN flood attacks. Disabling ICMP redirects prevents route injection. kptr_restrict = 2 hides kernel pointers from /proc: limits information available to local exploit code. dmesg_restrict stops unprivileged users reading kernel ring buffer. These apply immediately and persist via /etc/sysctl.d/. |
|
| 14 | Secure shared memory | hardening |
sudo nano /etc/fstab
# add this line:
tmpfs /run/shm tmpfs defaults,noexec,nosuid,nodev 0 0
sudo mount -a
mount | grep shm
|
Shared memory mounted with noexec,nosuid prevents attackers from writing and executing shellcode through /dev/shm or /run/shm. A simple mitigation for a class of local privilege escalation techniques. Verify the mount flags appear in mount | grep shm output. |
|
| 15 | Lock down cron access | hardening |
sudo bash -c 'echo "root" > /etc/cron.allow'
sudo bash -c 'echo "deploy" >> /etc/cron.allow'
sudo rm -f /etc/cron.deny
sudo chmod 600 /etc/crontab
sudo chmod 700 /etc/cron.d /etc/cron.daily /etc/cron.hourly /etc/cron.weekly /etc/cron.monthly
|
If cron.allow exists, only users listed in it can use cron: all others are denied regardless of cron.deny. Restricting cron directory permissions prevents unprivileged users from inspecting scheduled tasks. List only the users that genuinely need scheduled jobs. |
|
| 16 | Disable IPv6 optional | hardening |
# /etc/sysctl.d/99-hardening.conf. Add if not using IPv6:
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1
net.ipv6.conf.lo.disable_ipv6 = 1
sudo sysctl --system
ip addr | grep inet6
# should return no output if disabled
|
Only disable IPv6 if you're not using it and your application doesn't need it. Reduces attack surface by eliminating an entire protocol stack from exposure, and simplifies firewall rules. Skip this if your provider assigns an IPv6 address you rely on or if you're running dual-stack applications. | |
| 17 | Install and baseline AIDE | detection |
sudo apt install -y aide
sudo aideinit
# takes a few minutes: building baseline hash database
sudo mv /var/lib/aide/aide.db.new /var/lib/aide/aide.db
# run a check against baseline:
sudo aide --check
# schedule daily checks via cron:
echo "0 3 * * * root /usr/bin/aide --check | mail -s 'AIDE report' you@example.com" | sudo tee /etc/cron.d/aide
|
AIDE (Advanced Intrusion Detection Environment) hashes every file in the filesystem and alerts on changes. Run aideinit immediately after hardening (before deploying any applications) so the baseline reflects a known-good state. Update the baseline after legitimate system changes with aide --update. |
|
| 18 | Install rkhunter | detection |
sudo apt install -y rkhunter
sudo rkhunter --update
sudo rkhunter --propupd
sudo rkhunter --check --sk
# --sk: skip key press prompts
# review /var/log/rkhunter.log for warnings
echo "0 4 * * * root rkhunter --check --sk --report-warnings-only | mail -s 'rkhunter' you@example.com" | sudo tee /etc/cron.d/rkhunter
|
rkhunter checks for known rootkits, suspicious files, hidden processes, and common backdoor signatures. Run --propupd immediately after install to baseline your binary properties: before it finds false positives on your own legit binaries. Expect some false positives; review warnings rather than treating all output as findings. |
|
| 19 | Configure auditd basics | detection |
sudo apt install -y auditd audispd-plugins
sudo systemctl enable --now auditd
# watch sensitive files:
sudo auditctl -w /etc/passwd -p wa -k passwd_changes
sudo auditctl -w /etc/sudoers -p wa -k sudoers_changes
sudo auditctl -w /etc/ssh/sshd_config -p wa -k sshd_config
sudo auditctl -w /var/log/auth.log -p wa -k auth_log
# query audit log:
sudo ausearch -k passwd_changes
sudo aureport --summary
|
auditd gives a kernel-level audit trail of who changed what and when. Watching /etc/passwd, /etc/sudoers, and sshd_config catches the most dangerous configuration changes. Rules added with auditctl are ephemeral: persist them in /etc/audit/rules.d/hardening.rules. |
|
| 20 | Set up log monitoring | detection |
sudo apt install -y logwatch
# /etc/logwatch/conf/logwatch.conf:
MailTo = you@example.com
Detail = Med
Range = yesterday
sudo logwatch --output stdout --range today --detail med
# key logs to check manually:
sudo tail -f /var/log/auth.log
sudo grep "Failed password\|Accepted publickey\|Invalid user" /var/log/auth.log | tail -20
|
logwatch sends a daily summary of auth events, failed logins, and service anomalies. The grep pattern on auth.log is the fastest manual triage: Invalid user entries show which usernames bots are trying, Failed password shows successful connection attempts that failed auth, Accepted publickey confirms legitimate logins. |
|
| 21 | Run lynis security audit | verify |
sudo apt install -y lynis
sudo lynis audit system
sudo lynis audit system --quick 2>/dev/null | grep -E "Hardening index|Warning|Suggestion" | head -30
# full report in /var/log/lynis.log
# target hardening index > 70 for a basic server
sudo lynis show details <TEST-ID>
|
lynis runs 200+ checks and produces a scored hardening index: the authoritative "how did we do" answer. Work through Warnings before Suggestions. A score above 70 is reasonable for a general-purpose server; above 80 requires more invasive measures. show details explains the remediation for any specific test ID. |
|
| 22 | Full port scan from outside | verify |
# run from a DIFFERENT machine, not the VPS itself:
nmap -Pn -p- --min-rate=2000 -sV <vps-ip>
nmap -Pn -sU --top-ports 100 <vps-ip>
# expected: only 22 (or custom SSH port), 80, 443 open
# UDP scan for common exposed services: DNS (53), NTP (123)
sudo nmap -Pn -sV --script=banner <vps-ip>
|
The definitive check: what does the internet actually see? Run from outside the VPS; local ss or netstat does not account for firewall rules. The banner script reveals software versions exposed to the world: anything unexpected is a finding. UDP scan catches services that TCP scans miss. |
|
| 23 | Final checklist closure | verify |
sudo ufw status verbose
sudo fail2ban-client status sshd
sudo systemctl is-active unattended-upgrades fail2ban auditd aide
sudo last -10
sudo lastb -10
sudo aide --check 2>&1 | tail -5
sudo lynis audit system --quick 2>/dev/null | grep "Hardening index"
|
last shows recent successful logins; lastb shows failed attempts: compare the two. All four services should report active. AIDE check on a fresh system should report no changes. Keep this block in a runbook. Run it after any system change to confirm nothing was inadvertently broken. |
No steps match this filter.