CH 01 · アトラクタ

code flows like water balance found in empty lines the terminal waits

公案 01 / 12 · シャッフル

ライフ バランス

latestLocking Down a VPS

Featured posts all 13 →
Cool image
01 · Latest

Locking Down a VPS

Hardening a server before the crypto miners arrive

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:

  • 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 using root, 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:

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:

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

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:

  • -I DOCKER-USER inserts the rule at the top of that chain.
  • -i eth0 matches the traffic coming in through eth0, the network card that faces the internet.
  • ! -s 198.51.100.7 matches every source that is not that IP.
  • -j DROP is what happens to whatever matched: it gets dropped.
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:

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

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:

  • 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 -l
    sudo ls -la /etc/cron.d
    systemctl 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_keys
    sudo cat /root/.ssh/authorized_keys
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.

Cool pic
02

A Generic Set

Generics, concurrency and data structures in Go

In computer science, a set is an abstract data type that can store distinct values, without any particular order. In this article we’ll take a look at how to implement this basic data structure using generics and a bit of concurrency.

Before Generics

Before generics were a thing in Go, people used maps to create custom sets when needed:

existingTitles := map[string]bool{}
existingTitles["Getting Started with Go"] = true
existingTitles["Understanding Goroutines"] = true
existingTitles["Getting Started with Go"] = true
if existingTitles["Getting Started with Go"] {
fmt.Println("Title already exists.")
}

The type of the value isn’t important, since we only care about the keys. Using bool is convenient because it lets us check for membership directly in a conditional:

if validCategories[category] {
// whatevs...
}

When you access a map with a key that doesn’t exist, Go returns the zero value for the map’s value type, i.e. false. That way the condition evaluates to false whenever category isn’t in the set.

Tip

If memory usage is a concern, you can use an empty struct as the map value type:

existingTitles := map[string]struct{}{}

Note that I’ve also initialized the map with {}. Without it, the declaration is invalid. If that’s too many braces for you, use:

existingTitles := make(map[string]struct{})

And if you’re only declaring the variable, you could instead write:

var existingTitles map[string]struct{}

Using struct{} for set values is the idiomatic approach in Go because it occupies zero bytes.

This pattern works well and is widely used in Go, but it’s really just using a map to simulate a set. Before generics, you’d need a separate set implementation for every element type — one for strings, one for ints, and so on. With generics, we write it once and let the type parameter do the rest.

A Generic Set

The general syntax for a generic type declaration in Go is:

type TypeName[T Constraint] UnderlyingType

Where:

  • TypeName is the name of the generic type.
  • T is the type parameter (a placeholder for a concrete type).
  • Constraint specifies which types T is allowed to be.
  • UnderlyingType is the actual type definition that uses T.

Our generic Set will take a single type parameter, E, which represents the type of elements stored in the set:

type Set[E comparable] map[E]struct{}

Let’s break it down:

  • E is the type parameter. You can think of it as a placeholder for the actual element type, such as string, int, or User.
  • comparable is the type constraint: It restricts E to types that can be compared with == and !=.
Note

Go maps use equality operators to determine whether a key already exists. When you look up a key or insert one, the map compares it with existing keys. Because of this, map keys must be comparable.

A Generic Function

Just like types, generic functions can also have type parameters. The general syntax is:

func FunctionName[T Constraint](parameters) ReturnType {
// ...
}

Where:

  • FunctionName is, well, you guessed it.
  • T is the type parameter.
  • Constraint specifies which types T is allowed to be.

The type parameter can be used in the function’s parameters, return type, or both.

Since we can’t use a map until it’s initialised, let’s provide a constructor function, which will be generic as well:

func NewSet[E comparable]() Set[E] {
return Set[E]{}
}

When we call this function, we need to specify the concrete element type. For example, to create a Set of strings:

names := NewSet[string]()

Note that a generic set is not a complete type until we instantiate it with a concrete type. Each instantiation gives us a different set type; we write the set implementation once, but each set still keeps its own element type.

Adding Elements

Now let’s write a generic method to add values to the set. We’ll make it variadic, so that it can add one or more elements at a time:

func (s Set[E]) Add(values ...E) {
for _, v := range values {
s[v] = struct{}{}
}
}

Since our set is backed by a map, adding an element means assigning that value as a key. The map value is struct{}{} because we don’t need to store any extra data; the presence of the key is enough. For example:

Making Add variadic gives us a more flexible API. We can still add a single element, but we can also add multiple elements in one call:

names := NewSet[string]()
names.Add("Alice")
names.Add("Bob", "Charlie", "Frankie")
fmt.Println(names) // map[Alice:{} Bob:{} Frankie: {} Charlie: {}]

Note how the values are empty structs, {}. That doesn’t look nice, let’s fix it in the next section.

Listing Set Members

Printing the set reveals its underlying map representation, which isn’t ideal if we simply want to inspect its contents. Let’s add a method that returns all the elements in the set as a slice. Because sets are inherently unordered, the order of the elements is undefined.

func (s Set[E]) Members() []E {
result := make([]E, 0, len(s))
for v := range s {
result = append(result, v)
}
return result
}

Let’s take a look now:

names := NewSet[string]()
names.Add("Alice")
names.Add("Bob")
names.Add("Frankie")
fmt.Println(names.Members()) // [Alice Bob Charlie]
Warning

The order of the elements is not guaranteed and may vary between runs!

String Method

Let’s also implement the String method so that our set prints more nicely:

func (s Set[E]) String() string {
return fmt.Sprintf("%v", s.Members())
}

With this method in place, we no longer need to call Members explicitly when printing a set:

fmt.Println(s) // [2 3 1]

You may notice that the elements appear in a different order each time you run the program, and that’s perfectly fine. By definition, a set is an unordered collection of distinct values. Since our implementation is backed by a map, it naturally inherits the map’s lack of ordering guarantees.

Checking for Membership

A set is primarily useful because it lets us answer a simple question efficiently:

Does this value belong to the set?

For sets, we don’t care about the value at all—we only care whether the key is present:

func (s Set[E]) Contains(v E) bool {
_, ok := s[v]
return ok
}
Note

Since our Set is backed by a map, we can take advantage of Go’s comma ok idiom. A map index expression can return two values:

  • The value associated with the key.
  • A boolean indicating whether the key exists in the map.

The blank identifier (_) discards the map value, while ok tells us whether v is a member of the set. For example:

names := NewSet[string]()
names.Add("Alice")
names.Add("Bob")
fmt.Println(names.Contains("Alice")) // true
fmt.Println(names.Contains("Charlie")) // false

Because map lookups are highly optimized, checking for membership in a set is typically an O(1) operation.

Union of Two Sets

A common operation on sets is the union of two sets: a new set containing all the elements that appear in either set.

union set

One way to implement this is to create a new set containing the members of the first set, and then add the members of the second set:

func (s Set[E]) Union(s2 Set[E]) Set[E] {
result := NewSet(s.Members()...)
result.Add(s2.Members()...)
return result
}

As you can see, we’re making use of our existing API to implement the Union:

  • NewSet to create the new set.
  • Add variadic to merge the second set without the need of a loop.

Let’s try it with two small sets of integers:

s1 := NewSet(1, 2, 3)
s2 := NewSet(3, 4, 5)
fmt.Println(s1.Union(s2)) // [1 2 3 4 5]

The resulting set contains every element from both sets, but only once. Even though both s1 and s2 contain 3, it appears only once in the union because sets cannot contain duplicate elements.

Intersection of Two Sets

Let’s also implement intersection. The intersection of two sets is a new set containing only the elements that both sets have in common.

union set

Unlike Union, we can’t simply combine the members of both sets. Instead, we need to examine each element of one set and check whether it also exists in the other:

func (s Set[E]) Intersection(s2 Set[E]) Set[E] {
result := NewSet[E]()
for _, v := range s.Members() {
if s2.Contains(v) {
result.Add(v)
}
}
return result
}

In other words, we iterate over the members of s, and whenever an element is also present in s2, we add it to the result. Let’s try it:

s1 := NewSet(1, 2, 3)
s2 := NewSet(3, 4, 5)
fmt.Println(s1.Intersection(s2)) // [3]

As expected, the only element shared by both sets is 3, so the intersection contains just that value.

Concurrency Safety

Maps in Go are not safe for concurrent use. If multiple goroutines read from and write to the same map simultaneously, the program will panic. To make our Set concurrency-safe, we can embed a sync.RWMutex and lock appropriately on every operation.

A Read-Write Mutex

Let’s update our Set type with an RWMutex:

type Set[E comparable] struct {
data map[E]struct{}
mutex *sync.RWMutex
}

A sync.RWMutex distinguishes between reads and writes:

  • Any number of goroutines can hold a read lock simultaneously. — Write locks are exclusive: when a writer holds it, no readers or other writers can proceed.

This makes it a good fit for a set, where reads (like Contains) are frequent and writes (like Add) are less so.

Important

We’ll store a pointer to the mutex rather than the mutex value itself. If we stored it by value, copying the Set would copy the mutex too — and two independent mutexes no longer protect the same data. Since it never makes sense to copy a mutex, defining the mutex field as a pointer prevents this from happening accidentally.

Before generics, duplicating data structures across types made sophistication impractical — nobody wants to maintain N versions of the same complex code. So corners got cut. Generics remove that disincentive, making it worthwhile to build data structures that are actually good.

Constructor

The constructor looks much the same as before, with two additions: it initializes the mutex with &sync.RWMutex{} and the underlying map explicitly, then returns a pointer to the Set struct rather than the struct itself — consistent with storing the mutex by pointer.

func NewSet[E comparable](vals ...E) *Set[E] {
s := Set[E]{
mutex: &sync.RWMutex{},
data: map[E]struct{}{},
}
for _, v := range vals {
s.data[v] = struct{}{}
}
return &s
}

Add

The behaviour of Add is the same as before, with one important difference: it must acquire a write lock before touching the map. This prevents any other goroutine from reading or writing while the update is in progress.

func (s *Set[E]) Add(vals ...E) {
s.mutex.Lock()
defer s.mutex.Unlock()
for _, v := range vals {
s.data[v] = struct{}{}
}
}

defer s.mutex.Unlock() ensures the lock is always released when Add returns, even if something panics mid-loop.

Members

Members doesn’t modify the map, so a write lock would be overkill. A read lock is enough — it allows other goroutines to read concurrently, while still blocking any writer that tries to modify the map at the same time.

func (s *Set[E]) Members() []E {
s.mutex.RLock()
defer s.mutex.RUnlock()
result := make([]E, 0, len(s.data))
for v := range s.data {
result = append(result, v)
}
return result
}

Contains

Contains is also read-only, so the same strategy applies.

func (s *Set[E]) Contains(v E) bool {
s.mutex.RLock()
defer s.mutex.RUnlock()
_, ok := s.data[v]
return ok
}

Putting It to the Test

To verify that our is concurrently safe, we need to exercise the Set concurrently — at least one goroutine writing, another reading, and enough repetitions that a data race has a fair chance to surface. A single read and write might get lucky; a thousand of each is harder to fluke.

s := NewSet(1, 2, 3)
var wg sync.WaitGroup
wg.Add(1)
go func() {
for i := 0; i < 1000; i++ {
s.Add(i)
}
wg.Done()
}()
for i := 0; i < 1000; i++ {
_ = s.Members()
}
wg.Wait()
fmt.Println("Huzzah!") // Huzzah!

If the locking is correct, our program won’t panic, and we should see the output:

Huzzah!

Let’s see what happens if we comment out the locking code in Add and run the same test:

func (s *Set[E]) Add(vals ...E) {
// s.mutex.Lock()
// defer s.mutex.Unlock()
// ...
}

If you run the program, you’d most probably see something like this:

fatal error: concurrent map iteration and map write
goroutine 1 [running]:
...

The Go runtime detected a concurrent read in Members and a write in Add, and since it can no longer guarantee the integrity of the data, it terminates the program immediately.

Intersection: Taming Mutex Churn

We could implement Intersection the same way as before — reusing Members, Contains, and Add — and it would be concurrency-safe without any extra work, since those methods already handle their own locking.

But there’s an efficiency concern. Since we call s2.Contains — which locks and unlocks the mutex — for every member of s, large sets will produce a lot of mutex churn. Mutexes are fast, but they aren’t free, and repeatedly acquiring and releasing a lock in a tight loop adds up.

A better approach is to lock s2 once, do all the membership checks while the lock is held, then release it:

func (s *Set[E]) Intersection(s2 *Set[E]) *Set[E] {
result := NewSet[E]()
s2.mutex.RLock()
defer s2.mutex.RUnlock()
for _, v := range s.Members() {
if _, ok := s2.data[v]; ok {
result.Add(v)
}
}
return result
}

One read lock on s2 for the entire operation, rather than one per element.

Note

It’s a trade-off, though. Holding a read lock on s2 for the entire operation avoids mutex churn, but it also means blocking any writer that wants to modify s2 for the full duration of the intersection. For large sets, that could be a long time.

Depending on the application, more granular locking — acquiring and releasing the lock for each individual Contains check — might actually be preferable. Less contention per operation, at the cost of more locking overhead overall. It just depends on whether your bottleneck is mutex churn or lock contention.

Unsafe Set

Not every application needs concurrency safety. If your set is only ever accessed from a single goroutine, the mutex overhead is pure waste. In that case, we can go back to the simpler implementation from the start of this article — same methods, no locking.

Rather than maintaining two entirely separate types, we can offer both through two constructors:

  • NewSet for the concurrency safe default.
  • NewUnsafeSet for when performance matters more than safety.

Users get the right tool for the job, and we only write the implementation once.

Types

The idea is to split the two concerns into two types:

  • UnsafeSet is the raw, lock-free implementation — just a map, same as we started with.
  • Set wraps it, adding a mutex to make it safe for concurrent use:
type UnsafeSet[E comparable] map[E]struct{}
type Set[E comparable] struct {
data UnsafeSet[E]
mutex *sync.RWMutex
}

Constructors

Each type gets its own constructor:

  • NewUnsafeSet just initialises the map and populates it.
  • NewSet builds on top of it, wrapping the UnsafeSet in a Set and initialising the mutex:
func NewUnsafeSet[E comparable](vals ...E) UnsafeSet[E] {
s := UnsafeSet[E]{}
for _, v := range vals {
s[v] = struct{}{}
}
return s
}
func NewSet[E comparable](vals ...E) *Set[E] {
return &Set[E]{
data: NewUnsafeSet[E](vals...),
mutex: &sync.RWMutex{},
}
}

Adding Items

UnsafeSet.Add is the same as before — iterate and assign. Set.Add wraps it with a write lock, ensuring no other goroutine can read or write the underlying map while the update is in progress:

func (s UnsafeSet[E]) Add(vals ...E) {
for _, v := range vals {
s[v] = struct{}{}
}
}
func (s *Set[E]) Add(vals ...E) {
s.mutex.Lock()
defer s.mutex.Unlock()
s.data.Add(vals...)
}

Listing Members

UnsafeSet.Members is the same implementation we wrote earlier: create a slice, iterate over the map keys, and append each element. Set.Members adds a read lock around that same logic:

func (s UnsafeSet[E]) Members() []E {
result := make([]E, 0, len(s))
for v := range s {
result = append(result, v)
}
return result
}
func (s *Set[E]) Members() []E {
s.mutex.RLock()
defer s.mutex.RUnlock()
return s.data.Members()
}

Since Members only reads from the map, the safe version uses RLock instead of Lock.

Checking for Membership

UnsafeSet.Contains uses the comma-ok idiom directly on the map. Set.Contains wraps the same check in a read lock:

func (s UnsafeSet[E]) Contains(v E) bool {
_, ok := s[v]
return ok
}
func (s *Set[E]) Contains(v E) bool {
s.mutex.RLock()
defer s.mutex.RUnlock()
return s.data.Contains(v)
}

Since membership checks only read from the map, the safe version uses RLock.

String Method

UnsafeSet.String formats the set by reusing Members. Set.String does the same through the safe Members method:

func (s UnsafeSet[E]) String() string {
return fmt.Sprintf("%v", s.Members())
}
func (s *Set[E]) String() string {
return fmt.Sprintf("%v", s.Members())
}

Both versions print the set as a slice, and the element order is still undefined.

Union of Two Sets

UnsafeSet.Union creates a new unsafe set, copies the members of the first set, and then adds the members of the second set. Set.Union does the same through safe snapshots of both sets:

func (s UnsafeSet[E]) Union(s2 UnsafeSet[E]) UnsafeSet[E] {
result := NewUnsafeSet(s.Members()...)
result.Add(s2.Members()...)
return result
}
func (s *Set[E]) Union(s2 *Set[E]) *Set[E] {
result := NewSet(s.Members()...)
result.Add(s2.Members()...)
return result
}

The safe version uses Members on both sets, so each read is protected by its own read lock.

Intersection of Two Sets

UnsafeSet.Intersection creates a new unsafe set and adds only the values that also exist in the second set. Set.Intersection takes safe snapshots before doing the same work:

func (s UnsafeSet[E]) Intersection(s2 UnsafeSet[E]) UnsafeSet[E] {
result := NewUnsafeSet[E]()
for _, v := range s.Members() {
if s2.Contains(v) {
result.Add(v)
}
}
return result
}
func (s *Set[E]) Intersection(s2 *Set[E]) *Set[E] {
result := NewSet[E]()
for _, v := range s.Members() {
if s2.Contains(v) {
result.Add(v)
}
}
return result
}

The safe version delegates reads through Members and Contains, so each map access is protected by a read lock.

Deleting Items

UnsafeSet.Delete removes values directly from the map. Set.Delete wraps that same operation with a write lock:

func (s UnsafeSet[E]) Delete(vals ...E) {
for _, v := range vals {
delete(s, v)
}
}
func (s *Set[E]) Delete(vals ...E) {
s.mutex.Lock()
defer s.mutex.Unlock()
s.data.Delete(vals...)
}

Deleting a value that is not in the set is safe: Go’s built-in delete function does nothing when the key does not exist.

Set Length

UnsafeSet.Len returns the number of elements in the map. Set.Len wraps the same operation with a read lock:

func (s UnsafeSet[E]) Len() int {
return len(s)
}
func (s *Set[E]) Len() int {
s.mutex.RLock()
defer s.mutex.RUnlock()
return s.data.Len()
}

Since Len only reads the map, the safe version uses RLock.

Closing Thoughts

This article is not really about building the perfect set implementation. The set is just a useful example: small enough to understand, but rich enough to show how generics and concurrency fit together in Go.

Note

That’s not to say the implementation is complete. There’s plenty more we could add:

  • An Equals method
  • An IsSubset method
  • A Subtract method that removes all members that belong to some other set
  • A Difference function to find the members that two sets don’t have in common
  • A Make function to pre-allocate memory
  • Map, Reduce, and Filter operations on set elements

These are left as an exercise for the reader.

If you need a production-ready set package, two good options are:

Cool Pic
03

Microsandbox

Caging the Autocomplete Beast

I wasn’t very happy with my current sandboxing solution (E2B), so decided to give a try to MicroSandbox, and was glad I switched.

What are sandboxes for?

We’re entering an era where AI agents don’t just suggest code, they write it and execute it. They also install packages, run scripts, inspect files, call CLIs, start dev servers, and sometimes touch code we barely understand yet.

That changes the infrastructure we need around development.

If an agent is going to run arbitrary commands, it needs a safe place to do it. Not my laptop. Not my production machine. Not a long-lived environment full of secrets. It needs a disposable, isolated computer where mistakes are contained and experiments are cheap.

That’s what sandboxes are for.

A good sandbox gives each agent its own environment: a filesystem, a shell, network boundaries, resource limits, and a way to run and inspect code without trusting it too much. For AI coding tools, this is becoming table stakes.

The Microsandbox CLI

Before using the Microsandbox SDK, it’s worth getting familiar with what Microsandbox can do through the Microsandbox CLI.

In this post we’ll look into how to:

  • Install the msb CLI.
  • Create a persistent Node-based sandbox.
  • Execute shell commands inside the sandbox.
  • Install runtime tools and project dependencies.
  • Create and run an Astro app inside the sandbox.
  • Expose the Astro dev server through a mapped local port.
  • Inspect, stop, restart, and remove the sandbox.

Installation

We can install the CLI globally, by downloading and running the following script:

Terminal window
curl -fsSL https://install.microsandbox.dev | sh
Warning

microsandbox requires Linux with KVM enabled, or macOS with Apple Silicon (M-series chip). Both use hardware virtualization.

After the installation, you’ll have to source ~/.zshrc, then verify the installation:

Terminal window
msb --version
msb 0.4.6

Using the msb CLI

In this section we’ll demo how to create a sandbox named astro-demo, which is nothing but a cointainerized Astro app, running in a Microsandbox.

1. Create A Persistent Node Sandbox

Let’s use the msb CLI to create a named sandbox from the node:22.22.3-slim Docker image and publish Astro’s default dev port:

Terminal window
msb run \
--name astro-demo \
--detach \
--replace \
-m 2G \
-c 2 \
-p 4324:4321 \
node:22.22.3-slim

Several things going on in the command above:

  • The --name flag will name our persistent sandbox as astro-demo.
  • The --detach flag to run the sandbox in the background and returns the terminal inmediately.
  • The --replace flag will recreate the sandbox if it already exists.
  • The -m 2G flag sets 2GB of memory.
  • The -c 2 flag sets 2 virtual CPUs.
  • The -p 4324:4321 is mapping ports from host 4324 -> sandbox 4321.
  • We’re using the node:22.22.3-slim Docker image, which gives us Node.js preinstalled, based on Debian slim. The slim variant is smaller than the full Node image, but still supports apt-get, so we can install tools like git and curl.

2. Prepare The Runtime

Now that our sandbox is running, we can install tools into it:

Terminal window
msb exec astro-demo -- sh -c "apt-get update && apt-get install -y git curl"

Enable pnpm as our package manager:

Terminal window
msb exec astro-demo -- corepack enable
msb exec astro-demo -- corepack prepare pnpm@latest --activate

Verify that everything was successfully installed by checking their versions:

Terminal window
msb exec astro-demo -- node --version
msb exec astro-demo -- pnpm --version
msb exec astro-demo -- git --version

3. Create An Astro App

Let’s create the app inside /home/workspace:

Terminal window
msb exec astro-demo -- sh -c "mkdir -p /home/workspace && cd /home/workspace && pnpm create astro@latest . --template basics --no-install --yes"

The command above will create without installing dependencies. Let’s install them:

Terminal window
msb exec astro-demo -- sh -c "cd /home/workspace && pnpm install --dangerously-allow-all-builds"
Tip

The --dangerously-allow-all-builds flag is for pnpm install. It allows packages with build/postinstall scripts to run during installation.

We use it because generated frontend apps often depend on packages that need install-time build steps. Without it, pnpm may skip those scripts and later commands can fail with ERR_PNPM_IGNORED_BUILDS.

Prefer running it in a separate install step:

Terminal window
pnpm install --dangerously-allow-all-builds

instead of passing it through pnpm create, where it may not be forwarded reliably.

If pnpm create astro prompts unexpectedly, use npm instead:

Terminal window
msb exec astro-demo -- sh -c "mkdir -p /home/workspace && cd /home/workspace && npm create astro@latest . -- --template basics --install --yes"

4. Start The Astro Dev Server

Ok, let’s start the Astro dev server on all interfaces so the published port can reach it:

Terminal window
msb exec astro-demo -- sh -c "cd /home/workspace && pnpm dev --host 0.0.0.0 --port 4321"

The command above also starts the sandbox if it was stopped. Now the sandboxed app should be available at https://localhost:4324 👍

Tip

You can start/stop the sandbox at anytime with:

Terminal window
msb stop astro-demo # Stop
msb start astro-demo # Start

Then inspect the logs:

Terminal window
msb logs astro-demo
Note

To start the Astro dev server in the background, we need to background the host-side msb exec process:

Terminal window
nohup msb exec astro-demo -- sh -c "cd /home/workspace && pnpm dev --host 0.0.0.0 --port 4321" </dev/null >/dev/null 2>&1 &
disown

Oof, lot to unpack:

  • nohup keeps msb exec alive after shell hangups.
  • </dev/null detaches stdin.
  • >/dev/null 2>&1 detaches output
  • & backgrounds the host msb exec process (outside the “”)
  • disown removes it from shell job control.

To stop the background process, find it with:

Terminal window
ps aux | grep "msb exec astro-demo"

Then kill the matching PID:

Terminal window
kill <PID>

It makes things quite difficult if you’re not used to this level of shell-fu, so nothing wrong if you prefer to run it in the foreground, and open new terminal tabs.

5. Run Commands Inside The Sandbox

Using msb we can inspect files within the sandbox:

Terminal window
msb exec astro-demo -- sh -c "cd /home/workspace && ls -la"

Read package metadata:

Terminal window
msb exec astro-demo -- sh -c "cd /home/workspace && cat package.json"

Run a build:

Terminal window
msb exec astro-demo -- sh -c "cd /home/workspace && pnpm build"

6. Test Environment Variables

Run a one-off command with an env var:

Terminal window
msb exec astro-demo -- sh -c "DEMO_ENV=hello node -e 'console.log(process.env.DEMO_ENV)'"

For app runtime env vars, start the dev server with env in the shell command:

Terminal window
msb exec astro-demo -- sh -c "cd /home/workspace && PUBLIC_DEMO_VALUE=hello pnpm dev --host 0.0.0.0 > /tmp/astro.log 2>&1 &"

7. Inspect Sandbox State

The msb CLI offers a bunch of commands for managing sandboxes. We can list them:

Terminal window
msb ls

Show the ones that are running:

Terminal window
msb ps

Inspect a particular sandbox:

Terminal window
msb inspect astro-demo

Show its metrics:

Terminal window
msb metrics astro-demo

Show its logs:

Terminal window
msb logs astro-demo

8. Stop And Resume

To start (or restart) an existing sandbox:

Terminal window
msb start astro-demo

To stop it:

Terminal window
msb stop astro-demo

9. Clean Up

Whenever we are done with a sandbox, we can stop it:

Terminal window
msb stop astro-demo

And remove it:

Terminal window
msb rm astro-demo

Huzzah!

We’ve played a bit with the CLI, now go have fun with the SDK.

Cool pic
04

Garage

An S3 object store so reliable you can run it outside datacenters

Most web apps eventually need to handle file uploads — profile pictures, attachments, assets. The instinct is to just write them to disk, but that breaks the moment your app restarts or scales.

Object Storage

Object storage (also called blob storage) is a way of storing data where each piece of data is kept as an independent object rather than inside a traditional file hierarchy or fixed disk blocks. Each object contains the data itself, some metadata describing it, and a unique identifier used to retrieve it.

My Use Case

Sometimes apps run on infrastructure where disk persistence isn’t reliable. That’s the case with Next.js apps, where local filesystem storage is ephemeral — files can disappear after restarts, redeploys, or when the app moves between instances. I needed an object storage solution that matches the production environment.

Why Garage

Garage is a lightweight, self-hosted S3-compatible store that gives you that — without handing your data to a third party. The project is not even hosted in GitHub but in deuxfleurs, which is the collective/organization behind Garage.

Note

deuxfleurs (aka 🌼🌼) is a French non-profit that builds decentralized, self-hosted infrastructure tools. Garage was originally built to power their own infrastructure and then open-sourced.

Using something like Garage (or MinIO) makes sense if:

  • You want full control over where data lives — no third party
  • You’re building for a client with data residency requirements
  • You’re deploying the whole stack on your own infra (VPS, bare metal) and want storage there too, not on AWS
  • You want prod to also be self-hosted — in which case Garage in dev mirrors prod exactly

Set Up a Garage Container

You can get familiar with several ways of getting Garage up and running in their quick start. We’ll be using a Docker container, so let’s add the following to our docker-compose.yml file:

services:
# Other services
garage:
image: dxflrs/garage:b72b090a097c8ee2711c8fb065d250ed68dcd0bf
container_name: garage_s3
ports:
- '3900:3900'
- '3901:3901'
environment:
- GARAGE_ALLOW_WORLD_READABLE=1
volumes:
- ./garage_config/garage.toml:/etc/garage.toml
- ./garage_metadata:/var/lib/garage/meta
- ./garage_data:/var/lib/garage/data

Garage Configuration

According to the aforementioned quick start, we need to create a configuration file:

# metadata_dir = "/tmp/meta"
# data_dir = "/tmp/data"
metadata_dir = "/var/lib/garage/meta"
data_dir = "/var/lib/garage/data"
db_engine = "sqlite"
replication_factor = 1
rpc_bind_addr = "[::]:3901"
rpc_public_addr = "127.0.0.1:3901"
# rpc_secret = "$(openssl rand -hex 32)"
rpc_secret = "b89a46551da109ca0ecac670ae2dff0482a1ab98aa3ec28a96f1c65a656dee34"
[s3_api]
s3_region = "garage"
api_bind_addr = "[::]:3900"
root_domain = ".s3.garage.localhost"
[s3_web]
bind_addr = "[::]:3902"
root_domain = ".web.garage.localhost"
index = "index.html"
[k2v_api]
api_bind_addr = "[::]:3904"
[admin]
api_bind_addr = "[::]:3903"
# admin_token = "$(openssl rand -base64 32)"
admin_token = "zNZmDBE9Tiqs8CaUmN90Loo/63T+c32x0xC8M0Rjk8U="
# metrics_token = "$(openssl rand -base64 32)"
metrics_token = "69VTAfJSVuaog72X8oxcReRFAQKJJelF4BJzQgeXjvk="
Important

This file is mounted as a volume in our Docker setup; the default location where garage looks up this file within the container is /etc/garage.toml.

To get the values for some configuration options, we have to run in the terminal the following commands:

  • openssl rand -hex 32 and paste the output in rpc_secret
  • openssl rand -base64 32 and paste the output in admin_token
  • openssl rand -base64 32 and paste the output in metrics_token

Creating a Cluster Layout

Creating a cluster layout for a Garage deployment means:

  1. Informing Garage of the disk space available on each node of the cluster (-c)
  2. As well as the name of the zone (e.g. datacenter), each machine is located in (-z).

Copy Node ID Prefix

Let’s start Garage with docker compose up garage, and check the status with:

Terminal window
docker exec -it garage_s3 /garage status
INFO garage_net::netapp: Connected to 127.0.0.1:3901, negotiating handshake...
INFO garage_net::netapp: Connection established to 2778c9ed427e0ca2
==== HEALTHY NODES ====
ID Hostname Address Tags Zone Capacity DataAvail
2778c9ed427e0ca2 0d45c890ad78 127.0.0.1:3901 NO ROLE ASSIGNED

Then let’s copy the prefix of the node, e.g. 2778 from 2778c9ed427e0ca2, and paste it in <NODE_ID_PREFIX>:

Terminal window
docker exec -it garage_s3 /garage layout assign -z dc1 -c 1G <NODE_ID_PREFIX>

Then apply the layout:

Terminal window
docker exec -it garage_s3 /garage layout apply --version 1

Which should output:

==== COMPUTATION OF A NEW PARTITION ASSIGNATION ====
Partitions are replicated 1 times on at least 1 distinct zones.
Optimal partition size: 3.9 MB
Usable capacity / total cluster capacity: 1000.0 MB / 1000.0 MB (100.0 %)
Effective capacity (replication factor 1): 1000.0 MB
dc1 Tags Partitions Capacity Usable capacity
2778c9ed427e0ca2 256 (256 new) 1000.0 MB 1000.0 MB (100.0%)
TOTAL 256 (256 unique) 1000.0 MB 1000.0 MB (100.0%)
New cluster layout with updated role assignment has been applied in cluster.
Data will now be moved around between nodes accordingly.

Create Bucket

Create bucket, which is the place where our image files will live:

Terminal window
docker exec -it garage_s3 /garage bucket create app-uploads
Note

You should get the output: Bucket app-uploads was created.

Add the bucket name to the .env file:

S3_BUCKET=app-uploads

Create Key

Let’s create the key that we’ll use to access the bucket we just created:

Terminal window
docker exec -it garage_s3 /garage key create next-demo-local

Which should output the keys:

Key name: next-demo-local
Key ID: GKbccef323a6f4dedd82f85d59
Secret key: 5ed99b90d1f7f0bd766755cfc3a9daad89ed747fb058dd66c502e544a3ed8f3c
Can create buckets: false
Key-specific bucket aliases:
Authorized buckets:

And paste these values in our .env file:

S3_ACCESS_KEY=GKbccef323a6f4dedd82f85d59
S3_SECRET_KEY=5ed99b90d1f7f0bd766755cfc3a9daad89ed747fb058dd66c502e544a3ed8f3c

Associate Key and Bucket

We need to grant the key access to the bucket:

Terminal window
docker exec -it garage_s3 /garage bucket allow --read --write --owner app-uploads --key next-demo-local

The command above should output something like:

New permissions for GKbccef323a6f4dedd82f85d59 on app-uploads: read true, write true, owner true.

It’s a good idea to verify with this:

Terminal window
docker exec -it garage_s3 /garage key info next-demo-local

Which should output:

Key name: next-demo-local
Key ID: GKbccef323a6f4dedd82f85d59
Secret key: (redacted)
Can create buckets: false
Key-specific bucket aliases:
Authorized buckets:
RWO app-uploads dfc275695b62a17e
Note

Note that Can create buckets is false, which means that this key cannot create new buckets, but it can still fully use the buckets explicitly granted to it, in this case app-uploads

Serving Files

Garage in this setup does not allow anonymous object reads, so a raw object URL like http://localhost:3900/app-uploads/events/... cannot be rendered directly in the browser.

Note

Whas is an Anonymous Object Read

Imagine you paste http://localhost:3900/app-uploads/events/a.png in browser:

  • Browser sends no S3 auth key/signature.
  • If storage still returns file, that’s an anonymous read. In our setup, Garage rejects that (AccessDenied), so objects are private by default. That’s why our app has to fetch files with credentials server-side (or use signed URLs).

To solve this, we expose a Next.js route handler at app/api/files/[...key]/route.ts. How it works:

  1. The events API returns Mongo data and sets image to a local app URL (for example: /api/files/events/my-image.png).
  2. The browser requests that local URL.
  3. The file route reconstructs the object key from the path (events/my-image.png).
  4. The route fetches the object from Garage using server-side credentials (s3Client + GetObjectCommand).
  5. The route streams bytes back with Content-Type, so the browser can display the image normally.

Why we need it:

  • Keeps Garage bucket private (no anonymous public reads).
  • Browser never needs storage credentials.
  • Works the same way in dev and prod: app API mediates access to object storage.
Featured projects all 4 →