TExcelTAD
Home › Linux Server Administration › Mini Project: Harden a Server & Front an App with TLS

Mini Project: Harden a Server & Front an App with TLS

Time to put the course together. You get a fresh Ubuntu 24.04 server and a small HTTP app. The goal: an app that runs as a sandboxed systemd service, reachable only through an HTTPS reverse proxy, on a server where SSH accepts keys only, root can't log in, the firewall opens only what is needed, password guessers get banned, logs rotate and certificates are watched.

The plan

# Step Lessons
1 Admin account, SSH keys, hardened sshd, narrow sudo SSH Keys, Hardening the SSH Server, sudo & sudoers
2 Firewall: SSH from the admin network, 80 and 443 from anywhere nftables, ufw & firewalld
3 Automatic security updates Patching & Unattended Upgrades
4 The app as a sandboxed, resource-limited service on localhost Writing a Service Unit, Sandboxing, cgroups v2
5 Nginx: HTTP→HTTPS redirect, TLS, proxy headers, HSTS Nginx as a Reverse Proxy, Terminating TLS
6 Certificates: ACME in production, a private CA here; expiry check ACME, Renewal & Expiry Monitoring
7 fail2ban for SSH and the app's login, log rotation fail2ban, logrotate
8 Verify from outside Listening Sockets, Debugging HTTP

Part 1: the root-only steps (on your practice VM)

These need root and a booted systemd, so they are a sample session. Run them on a practice VM, with a second SSH session open the whole time:

bash
# as the initial cloud user (ubuntu), from your workstation's key
$ sudo adduser --disabled-password --gecos "" ada
$ sudo groupadd ssh-users && sudo usermod -aG sudo,ssh-users ada
$ sudo install -d -m 700 -o ada -g ada /home/ada/.ssh
$ echo "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIK0x... ada@laptop" | sudo tee /home/ada/.ssh/authorized_keys
$ sudo chown ada:ada /home/ada/.ssh/authorized_keys && sudo chmod 600 /home/ada/.ssh/authorized_keys
$ sudo usermod -aG ssh-users ubuntu                       # keep the current login working until ada is tested
# step 1: install the validated files from Part 2
$ sudo install -m 600 server/sshd_config.d/10-hardening.conf /etc/ssh/sshd_config.d/
$ sudo sshd -t && sudo systemctl reload ssh
$ ssh ada@web1 sudo -v                                    # from the workstation, in a NEW terminal
# step 2: firewall
$ sudo ufw default deny incoming && sudo ufw default allow outgoing
$ sudo ufw limit from 198.51.100.0/24 to any port 22 proto tcp comment 'admin ssh'
$ sudo ufw allow 80,443/tcp
$ sudo ufw enable
# step 3: updates
$ sudo apt install -y unattended-upgrades needrestart nginx fail2ban
$ sudo dpkg-reconfigure -f noninteractive unattended-upgrades
# steps 4-7: install the files from Part 2, then
$ sudo systemctl daemon-reload && sudo systemctl enable --now notes.service
$ sudo nginx -t && sudo systemctl reload nginx
$ sudo fail2ban-client -t && sudo systemctl enable --now fail2ban

In production, step 6 is certbot certonly --webroot -w /var/www/acme -d notes.example.com with a deploy hook that reloads Nginx, instead of the private CA used in Part 2.

Part 2: build and validate every file

Everything that can be checked without root is checked here, in one session, exactly as a CI job for your server configuration repository would do it. It writes the files into server/, validates each with its own tool, then runs the app and Nginx locally (on ports 8080/8443 instead of 80/443) and tests the result from the outside like a client:

bash · try it yourself
set -u
mkdir -p server/{sshd_config.d,sudoers.d,systemd,nginx,fail2ban,logrotate.d,tls} app && cd server
ok() { echo "PASS $1"; }; bad() { echo "FAIL $1"; }

# --- 1. SSH and sudo -------------------------------------------------------------
ssh-keygen -q -t ed25519 -N "" -f tls/hostkey
cat > sshd_config.d/10-hardening.conf <<'EOF'
PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no
AuthenticationMethods publickey
AllowGroups ssh-users
MaxAuthTries 3
LoginGraceTime 20
X11Forwarding no
AllowAgentForwarding no
AllowTcpForwarding no
EOF
echo "PasswordAuthentication yes" > sshd_config.d/50-cloud-init.conf      # what the cloud image ships
printf 'Include %s/sshd_config.d/*.conf\nHostKey %s/tls/hostkey\nPidFile %s/sshd.pid\n' "$PWD" "$PWD" "$PWD" > sshd_config
sshd -t -f sshd_config && ok "sshd syntax"
[ "$(sshd -T -f sshd_config | grep -cE '^(permitrootlogin no|passwordauthentication no|kbdinteractiveauthentication no|allowgroups ssh-users)
  

)" = 4 ] \
  && ok "sshd effective policy" || bad "sshd effective policy"
echo 'deploy ALL=(root) NOPASSWD: /usr/bin/systemctl restart notes.service' > sudoers.d/60-deploy
visudo -c -s -q -f sudoers.d/60-deploy && ok "sudoers"

# --- 4. the app as a sandboxed service --------------------------------------------
cat > systemd/notes.service <<'EOF'
[Unit]
Description=Notes app
After=network.target

[Service]
Type=exec
ExecStart=/usr/bin/python3 -m http.server 9000 --bind 127.0.0.1 --directory /usr/share/doc
DynamicUser=yes
Restart=on-failure
RestartSec=2s
MemoryMax=256M
CPUQuota=100%
TasksMax=64
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
PrivateDevices=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectControlGroups=yes
RestrictNamespaces=yes
RestrictAddressFamilies=AF_INET AF_INET6
CapabilityBoundingSet=
SystemCallFilter=@system-service
UMask=0077

[Install]
WantedBy=multi-user.target
EOF
[ -z "$(systemd-analyze verify systemd/notes.service 2>&1)" ] && ok "unit file"
systemd-analyze security --offline=true --threshold=30 systemd/notes.service > /dev/null && ok "unit exposure <= 3.0"

# --- 6. certificates (a private CA here; ACME in production) -----------------------
openssl req -x509 -new -noenc -newkey ec -pkeyopt ec_paramgen_curve:P-256 -keyout tls/ca.key -out tls/ca.crt -days 365 -subj "/CN=Lab CA" 2>/dev/null
openssl req -new -noenc -newkey ec -pkeyopt ec_paramgen_curve:P-256 -keyout tls/notes.key -subj "/CN=notes.example.test" 2>/dev/null |
  openssl x509 -req -CA tls/ca.crt -CAkey tls/ca.key -set_serial 100 -days 90 -out tls/notes.crt \
    -extfile <(printf 'subjectAltName=DNS:notes.example.test\nextendedKeyUsage=serverAuth\nbasicConstraints=critical,CA:FALSE\n') 2>/dev/null
openssl verify -CAfile tls/ca.crt tls/notes.crt > /dev/null && ok "certificate chain"
openssl x509 -in tls/notes.crt -noout -checkend $((30 * 86400)) > /dev/null && ok "certificate valid for 30+ days"

# --- 5. nginx: redirect, TLS, headers ---------------------------------------------
cat > nginx/nginx.conf <<EOF
pid $PWD/nginx.pid;
error_log $PWD/nginx-error.log;
events {}
http {
  access_log off;
  server_tokens off;
  server {
    listen 127.0.0.1:8080;
    server_name notes.example.test;
    location /.well-known/acme-challenge/ { root $PWD/acme; }
    location / { return 301 https://\$host:8443\$request_uri; }
  }
  server {
    listen 127.0.0.1:8443 ssl;
    server_name notes.example.test;
    ssl_certificate     $PWD/tls/notes.crt;
    ssl_certificate_key $PWD/tls/notes.key;
    ssl_protocols       TLSv1.2 TLSv1.3;
    add_header Strict-Transport-Security "max-age=31536000" always;
    add_header X-Content-Type-Options nosniff always;
    client_max_body_size 2m;
    location / {
      proxy_pass http://127.0.0.1:9000;
      proxy_set_header Host \$host;
      proxy_set_header X-Real-IP \$remote_addr;
      proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto https;
    }
  }
}
EOF
nginx -t -c "$PWD/nginx/nginx.conf" -e stderr 2>/dev/null && ok "nginx config"

# --- 7. fail2ban filter and log rotation -------------------------------------------
printf 'Jan 15 10:00:01 web1 sshd[1201]: Failed password for invalid user admin from 203.0.113.7 port 50122 ssh2\nJan 15 10:00:09 web1 sshd[1210]: Accepted publickey for ada from 198.51.100.4 port 51000 ssh2: ED25519 SHA256:k\n' > auth.sample
fail2ban-regex auth.sample sshd | grep -q '1 matched' && ok "fail2ban sshd filter"
mkdir -p logs && echo "x" > logs/access.log
printf '%s/logs/*.log {\n  daily\n  rotate 14\n  compress\n  delaycompress\n  missingok\n  notifempty\n  create 0640\n}\n' "$PWD" > logrotate.d/nginx
logrotate -d -s state logrotate.d/nginx > /dev/null 2>&1 && ok "logrotate config"

# --- 8. run it and test like a client ------------------------------------------------
mkdir -p acme/.well-known/acme-challenge && echo "token.thumb" > acme/.well-known/acme-challenge/token
python3 -m http.server 9000 --bind 127.0.0.1 --directory ../app > app.log 2>&1 &
echo "notes app" > ../app/index.html
for i in $(seq 50); do curl -s 127.0.0.1:9000/ > /dev/null && break; sleep 0.1; done
nginx -c "$PWD/nginx/nginx.conf" -e stderr 2>/dev/null
for i in $(seq 50); do curl -sk https://127.0.0.1:8443/ > /dev/null && break; sleep 0.1; done
R="--resolve notes.example.test:8080:127.0.0.1 --resolve notes.example.test:8443:127.0.0.1 --cacert tls/ca.crt"
echo "--- client view"
curl -s $R -o /dev/null -w 'http  /       -> %{http_code} %{redirect_url}\n' http://notes.example.test:8080/
curl -s $R -w '  (acme challenge over plain http: %{http_code})\n' http://notes.example.test:8080/.well-known/acme-challenge/token
curl -s $R https://notes.example.test:8443/
curl -s $R -D - -o /dev/null https://notes.example.test:8443/ | grep -iE '^(strict-transport-security|x-content-type-options|server):' | tr -d '\r'
openssl s_client -connect 127.0.0.1:8443 -servername notes.example.test -tls1_1 -cipher 'DEFAULT:@SECLEVEL=0' < /dev/null > /dev/null 2>&1 || echo "TLS 1.1 refused"
echo "--- listeners (app on loopback only, proxy in front)"
ss -Htln | awk '{print $4}' | sort
nginx -c "$PWD/nginx/nginx.conf" -e stderr -s quit 2>/dev/null; kill %1
PASS sshd syntax
PASS sshd effective policy
PASS sudoers
PASS unit file
PASS unit exposure <= 3.0
PASS certificate chain
PASS certificate valid for 30+ days
PASS nginx config
PASS fail2ban sshd filter
PASS logrotate config
--- client view
http  /       -> 301 https://notes.example.test:8443/
token.thumb
  (acme challenge over plain http: 200)
notes app
Server: nginx
Strict-Transport-Security: max-age=31536000
X-Content-Type-Options: nosniff
TLS 1.1 refused
--- listeners (app on loopback only, proxy in front)
127.0.0.1:8080
127.0.0.1:8443
127.0.0.1:9000

Walkthrough

  • SSH: the check runs sshd -T on the combined configuration, including the cloud-init drop-in that tried to re-enable passwords; 10-hardening.conf wins because it is read first. Checking the effective policy, not just the syntax, is what makes this test worth having.
  • sudo: one exact command for the deploy user, verified in strict mode.
  • The service runs under a throwaway UID with a read-only system, no capabilities, a syscall filter and memory, CPU and task limits, and listens on 127.0.0.1 only. Its exposure score must stay at or below 3.0, so a later edit that removes the sandbox fails the check.
  • Certificates: a private CA stands in for Let's Encrypt; the chain verifies and the certificate is good for more than 30 days, the same -checkend rule the expiry monitor uses.
  • Nginx answers plain HTTP only with the ACME challenge directory and a redirect, terminates TLS 1.2/1.3 (1.1 is refused), adds HSTS and nosniff, hides its version (server_tokens off, so the Server: header says just nginx) and passes the proxy headers.
  • fail2ban counts the failed password and ignores the successful key login; logrotate accepts the config.
  • Listeners: the app's port 9000 and the proxy's ports are all on 127.0.0.1 here; on the server, Nginx listens on 0.0.0.0:80/443, the app stays on 127.0.0.1:9000, and ss -tlnp is the final proof that nothing else is exposed.

Check from outside

The last step on the real server is the one people skip: test from another machine, through the real network path.

bash
$ nmap -Pn -p 22,80,443,9000 web1.example.com          # from outside the admin network
PORT     STATE    SERVICE
22/tcp   filtered ssh
80/tcp   open     http
443/tcp  open     https
9000/tcp filtered cslistener
$ curl -sI https://notes.example.com | head -1
HTTP/2 200
$ ssh -o PreferredAuthentications=password ada@web1.example.com
ada@web1.example.com: Permission denied (publickey).

Extend it

  1. Replace ufw with the hand-written nftables rule set from nftables, including a rollback timer when you apply it.
  2. Put the validation session into CI (a GitHub Actions or GitLab job running these checks on every change to the server/ directory), so a broken file never reaches a server (CI/CD Pipelines).
  3. Turn Part 1 into an Ansible playbook that installs the validated files, with validate: on every template (Ansible).
  4. Add a systemd timer that runs the certificate check script and the backup from Backups with rsync, and do a restore drill.
  5. Replace the Nginx part with Caddy and automatic HTTPS, and compare the size of the configuration.

Test yourself

Why does the project check sshd -T output instead of only sshd -t?

  1. -T is faster
  2. Syntax can be valid while an included drop-in still enables passwords; -T shows the effective policy
  3. -t needs root
  4. -T also restarts sshd

Why does the app listen on 127.0.0.1:9000 instead of 0.0.0.0:9000?

  1. Loopback is faster
  2. Only the reverse proxy should reach it; even if the firewall were misconfigured, the app wouldn't be exposed directly
  3. Python requires it
  4. TLS needs it

Why does the HTTP server block still serve /.well-known/acme-challenge/ instead of redirecting everything?

  1. For SEO
  2. ACME HTTP-01 validation starts over plain HTTP on port 80; the challenge files must be reachable there
  3. Browsers require it
  4. To support TLS 1.1