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.

Warning

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:

Terminal window
sudo journalctl -u ssh

Don’t be surprised to see failed login attempts in your logs within minutes of the first boot.

Tip

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:

Terminal window
sudo systemctl list-units | grep ssh

In 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).

Note

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:

Terminal window
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:

  1. Wrong passwords show up as: Failed password from root from 123.69.69.69
  2. Invalid users show up as: Invalid users bob from 123.69.69.69
  3. 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:

Terminal window
sudo journalctl -u ssh --since "24 hours ago" | grep 'Accepted'

To follow login activity in real time:

Terminal window
sudo journalctl -u ssh -f

The logs show who tried to get in. To see who is logged in right now, and from where, run w:

Terminal window
w

You 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:

Terminal window
timedatectl

If for whatever reason the date and time don’t match ours, we can set them properly with:

Terminal window
sudo timedatectl set-timezone Europe/Helsinki
Tip

To see the list of available timezones, run:

Terminal window
timedatectl list-timezones | grep -i helsinki

The 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:

Terminal window
sudo timedatectl set-ntp true

Checking 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:

Terminal window
journalctl --list-boots

Each 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 EET

The 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.

Tip

To see what was going on with SSH right before that reboot, we can pass the index to -b:

Terminal window
sudo journalctl -u ssh -b -1

If 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:

  1. Our server has never been rebooted. This is the most likely one, especially on a fresh VPS.

  2. 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:

Terminal window
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:

Terminal window
sudo systemctl restart systemd-journald
  1. 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:
Terminal window
journalctl --disk-usage
  1. 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.

Note

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:

Terminal window
sudo apt update && sudo apt upgrade

The first command refreshes the list of available packages, and the second one installs the new versions.

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:

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

The second command asks if we want to download and install updates automatically. Say yes.

A day or two later, it’s worth checking that the automatic updates are really happening:

Terminal window
sudo tail /var/log/unattended-upgrades/unattended-upgrades.log

Each 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.

Reboot Required

Some updates, like a new kernel, only kick in after a reboot. To find out if it’s time to restart:

Terminal window
ls /var/run/reboot-required

If the file exists, a reboot is pending.

If a reboot is pending, let’s restart the server so the new kernel takes over:

Terminal window
sudo reboot

The 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.

Tip

If you want to reboot at a specific time, use shutdown instead of reboot:

Terminal window
sudo shutdown -r 23:00

It’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:

Terminal window
sudo --version

If the answer is command not found, we install it. As root:

Terminal window
apt install sudo

Ubuntu ships it out of the box. A minimal Debian image may not.

Creating a User

Let’s create that user and allow it to use sudo. We run these as root:

Terminal window
adduser frankie
usermod -aG sudo frankie

The first command asks for a password and a few optional details. The second one adds our user to the sudo group.

Before going any further, let’s check that it works. We switch to the new user and ask who we are when using sudo:

Terminal window
su - frankie
sudo whoami

If the answer is root, we’re good.

Warning

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:

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:

Terminal window
sudo visudo -f /etc/sudoers.d/bob

In this example, bob is only allowed to restart and reload nginx:

bob ALL=(root) /usr/bin/systemctl restart nginx, /usr/bin/systemctl reload nginx

Reading 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.

Warning

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:

Terminal window
sudo -l -U frankie

The -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) ALL

Which 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 nginx

Without -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:

Terminal window
awk -F: '$3 >= 1000 && $3 < 65534 {print $1}' /etc/passwd

Ideally 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:

Terminal window
sudo -l -U ubuntu
Warning

Before 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:

Terminal window
sudo userdel -r ubuntu

The user is gone, but its sudo rule may still be lying around. A quick search tells us:

Terminal window
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.

Note

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:

Terminal window
lastlog

The 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:

Terminal window
lastlog -b 90

Say 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:

Terminal window
sudo usermod --lock --expiredate 1 bob

The --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:

Terminal window
pgrep -u bob -l
sudo crontab -u bob -l

If nobody complained, and nothing broke, we can say goodbye. The -r flag takes his home folder with him:

Terminal window
sudo userdel -r bob
Tip

If 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:

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:

Terminal window
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:

  1. Where to save the key. The default, ~/.ssh/id_ed25519, is fine.
  2. 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:

Terminal window
ssh-copy-id frankie@203.0.113.10

It asks for the user’s password, for what will hopefully be the last time.

Tip

If our computer doesn’t have ssh-copy-id (looking at you, Windows), this does the same job by hand:

Terminal window
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:

Terminal window
ssh frankie@203.0.113.10

This 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:

Terminal window
sudo journalctl -u ssh | grep Accepted

The last line should say Accepted publickey for frankie, where before it said Accepted password.

Note

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.

Warning

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:

Terminal window
sudo nano /etc/ssh/sshd_config.d/00-hardening.conf

With two lines in it:

PasswordAuthentication no
KbdInteractiveAuthentication no

The 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.

Warning

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:

Terminal window
sudo sshd -t
Note

No 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:

Terminal window
sudo sshd -T | grep -i passwordauthentication

It should answer passwordauthentication no. If it says yes, some other file is winning.

Now we restart the service:

sh sudo systemctl restart ssh

Warning

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:

Terminal window
ssh -o PubkeyAuthentication=no frankie@203.0.113.10

The 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.

Note

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.

Warning

Before closing this door, let’s make sure frankie can really become root:

Terminal window
sudo whoami

If the answer isn’t root, stop here and fix that first.

We open the same file as before:

Terminal window
sudo nano /etc/ssh/sshd_config.d/00-hardening.conf

And add one more line:

PermitRootLogin no
Note

The 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:

Terminal window
sudo sshd -t
sudo sshd -T | grep -i permitrootlogin

It should answer permitrootlogin no. Then we restart the service:

sh sudo systemctl restart ssh

And from a second terminal, we knock on the door we just closed:

Terminal window
ssh root@203.0.113.10
root@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:

Terminal window
sudo -i
Tip

root 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:

Terminal window
sudo ss -tlnp | grep 5522

No output means nobody is listening there.

Warning

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:

Terminal window
sudo nano /etc/ssh/sshd_config.d/00-hardening.conf

One more line:

Port 5522

Then the usual routine:

Terminal window
sudo sshd -t
sudo 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:

Terminal window
sudo systemctl restart ssh

Ubuntu 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:

Terminal window
sudo systemctl daemon-reload
sudo systemctl restart ssh.socket
Warning

You 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:

Terminal window
ssh -p 5522 frankie@203.0.113.10

And the old port should be dead:

Terminal window
ssh frankie@203.0.113.10
ssh: connect to host 203.0.113.10 port 22: Connection refused

Saving 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 5522

And from now on, this is enough:

Terminal window
ssh box

Setting 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.

Tip

The name of the game is very simple:

  1. Deny access to incoming traffic for all ports.
  2. Allow all outgoing traffic, so our box can still reach the internet.
  3. Allow incoming traffic only for the ports our apps need, starting with SSH.
  4. Enable the firewall, and check that we can still get in.

Before closing anything, let’s see what’s open right now:

Terminal window
sudo ss -tlnp

The 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.

Warning

⚠️ 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:

Terminal window
sudo apt install ufw
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow 5522/tcp
sudo ufw enable

Then we ask how things are:

Terminal window
sudo ufw status verbose
Status: active
Default: deny (incoming), allow (outgoing), disabled (routed)
To Action From
-- ------ ----
5522/tcp ALLOW IN Anywhere
5522/tcp (v6) ALLOW IN Anywhere (v6)

✅ And, as always, we open a second terminal and check that we can still get in:

Terminal window
ssh box

Opening More Ports

The day our box starts serving something, a website for example, we open the ports it needs, and only those:

Terminal window
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

And to close one again:

Terminal window
sudo ufw delete allow 80/tcp
Note

Most 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:

Terminal window
docker run -d -p 8080:80 nginx

ufw status won’t even show it. To see what our containers are really publishing, we ask Docker:

Terminal window
docker ps --format '{{.Names}}\t{{.Ports}}'
web 0.0.0.0:8080->80/tcp

That 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:

Terminal window
docker run -d -p 127.0.0.1:8080:80 nginx
web 127.0.0.1:8080->80/tcp

Now 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.

Tip

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:

Terminal window
sudo iptables -I DOCKER-USER -i eth0 ! -s 198.51.100.7 -j DROP

Piece by piece:

Warning

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:

Terminal window
sudo usermod -aG docker frankie

It’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:

Terminal window
docker run --rm -it -v /:/host alpine chroot /host

So 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:

Terminal window
getent group docker

And to take somebody out:

Terminal window
sudo gpasswd -d bob docker

Installing 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.

Terminal window
sudo apt install fail2ban python3-systemd

The second package is what lets it read the journal. It usually comes along by itself, but asking for it doesn’t hurt.

Setting 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:

Terminal window
sudo nano /etc/fail2ban/jail.local
[DEFAULT]
bantime = 1h
findtime = 10m
maxretry = 5
backend = systemd
[sshd]
enabled = true
port = 5522

In 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.

Warning

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:

Terminal window
sudo systemctl enable fail2ban
sudo systemctl restart fail2ban

Checking on the Jail

Terminal window
sudo fail2ban-client status sshd
Status 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:

Terminal window
sudo fail2ban-client set sshd unbanip 198.51.100.7
Tip

If 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.7

Most 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:

Terminal window
git log --all --oneline -- .env

No output means it never did.

Warning

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:

Terminal window
chmod 600 .env
ls -l .env
Note

Those 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 folder

The 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 .env

That’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:

Terminal window
sudo find / -xdev -type f -name '.env*' -perm -o=r 2>/dev/null

Whatever 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:

Terminal window
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:

Terminal window
export STRIPE_KEY=sk_live_abc123

It only works if this answers ignorespace or ignoreboth:

Terminal window
echo $HISTCONTROL

If it doesn’t, we add HISTCONTROL=ignoreboth to our ~/.bashrc. And to check what we’ve already left behind:

Terminal window
grep -i -E 'pass|token|secret|key' ~/.bash_history
Note

The 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.

Note

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:

Terminal window
vim -i NONE -n .env

We make the file first, lock it, and only then put something in it:

Terminal window
touch .env
chmod 600 .env
nano .env

What 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:

Terminal window
set -a; source .env; set +a

The 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 = frankie
password = MyPassword

With 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:

Terminal window
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 yes

And we clone using that name:

Terminal window
git clone github-myapp:frankie/myapp.git

If 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.

Note

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:

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 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.

Tip

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:

Terminal window
sudo apt install btop

With 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:

Terminal window
sudo ls -l /proc/1234/exe
ps -o pid,ppid,user,lstart,cmd -p 1234

And who is it talking to:

Terminal window
sudo ss -tnp | grep 'pid=1234'
Tip

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:

Terminal window
sudo kill -STOP 1234

Following 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:

Terminal window
sudo journalctl -u ssh | grep bob

An 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:

Warning

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:

  1. We take a snapshot of it from the panel of our provider, in case we want to keep investigating.
  2. We build a new box from scratch, going through this checklist again.
  3. We fix the hole they came through, before the new box goes live.
  4. We rotate every secret that was on the old box. All of them.
  5. 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:

  1. Read the SSH logs, and set the clock right so they make sense.
  2. Update the system, and let it keep itself updated.
  3. Create our own user with sudo, and remove the ones nobody needs.
  4. Log in with SSH keys.
  5. Turn off password logins, and then root logins.
  6. Move SSH to another port, for the sake of quiet logs.
  7. Put up a firewall: deny everything, allow what our apps need, and keep an eye on Docker.
  8. Let Fail2ban deal with the stubborn ones.
  9. 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.