cloud-init.yaml.tftpl 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. #cloud-config
  2. # SPDX-License-Identifier: Apache-2.0
  3. # Hardened Docker host. SSH and the Portainer UI are reachable only through
  4. # Twingate (the cloud firewall admits the connector tag and nothing else); the
  5. # sshd settings below are the second layer. Changing this file changes
  6. # user_data, which forces a droplet rebuild. UNAPPLIED and untested on a real
  7. # machine.
  8. # First-hour order (the same one the stage guides state): update, baseline,
  9. # harden, then applications. In this file: the package update, upgrade and
  10. # unattended-upgrades come first, the baseline (users, sshd settings, files) is
  11. # written next, the hardening is switched on (sshd restarted) before Docker is
  12. # installed, and Portainer is started last.
  13. # No credential is rendered here: user-data is readable from the metadata
  14. # endpoint and ends up in state. The daemons' credentials stay in Doppler and
  15. # are entered in Portainer over Twingate (design section 6).
  16. disable_root: true
  17. # Local time, so the reboot window below is read in the same zone.
  18. timezone: ${timezone}
  19. ssh_pwauth: false
  20. package_update: true
  21. package_upgrade: true
  22. packages:
  23. - unattended-upgrades
  24. - chrony
  25. - ca-certificates
  26. - curl
  27. - gnupg
  28. users:
  29. - name: cah-admin
  30. gecos: CAH admin
  31. lock_passwd: true
  32. shell: /bin/bash
  33. groups: [sudo]
  34. sudo: ALL=(ALL) NOPASSWD:ALL
  35. ssh_authorized_keys:
  36. - ${admin_ssh_public_key}
  37. write_files:
  38. # First boot races Ubuntu's own apt-daily and unattended-upgrades for the
  39. # dpkg lock; wait for it instead of failing the Docker install.
  40. - path: /etc/apt/apt.conf.d/99cah-lock-wait
  41. permissions: "0644"
  42. content: |
  43. DPkg::Lock::Timeout "300";
  44. - path: /etc/ssh/sshd_config.d/99-cah-hardening.conf
  45. permissions: "0644"
  46. content: |
  47. PermitRootLogin no
  48. PasswordAuthentication no
  49. KbdInteractiveAuthentication no
  50. PubkeyAuthentication yes
  51. X11Forwarding no
  52. AllowUsers cah-admin
  53. MaxAuthTries 3
  54. LoginGraceTime 20
  55. - path: /etc/apt/apt.conf.d/20auto-upgrades
  56. permissions: "0644"
  57. content: |
  58. APT::Periodic::Update-Package-Lists "1";
  59. APT::Periodic::Unattended-Upgrade "1";
  60. # The Docker origin line is what lets unattended-upgrades patch Docker Engine
  61. # (design section 5.3: live-restore keeps the containers up through it). The
  62. # origin and suite spelling is unverified on a real machine; check it with
  63. # `unattended-upgrade --dry-run -d` after the first boot.
  64. - path: /etc/apt/apt.conf.d/52cah-unattended-upgrades
  65. permissions: "0644"
  66. content: |
  67. Unattended-Upgrade::Allowed-Origins {
  68. "$${distro_id}:$${distro_codename}-security";
  69. "$${distro_id}ESMApps:$${distro_codename}-apps-security";
  70. "$${distro_id}ESM:$${distro_codename}-infra-security";
  71. "Docker:$${distro_codename}";
  72. };
  73. Unattended-Upgrade::Remove-Unused-Dependencies "true";
  74. Unattended-Upgrade::Automatic-Reboot "true";
  75. Unattended-Upgrade::Automatic-Reboot-WithUsers "true";
  76. Unattended-Upgrade::Automatic-Reboot-Time "${reboot_time}";
  77. # ip_forward is deliberately not set here: Docker needs it on.
  78. # rp_filter is loose (2), not strict, so replies on the second interface survive.
  79. - path: /etc/sysctl.d/99-cah-hardening.conf
  80. permissions: "0644"
  81. content: |
  82. net.ipv4.conf.all.rp_filter = 2
  83. net.ipv4.conf.default.rp_filter = 2
  84. net.ipv4.conf.all.accept_redirects = 0
  85. net.ipv4.conf.default.accept_redirects = 0
  86. net.ipv4.conf.all.send_redirects = 0
  87. net.ipv4.conf.default.send_redirects = 0
  88. net.ipv6.conf.all.accept_redirects = 0
  89. net.ipv6.conf.default.accept_redirects = 0
  90. net.ipv4.conf.all.accept_source_route = 0
  91. net.ipv4.conf.default.accept_source_route = 0
  92. net.ipv6.conf.all.accept_source_route = 0
  93. net.ipv6.conf.default.accept_source_route = 0
  94. net.ipv4.tcp_syncookies = 1
  95. net.ipv4.conf.all.log_martians = 1
  96. net.ipv4.conf.default.log_martians = 1
  97. # The pinned-key check: gpg lists the downloaded key file; this accepts it
  98. # only when it holds exactly ONE primary key (one pub record, no private
  99. # keys) whose primary fingerprint equals the pin. A subkey carries its own fpr
  100. # record, so an fpr is accepted only directly after a sub record; a second fpr
  101. # that follows no sub, or any second pub, is refused. So a bundle of the
  102. # pinned key plus an attacker key is never trusted.
  103. - path: /usr/local/sbin/cah-apt-key-check
  104. permissions: "0755"
  105. owner: root:root
  106. content: |
  107. #!/usr/bin/env bash
  108. set -euo pipefail
  109. refuse() { echo "cah-apt-key-check: refusing: $1" >&2; exit 1; }
  110. [ "$#" -eq 2 ] || refuse "usage: cah-apt-key-check <keyfile> <fingerprint>"
  111. keyfile="$1"
  112. pin="$2"
  113. listing="$(gpg --show-keys --with-colons "$keyfile")" || refuse "gpg could not read the key file"
  114. pubs=0
  115. primary=""
  116. prev=""
  117. while IFS=: read -r rec _ _ _ _ _ _ _ _ f10 _; do
  118. case "$rec" in
  119. pub) pubs=$((pubs + 1)); prev=pub ;;
  120. sub) prev=sub ;;
  121. sec|ssb) refuse "the file holds a private key" ;;
  122. fpr)
  123. if [ "$prev" = pub ] && [ -z "$primary" ]; then
  124. primary="$f10"
  125. prev=fpr
  126. elif [ "$prev" = sub ]; then
  127. prev=fpr
  128. else
  129. refuse "an unexpected extra fingerprint record"
  130. fi
  131. ;;
  132. esac
  133. done <<< "$listing"
  134. [ "$pubs" -eq 1 ] || refuse "expected exactly one public key, found $pubs"
  135. [ "$primary" = "$pin" ] || refuse "the key fingerprint is not the pinned one"
  136. # The Docker API stays on the local socket: no hosts key at all, so no TCP
  137. # listener of any kind. "ip" is the address a published port binds to when a
  138. # compose file names none, so a forgotten address lands on loopback and never
  139. # on every interface. live-restore keeps containers running while the daemon
  140. # restarts for an upgrade. Logs are capped so a chatty daemon cannot fill the disk.
  141. - path: /etc/docker/daemon.json
  142. permissions: "0644"
  143. content: |
  144. {
  145. "ip": "127.0.0.1",
  146. "live-restore": true,
  147. "userland-proxy": false,
  148. "log-driver": "json-file",
  149. "log-opts": {
  150. "max-size": "10m",
  151. "max-file": "3"
  152. }
  153. }
  154. # Portainer CE, pinned to an exact tag and an image digest. The only published port is bound to
  155. # the droplet's private VPC address, which cah-portainer-up writes to .env;
  156. # ":?" makes compose refuse to start when it is unset, so there is no wildcard
  157. # fallback. Port 8000 (the Edge agent tunnel) and 9000 (plain HTTP) are not
  158. # published. The Docker socket is root on this host: Portainer is reachable
  159. # only through Twingate by the admins group (threat model, Docker socket).
  160. - path: /opt/portainer/compose.yaml
  161. permissions: "0644"
  162. content: |
  163. services:
  164. portainer:
  165. image: portainer/portainer-ce:${portainer_version}
  166. restart: unless-stopped
  167. mem_limit: 384m
  168. security_opt:
  169. - no-new-privileges:true
  170. ports:
  171. - "$${PORTAINER_BIND:?}:${portainer_port}:9443"
  172. volumes:
  173. - /var/run/docker.sock:/var/run/docker.sock
  174. - portainer_data:/data
  175. volumes:
  176. portainer_data: {}
  177. # Reads the private VPC address from the droplet metadata endpoint and starts
  178. # Portainer bound to it. Fails closed: without an RFC 1918 address nothing is
  179. # started and nothing listens.
  180. - path: /usr/local/sbin/cah-portainer-up
  181. permissions: "0750"
  182. owner: root:root
  183. content: |
  184. #!/usr/bin/env bash
  185. set -euo pipefail
  186. addr=""
  187. addr="$(curl -fsS --max-time 5 http://169.254.169.254/metadata/v1/interfaces/private/0/ipv4/address)" || addr=""
  188. case "$addr" in
  189. 10.*|192.168.*|172.1[6-9].*|172.2[0-9].*|172.3[01].*) ;;
  190. *) addr="" ;;
  191. esac
  192. if ! [[ "$addr" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  193. echo "cah-portainer-up: no private VPC address found; refusing to start Portainer" >&2
  194. exit 1
  195. fi
  196. umask 077
  197. printf 'PORTAINER_BIND=%s\n' "$addr" > /opt/portainer/.env
  198. docker compose --project-directory /opt/portainer up -d
  199. echo "cah-portainer-up: Portainer bound to $addr:${portainer_port}"
  200. # Starts Portainer again after a reboot, once Docker is up. The container
  201. # also has restart: unless-stopped; this unit re-derives the address.
  202. - path: /etc/systemd/system/cah-portainer.service
  203. permissions: "0644"
  204. content: |
  205. [Unit]
  206. Description=Portainer CE, bound to the private VPC address
  207. After=docker.service network-online.target
  208. Requires=docker.service
  209. Wants=network-online.target
  210. [Service]
  211. Type=oneshot
  212. RemainAfterExit=yes
  213. ExecStart=/usr/local/sbin/cah-portainer-up
  214. [Install]
  215. WantedBy=multi-user.target
  216. %{~ if onion_service_enabled }
  217. # Optional onion service (issue #391): a static nginx origin published on the
  218. # loopback address only, and Tor with one version 3 onion service that
  219. # forwards to it. Nothing here opens a port to the internet. The service key
  220. # is made by Tor on this host and is never part of user-data, the plan or the
  221. # state; the address is read on the host and is not printed anywhere below.
  222. # Tor is a client only: no relay, no exit, no bridge, no SOCKS listener, no
  223. # control port. ReachableAddresses keeps its outbound connections on 443 and 80.
  224. # The file exists before the package is installed; the install keeps it
  225. # (--force-confold), so Tor starts with this configuration or not at all.
  226. - path: /etc/tor/torrc
  227. permissions: "0644"
  228. content: |
  229. SocksPort 0
  230. Log notice syslog
  231. ReachableAddresses *:443,*:80
  232. HiddenServiceDir /var/lib/tor/cah-site/
  233. HiddenServiceVersion 3
  234. HiddenServicePort 80 127.0.0.1:8080
  235. - path: /opt/onion-origin/compose.yaml
  236. permissions: "0644"
  237. content: |
  238. services:
  239. origin:
  240. image: docker.io/library/${onion_origin_image}
  241. restart: unless-stopped
  242. mem_limit: 64m
  243. pids_limit: 64
  244. read_only: true
  245. cap_drop:
  246. - ALL
  247. cap_add:
  248. - CHOWN
  249. - SETGID
  250. - SETUID
  251. security_opt:
  252. - no-new-privileges:true
  253. ports:
  254. - "127.0.0.1:8080:8080"
  255. volumes:
  256. - /opt/onion-origin/default.conf:/etc/nginx/conf.d/default.conf:ro
  257. - /opt/onion-origin/www:/usr/share/nginx/html:ro
  258. tmpfs:
  259. - /run
  260. - /tmp
  261. - /var/cache/nginx
  262. - path: /opt/onion-origin/default.conf
  263. permissions: "0644"
  264. content: |
  265. server_tokens off;
  266. server {
  267. listen 8080 default_server;
  268. server_name _;
  269. root /usr/share/nginx/html;
  270. index index.html;
  271. location / {
  272. try_files $uri =404;
  273. }
  274. error_page 404 /404.html;
  275. location = /404.html {
  276. internal;
  277. }
  278. }
  279. - path: /opt/onion-origin/www/index.html
  280. permissions: "0644"
  281. content: |
  282. <!doctype html>
  283. <html lang="en"><head><meta charset="utf-8"><title>Lab page</title></head>
  284. <body><p>A static lab page. It loads nothing from anywhere else.</p></body></html>
  285. - path: /opt/onion-origin/www/404.html
  286. permissions: "0644"
  287. content: |
  288. <!doctype html>
  289. <html lang="en"><head><meta charset="utf-8"><title>Not found</title></head>
  290. <body><p>Not found.</p></body></html>
  291. # Starts the origin, installs Tor, checks the configuration and only then
  292. # starts the service. Fails closed. The address is not printed.
  293. - path: /usr/local/sbin/cah-onion-up
  294. permissions: "0750"
  295. owner: root:root
  296. content: |
  297. #!/usr/bin/env bash
  298. set -euo pipefail
  299. export DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a
  300. docker compose --project-directory /opt/onion-origin up -d
  301. for attempt in $(seq 1 5); do
  302. apt-get update -q && apt-get install -yq -o Dpkg::Options::=--force-confold tor && break
  303. [ "$attempt" -lt 5 ] || { echo "cah-onion-up: tor install failed" >&2; exit 1; }
  304. sleep 30
  305. done
  306. tor --verify-config -f /etc/tor/torrc > /dev/null
  307. systemctl enable tor@default
  308. systemctl restart tor@default
  309. for _ in $(seq 1 30); do
  310. [ -s /var/lib/tor/cah-site/hostname ] && break
  311. sleep 2
  312. done
  313. [ -s /var/lib/tor/cah-site/hostname ] || { echo "cah-onion-up: the service key was not created" >&2; exit 1; }
  314. echo "cah-onion-up: the onion service key exists on this host; the address is not printed here"
  315. %{~ endif }
  316. runcmd:
  317. - [sysctl, --system]
  318. - [bash, -c, "sshd -t && systemctl restart ssh"]
  319. - [systemctl, enable, --now, chrony]
  320. # Install Docker Engine from Docker's signed apt repository instead of
  321. # running a piped installer script. The repository key is checked against a
  322. # pinned fingerprint before it is trusted: the file must hold exactly one
  323. # key, the pinned one (cah-apt-key-check). Retry up to 10 times, 30 seconds
  324. # apart. Never add set -x here.
  325. - - bash
  326. - -o
  327. - pipefail
  328. - -c
  329. - |
  330. export DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a
  331. KEYRING=/usr/share/keyrings/docker-keyring.gpg
  332. FPR=${docker_key_fingerprint}
  333. for attempt in $(seq 1 10); do
  334. if curl -fsSL --proto '=https' --tlsv1.2 --retry 5 -o /root/docker.gpg.key https://download.docker.com/linux/ubuntu/gpg \
  335. && /usr/local/sbin/cah-apt-key-check /root/docker.gpg.key "$FPR" \
  336. && gpg --dearmor --yes -o "$KEYRING" /root/docker.gpg.key \
  337. && 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 \
  338. && apt-get update -q \
  339. && apt-get install -yq docker-ce docker-ce-cli containerd.io docker-compose-plugin \
  340. && systemctl enable --now docker \
  341. && sleep 5 && systemctl is-active --quiet docker; then
  342. echo "cah: docker install succeeded on attempt $attempt"
  343. exit 0
  344. fi
  345. echo "cah: docker install attempt $attempt of 10 failed"
  346. sleep 30
  347. done
  348. echo "cah: docker install failed after 10 attempts" >&2
  349. exit 1
  350. - [/usr/local/sbin/cah-portainer-up]
  351. %{~ if onion_service_enabled }
  352. - [/usr/local/sbin/cah-onion-up]
  353. %{~ endif }
  354. - [systemctl, daemon-reload]
  355. - [systemctl, enable, cah-portainer.service]
  356. # Leave the outcome where someone can read it later. No credential is read here.
  357. - - bash
  358. - -c
  359. - |
  360. umask 027
  361. {
  362. echo "== date"; date
  363. echo "== systemctl is-active docker"; systemctl is-active docker
  364. echo "== docker ps"; docker ps
  365. %{~ if onion_service_enabled }
  366. echo "== systemctl is-active tor@default"; systemctl is-active tor@default
  367. %{~ endif }
  368. echo "== /var/log/cloud-init-output.log (last 50)"; tail -n 50 /var/log/cloud-init-output.log
  369. } > /var/log/cah-docker-host-install.log 2>&1
  370. chmod 0640 /var/log/cah-docker-host-install.log