| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375 |
- #cloud-config
- # SPDX-License-Identifier: Apache-2.0
- # Hardened Docker host. SSH and the Portainer UI are reachable only through
- # Twingate (the cloud firewall admits the connector tag and nothing else); the
- # sshd settings below are the second layer. Changing this file changes
- # user_data, which forces a droplet rebuild. UNAPPLIED and untested on a real
- # machine.
- # First-hour order (the same one the stage guides state): update, baseline,
- # harden, then applications. In this file: the package update, upgrade and
- # unattended-upgrades come first, the baseline (users, sshd settings, files) is
- # written next, the hardening is switched on (sshd restarted) before Docker is
- # installed, and Portainer is started last.
- # No credential is rendered here: user-data is readable from the metadata
- # endpoint and ends up in state. The daemons' credentials stay in Doppler and
- # are entered in Portainer over Twingate (design section 6).
- disable_root: true
- # Local time, so the reboot window below is read in the same zone.
- timezone: ${timezone}
- ssh_pwauth: false
- package_update: true
- package_upgrade: true
- packages:
- - unattended-upgrades
- - chrony
- - ca-certificates
- - curl
- - gnupg
- users:
- - name: cah-admin
- gecos: CAH admin
- lock_passwd: true
- shell: /bin/bash
- groups: [sudo]
- sudo: ALL=(ALL) NOPASSWD:ALL
- ssh_authorized_keys:
- - ${admin_ssh_public_key}
- write_files:
- # First boot races Ubuntu's own apt-daily and unattended-upgrades for the
- # dpkg lock; wait for it instead of failing the Docker install.
- - path: /etc/apt/apt.conf.d/99cah-lock-wait
- permissions: "0644"
- content: |
- DPkg::Lock::Timeout "300";
- - path: /etc/ssh/sshd_config.d/99-cah-hardening.conf
- permissions: "0644"
- content: |
- PermitRootLogin no
- PasswordAuthentication no
- KbdInteractiveAuthentication no
- PubkeyAuthentication yes
- X11Forwarding no
- AllowUsers cah-admin
- MaxAuthTries 3
- LoginGraceTime 20
- - path: /etc/apt/apt.conf.d/20auto-upgrades
- permissions: "0644"
- content: |
- APT::Periodic::Update-Package-Lists "1";
- APT::Periodic::Unattended-Upgrade "1";
- # The Docker origin line is what lets unattended-upgrades patch Docker Engine
- # (design section 5.3: live-restore keeps the containers up through it). The
- # origin and suite spelling is unverified on a real machine; check it with
- # `unattended-upgrade --dry-run -d` after the first boot.
- - path: /etc/apt/apt.conf.d/52cah-unattended-upgrades
- permissions: "0644"
- content: |
- Unattended-Upgrade::Allowed-Origins {
- "$${distro_id}:$${distro_codename}-security";
- "$${distro_id}ESMApps:$${distro_codename}-apps-security";
- "$${distro_id}ESM:$${distro_codename}-infra-security";
- "Docker:$${distro_codename}";
- };
- Unattended-Upgrade::Remove-Unused-Dependencies "true";
- Unattended-Upgrade::Automatic-Reboot "true";
- Unattended-Upgrade::Automatic-Reboot-WithUsers "true";
- Unattended-Upgrade::Automatic-Reboot-Time "${reboot_time}";
- # ip_forward is deliberately not set here: Docker needs it on.
- # rp_filter is loose (2), not strict, so replies on the second interface survive.
- - path: /etc/sysctl.d/99-cah-hardening.conf
- permissions: "0644"
- content: |
- net.ipv4.conf.all.rp_filter = 2
- net.ipv4.conf.default.rp_filter = 2
- net.ipv4.conf.all.accept_redirects = 0
- net.ipv4.conf.default.accept_redirects = 0
- net.ipv4.conf.all.send_redirects = 0
- net.ipv4.conf.default.send_redirects = 0
- net.ipv6.conf.all.accept_redirects = 0
- net.ipv6.conf.default.accept_redirects = 0
- net.ipv4.conf.all.accept_source_route = 0
- net.ipv4.conf.default.accept_source_route = 0
- net.ipv6.conf.all.accept_source_route = 0
- net.ipv6.conf.default.accept_source_route = 0
- net.ipv4.tcp_syncookies = 1
- net.ipv4.conf.all.log_martians = 1
- net.ipv4.conf.default.log_martians = 1
- # The pinned-key check: gpg lists the downloaded key file; this accepts it
- # only when it holds exactly ONE primary key (one pub record, no private
- # keys) whose primary fingerprint equals the pin. A subkey carries its own fpr
- # record, so an fpr is accepted only directly after a sub record; a second fpr
- # that follows no sub, or any second pub, is refused. So a bundle of the
- # pinned key plus an attacker key is never trusted.
- - path: /usr/local/sbin/cah-apt-key-check
- permissions: "0755"
- owner: root:root
- content: |
- #!/usr/bin/env bash
- set -euo pipefail
- refuse() { echo "cah-apt-key-check: refusing: $1" >&2; exit 1; }
- [ "$#" -eq 2 ] || refuse "usage: cah-apt-key-check <keyfile> <fingerprint>"
- keyfile="$1"
- pin="$2"
- listing="$(gpg --show-keys --with-colons "$keyfile")" || refuse "gpg could not read the key file"
- pubs=0
- primary=""
- prev=""
- while IFS=: read -r rec _ _ _ _ _ _ _ _ f10 _; do
- case "$rec" in
- pub) pubs=$((pubs + 1)); prev=pub ;;
- sub) prev=sub ;;
- sec|ssb) refuse "the file holds a private key" ;;
- fpr)
- if [ "$prev" = pub ] && [ -z "$primary" ]; then
- primary="$f10"
- prev=fpr
- elif [ "$prev" = sub ]; then
- prev=fpr
- else
- refuse "an unexpected extra fingerprint record"
- fi
- ;;
- esac
- done <<< "$listing"
- [ "$pubs" -eq 1 ] || refuse "expected exactly one public key, found $pubs"
- [ "$primary" = "$pin" ] || refuse "the key fingerprint is not the pinned one"
- # The Docker API stays on the local socket: no hosts key at all, so no TCP
- # listener of any kind. "ip" is the address a published port binds to when a
- # compose file names none, so a forgotten address lands on loopback and never
- # on every interface. live-restore keeps containers running while the daemon
- # restarts for an upgrade. Logs are capped so a chatty daemon cannot fill the disk.
- - path: /etc/docker/daemon.json
- permissions: "0644"
- content: |
- {
- "ip": "127.0.0.1",
- "live-restore": true,
- "userland-proxy": false,
- "log-driver": "json-file",
- "log-opts": {
- "max-size": "10m",
- "max-file": "3"
- }
- }
- # Portainer CE, pinned to an exact tag and an image digest. The only published port is bound to
- # the droplet's private VPC address, which cah-portainer-up writes to .env;
- # ":?" makes compose refuse to start when it is unset, so there is no wildcard
- # fallback. Port 8000 (the Edge agent tunnel) and 9000 (plain HTTP) are not
- # published. The Docker socket is root on this host: Portainer is reachable
- # only through Twingate by the admins group (threat model, Docker socket).
- - path: /opt/portainer/compose.yaml
- permissions: "0644"
- content: |
- services:
- portainer:
- image: portainer/portainer-ce:${portainer_version}
- restart: unless-stopped
- mem_limit: 384m
- security_opt:
- - no-new-privileges:true
- ports:
- - "$${PORTAINER_BIND:?}:${portainer_port}:9443"
- volumes:
- - /var/run/docker.sock:/var/run/docker.sock
- - portainer_data:/data
- volumes:
- portainer_data: {}
- # Reads the private VPC address from the droplet metadata endpoint and starts
- # Portainer bound to it. Fails closed: without an RFC 1918 address nothing is
- # started and nothing listens.
- - path: /usr/local/sbin/cah-portainer-up
- permissions: "0750"
- owner: root:root
- content: |
- #!/usr/bin/env bash
- set -euo pipefail
- addr=""
- addr="$(curl -fsS --max-time 5 http://169.254.169.254/metadata/v1/interfaces/private/0/ipv4/address)" || addr=""
- case "$addr" in
- 10.*|192.168.*|172.1[6-9].*|172.2[0-9].*|172.3[01].*) ;;
- *) addr="" ;;
- esac
- if ! [[ "$addr" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
- echo "cah-portainer-up: no private VPC address found; refusing to start Portainer" >&2
- exit 1
- fi
- umask 077
- printf 'PORTAINER_BIND=%s\n' "$addr" > /opt/portainer/.env
- docker compose --project-directory /opt/portainer up -d
- echo "cah-portainer-up: Portainer bound to $addr:${portainer_port}"
- # Starts Portainer again after a reboot, once Docker is up. The container
- # also has restart: unless-stopped; this unit re-derives the address.
- - path: /etc/systemd/system/cah-portainer.service
- permissions: "0644"
- content: |
- [Unit]
- Description=Portainer CE, bound to the private VPC address
- After=docker.service network-online.target
- Requires=docker.service
- Wants=network-online.target
- [Service]
- Type=oneshot
- RemainAfterExit=yes
- ExecStart=/usr/local/sbin/cah-portainer-up
- [Install]
- WantedBy=multi-user.target
- %{~ if onion_service_enabled }
- # Optional onion service (issue #391): a static nginx origin published on the
- # loopback address only, and Tor with one version 3 onion service that
- # forwards to it. Nothing here opens a port to the internet. The service key
- # is made by Tor on this host and is never part of user-data, the plan or the
- # state; the address is read on the host and is not printed anywhere below.
- # Tor is a client only: no relay, no exit, no bridge, no SOCKS listener, no
- # control port. ReachableAddresses keeps its outbound connections on 443 and 80.
- # The file exists before the package is installed; the install keeps it
- # (--force-confold), so Tor starts with this configuration or not at all.
- - path: /etc/tor/torrc
- permissions: "0644"
- content: |
- SocksPort 0
- Log notice syslog
- ReachableAddresses *:443,*:80
- HiddenServiceDir /var/lib/tor/cah-site/
- HiddenServiceVersion 3
- HiddenServicePort 80 127.0.0.1:8080
- - path: /opt/onion-origin/compose.yaml
- permissions: "0644"
- content: |
- services:
- origin:
- image: docker.io/library/${onion_origin_image}
- restart: unless-stopped
- mem_limit: 64m
- pids_limit: 64
- read_only: true
- cap_drop:
- - ALL
- cap_add:
- - CHOWN
- - SETGID
- - SETUID
- security_opt:
- - no-new-privileges:true
- ports:
- - "127.0.0.1:8080:8080"
- volumes:
- - /opt/onion-origin/default.conf:/etc/nginx/conf.d/default.conf:ro
- - /opt/onion-origin/www:/usr/share/nginx/html:ro
- tmpfs:
- - /run
- - /tmp
- - /var/cache/nginx
- - path: /opt/onion-origin/default.conf
- permissions: "0644"
- content: |
- server_tokens off;
- server {
- listen 8080 default_server;
- server_name _;
- root /usr/share/nginx/html;
- index index.html;
- location / {
- try_files $uri =404;
- }
- error_page 404 /404.html;
- location = /404.html {
- internal;
- }
- }
- - path: /opt/onion-origin/www/index.html
- permissions: "0644"
- content: |
- <!doctype html>
- <html lang="en"><head><meta charset="utf-8"><title>Lab page</title></head>
- <body><p>A static lab page. It loads nothing from anywhere else.</p></body></html>
- - path: /opt/onion-origin/www/404.html
- permissions: "0644"
- content: |
- <!doctype html>
- <html lang="en"><head><meta charset="utf-8"><title>Not found</title></head>
- <body><p>Not found.</p></body></html>
- # Starts the origin, installs Tor, checks the configuration and only then
- # starts the service. Fails closed. The address is not printed.
- - path: /usr/local/sbin/cah-onion-up
- permissions: "0750"
- owner: root:root
- content: |
- #!/usr/bin/env bash
- set -euo pipefail
- export DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a
- docker compose --project-directory /opt/onion-origin up -d
- for attempt in $(seq 1 5); do
- apt-get update -q && apt-get install -yq -o Dpkg::Options::=--force-confold tor && break
- [ "$attempt" -lt 5 ] || { echo "cah-onion-up: tor install failed" >&2; exit 1; }
- sleep 30
- done
- tor --verify-config -f /etc/tor/torrc > /dev/null
- systemctl enable tor@default
- systemctl restart tor@default
- for _ in $(seq 1 30); do
- [ -s /var/lib/tor/cah-site/hostname ] && break
- sleep 2
- done
- [ -s /var/lib/tor/cah-site/hostname ] || { echo "cah-onion-up: the service key was not created" >&2; exit 1; }
- echo "cah-onion-up: the onion service key exists on this host; the address is not printed here"
- %{~ endif }
- runcmd:
- - [sysctl, --system]
- - [bash, -c, "sshd -t && systemctl restart ssh"]
- - [systemctl, enable, --now, chrony]
- # Install Docker Engine from Docker's signed apt repository instead of
- # running a piped installer script. The repository key is checked against a
- # pinned fingerprint before it is trusted: the file must hold exactly one
- # key, the pinned one (cah-apt-key-check). Retry up to 10 times, 30 seconds
- # apart. Never add set -x here.
- - - bash
- - -o
- - pipefail
- - -c
- - |
- export DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a
- KEYRING=/usr/share/keyrings/docker-keyring.gpg
- FPR=${docker_key_fingerprint}
- for attempt in $(seq 1 10); do
- if curl -fsSL --proto '=https' --tlsv1.2 --retry 5 -o /root/docker.gpg.key https://download.docker.com/linux/ubuntu/gpg \
- && /usr/local/sbin/cah-apt-key-check /root/docker.gpg.key "$FPR" \
- && gpg --dearmor --yes -o "$KEYRING" /root/docker.gpg.key \
- && echo "deb [arch=$(dpkg --print-architecture) signed-by=$KEYRING] https://download.docker.com/linux/ubuntu $(. /etc/os-release && echo "$VERSION_CODENAME") stable" > /etc/apt/sources.list.d/docker.list \
- && apt-get update -q \
- && apt-get install -yq docker-ce docker-ce-cli containerd.io docker-compose-plugin \
- && systemctl enable --now docker \
- && sleep 5 && systemctl is-active --quiet docker; then
- echo "cah: docker install succeeded on attempt $attempt"
- exit 0
- fi
- echo "cah: docker install attempt $attempt of 10 failed"
- sleep 30
- done
- echo "cah: docker install failed after 10 attempts" >&2
- exit 1
- - [/usr/local/sbin/cah-portainer-up]
- %{~ if onion_service_enabled }
- - [/usr/local/sbin/cah-onion-up]
- %{~ endif }
- - [systemctl, daemon-reload]
- - [systemctl, enable, cah-portainer.service]
- # Leave the outcome where someone can read it later. No credential is read here.
- - - bash
- - -c
- - |
- umask 027
- {
- echo "== date"; date
- echo "== systemctl is-active docker"; systemctl is-active docker
- echo "== docker ps"; docker ps
- %{~ if onion_service_enabled }
- echo "== systemctl is-active tor@default"; systemctl is-active tor@default
- %{~ endif }
- echo "== /var/log/cloud-init-output.log (last 50)"; tail -n 50 /var/log/cloud-init-output.log
- } > /var/log/cah-docker-host-install.log 2>&1
- chmod 0640 /var/log/cah-docker-host-install.log
|