As soon as our fresh VPS goes live, evil bots scanning the internet 24/7, will start pounding its public IP with guessed passwords. So don’t be surprised to see failed login attempts in your logs within minutes of the first boot.
Before the paranoia kicks in: it’s not personal. Nobody is targeting you or your server; you’re just one more address on the list. And the bots that do get in rarely want your data. They want your CPU/GPU, to mine crypto on your bill, or make it join a botnet to launch DDOS attacks.
This post is the checklist I go through before putting anything real on a server.
In this post we will cover some basic steps to harden a server against automated attacks. This is not a complete guide, and it is not a replacement for professional security advice. If you are running a production server, please consult with a security expert.
Checking the SSH Logs
The SSH logs are worth keeping an eye on, starting from day one:
sudo journalctl -u sshDon’t be surprised to see failed login attempts in your logs within minutes of the first boot.
If you don’t see any logs, even though you are logged in via SSH, it may be that your VPS distro doesn’t call the unit ssh. To find out what unit is used for SSH, you can run:
sudo systemctl list-units | grep sshIn Debian and Ubuntu the service running SSH it’s named ssh, whereas in CentOS it’s called sshd.
All that journalctl does is to read the systemd journal, the binary files under /var/log/journal/ where systemd collects the logs of every service (included the service running SSH on our Distro).
Some distros also keep a plain-text copy of the SSH logs:
| Distro | File |
|---|---|
| Ubuntu, Debian 11 and older | /var/log/auth.log |
| CentOS, RHEL, Rocky, Alma | /var/log/secure |
| Debian 12 and newer, Arch | none, journal only |
Debian doesn’t include a copy of rsyslog, the program that saves the journal entries as plain text. Debian stopped installing it by default in version 12, and Arch doesn’t either, so on those the journal is the only place to look.
To check for login attempts we can use:
sudo journalctl -u ssh | grep -c 'Failed password'The command above prints the number of failed password attempts. Drop the -c to see the usernames and IPs of the attackers. There are three types of output:
- Wrong passwords show up as:
Failed password from root from 123.69.69.69 - Invalid users show up as:
Invalid users bob from 123.69.69.69 - Accepted logins show up as:
Accepted public key for frankie from 123.69.69.69
The first two are useful because we can tell if someone has been trying to login unsuccessfully. The last one particularly requires attention, because it means that someone gained access to our box! For that reason, we may want to check for these events:
sudo journalctl -u ssh --since "24 hours ago" | grep 'Accepted'To follow login activity in real time:
sudo journalctl -u ssh -fThe logs show who tried to get in. To see who is logged in right now, and from where, run w:
wYou should see at least one line: yourself. Any session you don’t recognise means the server is already compromised.
Setting the right Timezone
In order to properly read the logs, we need to set the correct timezone in our server. Otherwise how can we understand when an attacker has logged in? To see the current timezone:
timedatectlIf for whatever reason the date and time don’t match ours, we can set them properly with:
sudo timedatectl set-timezone Europe/HelsinkiTo see the list of available timezones, run:
timedatectl list-timezones | grep -i helsinkiThe timezone only changes how the time is displayed. Whether the clock itself is right depends on the line System clock synchronized: yes in the output of timedatectl. If it says no, turn syncing on:
sudo timedatectl set-ntp trueChecking for Unexpected Reboots
Now that the clock is right, there’s one more thing the journal can tell us: every time our box has been started. To list the boots:
journalctl --list-bootsEach line is one boot, with the time of its first and last log entry; in other words, when the server went up and when it went down:
IDX BOOT ID FIRST ENTRY LAST ENTRY -1 a97e… Wed 2026-11-25 18:40:52 EET Sun 2026-11-29 02:03:30 EET 0 c40b… Sun 2026-11-29 02:04:01 EET Mon 2026-11-30 17:20:45 EETThe boot with index 0 is the current one, -1 the one before it, and so on. If we see a reboot we don’t remember doing, say at 2 a.m. on a Sunday, it’s worth finding out why. Most of the time it’s our provider doing maintenance, or a crash, but it could also be someone who isn’t us.
To see what was going on with SSH right before that reboot, we can pass the index to -b:
sudo journalctl -u ssh -b -1If the only entry we see is the current boot (index 0), don’t panic yet. There are four possible explanations, and three of them are boring:
-
Our server has never been rebooted. This is the most likely one, especially on a fresh VPS.
-
The journal isn’t being saved to disk. If the folder
/var/log/journal/doesn’t exist, the journal lives in memory and is lost on every reboot. To check:
ls /var/log/journal/If the folder is missing, we can tell systemd to keep the journal on disk by setting Storage=persistent in /etc/systemd/journald.conf, and then restarting the service:
sudo systemctl restart systemd-journald- The older entries were deleted to make room. The journal has a size limit, and when it’s reached, the oldest boots go first. To see how much space it’s using:
journalctl --disk-usage- Someone cleared the journal. Only when none of the above apply should we start worrying, because an attacker may have deleted the logs to hide their tracks.
Updating the System
Most compromised servers don’t fall to zero-day exploits, but to well-known vulnerabilities. Distro maintainers often patch these within days, but a patch does nothing until we install it. Meanwhile the hole is public, and so are the tools to exploit it, which is exactly what the bots are counting on.
A good example is regreSSHion, a bug in OpenSSH disclosed in July 2024 that could let an attacker run code as root without even logging in. Distros shipped the fix the same day, but it only protected the servers that installed it.
The image our provider used to create the VPS may be months old, which means our box was born with security holes that have been public for a while. Before doing anything else, let’s patch them:
sudo apt update && sudo apt upgradeThe first command refreshes the list of available packages, and the second one installs the new versions.
sudo dnf upgradeA single command does both jobs: it refreshes the list of packages and installs the new versions. The same goes for Fedora, Rocky and Alma.
sudo pacman -SyuThe flags stand for sync (S), refresh the package list (y) and upgrade (u).
Automatic Updates
Updating once is not enough, though; new holes are found every week. Since nobody remembers to log in and update, we can let the server install the patches by itself:
sudo apt install unattended-upgradessudo dpkg-reconfigure -plow unattended-upgradesThe second command asks if we want to download and install updates automatically. Say yes.
sudo dnf install dnf-automaticsudo systemctl enable --now dnf-automatic-install.timerThe timer downloads and installs updates once a day. By default it takes all of them; to stick to security patches, set upgrade_type = security in /etc/dnf/automatic.conf.
Arch doesn’t ship a tool for this, and for a reason: it’s a rolling release, and now and then an update needs a manual step. Automating it is a good way to wake up to a broken server, so here we update by hand, and often:
sudo pacman -SyuA day or two later, it’s worth checking that the automatic updates are really happening:
sudo tail /var/log/unattended-upgrades/unattended-upgrades.logEach run leaves a few lines here, saying which packages it found and which ones it upgraded. The file may be missing until the first run has happened.
sudo journalctl -u dnf-automatic-installThe timer runs a service with the same name, so its output lands in the journal. For a summary of what got installed, and when, there’s also sudo dnf history.
grep -i upgraded /var/log/pacman.log | tailNothing is automatic here, but pacman keeps a log of every package it has touched, so we can see when we last updated.
Reboot Required
Some updates, like a new kernel, only kick in after a reboot. To find out if it’s time to restart:
ls /var/run/reboot-requiredIf the file exists, a reboot is pending.
sudo dnf needs-restarting -rIt answers in plain words whether a reboot is required. If the command is missing, install it with sudo dnf install dnf-utils.
uname -r && pacman -Q linuxThere’s no flag file here, so we compare the kernel that is running with the one that is installed. If the versions differ, it’s time to reboot.
If a reboot is pending, let’s restart the server so the new kernel takes over:
sudo rebootThe SSH session will drop; give it a minute and log back in. And this time, when a new entry shows up in journalctl --list-boots, we’ll know who did it.
If you want to reboot at a specific time, use shutdown instead of reboot:
sudo shutdown -r 23:00It’s also possible to enable automatic reboots after kernel updates, but I don’t recommend it. If the server is unreachable after a reboot, we may not be able to log in and fix it. Better to reboot manually, when we can check that everything is working.
Create a Non-Root User
So far we’ve been logged in as root, the one user that can do anything, including wiping the whole server with a typo. It’s also the first name every bot tries; we saw it in the logs. The fix is to work as a regular user, and borrow root’s powers only when we need them, one command at a time, with sudo.
Installing Sudo
First, let’s make sure sudo is there at all:
sudo --versionIf the answer is command not found, we install it. As root:
apt install sudoUbuntu ships it out of the box. A minimal Debian image may not.
dnf install sudoIt’s almost always there already, but some minimal images leave it out.
pacman -S sudoArch never installs it by default.
Creating a User
Let’s create that user and allow it to use sudo. We run these as root:
adduser frankieusermod -aG sudo frankieThe first command asks for a password and a few optional details. The second one adds our user to the sudo group.
useradd -m frankiepasswd frankieusermod -aG wheel frankieHere the group that is allowed to use sudo is called wheel.
pacman -S sudouseradd -m -G wheel frankiepasswd frankieArch doesn’t even install sudo by default. After that, we run EDITOR=nano visudo and uncomment the line that starts with %wheel.
Before going any further, let’s check that it works. We switch to the new user and ask who we are when using sudo:
su - frankiesudo whoamiIf the answer is root, we’re good.
Don’t close the root session yet. Open a second terminal and make sure the new user can log in over SSH. If something is wrong, the first session is our only way back in.
You may be wondering: what’s the point of creating a new user if we can just use sudo? The answer is doublefold:
- They need to guess the username, not just the password (security by obscurity).
- Every time we use
sudo, the command is logged in/var/log/auth.log(or/var/log/secure), so we can see what the user did. If we were usingroot, there would be no record of it.
Limiting What a User Can Do
Being in the sudo group (or wheel) is all or nothing: our user can run any command as root. That’s fine for us, but sooner or later we’ll need a second user, say a colleague or a deploy script, that should only be able to do one or two things.
For that we write a rule in a file of its own under /etc/sudoers.d/. We never edit these files directly; we use visudo, which checks the syntax before saving, because a broken rule can lock everybody out of sudo:
sudo visudo -f /etc/sudoers.d/bobIn this example, bob is only allowed to restart and reload nginx:
bob ALL=(root) /usr/bin/systemctl restart nginx, /usr/bin/systemctl reload nginxReading the rule from left to right: who it applies to (bob), on which machines (ALL, which matters only if we share the file between servers), as which user the commands run (root), and the commands themselves, always with their full path.
For this to work, bob must not be in the sudo or wheel group, or the group’s rule wins and he can do everything. Also, be picky about the commands: anything that opens an editor or pages its output (vim, less, even systemctl status) can be turned into a root shell.
To check what a user is allowed to do, we can ask sudo itself:
sudo -l -U frankieThe -l flag stands for list, and -U for the user we’re asking about. For our admin user, the last lines of the answer look like this:
User frankie may run the following commands on our-server: (ALL : ALL) ALLWhich reads as: running as any user and any group, any command. For bob, we would see only his two commands instead:
User bob may run the following commands on our-server: (root) /usr/bin/systemctl restart nginx, /usr/bin/systemctl reload nginxWithout -U, a plain sudo -l lists the permissions of whoever is typing. Asking about somebody else only works if we are root or have sudo rights ourselves.
Removing Default Users
Many providers build their images with a default user already inside: ubuntu, debian, centos, ec2-user, admin… These names are no secret, so they’re high on every bot’s list, and to make things worse, they usually come with full sudo rights. Once our own user works, they’re just one more door to watch.
Let’s see which users on the server are meant for people. Regular users get an ID of 1000 or higher, so we can filter the list by that:
awk -F: '$3 >= 1000 && $3 < 65534 {print $1}' /etc/passwdIdeally the answer is one line: our own user. For any other name, we can ask what it’s allowed to do with the command from the previous section:
sudo -l -U ubuntuBefore deleting anything, make sure we’re not logged in as that user, and that our own user can log in over SSH and use sudo. Otherwise we’re sawing off the branch we’re sitting on.
If nothing depends on the leftover user, we remove it, home folder included:
sudo userdel -r ubuntuThe user is gone, but its sudo rule may still be lying around. A quick search tells us:
sudo grep -r ubuntu /etc/sudoers.d/If a file shows up, and it only talks about the user we just removed, it can go too.
The file /etc/passwd is full of other users with an ID below 1000: www-data, sshd, systemd-network and friends. Those are system users. Services run under them, nobody can log in with them, and they should be left alone.
Removing Unused Users
Default users are not the only ones that pile up. Over time a server collects accounts that nobody uses any more: a colleague who left, a deploy user from an old project, that test account we swore we’d delete. Each of them is a password or a key that could still open the door.
To find them, we can ask when each user logged in for the last time:
lastlogThe ones to look at are the regular users that say **Never logged in**, or show a date from long ago. To see only those who haven’t logged in during the last 90 days:
lastlog -b 90Say we found bob, and nobody remembers what he was for. Deleting him straight away is risky, since some forgotten script may still depend on him, so first we disable the account and wait a couple of weeks to see if anything breaks:
sudo usermod --lock --expiredate 1 bobThe --lock flag disables his password, but that alone wouldn’t stop him from logging in with an SSH key. That’s what --expiredate 1 is for: it marks the whole account as expired, and an expired account can’t log in by any means.
Meanwhile, it’s worth checking if bob left something running, or scheduled:
pgrep -u bob -lsudo crontab -u bob -lIf nobody complained, and nothing broke, we can say goodbye. The -r flag takes his home folder with him:
sudo userdel -r bobIf we changed our mind while the account was disabled, bringing bob back is one command: sudo usermod --unlock --expiredate '' bob.
Logging In with SSH Keys
A password, no matter how long, is something that can be guessed, and guessing is all the bots do, day and night. An SSH key takes that game away from them. It comes as a pair:
- A private key that never leaves our computer.
- And a public key that we hand to the server.
The server only lets in whoever can prove they hold the private half, and there’s nothing to guess.
Generating a Key Pair
This part happens on our own computer, not on the server:
ssh-keygen -t ed25519 -C "frankie@laptop"The -t flag picks the type of key (ed25519 is the modern choice), and -C adds a comment, so that later we can tell which key belongs to which machine. The command asks two things:
- Where to save the key. The default,
~/.ssh/id_ed25519, is fine. - A passphrase. It’s tempting to leave it empty, but it’s what protects the key if our laptop gets lost or stolen.
We end up with two files: id_ed25519, the private key, which we never share with anybody, and id_ed25519.pub, the public one, which can go anywhere.
Copying the Public Key to the Server
The server keeps the public keys it trusts in a file inside each user’s home: ~/.ssh/authorized_keys. There’s a command that puts ours in there:
ssh-copy-id frankie@203.0.113.10It asks for the user’s password, for what will hopefully be the last time.
If our computer doesn’t have ssh-copy-id (looking at you, Windows), this does the same job by hand:
cat ~/.ssh/id_ed25519.pub | ssh frankie@203.0.113.10 "mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"Testing the Key
Now we log in again:
ssh frankie@203.0.113.10This time the server shouldn’t ask for the user’s password. If we get a prompt at all, it’s for the passphrase of our key, and that one is checked on our computer, never sent anywhere.
To be sure, we can go back to our old friend, the logs:
sudo journalctl -u ssh | grep AcceptedThe last line should say Accepted publickey for frankie, where before it said Accepted password.
If the server keeps asking for the password, the usual suspect is permissions. The folder ~/.ssh must be readable only by its owner (chmod 700), and the file authorized_keys too (chmod 600). If they’re more open than that, SSH ignores the key without saying a word.
Our key works, but the server still accepts passwords from anybody who wants to try. Closing that door is the next step.
Disabling Password Logins
Our key gets us in, so passwords have no job left. Time to tell the SSH server to stop accepting them.
Make sure we can log in with our key before disabling passwords. If we lock ourselves out, the only way back is the web console of our VPS provider.
The settings of the SSH server live in /etc/ssh/sshd_config, but we won’t touch that file. Instead, we use the folder next to it: sshd_config. The server loads every .conf file inside /etc/ssh/sshd_config.d/, so we add one of our own:
sudo nano /etc/ssh/sshd_config.d/00-hardening.confWith two lines in it:
PasswordAuthentication noKbdInteractiveAuthentication noThe first one is the obvious one. The second closes a side door: a different way of logging in that, on most servers, ends up asking for the very same password.
The 00- in the name isn’t decoration. When a setting appears more than once, SSH keeps the first one it reads, and the files are read in alphabetical order. Some cloud images ship a 50-cloud-init.conf with PasswordAuthentication yes in it, and if our file came after, it would be ignored without a single complaint.
Before restarting anything, we ask SSH to check our work:
sudo sshd -tNo output means no typos, but we can check the exit code using echo $?. A 0 means everything is fine, a 1 means there’s a syntax error somewhere.
And to see what SSH actually ended up with, after reading all the files:
sudo sshd -T | grep -i passwordauthenticationIt should answer passwordauthentication no. If it says yes, some other file is winning.
Now we restart the service:
sh sudo systemctl restart ssh
sh sudo systemctl restart sshd sh sudo systemctl restart sshd Same rule as before: don’t close this session. Restarting SSH doesn’t kick us out, so we keep it open and test from a second terminal.
From that second terminal, we try to get in with a password on purpose:
ssh -o PubkeyAuthentication=no frankie@203.0.113.10The server shouldn’t even ask for one:
frankie@203.0.113.10: Permission denied (publickey).A normal ssh frankie@203.0.113.10 should still work as before. If both things are true, we’re done, and the bots can keep guessing passwords that nobody is listening to.
From now on, our key is the only way in. If we lose it, the way back is the web console of our VPS provider, so it’s worth checking that we know where that is before we need it.
Disabling Root Logins
There’s one username every bot already knows, because it exists on every Linux box: root. That’s half of the login given away for free, and the other half opens every door in the house. We have frankie and sudo now, so root has no reason to come in through SSH anymore.
Before closing this door, let’s make sure frankie can really become root:
sudo whoamiIf the answer isn’t root, stop here and fix that first.
We open the same file as before:
sudo nano /etc/ssh/sshd_config.d/00-hardening.confAnd add one more line:
PermitRootLogin noThe default on most distros is prohibit-password, which sounds safe enough: root can’t use a password, but can still get in with a key. And many VPS providers drop our key into root’s account when they create the server. With no, there’s nothing left to try.
Same routine as before. We check for typos, and then for what SSH ended up with:
sudo sshd -tsudo sshd -T | grep -i permitrootloginIt should answer permitrootlogin no. Then we restart the service:
sh sudo systemctl restart ssh
sh sudo systemctl restart sshd sh sudo systemctl restart sshd And from a second terminal, we knock on the door we just closed:
ssh root@203.0.113.10root@203.0.113.10: Permission denied (publickey).From now on, we log in as frankie, and when a job really needs root, we ask for it:
sudo -iroot hasn’t gone anywhere, it just can’t use SSH. It can still log in through the web console of our VPS provider, which is exactly the way back we’d need if we ever locked ourselves out.
Changing the SSH Port
Let’s be honest about this one: moving SSH to another port doesn’t make our box any safer. With passwords and root out of the game, the bots weren’t getting in anyway. What it does is make them shut up. Almost all of them knock on port 22 and nowhere else, so on a different port, our logs go from thousands of failed attempts a day to a handful, and whatever is left is worth reading.
First we pick a port. Anything between 1024 and 65535 that nobody else is using will do. We’ll go with 5522, after checking that it’s free:
sudo ss -tlnp | grep 5522No output means nobody is listening there.
If there’s a firewall in front of our box, in the panel of our VPS provider or on the box itself, the new port has to be open there before we move SSH to it. Otherwise we’re changing the lock and leaving the key inside.
Back to our file:
sudo nano /etc/ssh/sshd_config.d/00-hardening.confOne more line:
Port 5522Then the usual routine:
sudo sshd -tsudo sshd -T | grep -i '^port'It should answer port 5522, and nothing else. If there’s a port 22 in there too, some other file is setting it, and SSH would listen on both.
Now we restart the service, and this is where the distros go their own ways:
sudo systemctl restart sshUbuntu 24.04 and later is the exception. There, it’s systemd that holds the port and wakes SSH up when somebody connects, so that’s who we have to tell:
sudo systemctl daemon-reloadsudo systemctl restart ssh.socketHere, SELinux only lets SSH use port 22, and firewalld only lets port 22 in. We tell both about the new one, and then restart:
sudo semanage port -a -t ssh_port_t -p tcp 5522sudo firewall-cmd --permanent --add-port=5522/tcpsudo firewall-cmd --reloadsudo systemctl restart sshdIf semanage is missing, it comes with dnf install policycoreutils-python-utils.
sudo systemctl restart sshdYou know the rule by now: don’t close this session, and test from a second terminal.
From that second terminal, we tell ssh which port to use with the -p flag:
ssh -p 5522 frankie@203.0.113.10And the old port should be dead:
ssh frankie@203.0.113.10ssh: connect to host 203.0.113.10 port 22: Connection refusedSaving the Port in Our SSH Config
Typing -p 5522 every time gets old fast. On our own computer, we can save the details of the server in ~/.ssh/config:
Host box HostName 203.0.113.10 User frankie Port 5522And from now on, this is enough:
ssh boxSetting Up a Firewall
SSH is the door we’ve been locking so far, but it’s not the only one. Every program that listens on a port is a door: a database, a dev server we forgot about, something that came with the image. A firewall turns that around. Everything is closed unless we say otherwise, so a program can listen all it wants, and nobody outside will ever reach it.
The name of the game is very simple:
- Deny access to incoming traffic for all ports.
- Allow all outgoing traffic, so our box can still reach the internet.
- Allow incoming traffic only for the ports our apps need, starting with SSH.
- Enable the firewall, and check that we can still get in.
Before closing anything, let’s see what’s open right now:
sudo ss -tlnpThe column to look at is Local Address:Port. An address like 0.0.0.0:5522 or [::]:5522 means the whole internet can knock there. One that starts with 127.0.0.1 only answers to the box itself, and that’s fine.
Closing Everything but SSH
The plan is the same on every distro: deny whatever comes in, allow whatever goes out, and open one hole for our SSH port.
⚠️ The order matters: The SSH port gets opened before the firewall is turned on, or we can lock ourselves out by cutting the connection we’re sitting on.
Here we use ufw, which stands for uncomplicated firewall, and delivers:
sudo apt install ufwsudo ufw default deny incomingsudo ufw default allow outgoingsudo ufw allow 5522/tcpsudo ufw enableThen we ask how things are:
sudo ufw status verboseStatus: activeDefault: deny (incoming), allow (outgoing), disabled (routed)
To Action From-- ------ ----5522/tcp ALLOW IN Anywhere5522/tcp (v6) ALLOW IN Anywhere (v6)Here the firewall is firewalld, and it’s usually running already, with everything closed except a few services. We make sure of that:
sudo systemctl enable --now firewalldWe opened port 5522 in the previous section, so what’s left is closing the old one, which is still allowed under the name ssh:
sudo firewall-cmd --permanent --remove-service=sshsudo firewall-cmd --reloadThen we ask how things are:
sudo firewall-cmd --list-allThe line ports: should show 5522/tcp, and services: whatever else is allowed in. If there’s something in there we don’t use (cockpit is a common one), it goes out the same way ssh did.
Arch comes with no firewall at all. We install ufw:
sudo pacman -S ufwsudo ufw default deny incomingsudo ufw default allow outgoingsudo ufw allow 5522/tcpsudo ufw enableAnd tell systemd to bring it back after a reboot:
sudo systemctl enable --now ufwThen we ask how things are:
sudo ufw status verbose✅ And, as always, we open a second terminal and check that we can still get in:
ssh boxOpening More Ports
The day our box starts serving something, a website for example, we open the ports it needs, and only those:
sudo ufw allow 80/tcpsudo ufw allow 443/tcpAnd to close one again:
sudo ufw delete allow 80/tcpsudo firewall-cmd --permanent --add-service=httpsudo firewall-cmd --permanent --add-service=httpssudo firewall-cmd --reloadAnd to close one again:
sudo firewall-cmd --permanent --remove-service=httpsudo firewall-cmd --reloadsudo ufw allow 80/tcpsudo ufw allow 443/tcpAnd to close one again:
sudo ufw delete allow 80/tcpMost VPS providers offer a firewall of their own in their panel. That one filters the traffic before it even reaches our box, and there’s nothing wrong with using both. Just remember that a port has to be open in both places to work.
Docker and the Firewall
If we run Docker on this box, there’s a surprise waiting: Docker doesn’t ask the firewall for permission. When a container publishes a port, Docker writes its own rules, and they’re checked before ours. So this container is open to the whole internet, no matter what ufw says:
docker run -d -p 8080:80 nginxufw status won’t even show it. To see what our containers are really publishing, we ask Docker:
docker ps --format '{{.Names}}\t{{.Ports}}'web 0.0.0.0:8080->80/tcpThat 0.0.0.0 is the bad news: everybody can knock. The fix, most of the time, is one more piece in the -p flag, telling Docker to publish the port only on the box itself:
docker run -d -p 127.0.0.1:8080:80 nginxweb 127.0.0.1:8080->80/tcpNow the container can only be reached from inside the box, which is all a reverse proxy needs. The proxy is the one facing the internet, on ports 80 and 443, and those go through our firewall like everything else.
In a compose.yaml, it’s the same idea:
ports: - "127.0.0.1:8080:80"And a container that only talks to other containers (a database, for example) doesn’t need a ports section at all.
Sometimes a container does need to be reachable from outside, but not by everybody. For that, we have to know how Docker gets around ufw in the first place. Firewall rules are kept in lists, called chains, and Docker has its own chains, which are read before the ones ufw writes. Among them, Docker leaves one empty for us, DOCKER-USER, and whatever we put there is read first of all.
This rule, for example, drops any traffic headed for our containers, unless it comes from the one IP we trust:
sudo iptables -I DOCKER-USER -i eth0 ! -s 198.51.100.7 -j DROPPiece by piece:
-I DOCKER-USERinserts the rule at the top of that chain.-i eth0matches the traffic coming in througheth0, the network card that faces the internet.! -s 198.51.100.7matches every source that is not that IP.-j DROPis what happens to whatever matched: it gets dropped.
The network card isn’t called eth0 on every box (ip route show default tells us the name on ours), and a rule added like this is gone after a reboot. The Docker docs explain how to make it stick.
The Docker Group
Almost every Docker tutorial has this line somewhere, so that we don’t have to type sudo before each docker command:
sudo usermod -aG docker frankieIt’s convenient, and it’s also a second sudo with no password. Anybody in the docker group can start a container with the whole disk of our box mounted inside, and be root in there:
docker run --rm -it -v /:/host alpine chroot /hostSo the rule is simple: the docker group is only for users we’d trust with full sudo anyway. All the care we took limiting what bob can do would be gone the moment he joins it.
To see who’s in:
getent group dockerAnd to take somebody out:
sudo gpasswd -d bob dockerInstalling Fail2ban
Remember the first thing we did on this box? Reading the SSH logs, looking for failed logins. Fail2ban does exactly that, all day long, and it acts on what it reads: when the same IP fails too many times, it gets banned at the firewall for a while.
With keys only and SSH on another port, there isn’t much left for it to catch. But it costs almost nothing, it takes care of the stubborn bots, make our logs less noisy and the day we run something else on this box (a web server, for example), it can watch that too.
sudo apt install fail2ban python3-systemdThe second package is what lets it read the journal. It usually comes along by itself, but asking for it doesn’t hurt.
It’s not in the default repos, so we add EPEL first:
sudo dnf install epel-releasesudo dnf install fail2bansudo pacman -S fail2banSetting Up the SSH Jail
Fail2ban calls each thing it watches a jail. Its defaults live in /etc/fail2ban/jail.conf, and just like with SSH, we leave that file alone, because the next update would overwrite it. Our settings go in a file next to it:
sudo nano /etc/fail2ban/jail.local[DEFAULT]bantime = 1hfindtime = 10mmaxretry = 5backend = systemd
[sshd]enabled = trueport = 5522In plain words: 5 failures within 10 minutes get an IP banned for 1 hour. The backend line tells it to read the journal, the same place journalctl reads from.
Don’t skip the port line. A ban only blocks the ports the jail knows about, and by default that’s 22. Without it, Fail2ban would proudly ban every bot from a port we no longer use.
Then we turn it on, now and after every reboot:
sudo systemctl enable fail2bansudo systemctl restart fail2banChecking on the Jail
sudo fail2ban-client status sshdStatus for the jail: sshd|- Filter| |- Currently failed: 0| `- Total failed: 0`- Actions |- Currently banned: 0 |- Total banned: 0 `- Banned IP list:On a public box, it won’t take long for those zeros to move.
And if one day the banned one is us, or a friend, we get into the box some other way (the web console of our provider, once more) and lift the ban by hand:
sudo fail2ban-client set sshd unbanip 198.51.100.7If we always connect from the same IP, we can tell Fail2ban to never ban it, with one more line under [DEFAULT]:
ignoreip = 127.0.0.1/8 ::1 198.51.100.7Most home connections change their IP every now and then, so this is mostly useful with a VPN or an office line.
Secrets and Keys
So far we’ve been locking the box. But sooner or later, we put things on it that are worth more than the box itself: the password of a database, the token of a payment API, the keys to our cloud storage. Those are our secrets, and they’re the first thing anybody looks for, whether they got in through a hole in our app or found our repo on GitHub.
Keeping Secrets Out of Git
The usual home for secrets is a .env file next to our app, and the usual accident is committing it. So before anything else, the file goes in .gitignore:
.env.env.*To find out if it ever slipped into the history of a repo:
git log --all --oneline -- .envNo output means it never did.
If a secret was pushed, even for a minute, deleting the file or rewriting the history doesn’t fix it. There are bots watching public repos for exactly this, and they’re faster than us. The only fix is to rotate it: make a new one, and kill the old one.
Locking the Files
On the box, a secret should be readable by the user that runs the app, and by nobody else:
chmod 600 .envls -l .envThose three digits are three audiences: the owner of the file, its group, and everybody else. Each digit is a sum: 4 to read, 2 to write, 1 to execute. So 600 reads like this:
- rw- --- ---│ │ │ └── others: nothing = 0│ │ └─────── group: nothing = 0│ └──────────── owner: read + write = 4 + 2 = 6└──────────────── type: - for a file, d for a folderThe 700 we used for the ~/.ssh folder adds the 1 for the owner. On a folder, “execute” means being allowed to go inside.
-rw------- 1 frankie frankie 214 Dec 1 10:12 .envThat’s the same permission SSH demanded for our keys, and for the same reason. To hunt for .env files that anybody on the box can read:
sudo find / -xdev -type f -name '.env*' -perm -o=r 2>/dev/nullWhatever shows up gets the chmod 600 treatment.
Minding the Shell History
Every command we type is saved in ~/.bash_history, secrets included. Something like this stays there in plain text, for whoever reads the file next:
export STRIPE_KEY=sk_live_abc123✅ The trick is a space before the command. On most distros, a line that starts with a space is not saved:
export STRIPE_KEY=sk_live_abc123It only works if this answers ignorespace or ignoreboth:
echo $HISTCONTROLIf it doesn’t, we add HISTCONTROL=ignoreboth to our ~/.bashrc. And to check what we’ve already left behind:
grep -i -E 'pass|token|secret|key' ~/.bash_historyThe same goes for secrets passed as flags, like mysql -pMyPassword. Besides ending up in the history, they show up in ps aux for every user on the box while the command runs.
Reading Secrets from Files
The space trick works, but it depends on us remembering it every single time. The better habit is not typing secrets into the shell at all. They go in a file with the right permissions, and our commands read them from there.
Vim users, one warning: Vim has a memory of its own. Whatever we yank, delete or search for can end up in ~/.viminfo, and a session that dies leaves a .env.swp behind. For files like this one, we can ask it to keep nothing:
vim -i NONE -n .envWe make the file first, lock it, and only then put something in it:
touch .envchmod 600 .envnano .envWhat we type inside an editor never reaches the history. And when we need those variables in our shell, we load the whole file instead of exporting them one by one:
set -a; source .env; set +aThe history gets that line, and nothing else. The set -a part tells the shell to export every variable it’s about to read, and set +a turns that off again.
Many tools have a file like this of their own. The mysql client, for example, reads ~/.my.cnf:
[client]user = frankiepassword = MyPasswordWith that in place (and its chmod 600), a plain mysql gets us in, and there’s no password in the history or in ps aux. PostgreSQL does the same with ~/.pgpass, and just like SSH, it refuses to use the file if anybody else can read it.
One Key for Each Job
When our box needs to pull code from a private repo, the lazy move is copying our own private key onto it. Let’s not. That key opens every repo and every server we have, and if the box falls, it all falls with it.
What we want is a key that lives on the box and does one job only, a deploy key. We create it on the server:
ssh-keygen -t ed25519 -f ~/.ssh/deploy_myapp -C "deploy@box"This one gets no passphrase, since nobody will be around to type it. That’s why we keep it on a short leash: the public half, ~/.ssh/deploy_myapp.pub, goes into the settings of that one repo (on GitHub, under Deploy keys), with read-only access.
Then we tell SSH when to use it, in ~/.ssh/config on the box:
Host github-myapp HostName github.com User git IdentityFile ~/.ssh/deploy_myapp IdentitiesOnly yesAnd we clone using that name:
git clone github-myapp:frankie/myapp.gitIf the box gets compromised, the damage is one repo that can be read. We delete the deploy key from GitHub, and that’s the end of it.
With Docker, secrets stay out of the image: no COPY .env and no ENV API_KEY=... in the Dockerfile, because anybody who gets the image gets them too. They’re handed to the container when it starts, with --env-file .env.
When in Doubt, Rotate
A secret that might have leaked has leaked. If it was in a commit, in a screenshot, in a chat, or on a box that behaved strangely, we don’t investigate first: we make a new one, replace it everywhere, and revoke the old one. Investigating can wait, the bots won’t.
The Missing Piece: Storing the Logs
Everything in this post is about keeping them out. What it doesn’t cover is finding out when somebody gets in anyway, and for that, the logs are the only witness we have.
The bad news is that attackers know it. In MITRE ATT&CK, the public catalogue of everything intruders do once they’re inside, wiping the logs has an entry of its own (T1070.002), and so does clearing the shell history (T1070.003). It’s not something they get to eventually: the scripts that drop a crypto miner on a box usually clean up after themselves in the same breath. That’s why, back at the beginning, a journal that starts later than our box was a reason to worry.
So reading the logs on the box only works for as long as nobody else has touched them. The fix is getting them out of the box the moment they’re written, and that’s the job of tools like these:
- Loki stores the logs, on a different machine. A small agent on our box ships every new line to it within seconds, so an intruder can wipe the local copy, but not the one that already left.
- Grafana is the window into Loki. It’s where we search the logs of all our boxes in one place, and more important, where we set up alerts, so that something reads the logs for us and shouts when it sees a login from a new IP, a user we didn’t create, or a journal that suddenly went quiet.
Between the two, we get the one thing this checklist can’t give us: knowing that something happened, even if whoever did it tried to hide it. Setting them up is a post of its own.
The Other Missing Piece: Monitoring and Alerting
Logs tell us what happened. They don’t tell us how the box is doing right now, and some visitors are very good at staying out of the logs. What they can’t hide is the work they came to do: a crypto miner needs our CPU, and a box that joined a botnet sends far more traffic than it ever did (ATT&CK has a code for this one too, T1496).
Monitoring is keeping track of those numbers over time: CPU, memory, disk, network. The point isn’t the pretty graphs, it’s learning what normal looks like for our box, because that’s the only way to notice when something isn’t. A tool like Prometheus collects the numbers every few seconds, and Grafana, the same one that reads our logs, draws them.
But nobody stares at graphs at 3 in the morning, and that’s when things tend to happen. Alerting is the other half: we write down what worries us, and a message reaches our phone when it comes true. Things like:
- The CPU (or the GPU) has been above 90% for fifteen minutes: the signature of a crypto miner.
- The disk is almost full: logs out of control, or somebody storing things that aren’t ours.
- The box is sending ten times its usual traffic: it may have joined a botnet, and be part of a DDoS attack on somebody else.
- The box is drowning in incoming traffic, or stopped answering: this time the DDoS may be aimed at us.
- Somebody logged in over SSH from an IP we’ve never seen: our key may not be only ours anymore.
The hard part is restraint. An alert is only worth having if we’d get out of bed for it, because ten messages a day that mean nothing teach us to ignore the one that does.
There’s a free version of this that takes two minutes. Most VPS providers show graphs of our box in their panel, and many let us set an alert on them. One for “CPU above 90% for a while” is enough to catch a miner, and since it lives outside the box, nobody who gets in can switch it off.
The full setup, with Prometheus, Loki and Grafana, comes in a separate post.
When the Phone Buzzes at 3 AM
One night the alert arrives: the CPU of our box is at 100%, at an hour when nobody should be visiting. The first instinct is to log in, find the process, and kill it. Let’s not. That process is the best lead we have. It knows who launched it, from where, and who it’s talking to, and all of that dies with it.
Meeting the Process
A tool like btop comes in handy here, and it’s worth having it installed before the day we need it:
sudo apt install btopsudo dnf install btopIt comes from EPEL, the same repo we added for Fail2ban.
sudo pacman -S btopWith the list of processes sorted by CPU, the culprit is sitting at the top, and next to it, the two things we came for: its PID, and the user it runs as.
With the PID (let’s say it’s 1234), we can ask a few questions. Where does the program live, and when was it started:
sudo ls -l /proc/1234/exeps -o pid,ppid,user,lstart,cmd -p 1234And who is it talking to:
sudo ss -tnp | grep 'pid=1234'If the process is doing damage and we can’t just watch, there’s something between leaving it alone and killing it. This freezes it in place, with everything about it still there to look at:
sudo kill -STOP 1234Following the User
The user is the thread to pull. With that name, we go to Loki (or to journalctl, if the logs never left the box) and read everything it did before the alert. Starting with how it got in:
sudo journalctl -u ssh | grep bobAn Accepted line from an IP that isn’t ours answers the big question. And if there are hundreds of failed attempts for that user before it, that’s news too: bots guess names like root and admin, so somebody hammering on bob knows that bob exists. The name leaked somewhere, and it’s worth finding out where.
If the user is one that never logs in, like www-data, nobody came through SSH. The hole is in the app that runs as that user.
Looking for What They Left
Visitors like this rarely leave empty-handed, and they never leave without a way back. These are the usual hiding places:
-
The folders everybody can write to, where programs get dropped:
Terminal window sudo ls -la /tmp /var/tmp /dev/shm -
Everything else that user is running:
Terminal window ps -u bob -o pid,lstart,cmd -
The scheduled jobs, which is how a miner comes back after we kill it:
Terminal window sudo crontab -u bob -lsudo ls -la /etc/cron.dsystemctl list-timers --all -
The SSH keys. One that we didn’t put there is a back door that survives any change of password:
Terminal window sudo cat /home/bob/.ssh/authorized_keyssudo cat /root/.ssh/authorized_keys
On a compromised box, we can’t fully trust what the box tells us. Whoever got in may have edited the logs, or the very tools we’re using to look. That’s one more reason to have a copy of the logs somewhere else.
Starting Over
Once we’ve learned what we can, it’s tempting to delete the miner, remove the strange key, and go back to bed. It’s a bad idea, even when we’re sure we found the problem. We know about the doors we found, and we have no way of knowing if there are others we didn’t. One cron job we missed, and they’re back by morning.
A compromised box doesn’t get cleaned, it gets replaced:
- We take a snapshot of it from the panel of our provider, in case we want to keep investigating.
- We build a new box from scratch, going through this checklist again.
- We fix the hole they came through, before the new box goes live.
- We rotate every secret that was on the old box. All of them.
- We destroy the old one.
Wrapping Up
That was a long walk for a “fresh” server, so here’s the whole checklist on one screen:
- Read the SSH logs, and set the clock right so they make sense.
- Update the system, and let it keep itself updated.
- Create our own user with
sudo, and remove the ones nobody needs. - Log in with SSH keys.
- Turn off password logins, and then root logins.
- Move SSH to another port, for the sake of quiet logs.
- Put up a firewall: deny everything, allow what our apps need, and keep an eye on Docker.
- Let Fail2ban deal with the stubborn ones.
- Keep our secrets in locked files, and out of Git and the shell history.
None of this makes a box unbreakable, and nothing does. But remember who’s knocking: it’s not somebody who wants our server, it’s a script going down a list, looking for the easy ones. An hour of work is enough to stop being one of them.
What’s left is the part we only described: getting the logs off the box, watching the numbers, and having something wake us up when they look wrong. That’s the next post.