Repository navigation
Expand file tree
/
Copy pathgen-certs.sh
More file actions
executable file
·291 lines (265 loc) · 13.7 KB
/
Copy pathgen-certs.sh
File metadata and controls
executable file
·291 lines (265 loc) · 13.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
#!/usr/bin/env bash
#
# Generate the ESTATE'S internal CA and the leaf certificates it signs.
#
# The estate's, and only the estate's: Grafana on the monitoring host and on
# the lab guest, and the wiki's Caddy on oracle (#847), serve leaves from this
# CA, and Prometheus and blackbox verify them against it. The sensitive tier on trinity has a certificate authority of
# its own — step-ca, with a root minted by scripts/tier-ca.sh — and every
# certificate Caddy serves there is issued over ACME and renewed without a
# runbook step. Nothing this script issues is for that host, and nothing that
# host serves comes from here. ADR-0037 says why they are two: the root below
# carries pathlen:0, so nothing beneath it may be a CA.
#
# Everything lands in certificates/, which is gitignored — along with *.pem and
# *.key — because the previous set of these was committed to a public repository
# and had to be purged from history. See docs/runbooks/purge-git-history.md.
# The control that matters is not the file mode, it is that these never become
# tracked files. `make validate` asserts that; so does CI.
#
# Grafana terminates TLS with a leaf issued here, and Prometheus verifies that
# certificate against this CA when it scrapes the grafana job — so both are a
# prerequisite of `make up` rather than groundwork for a someday service. What
# this script buys is that issuing one stays a single command rather than a
# research project, and that the CA is created deliberately rather than
# improvised at the point of need.
#
# Usage:
# scripts/gen-certs.sh --ca create the CA (refuses if it exists)
# scripts/gen-certs.sh --host <fqdn> [--ip IP] [--dns NAME]
# scripts/gen-certs.sh --list show what exists, and when it expires
#
# --ip <addr> add an IP SAN; repeatable. Internal DNS is unresolved in
# this lab (docs/roadmap.md), so most leaves want one.
# --dns <name> add an extra DNS SAN; repeatable. A service reached under
# more than one name — its FQDN from a browser and its compose
# service name from inside the network — needs every one of
# them, or verification fails for the names that are missing.
# --client issue a CLIENT certificate (extendedKeyUsage=clientAuth)
# instead of a server one. Every other leaf here is
# serverAuth only, and that is what makes a client one
# mean something: Go's crypto/tls requires clientAuth of a
# client certificate, so a key lifted from Grafana or the
# ingest proxy cannot pass as a client. The first is
# morpheus's, for TLS syslog to Alloy (#1049), whose
# listener pins that exact certificate rather than
# trusting every client leaf this CA signs.
# --csr <file> sign a certificate signing request made ELSEWHERE, so the
# private key never leaves the device that made it. No key
# is written here. The CSR supplies only its public key:
# the subject is /CN=<host>/O=matrix.elysium and the SANs
# are the ones given here, whatever the CSR asked for. The
# first is the APC card on mjolnir, which can make a key and
# a CSR but has nowhere to import a key from this host
# except a Security Wizard .p15.
# --days <n> leaf lifetime, default 825
# --force overwrite an existing CA or leaf
#
# The CA key is not passphrase-protected. That is a deliberate trade and worth
# stating: a passphrase is what made the previous leak survivable, but it also
# means every issuance is interactive, which is how a lab ends up with one
# long-lived certificate nobody dares reissue. The exposure this time is bounded
# by the key never being committed and never leaving this host except as ONE
# offline copy, on the medium that already holds the age key's second copy —
# docs/runbooks/back-up-the-ca-key.md, and #496 for why a copy and not a
# passphrase. If you would rather have the passphrase, add -aes256 to the CA
# key generation below and accept the prompt on every issue.
set -euo pipefail
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
CERT_DIR="${REPO_ROOT}/certificates"
CA_KEY="${CERT_DIR}/ca-key.pem"
CA_CRT="${CERT_DIR}/ca.pem"
CA_SUBJECT='/CN=Matrix Elysium Internal CA/O=matrix.elysium'
CA_DAYS=3650
LEAF_DAYS=825
die() { printf '\033[0;31merror:\033[0m %s\n' "$*" >&2; exit 1; }
info() { printf '\033[0;34m--\033[0m %s\n' "$*"; }
ok() { printf '\033[0;32mok\033[0m — %s\n' "$*"; }
head_() { printf '\n\033[1m%s\033[0m\n' "$*"; }
MODE=""
HOST=""
IPS=()
DNS=()
FORCE=0
CLIENT=0
CSR=""
while (($#)); do
case "$1" in
--ca) MODE="ca"; shift ;;
--list) MODE="list"; shift ;;
--host) MODE="leaf"; HOST="${2:?--host needs an FQDN}"; shift 2 ;;
--ip) IPS+=("${2:?--ip needs an address}"); shift 2 ;;
--dns) DNS+=("${2:?--dns needs a name}"); shift 2 ;;
--days) LEAF_DAYS="${2:?--days needs a number}"; shift 2 ;;
--force) FORCE=1; shift ;;
--client) CLIENT=1; shift ;;
--csr) CSR="${2:?--csr needs a file}"; shift 2 ;;
# Printed straight from the comment block above rather than kept as a
# second copy that drifts. Bounded by where the comments stop, not by a
# line number: the literal 2,32p this replaced had already slipped and was
# truncating the last paragraph mid-sentence.
-h|--help) awk 'NR>1 && /^#/ {sub(/^# ?/, ""); print; next} NR>1 {exit}' "${BASH_SOURCE[0]}"; exit 0 ;;
*) die "unknown argument: $1" ;;
esac
done
[[ -z "${CSR}" || "${MODE}" == "leaf" ]] || die "--csr signs a leaf: give it with --host <fqdn>"
[[ -n "${MODE}" ]] || die "nothing to do — try --ca, --host <fqdn>, or --list (see --help)"
command -v openssl >/dev/null 2>&1 || die "openssl not found"
# 0700: the directory itself, not just the keys. A 0644 directory with 0600 keys
# still tells any local user exactly which hosts have certificates.
mkdir -p "${CERT_DIR}"
chmod 700 "${CERT_DIR}"
umask 077
# ---------------------------------------------------------------------------
# --list
# ---------------------------------------------------------------------------
if [[ "${MODE}" == "list" ]]; then
head_ "certificates/"
shopt -s nullglob
found=0
for crt in "${CERT_DIR}"/*.pem; do
[[ "${crt}" == *-key.pem ]] && continue
found=1
subject="$(openssl x509 -in "${crt}" -noout -subject 2>/dev/null | sed 's/^subject=//')"
enddate="$(openssl x509 -in "${crt}" -noout -enddate 2>/dev/null | cut -d= -f2)"
if openssl x509 -in "${crt}" -noout -checkend 0 >/dev/null 2>&1; then
state="valid"
else
state="\033[0;31mEXPIRED\033[0m"
fi
printf ' %-28s %b until %s\n' "$(basename "${crt}")" "${state}" "${enddate}"
printf ' %s\n' "${subject}"
done
((found)) || printf ' (nothing yet — start with %s --ca)\n' "$(basename "$0")"
printf '\n'
exit 0
fi
# ---------------------------------------------------------------------------
# --ca
# ---------------------------------------------------------------------------
if [[ "${MODE}" == "ca" ]]; then
if [[ -s "${CA_KEY}" ]] && ((! FORCE)); then
die "${CA_KEY#"${REPO_ROOT}"/} already exists.
Regenerating the CA invalidates every leaf it has signed and every trust store
that holds it. Pass --force only if that is what you mean."
fi
info "creating the CA (${CA_DAYS} days)"
# pathlen:0 is deliberate and load-bearing: nothing beneath this root may be
# a CA, so a leaf key lifted from Grafana cannot be turned into a signer of
# anything else. It also means this root CANNOT have an intermediate — a
# leaf beneath one fails "path length constraint exceeded" in every client
# here — which is why the sensitive tier's step-ca has a root of its own
# rather than sitting beneath this one (ADR-0037, measured before deciding).
# Lifting it means re-minting this root and re-trusting it everywhere.
#
# And the key stays on the monitoring host. ADR-0043 decided it does not
# follow the deployment toolchain to `phoenix` on VLAN 30: that host holds
# credentials for every other host, and the key every other host trusts
# must not sit beside them. Nothing below enforces that — the path is
# relative to whichever checkout runs this — so this comment is the guard.
openssl req -x509 -newkey rsa:4096 -sha256 -nodes \
-keyout "${CA_KEY}" -out "${CA_CRT}" -days "${CA_DAYS}" \
-subj "${CA_SUBJECT}" \
-addext "basicConstraints=critical,CA:TRUE,pathlen:0" \
-addext "keyUsage=critical,keyCertSign,cRLSign" 2>/dev/null
chmod 600 "${CA_KEY}"
chmod 644 "${CA_CRT}"
# The new key starts unproved, and says so now rather than on the next
# morning's timer: ca-key-state.sh writes its fingerprint at 0 and drops the
# old key's proof, so CaKeyBackupUnproven fires until the offline copy is
# replaced and proved again. `|| true` because a workstation with no textfile
# directory is not a reason to fail the mint (#496).
"${REPO_ROOT}/scripts/ca-key-state.sh" --record || true
ok "CA created"
printf ' key %s (never commit; ONE offline copy, proved — docs/runbooks/back-up-the-ca-key.md)\n' "${CA_KEY#"${REPO_ROOT}"/}"
printf ' cert %s (safe to distribute — this is what clients trust)\n' "${CA_CRT#"${REPO_ROOT}"/}"
printf '\nIssue a leaf with:\n scripts/gen-certs.sh --host grafana.matrix.elysium --ip 10.0.99.20 --dns grafana\n'
printf 'Then back the key up, and prove the copy:\n make certs-verify-backup KEY=/path/to/the/copy\n\n'
exit 0
fi
# ---------------------------------------------------------------------------
# --host <fqdn>
# ---------------------------------------------------------------------------
[[ -s "${CA_KEY}" && -s "${CA_CRT}" ]] || die "no CA yet — run: scripts/gen-certs.sh --ca"
KEY="${CERT_DIR}/${HOST}-key.pem"
CRT="${CERT_DIR}/${HOST}.pem"
if [[ -n "${CSR}" ]]; then
# The key is the device's. Guard the certificate instead, and refuse a CSR
# whose own signature does not verify: that is a request nobody holding the
# matching key made.
[[ -s "${CSR}" ]] || die "no CSR at ${CSR}"
if [[ -s "${CRT}" ]] && ((! FORCE)); then
die "${CRT#"${REPO_ROOT}"/} already exists — pass --force to replace it"
fi
openssl req -in "${CSR}" -noout -verify >/dev/null 2>&1 \
|| die "${CSR} is not a CSR whose signature verifies"
elif ((! FORCE)); then
# The certificate as well as the key: a leaf signed from a device's CSR
# has no key here, and reissuing it without --csr would replace it with
# one for a local key the device cannot import.
for f in "${KEY}" "${CRT}"; do
[[ -s "${f}" ]] && die "${f#"${REPO_ROOT}"/} already exists — pass --force to replace it"
done
fi
# A certificate with no subjectAltName is rejected outright by every current
# browser and by Go's crypto/tls, which is what Prometheus, Alertmanager and
# Grafana are built on. CN alone has not been sufficient for years, and the
# failure — "x509: certificate relies on legacy Common Name field" — reads as a
# trust problem rather than a missing field, so it costs an hour to diagnose.
SAN="DNS:${HOST}"
for name in "${DNS[@]}"; do
SAN+=",DNS:${name}"
done
for ip in "${IPS[@]}"; do
SAN+=",IP:${ip}"
done
# 825 days is not arbitrary: browsers reject leaf certificates valid for longer.
# A 10-year leaf looks like less work and produces something nothing will trust.
if ((LEAF_DAYS > 825)); then
die "leaf lifetime ${LEAF_DAYS} exceeds 825 days, which browsers reject outright"
fi
# One purpose per key: a leaf is a server or a client, never both, so a
# client key that leaks cannot serve a TLS endpoint and a server key that
# leaks cannot authenticate as a sender.
EKU="serverAuth"
((CLIENT)) && EKU="clientAuth"
info "issuing ${HOST} (${LEAF_DAYS} days, ${EKU})"
info "SANs: ${SAN}"
TMP="$(mktemp -d)"
trap 'rm -rf "${TMP}"' EXIT INT TERM
if [[ -n "${CSR}" ]]; then
cp "${CSR}" "${TMP}/csr.pem"
else
openssl req -newkey rsa:2048 -sha256 -nodes \
-keyout "${KEY}" -out "${TMP}/csr.pem" \
-subj "/CN=${HOST}/O=matrix.elysium" 2>/dev/null
fi
# -subj overrides the request's subject, and -extfile is the only source of
# extensions: x509 -req copies none from the CSR. So a CSR from a device says
# nothing about the names this CA vouches for.
openssl x509 -req -in "${TMP}/csr.pem" -sha256 \
-subj "/CN=${HOST}/O=matrix.elysium" \
-CA "${CA_CRT}" -CAkey "${CA_KEY}" -CAcreateserial \
-CAserial "${CERT_DIR}/ca.srl" \
-out "${CRT}" -days "${LEAF_DAYS}" \
-extfile <(printf 'subjectAltName=%s\nbasicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature,keyEncipherment\nextendedKeyUsage=%s\n' "${SAN}" "${EKU}") 2>/dev/null
# 0640, not 0600. A container serving this key runs as its own uid — Grafana is
# 472:0 — and cannot read a file owned by the operator at 0600. The compose
# service is given the operator's gid as a supplementary group instead of the
# key being made world-readable. This costs nothing: certificates/ is 0700, so
# no other local user can traverse to the file whatever its own mode says.
[[ -n "${CSR}" ]] || chmod 640 "${KEY}"
chmod 644 "${CRT}"
# Prove it verifies against the CA now, rather than discovering at deploy time
# that the chain does not build.
openssl verify -CAfile "${CA_CRT}" -purpose "$( ((CLIENT)) && echo sslclient || echo sslserver)" "${CRT}" >/dev/null 2>&1 \
|| die "the issued certificate does not verify against the CA — refusing to report success"
ok "issued ${CRT#"${REPO_ROOT}"/}"
if [[ -n "${CSR}" ]]; then
printf ' key on the device that made %s; none here\n' "${CSR}"
else
printf ' key %s\n' "${KEY#"${REPO_ROOT}"/}"
fi
printf ' SANs %s\n' "${SAN}"
printf ' EKU %s\n' "${EKU}"
printf ' verified against %s\n\n' "${CA_CRT#"${REPO_ROOT}"/}"