Hardening zyvop.com's Deploy Path: SSH Keys, Firewalls, fail2ban, and Secrets I Can Rotate

How I lock down the path from GitHub to production: key-only SSH, forced commands, firewalls that account for Docker, fail2ban, and secrets with a rotation plan.

15 min read
AI-assisted

AI tooling disclosure

Generative AI materially contributed to this article.

Human review confirmed by the author.

Hardening zyvop.com's Deploy Path: SSH Keys, Firewalls, fail2ban, and Secrets I Can Rotate

My last few posts built a pipeline that can change production on its own: GitHub Actions connects to a deploy host, which connects to every app server. That's convenient, and it also makes the pipeline the most powerful door into zyvop.com. This post is about making that door hard to open, and making sure that if a key or secret leaks anyway, the damage is small and fixable.

I'm protecting against five things:

  1. Internet scanners guessing SSH passwords all day.

  2. A leaked CI key. What can an attacker do with it?

  3. A compromised app server. How far can they get from there?

  4. A secret that ends up in git, a log, or a chat message.

  5. Stale credentials that nobody remembers to retire.

TL;DR

  • SSH: keys only, verified with sshd -T, and each hop of the deploy path uses its own key restricted to one forced command.

  • Firewalls: default deny on every host. Docker bypasses ufw for published ports, so I bind those to private addresses and enforce sources at the cloud firewall.

  • fail2ban: useful for noise and defense in depth, but key-only SSH is what actually keeps people out.

  • Secrets: a documented home for each one, least-privilege database roles, files instead of environment variables, and an overlap-based rotation procedure.

All IPs below are placeholders, like in my earlier posts.


The path I'm protecting

flowchart LR
    V([Visitors]) -- "80, 443" --> LB[Load balancer]
    LB -- "3000" --> APPS

    GH["GitHub Actions"] -- "ssh, forced command" --> DH["Deploy host"]
    DH -- "ssh, forced command" --> APPS["App servers (x3)"]
    DH -- "5432, migrations only" --> DB[(Postgres)]
    APPS -- "5432" --> DB
    APPS -- "6379" --> RD[(Redis)]

    ME(["Me (admin IP or VPN)"]) -- "ssh" --> DH
    ME -- "ssh" --> APPS
    ME -- "ssh tunnel" --> MON["Monitoring server"]
    MON -- "9100, 9102, 9187, 9121" --> APPS

Everything not drawn is blocked. Here's the same thing as a rule list, with who enforces each rule:

Host

Port

Allowed sources

Enforced by

Load balancer

80, 443

Anyone

Cloud firewall and ufw

App server

3000 (published by Docker)

Load balancer only

Cloud firewall, plus a private-IP bind

App server

9102 (published by Docker)

Monitoring server only

Cloud firewall, plus a private-IP bind

App server

9100 (node_exporter on the host)

Monitoring server

ufw

App server

22

Deploy host and my admin IP

ufw, plus from= on the key

Deploy host

22

Anyone, rate-limited (GitHub runner IPs vary)

ufw limit, key-only auth, fail2ban

Postgres

5432

App servers and the deploy host

Cloud firewall or ufw

Redis

6379

App servers

Cloud firewall or ufw

Exporters

9187, 9121

Monitoring server

ufw

Monitoring UIs

9090, 9093, 3000

Nobody on the network (SSH tunnel only)

Bound to 127.0.0.1


Step 1: SSH, keys only

1a. Turn off passwords, and make sure it actually took

I put my settings in a drop-in file:

# /etc/ssh/sshd_config.d/00-hardening.conf
PasswordAuthentication no
KbdInteractiveAuthentication no
PermitRootLogin no
PubkeyAuthentication yes
AuthenticationMethods publickey
AllowUsers admin deploy
MaxAuthTries 3
LoginGraceTime 20
X11Forwarding no
AllowAgentForwarding no
AllowTcpForwarding no

The file name matters. For each setting, sshd keeps the first value it reads, and on Debian and Ubuntu the sshd_config.d/*.conf files are included at the top of sshd_config, in alphabetical order. Ubuntu cloud images and servers installed from the ISO can ship a 50-cloud-init.conf containing PasswordAuthentication yes. A hardening file named 99-hardening.conf would silently lose to it, and so would the setting I edit in the main file. 00- sorts first, so mine wins.

Debian also turns X11Forwarding on by default, which is why I switch it off explicitly. On the monitoring server I use AllowTcpForwarding local instead of no, because that's how I reach Grafana through an SSH tunnel.

I apply it carefully, so I can't lock myself out:

sudo sshd -t                  # syntax check: prints nothing when the config is valid
sudo systemctl reload ssh     # the service is called "ssh" on Debian and Ubuntu

Before closing my current session, I open a second one and confirm I can log in. Then I check what sshd is actually using, not what I think I told it:

#!/usr/bin/env bash
# check-ssh-hardening.sh: compare sshd's EFFECTIVE config with what I expect
set -euo pipefail

declare -A want=(
  [passwordauthentication]=no
  [kbdinteractiveauthentication]=no
  [permitrootlogin]=no
  [pubkeyauthentication]=yes
  [authenticationmethods]=publickey
  [x11forwarding]=no
  [allowagentforwarding]=no
  [allowtcpforwarding]=no
  [maxauthtries]=3
  [logingracetime]=20
)

effective="$(sudo sshd -T)"
status=0
for key in "${!want[@]}"; do
  got="$(awk -v k="$key" '$1 == k { print $2; exit }' <<< "$effective")"
  if [[ "$got" == "${want[$key]}" ]]; then
    echo "ok    $key = $got"
  else
    echo "FAIL  $key = ${got:-<unset>} (want ${want[$key]})"
    status=1
  fi
done
exit "$status"

sshd -T prints the effective configuration, so if a stray file overrides me, this script says so. I run it after every SSH change, and as part of my monitoring checks.

1b. People: one key per device, with a passphrase

ssh-keygen -t ed25519 -a 100 -C "me@laptop-2026"

ed25519 keys are short and fast, and -a 100 makes a stolen key file slower to crack. The comment names the owner and device, so I can tell whose key is whose in authorized_keys, and I remove a key when a device is lost or retired.

1c. The deploy path: two hops, two keys, each restricted to one command

In my CI/CD post, the CI key can only run a forced command on the deploy host. The second hop, from the deploy host to the app servers, deserves the same treatment. Otherwise a compromised deploy host could do anything on every app server.

# deploy host, ~deploy/.ssh/authorized_keys: the CI key from my CI/CD post
restrict,command="/srv/zyvop/ci-entry.sh" ssh-ed25519 AAAA...ci-key... github-actions-deploy

# each app server, ~deploy/.ssh/authorized_keys: the deploy host's key
restrict,from="10.0.1.6",command="/srv/zyvop/app-entry.sh" ssh-ed25519 AAAA...deploy-host-key... deploy-host-to-apps

restrict turns off forwarding and terminal allocation, command= forces one script no matter what the client asks for, and from= means the key only works from the deploy host's address. The CI key can't use from=, because GitHub's runner addresses change.

The app server's script validates its input the same way the deploy host's does:

#!/usr/bin/env bash
# /srv/zyvop/app-entry.sh: the only thing the deploy host's key may run on an app server
set -euo pipefail

cmd="${SSH_ORIGINAL_COMMAND:-}"
if [[ "$cmd" == *$'\n'* ]]; then
  echo "unexpected input" >&2
  exit 2
fi

read -r action version extra <<< "$cmd"
action="${action:-}"
version="${version:-}"
extra="${extra:-}"

if [[ -n "$extra" || "$action" != "up" || ! "$version" =~ ^[0-9a-f]{40}$ ]]; then
  echo "not allowed" >&2
  exit 2
fi

export APP_VERSION="$version"
exec docker compose -f /srv/zyvop/compose.yml up -d --pull always

Then one line changes in deploy-rolling.sh from my zero-downtime post. The deploy host no longer sends a raw docker compose command, it just asks for a version:

# before
ssh "$host" "APP_VERSION=$VERSION docker compose -f /srv/zyvop/compose.yml up -d --pull always"

# after
ssh "$host" "up $VERSION"

lb.sh gets the same treatment: its key on the load balancer is limited to a script that only accepts drain and enable for a known server.

A few details about the deploy account:

  • Create it without a password: sudo adduser --disabled-password --gecos "" deploy.

  • Give it a real shell. sshd runs a forced command through the account's shell, so nologin would break it. The restrictions come from the key, not the shell.

  • No sudo. But the account has to run Docker, and membership of the docker group is root-equivalent. The forced commands are what keep that power on a leash, and rootless Docker is the stronger option if I want to go further.

  • Pin the app servers' host keys in the deploy host's known_hosts, the same way I pinned the deploy host's key in GitHub.


Step 2: Firewalls, and the Docker catch

My rule on every host is default deny incoming, then open only what that host's job needs.

The catch

Docker publishes container ports by rewriting packets in the nat table, before they reach the INPUT chain where ufw's rules live. So a port Docker publishes is reachable no matter what ufw says. Docker's own documentation says so. A ufw deny 3000 looks like protection and does nothing.

My app container publishes ports 3000 (traffic) and 9102 (metrics). Three layers handle that:

  1. Publish on a specific private address, never on all interfaces.

    services:
      app:
        image: ghcr.io/your-github-username/zyvop:${APP_VERSION}
        ports:
          - "10.0.1.11:3000:3000"   # reachable from the private network only
          - "10.0.1.11:9102:9102"   # metrics, scraped by the monitoring server
  2. Restrict who can reach those ports at the cloud provider's firewall (security groups or similar). That filter sits outside the server, so Docker can't bypass it. Port 3000 accepts the load balancer only, and 9102 accepts the monitoring server only.

  3. If I ever need source filtering on the host itself, Docker provides the DOCKER-USER chain for exactly that. Packets there have already been NAT'd, so rules match the container's port, not the published one. I'd follow Docker's firewall documentation and not improvise.

I also run node_exporter as a systemd service on the host, not in Docker, so ufw really does protect port 9100.

The app-server firewall

#!/usr/bin/env bash
# firewall-app.sh: host firewall for an app server. Run as root, with a second SSH session open.
set -euo pipefail

ADMIN_IP="203.0.113.10"        # my home or VPN address (placeholder)
DEPLOY_HOST_IP="10.0.1.6"
MONITOR_IP="10.0.1.20"

ufw default deny incoming
ufw default allow outgoing

# SSH rules go in BEFORE enabling: turning the firewall on can drop existing connections
ufw allow proto tcp from "$ADMIN_IP"       to any port 22
ufw allow proto tcp from "$DEPLOY_HOST_IP" to any port 22

# node_exporter runs on the host, so ufw sees this traffic
ufw allow proto tcp from "$MONITOR_IP" to any port 9100

ufw --force enable
ufw status verbose

Two details:

  • No ufw rules for 3000 and 9102. They'd have no effect, and a rule that does nothing is worse than no rule, because it makes me think I'm covered.

  • IPv6: ufw only filters IPv6 if IPV6=yes is set in /etc/default/ufw. I check that, and make sure the cloud firewall covers IPv6 as well.

The deploy host is the exception

GitHub-hosted runners connect from addresses I can't list, so port 22 on the deploy host has to accept connections from anywhere. I make that as safe as I can:

ufw limit 22/tcp comment 'CI and admin SSH'

limit allows connections but denies an address that attempts 6 or more in 30 seconds. Combined with key-only authentication, a forced command, and fail2ban, the exposed surface is small. If it still bothers me, I move to a self-hosted runner inside the private network and close port 22 to the internet entirely.


Step 3: fail2ban

I'm honest about what fail2ban does here. With passwords disabled, a brute-force attacker cannot get in, so it isn't what keeps people out. What it does is cut log noise and CPU load, and drop scanners after a few failed tries. It also protects other services later, like anything behind HTTP auth.

# /etc/fail2ban/jail.d/sshd.local
[DEFAULT]
ignoreip = 127.0.0.1/8 ::1 10.0.1.0/24 203.0.113.10
bantime  = 1h
findtime = 10m
maxretry = 5
bantime.increment = true
banaction = ufw

[sshd]
enabled = true
  • ignoreip keeps me, the private network, and the deploy host from being banned by accident.

  • bantime.increment doubles the ban for repeat offenders.

  • banaction = ufw makes bans go through ufw, so the two tools agree.

  • .local files override .conf files, and later files win. That's the opposite of sshd, where the first value wins, so I keep both rules straight.

  • I leave the log path and backend alone, so the distribution's defaults apply.

I don't trust it until I've seen it work. From another machine, I make six failed logins (ssh -o PubkeyAuthentication=no admin@host), then run sudo fail2ban-client status sshd to see the ban, and sudo fail2ban-client set sshd unbanip <address> to lift it.

One more caveat: if I ever misconfigure the CI key, the failed attempts from GitHub's runner address can get that address banned for an hour. If deploys suddenly time out after a key change, fail2ban-client status sshd is the first place I look.


Step 4: Where secrets live

A secret I can't locate is a secret I can't rotate. This is my inventory:

Secret

Lives in

Who can read it

CI deploy key (private half)

GitHub production environment secret

Jobs on main after approval

CI deploy key (public half)

Deploy host authorized_keys, forced command

Nobody needs to, it's public

Deploy host to app servers key

~deploy/.ssh/id_ed25519 on the deploy host, mode 0600

The deploy user on that host

Registry read token

~deploy/.docker/config.json on each server, mode 0600

The deploy user

App runtime secrets

/srv/zyvop/app.env on app servers, root:deploy, mode 0640

root and deploy

Migration database login

/srv/zyvop/migrate.env on the deploy host, root:deploy, mode 0640

root and deploy

Alert webhook URLs

The monitoring server's alertmanager.yml

Root and the Alertmanager user

And where they must never be: in git, in an image layer or build argument, in CI logs, or in a chat message. Secrets pasted into any of those should be treated as leaked.

Give the app and the migrations different database logins

The app doesn't need permission to drop tables, and migrations do. So they use different roles, and a compromised app server can't change the schema:

CREATE ROLE zyvop_app NOLOGIN;                                    -- holds the app's privileges
CREATE ROLE zyvop_app_a LOGIN PASSWORD '...' IN ROLE zyvop_app;   -- a login that inherits them
CREATE ROLE zyvop_migrate LOGIN PASSWORD '...';                   -- owns the tables, runs migrations

ALTER DEFAULT PRIVILEGES FOR ROLE zyvop_migrate IN SCHEMA public
  GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO zyvop_app;
ALTER DEFAULT PRIVILEGES FOR ROLE zyvop_migrate IN SCHEMA public
  GRANT USAGE, SELECT ON SEQUENCES TO zyvop_app;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO zyvop_app;
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO zyvop_app;

The tables need to be owned by zyvop_migrate for that to hold, so I reassign existing ones with ALTER TABLE ... OWNER TO zyvop_migrate. The app servers get zyvop_app_a's password in app.env, and migrate.sh from my CI/CD post changes one flag so it uses the migration login:

docker run --rm --env-file /srv/zyvop/migrate.env \

The _a suffix is deliberate. It sets up zero-downtime password rotation, which I explain in the next step.

Files, not environment variables

Docker's documentation points out that environment variables are visible to every process in the container and can easily end up in logs. They also appear in docker inspect for anyone with Docker access. Compose can mount a secret as a file under /run/secrets/ instead:

services:
  app:
    environment:
      DATABASE_PASSWORD_FILE: /run/secrets/db_password
    secrets:
      - db_password

secrets:
  db_password:
    file: /srv/zyvop/secrets/db_password

The _FILE suffix is only a convention. Some official images understand it, but my app has to read it itself:

import { readFileSync } from "node:fs";

export function secret(name) {
  const file = process.env[`${name}_FILE`];
  if (file) return readFileSync(file, "utf8").trim();
  const value = process.env[name];
  if (value) return value;
  throw new Error(`Missing secret: set ${name}_FILE or ${name}`);
}

It accepts either form, so I can migrate secrets one at a time. The container's user has to be able to read the mounted file, and I confirm that with docker compose exec app cat /run/secrets/db_password after the first deploy.

Auditing permissions

#!/usr/bin/env bash
# audit-secrets.sh: flag secret files with the wrong owner or permissions
set -uo pipefail
ROOT="${ROOT:-}"      # empty on a real server
status=0

check() {   # path, expected mode, expected owner:group
  local path="$ROOT$1" mode="$2" owner="$3" got_mode got_owner
  if [[ ! -e "$path" ]]; then echo "skip  $1 (not present)"; return; fi
  got_mode="$(stat -c '%a' "$path")"
  got_owner="$(stat -c '%U:%G' "$path")"
  if [[ "$got_mode" == "$mode" && "$got_owner" == "$owner" ]]; then
    echo "ok    $1 ($got_mode $got_owner)"
  else
    echo "FAIL  $1 is $got_mode $got_owner, want $mode $owner"
    status=1
  fi
}

check /srv/zyvop/app.env                 640 root:deploy
check /srv/zyvop/migrate.env             640 root:deploy
check /home/deploy/.ssh                  700 deploy:deploy
check /home/deploy/.ssh/authorized_keys  600 deploy:deploy
check /home/deploy/.ssh/id_ed25519       600 deploy:deploy
check /home/deploy/.docker/config.json   600 deploy:deploy
exit "$status"

I also turn on secret scanning for the repository where my plan allows it, and run a scanner such as gitleaks as a pre-commit hook, so a secret gets caught before it's pushed, not after.


Step 5: Rotating secrets without breaking anything

The rule I follow is overlap. At every point, the old and new secrets are both valid, and I only revoke the old one after the new one is proven.

flowchart LR
    A["1. Add the NEW secret<br/>(the old one still works)"] --> B["2. Ship it<br/>(deploy or update the store)"]
    B --> C{"3. Does everything work<br/>with the new one?"}
    C -- No --> R["Fix it, or remove the NEW one<br/>(nothing was lost)"]
    C -- Yes --> D["4. Revoke the OLD secret"]
    D --> E["5. Confirm the old one is refused"]

Secret

How the overlap works

My starting cadence

CI deploy SSH key

authorized_keys can hold both keys at once

Every 90 days

Deploy host to apps key

Same: both public keys in each app server's file

Every 90 days

Registry read token

Create the new token, docker login on each server, then revoke the old one

Every 90 days

Session secret

An array of secrets, newest first (below)

Every 6 to 12 months

JWT signing key

Publish both verification keys with key IDs, sign with the new one, drop the old after tokens expire

Every 6 to 12 months

Database login

Two interchangeable logins on one privilege role

Every 6 months

Webhook URLs and API keys

Regenerate at the provider, update the config, reload

When leaked, or yearly

The cadences are my starting points, not standards. The real triggers are a suspected leak, a lost device, or someone leaving.

Rotating the CI key

# 1. New key pair on my machine. No passphrase: only CI uses it, and a forced command limits it.
ssh-keygen -t ed25519 -N "" -C "github-actions-deploy-2027-01" -f ./ci-key-new

# 2. On the deploy host: add the NEW public key to authorized_keys, with the same options line,
#    next to the old one. Both work during the overlap.

# 3. Point GitHub at the new private key (environment secret)
gh secret set DEPLOY_SSH_KEY --env production < ./ci-key-new

# 4. Run a deploy (or the rollback workflow) and confirm it succeeds.

# 5. Remove the OLD line from authorized_keys, then confirm the old key is refused.

# 6. Delete the local copy
rm ./ci-key-new ./ci-key-new.pub

gh encrypts the value locally before sending it to GitHub. The new key is the one that gets registered at step 3, so nothing breaks if I need to stop after step 2.

Rotating the session secret with zero logouts

Back in my scaling post, the session secret was a single value. Changing it logs everyone out. The express-session docs describe the fix: pass an array, where only the first element signs new cookies, and all of them verify existing ones.

import { secret } from "./secret.js";

// SESSION_SECRETS="newest,previous": comma-separated, newest first
const sessionSecrets = secret("SESSION_SECRETS")
  .split(",")
  .map((s) => s.trim())
  .filter(Boolean);

app.use(session({ secret: sessionSecrets, /* ...the rest as before... */ }));

To rotate: put the new secret first, keep the old one second, deploy, and drop the old one only after the longest session lifetime (my cookie's maxAge) has passed.

Rotating the database login

This is where the _a login pays off. I create a second login on the same privilege role, point the app at it, and retire the first:

CREATE ROLE zyvop_app_b LOGIN PASSWORD '...' IN ROLE zyvop_app;
-- update app.env with zyvop_app_b's credentials, roll the deploy, then:
ALTER ROLE zyvop_app_a NOLOGIN;

I never change the password of the login that's currently in use, because during a rolling deploy some servers would still hold the old password and start failing their next connection.

When I suspect a leak

The overlap rule bends for emergencies: revoke first, then replace. A short disruption is better than a leaked credential staying valid. I revoke the exposed secret, issue a new one, deploy, and then check the logs for anything the old one did.


Verify from the outside

Hardening isn't done until I've tested it the way an attacker would:

Check

Expected result

nmap -Pn -p- <each public IP> from outside my network

Only 80 and 443 on the load balancer, and 22 on the deploy host

ssh -o PubkeyAuthentication=no admin@host

Permission denied (publickey)

The CI key running something other than a deploy

not allowed

./check-ssh-hardening.sh on every server

Every line says ok

sudo ufw status verbose

Default deny incoming, and only the rules I wrote

sudo fail2ban-client status sshd

The jail is running

./audit-secrets.sh

Every line says ok or skip

docker compose ps on an app server

Ports bound to 10.0.1.x, never 0.0.0.0

The external scan matters most, because Docker, ufw, and the cloud firewall all affect the result, and only a test from outside accounts for all three.


Mistakes I'm trying not to make

  1. Naming the SSH drop-in 99-something, so a cloud-init file wins.

  2. Trusting ufw status for Docker ports. It doesn't see them.

  3. Enabling the firewall before the SSH rule, and locking myself out.

  4. Closing my only SSH session before testing a second one.

  5. Using the same key for CI and for the deploy host.

  6. Putting secrets in environment variables, git, or image layers.

  7. Rotating by replacing. Revoking the old secret before the new one is proven causes outages.

  8. Never practicing a rotation, so the first time is an emergency.

  9. Giving the app a database login that can drop tables.

  10. Hardening once and never checking again. Drift happens, so the check scripts run on a schedule.


My hardening checklist

  • 00-hardening.conf sets key-only SSH, and sshd -T confirms the effective values

  • No root login, AllowUsers set, forwarding off (except where I need tunnels)

  • One passphrase-protected key per person and device, with a labelled comment

  • CI key restricted by restrict and a forced command that validates its input

  • Deploy host to app servers key restricted by restrict, from=, and its own forced command

  • deploy account has no password, no sudo, and a real shell

  • Default deny incoming on every host, with SSH rules added before enable

  • Docker ports published on private addresses, with sources restricted at the cloud firewall

  • ufw limit on the deploy host's public SSH port

  • fail2ban running, my IPs in ignoreip, and a ban actually tested

  • Every secret has a documented home, and none live in git, images, or logs

  • The app and migrations use separate database roles

  • Secrets read from files where the app supports it

  • Rotation procedure written down and practiced for each secret

  • External port scan run, and audit-secrets.sh and check-ssh-hardening.sh passing


Final thoughts

Hardening is mostly about limiting what each credential can do and knowing where it lives. A leaked CI key can run one validated command, not a shell. A compromised app server can't change the schema. A rotated secret doesn't cause an outage. None of that stops every attack, but together they turn a catastrophic breach into a contained one, and a 3 a.m. emergency into a procedure I've already practiced.

What's still missing is the thing that makes all of this recoverable when it goes wrong: backups I've actually restored. That's the next post.

What's the most surprising thing you've found exposed on one of your own servers? Tell me in the comments and I'll cover it in a follow-up.

Comments0

Join the discussion by logging into your account.

No comments yet. Start the conversation.

Sanju Singh

Passionate developer sharing knowledge about modern web technologies and best practices.

Subscribe to Sanju Singh's Newsletter

Direct email dispatches when new stories are published. Zero algorithms.