-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
372 lines (351 loc) · 11.8 KB
/
Copy pathmain.go
File metadata and controls
372 lines (351 loc) · 11.8 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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
// SPDX-License-Identifier: AGPL-3.0-or-later
// pilot-ca — offline tooling for the Pilot Protocol root CA used to
// authenticate beacon WSS endpoints in compat mode.
//
// The root CA private key is the trust anchor for every compat-mode
// daemon's TLS handshake. It must never leave the operator's secure
// machine (Yubikey-backed or air-gapped). This binary is the only
// production code that touches it.
//
// Subcommands:
//
// pilot-ca init-root <out-dir>
// Generate a fresh Ed25519 root CA keypair + self-signed root cert.
// Writes <out-dir>/root.key (mode 0600) and <out-dir>/root.crt.
// The .key file must be moved to offline storage immediately.
//
// pilot-ca issue-beacon <root-dir> <hostname> <out-dir>
// Sign a leaf cert for a beacon hostname using the root CA in
// <root-dir>. Writes <out-dir>/<hostname>.key and <out-dir>/<hostname>.crt.
// Leaf certs are P-256 ECDSA (TLS-friendly) with SAN = hostname.
// Validity: 90 days. Re-run before expiry; Caddy reloads
// automatically on file change.
//
// pilot-ca verify <root.crt> <leaf.crt> [hostname]
// Confirm a leaf cert chains to the root, is currently valid,
// and (when hostname is given) that the leaf SAN matches hostname.
// Exit 0 on success.
//
// The root cert (PEM) is what gets embedded in pilot-daemon via
// //go:embed. The root key stays offline. Beacon operators receive
// only the leaf cert + leaf key.
package main
import (
"crypto/ecdsa"
"crypto/ed25519"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"flag"
"fmt"
"math/big"
"os"
"path/filepath"
"regexp"
"time"
)
const (
rootValidYears = 10 // root rotates rarely
leafValidDays = 90 // leaf rotates often
caCommonName = "Pilot Protocol Root CA"
)
// hostnameRE is a strict DNS-name regex applied to issue-beacon's
// hostname argument. We restrict to lowercase letters, digits, and
// hyphens (with dot separators) — the same shape Caddy and most TLS
// stacks accept as a SAN DNSName. The strict allowlist guarantees no
// path separator (`/`, `\`), no parent-dir token (`..`), and no
// shell-metacharacter ever reaches filepath.Join when we build
// <outDir>/<hostname>.{key,crt}.
//
// Length is capped at 253 (the DNS hostname maximum) and each label
// at 63 (the DNS label maximum).
var hostnameRE = regexp.MustCompile(`^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$`)
// validateHostname enforces hostnameRE and the 253-char total length
// cap. Returns a clear error for the issue-beacon caller — never
// silently accepts a name that could escape outDir via filepath.Join.
func validateHostname(hostname string) error {
if hostname == "" {
return fmt.Errorf("hostname required")
}
if len(hostname) > 253 {
return fmt.Errorf("hostname %q exceeds 253-char DNS limit", hostname)
}
if !hostnameRE.MatchString(hostname) {
return fmt.Errorf("hostname %q is not a valid DNS name (allowed: lowercase letters, digits, hyphen, dot; no path separators, no '..')", hostname)
}
return nil
}
func main() {
flag.Usage = func() {
fmt.Fprintln(os.Stderr, "usage: pilot-ca <subcommand> [args...]")
fmt.Fprintln(os.Stderr, " init-root <out-dir>")
fmt.Fprintln(os.Stderr, " issue-beacon <root-dir> <hostname> <out-dir>")
fmt.Fprintln(os.Stderr, " verify <root.crt> <leaf.crt> [hostname]")
}
flag.Parse()
args := flag.Args()
if len(args) < 1 {
flag.Usage()
os.Exit(2)
}
switch args[0] {
case "init-root":
if len(args) != 2 {
flag.Usage()
os.Exit(2)
}
if err := initRoot(args[1]); err != nil {
die("init-root: %v", err)
}
case "issue-beacon":
if len(args) != 4 {
flag.Usage()
os.Exit(2)
}
if err := issueBeacon(args[1], args[2], args[3]); err != nil {
die("issue-beacon: %v", err)
}
case "verify":
hostname := ""
if len(args) == 3 {
// verify <root.crt> <leaf.crt> — chain-only (backward compat)
} else if len(args) == 4 {
hostname = args[3]
} else {
flag.Usage()
os.Exit(2)
}
if err := verifyChain(args[1], args[2], hostname); err != nil {
die("verify: %v", err)
}
default:
flag.Usage()
os.Exit(2)
}
}
// initRoot generates a fresh Ed25519 keypair and a self-signed CA
// certificate. The .key file is written with mode 0600 — the operator
// is expected to move it to offline storage immediately after running.
func initRoot(outDir string) error {
if err := os.MkdirAll(outDir, 0o700); err != nil {
return fmt.Errorf("mkdir: %w", err)
}
keyPath := filepath.Join(outDir, "root.key")
if _, err := os.Stat(keyPath); err == nil {
return fmt.Errorf("refusing to overwrite existing %s — move it to offline storage first", keyPath)
}
pub, priv, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
return fmt.Errorf("generate key: %w", err)
}
serial, err := randomSerial()
if err != nil {
return err
}
now := time.Now().UTC()
tmpl := &x509.Certificate{
SerialNumber: serial,
Subject: pkix.Name{
CommonName: caCommonName,
Organization: []string{"Pilot Protocol"},
},
NotBefore: now,
NotAfter: now.AddDate(rootValidYears, 0, 0),
IsCA: true,
BasicConstraintsValid: true,
KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
MaxPathLen: 0,
MaxPathLenZero: true,
}
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, pub, priv)
if err != nil {
return fmt.Errorf("self-sign root: %w", err)
}
if err := writePEM(keyPath, "PRIVATE KEY", mustMarshalPKCS8(priv), 0o600); err != nil {
return err
}
if err := writePEM(filepath.Join(outDir, "root.crt"), "CERTIFICATE", der, 0o644); err != nil {
return err
}
fmt.Printf("Root CA generated.\n")
fmt.Printf(" root.key %s (mode 0600 — MOVE TO OFFLINE STORAGE NOW)\n", keyPath)
fmt.Printf(" root.crt %s (mode 0644 — embed in cmd/daemon)\n", filepath.Join(outDir, "root.crt"))
fmt.Printf(" not-after %s\n", tmpl.NotAfter.Format(time.RFC3339))
return nil
}
// issueBeacon signs a leaf cert for one beacon hostname. Output is a
// P-256 ECDSA keypair + leaf cert chained to the root. Leaf cert
// validity is 90 days; re-issue before expiry.
func issueBeacon(rootDir, hostname, outDir string) error {
if err := validateHostname(hostname); err != nil {
return err
}
rootCert, rootKey, err := loadRoot(rootDir)
if err != nil {
return err
}
if err := os.MkdirAll(outDir, 0o755); err != nil {
return fmt.Errorf("mkdir: %w", err)
}
leafKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return fmt.Errorf("generate leaf key: %w", err)
}
serial, err := randomSerial()
if err != nil {
return err
}
now := time.Now().UTC()
tmpl := &x509.Certificate{
SerialNumber: serial,
Subject: pkix.Name{
CommonName: hostname,
Organization: []string{"Pilot Protocol"},
},
NotBefore: now,
NotAfter: now.AddDate(0, 0, leafValidDays),
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
DNSNames: []string{hostname},
BasicConstraintsValid: true,
IsCA: false,
}
der, err := x509.CreateCertificate(rand.Reader, tmpl, rootCert, &leafKey.PublicKey, rootKey)
if err != nil {
return fmt.Errorf("sign leaf: %w", err)
}
keyPath := filepath.Join(outDir, hostname+".key")
crtPath := filepath.Join(outDir, hostname+".crt")
if err := writePEM(keyPath, "PRIVATE KEY", mustMarshalPKCS8(leafKey), 0o600); err != nil {
return err
}
if err := writePEM(crtPath, "CERTIFICATE", der, 0o644); err != nil {
return err
}
fmt.Printf("Leaf cert issued for %s.\n", hostname)
fmt.Printf(" %s (mode 0600 — deploy to beacon TLS config)\n", keyPath)
fmt.Printf(" %s (mode 0644 — deploy alongside .key)\n", crtPath)
fmt.Printf(" not-after %s (rotate before)\n", tmpl.NotAfter.Format(time.RFC3339))
return nil
}
// verifyChain confirms a leaf cert chains to a root cert and is valid
// for the current wall clock. When hostname is non-empty, the leaf's
// SAN is also checked against hostname via x509.VerifyOptions.DNSName.
// Used in CI before bundling a leaf into a beacon deployment, and as a
// sanity check in install/upgrade scripts.
func verifyChain(rootCrtPath, leafCrtPath, hostname string) error {
rootPEM, err := os.ReadFile(rootCrtPath)
if err != nil {
return fmt.Errorf("read root cert: %w", err)
}
leafPEM, err := os.ReadFile(leafCrtPath)
if err != nil {
return fmt.Errorf("read leaf cert: %w", err)
}
pool := x509.NewCertPool()
if !pool.AppendCertsFromPEM(rootPEM) {
return fmt.Errorf("root cert PEM parse failed")
}
leafBlock, _ := pem.Decode(leafPEM)
if leafBlock == nil {
return fmt.Errorf("leaf cert PEM parse failed")
}
leaf, err := x509.ParseCertificate(leafBlock.Bytes)
if err != nil {
return fmt.Errorf("leaf parse: %w", err)
}
opts := x509.VerifyOptions{
Roots: pool,
KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
}
if hostname != "" {
opts.DNSName = hostname
}
if _, err := leaf.Verify(opts); err != nil {
return fmt.Errorf("verify failed: %w", err)
}
fmt.Printf("OK — %s chains to %s\n", leafCrtPath, rootCrtPath)
if hostname != "" {
fmt.Printf(" hostname=%s CN=%s not-after=%s\n", hostname, leaf.Subject.CommonName, leaf.NotAfter.Format(time.RFC3339))
} else {
fmt.Printf(" CN=%s not-after=%s\n", leaf.Subject.CommonName, leaf.NotAfter.Format(time.RFC3339))
}
return nil
}
// loadRoot reads root.crt + root.key out of rootDir. Errors loudly
// if either is missing — the operator should never invoke issue-beacon
// without the root key being present.
func loadRoot(rootDir string) (*x509.Certificate, any, error) {
crtPEM, err := os.ReadFile(filepath.Join(rootDir, "root.crt"))
if err != nil {
return nil, nil, fmt.Errorf("read root.crt: %w", err)
}
keyPEM, err := os.ReadFile(filepath.Join(rootDir, "root.key"))
if err != nil {
return nil, nil, fmt.Errorf("read root.key: %w (must be online for issue-beacon — temporary mount from offline storage)", err)
}
crtBlock, _ := pem.Decode(crtPEM)
if crtBlock == nil {
return nil, nil, fmt.Errorf("root.crt: invalid PEM")
}
crt, err := x509.ParseCertificate(crtBlock.Bytes)
if err != nil {
return nil, nil, fmt.Errorf("root.crt parse: %w", err)
}
if !crt.IsCA {
return nil, nil, fmt.Errorf("root.crt: certificate is not a CA (IsCA=false)")
}
if !crt.BasicConstraintsValid {
return nil, nil, fmt.Errorf("root.crt: basic constraints missing or invalid")
}
keyBlock, _ := pem.Decode(keyPEM)
if keyBlock == nil {
return nil, nil, fmt.Errorf("root.key: invalid PEM")
}
key, err := x509.ParsePKCS8PrivateKey(keyBlock.Bytes)
if err != nil {
return nil, nil, fmt.Errorf("root.key parse: %w", err)
}
return crt, key, nil
}
func mustMarshalPKCS8(key any) []byte {
b, err := x509.MarshalPKCS8PrivateKey(key)
if err != nil {
panic(err)
}
return b
}
func writePEM(path, blockType string, der []byte, mode os.FileMode) error {
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, mode)
if err != nil {
return fmt.Errorf("open %s: %w", path, err)
}
defer f.Close()
if err := pem.Encode(f, &pem.Block{Type: blockType, Bytes: der}); err != nil {
return fmt.Errorf("encode %s: %w", path, err)
}
// fsync the data file so a crash after writePEM returns doesn't lose the cert.
if err := f.Sync(); err != nil {
return fmt.Errorf("sync %s: %w", path, err)
}
// fsync the parent directory so the directory entry is committed.
if dir, err := os.Open(filepath.Dir(path)); err == nil {
dir.Sync() // best-effort; Close will report any delayed error
dir.Close()
}
return nil
}
func randomSerial() (*big.Int, error) {
limit := new(big.Int).Lsh(big.NewInt(1), 128) // 128-bit serial
n, err := rand.Int(rand.Reader, limit)
if err != nil {
return nil, fmt.Errorf("serial: %w", err)
}
return n, nil
}
func die(format string, a ...any) {
fmt.Fprintf(os.Stderr, "pilot-ca: "+format+"\n", a...)
os.Exit(1)
}