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

My last few [posts](https://zyvop.com/what-i-monitor-on-zyvop-com-and-the-alerts-worth-waking-up-for-17wfz) 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

![Mermaid Diagram](https://mermaid.ink/img/pako:eNqFUltv2jAU_itn5ylIjhQuWwsPk2CspRJQBBovMQ8mOSTWHDuyTVtW8d8nk5RN7GEvluzvdvzZ75iZnHCEB2Ves1JYD_M11wAA2yjdSie9sW7XgTgGjvcJg8GgzxHi-CvMJ-nciBz2Qgmdkd01uvmkIfeTJGmZ49Vqw3UDP85Sjo_Sz457GGdeGu047hqJcyWDg7EZ5ZCZqhI6bx2mQTWlWpkTlMZ5jm3adPY_aQhPOY7rGhzZF7IOord-5x-Hz4N-j0ElCysuU4HR6vQRP0mjlXG-sOQ6rS74_lFeibfgl_7dsAXX0zRaUy4vFg1v8T1KOS4IIpFXUsPTCoyF7WoZ5utcr3Zt4UN1izQN32Dgj1qTaimL52WIMjo8qdRF28a1h8XzslEOu0nCYNhNemG9vwtrr_tXEDKsyFZC5jh6R19SFX5QTgdxVB5Zc7IVVoq9Ihc4B6P9g6ikOuEIY1HXimJ3cp4qBhMl9c-FyDaX_YPRngHHDRWG4McTRwZrszfeMJiReiEvM8FgbKVQDJzQLnZk5QHZJWQjf4VZuoP6Dc9nhvvim1HG4gg_vZbSE55_A-7V3CE?type=png)

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:

```text
# /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:

```bash
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:

```bash
#!/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

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

```text
# 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:

```bash
#!/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:

```bash
# 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.**
    
    ```yaml
    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

```bash
#!/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:

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

```toml
# /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:

```sql
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:

```bash
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:

```yaml
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:

```javascript
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

```bash
#!/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.

![Mermaid Diagram](https://mermaid.ink/img/pako:eNpNkV1r2zAUhv_K6bnaQPbo1t2E0pGPhg66DhLaMaxeKPZxLCLrGOkkbhby34fl0O1SBz3P--rohCVXhBOsHfdlY4LA40p7AIBpofE6h2lVgTQET_e_IFIZSG434dPdh2HGrgL2BFGsc9Bz2MWPGl8hy-5gVmj8nMO6sR3YC1NR5_gIHGDfVUYoiaNwoAEbY2eJnp80fslhwRSBDhSO0li_TRFJ1VtpEu2pHyp803ge-TlkGTxxsqwKjUv7BlbUEBqo5QO9v4Y9jbU8X-wmguMo_8ok2W-KybYoNN7ksKID70bLz8fFZSfvxCJdvS80fs1hzr62oYX_d2UjBKr3kSqNr6iwpdAaW-HkhNJQO_xFRbXZO0E1Tl5MsGbjKA53avayNK11R5xgZrrOURaPUahVMHPW736Ycp3OS_aiQOOatkzw_F2jghVvWFjBA7kDiS2NgmmwximIxscsUrA1qhSytn-GLtc33Ruezwo32zk7DjjBq76xQnj-CyUIt1Y?type=png)

| 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

```bash
# 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.

```javascript
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:

```sql
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- &lt;each public IP&gt; 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._

---

*Published via [ZyVOP](https://zyvop.com/hardening-zyvop-com-s-deploy-path-ssh-keys-firewalls-fail2ban-and-secrets-i-can-rotate-9ew5u?utm_source=hashnode&utm_medium=crosspost&utm_campaign=syndication) — Write once in Markdown, auto-backup to GitHub, and syndicate to Dev.to, Medium & Hashnode in 1 click.*
