blob: 9a1b634f99c61fa0cf025c1a3babeccd89e2adaf [file] [log] [blame]
Lorenz Bruna4ea9d02019-10-31 11:40:30 +01001// Copyright 2020 The Monogon Project Authors.
2//
3// SPDX-License-Identifier: Apache-2.0
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
Leopold Schabel68c58752019-11-14 21:00:59 +010017// package ca implements a simple standards-compliant certificate authority.
18// It only supports ed25519 keys, and does not maintain any persistent state.
19//
Serge Bazanskicb883e22020-07-06 17:47:55 +020020// The CA is backed by etcd storage, and can also bootstrap itself without a yet running etcd storage (and commit
21// in-memory secrets to etcd at a later date).
22//
Leopold Schabel68c58752019-11-14 21:00:59 +010023// CA and certificates successfully pass https://github.com/zmap/zlint
24// (minus the CA/B rules that a public CA would adhere to, which requires
25// things like OCSP servers, Certificate Policies and ECDSA/RSA-only keys).
Lorenz Bruna4ea9d02019-10-31 11:40:30 +010026package ca
27
Leopold Schabel68c58752019-11-14 21:00:59 +010028// TODO(leo): add zlint test
29
Lorenz Bruna4ea9d02019-10-31 11:40:30 +010030import (
Serge Bazanskicb883e22020-07-06 17:47:55 +020031 "context"
Lorenz Bruna4ea9d02019-10-31 11:40:30 +010032 "crypto"
33 "crypto/ed25519"
34 "crypto/rand"
35 "crypto/sha1"
36 "crypto/x509"
37 "crypto/x509/pkix"
38 "encoding/asn1"
Serge Bazanskicb883e22020-07-06 17:47:55 +020039 "encoding/hex"
Lorenz Bruna4ea9d02019-10-31 11:40:30 +010040 "errors"
41 "fmt"
42 "math/big"
Lorenz Brun52f7f292020-06-24 16:42:02 +020043 "net"
Lorenz Bruna4ea9d02019-10-31 11:40:30 +010044 "time"
Serge Bazanskicb883e22020-07-06 17:47:55 +020045
46 "go.etcd.io/etcd/clientv3"
Lorenz Bruna4ea9d02019-10-31 11:40:30 +010047)
48
Serge Bazanskicb883e22020-07-06 17:47:55 +020049const (
50 // TODO(q3k): move this to a declarative storage layer
51 pathCACertificate = "/etcd-ca/ca.der"
52 pathCAKey = "/etcd-ca/ca-key.der"
53 pathCACRL = "/etcd-ca/crl.der"
54 pathIssuedCertificates = "/etcd-ca/certs/"
55)
56
57func pathIssuedCertificate(serial *big.Int) string {
58 return pathIssuedCertificates + hex.EncodeToString(serial.Bytes())
59}
60
Lorenz Bruna4ea9d02019-10-31 11:40:30 +010061var (
62 // From RFC 5280 Section 4.1.2.5
63 unknownNotAfter = time.Unix(253402300799, 0)
64)
65
66type CA struct {
67 // TODO: Potentially protect the key with memguard
Serge Bazanskicb883e22020-07-06 17:47:55 +020068 privateKey *ed25519.PrivateKey
Lorenz Bruna4ea9d02019-10-31 11:40:30 +010069 CACert *x509.Certificate
70 CACertRaw []byte
Serge Bazanskicb883e22020-07-06 17:47:55 +020071
72 // bootstrapIssued are certificates that have been issued by the CA before it has been successfully Saved to etcd.
73 bootstrapIssued [][]byte
74 // canBootstrapIssue is set on CAs that have been created by New and not yet stored to etcd. If not set,
75 // certificates cannot be issued in-memory.
76 canBootstrapIssue bool
Lorenz Bruna4ea9d02019-10-31 11:40:30 +010077}
78
79// Workaround for https://github.com/golang/go/issues/26676 in Go's crypto/x509. Specifically Go
Lorenz Brun878f5f92020-05-12 16:15:39 +020080// violates Section 4.2.1.2 of RFC 5280 without this.
81// Fixed for 1.15 in https://go-review.googlesource.com/c/go/+/227098/.
Lorenz Bruna4ea9d02019-10-31 11:40:30 +010082//
83// Taken from https://github.com/FiloSottile/mkcert/blob/master/cert.go#L295 written by one of Go's
Leopold Schabel68c58752019-11-14 21:00:59 +010084// crypto engineers (BSD 3-clause).
Lorenz Bruna4ea9d02019-10-31 11:40:30 +010085func calculateSKID(pubKey crypto.PublicKey) ([]byte, error) {
86 spkiASN1, err := x509.MarshalPKIXPublicKey(pubKey)
87 if err != nil {
88 return nil, err
89 }
90
91 var spki struct {
92 Algorithm pkix.AlgorithmIdentifier
93 SubjectPublicKey asn1.BitString
94 }
95 _, err = asn1.Unmarshal(spkiASN1, &spki)
96 if err != nil {
97 return nil, err
98 }
99 skid := sha1.Sum(spki.SubjectPublicKey.Bytes)
100 return skid[:], nil
101}
102
Serge Bazanskicb883e22020-07-06 17:47:55 +0200103// New creates a new certificate authority with the given common name. The newly created CA will be stored in memory
104// until committed to etcd by calling .Save.
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100105func New(name string) (*CA, error) {
106 pubKey, privKey, err := ed25519.GenerateKey(rand.Reader)
107 if err != nil {
108 panic(err)
109 }
110
111 serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 127)
112 serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
113 if err != nil {
Leopold Schabel68c58752019-11-14 21:00:59 +0100114 return nil, fmt.Errorf("failed to generate serial number: %w", err)
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100115 }
116
117 skid, err := calculateSKID(pubKey)
118 if err != nil {
119 return nil, err
120 }
121
122 caCert := &x509.Certificate{
123 SerialNumber: serialNumber,
124 Subject: pkix.Name{
125 CommonName: name,
126 },
127 IsCA: true,
128 BasicConstraintsValid: true,
129 NotBefore: time.Now(),
130 NotAfter: unknownNotAfter,
131 KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign | x509.KeyUsageDigitalSignature,
132 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageOCSPSigning},
133 AuthorityKeyId: skid,
134 SubjectKeyId: skid,
135 }
136
137 caCertRaw, err := x509.CreateCertificate(rand.Reader, caCert, caCert, pubKey, privKey)
138 if err != nil {
Leopold Schabel68c58752019-11-14 21:00:59 +0100139 return nil, fmt.Errorf("failed to create root certificate: %w", err)
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100140 }
141
142 ca := &CA{
Serge Bazanskicb883e22020-07-06 17:47:55 +0200143 privateKey: &privKey,
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100144 CACertRaw: caCertRaw,
145 CACert: caCert,
Serge Bazanskicb883e22020-07-06 17:47:55 +0200146
147 canBootstrapIssue: true,
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100148 }
149
150 return ca, nil
151}
152
Serge Bazanskicb883e22020-07-06 17:47:55 +0200153// Load restores CA state from etcd.
154func Load(ctx context.Context, kv clientv3.KV) (*CA, error) {
155 resp, err := kv.Txn(ctx).Then(
156 clientv3.OpGet(pathCACertificate),
157 clientv3.OpGet(pathCAKey),
158 // We only read the CRL to ensure it exists on etcd (and early fail on inconsistency)
159 clientv3.OpGet(pathCACRL)).Commit()
160 if err != nil {
161 return nil, fmt.Errorf("failed to retrieve CA from etcd: %w", err)
162 }
163
164 var caCert, caKey, caCRL []byte
165 for _, el := range resp.Responses {
166 for _, kv := range el.GetResponseRange().GetKvs() {
167 switch string(kv.Key) {
168 case pathCACertificate:
169 caCert = kv.Value
170 case pathCAKey:
171 caKey = kv.Value
172 case pathCACRL:
173 caCRL = kv.Value
174 }
175 }
176 }
177 if caCert == nil || caKey == nil || caCRL == nil {
178 return nil, fmt.Errorf("failed to retrieve CA from etcd, missing at least one of {ca key, ca crt, ca crl}")
179 }
180
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100181 if len(caKey) != ed25519.PrivateKeySize {
Leopold Schabel68c58752019-11-14 21:00:59 +0100182 return nil, errors.New("invalid CA private key size")
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100183 }
184 privateKey := ed25519.PrivateKey(caKey)
185
186 caCertVal, err := x509.ParseCertificate(caCert)
187 if err != nil {
Serge Bazanskicb883e22020-07-06 17:47:55 +0200188 return nil, fmt.Errorf("failed to parse CA certificate: %w", err)
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100189 }
190 return &CA{
Serge Bazanskicb883e22020-07-06 17:47:55 +0200191 privateKey: &privateKey,
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100192 CACertRaw: caCert,
193 CACert: caCertVal,
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100194 }, nil
195}
196
Serge Bazanskicb883e22020-07-06 17:47:55 +0200197// Save stores a newly created CA into etcd, committing both the CA data and any certificates issued until then.
198func (c *CA) Save(ctx context.Context, kv clientv3.KV) error {
199 crl, err := c.makeCRL(nil)
200 if err != nil {
201 return fmt.Errorf("failed to generate initial CRL: %w", err)
202 }
203
204 ops := []clientv3.Op{
205 clientv3.OpPut(pathCACertificate, string(c.CACertRaw)),
206 clientv3.OpPut(pathCAKey, string([]byte(*c.privateKey))),
207 clientv3.OpPut(pathCACRL, string(crl)),
208 }
209 for i, certRaw := range c.bootstrapIssued {
210 cert, err := x509.ParseCertificate(certRaw)
211 if err != nil {
212 return fmt.Errorf("failed to parse in-memory certificate %d", i)
213 }
214 ops = append(ops, clientv3.OpPut(pathIssuedCertificate(cert.SerialNumber), string(certRaw)))
215 }
216
217 res, err := kv.Txn(ctx).If(
218 clientv3.Compare(clientv3.CreateRevision(pathCAKey), "=", 0),
219 ).Then(ops...).Commit()
220 if err != nil {
221 return fmt.Errorf("failed to store CA to etcd: %w", err)
222 }
223 if !res.Succeeded {
224 // This should pretty much never happen, but we want to catch it just in case.
225 return fmt.Errorf("failed to store CA to etcd: CA already present - cluster-level data inconsistency")
226 }
227 c.bootstrapIssued = nil
228 c.canBootstrapIssue = false
229 return nil
230}
231
232// Issue issues a certificate. If kv is non-nil, the newly issued certificate will be immediately stored to etcd,
233// otherwise it will be kept in memory (until .Save is called). Certificates can only be issued to memory on
234// newly-created CAs that have not been saved to etcd yet.
235func (c *CA) Issue(ctx context.Context, kv clientv3.KV, commonName string, externalAddress net.IP) (cert []byte, privkey []byte, err error) {
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100236 serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 127)
237 serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
238 if err != nil {
Serge Bazanskicb883e22020-07-06 17:47:55 +0200239 err = fmt.Errorf("failed to generate serial number: %w", err)
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100240 return
241 }
242
243 pubKey, privKeyRaw, err := ed25519.GenerateKey(rand.Reader)
244 if err != nil {
245 return
246 }
247 privkey, err = x509.MarshalPKCS8PrivateKey(privKeyRaw)
248 if err != nil {
249 return
250 }
251
252 etcdCert := &x509.Certificate{
253 SerialNumber: serialNumber,
254 Subject: pkix.Name{
Leopold Schabel68c58752019-11-14 21:00:59 +0100255 CommonName: commonName,
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100256 OrganizationalUnit: []string{"etcd"},
257 },
258 IsCA: false,
259 BasicConstraintsValid: true,
260 NotBefore: time.Now(),
261 NotAfter: unknownNotAfter,
262 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
Leopold Schabel68c58752019-11-14 21:00:59 +0100263 DNSNames: []string{commonName},
Serge Bazanskicb883e22020-07-06 17:47:55 +0200264 IPAddresses: []net.IP{externalAddress},
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100265 }
Serge Bazanskicb883e22020-07-06 17:47:55 +0200266 cert, err = x509.CreateCertificate(rand.Reader, etcdCert, c.CACert, pubKey, c.privateKey)
267 if err != nil {
268 err = fmt.Errorf("failed to sign new certificate: %w", err)
269 return
270 }
271
272 if kv != nil {
273 path := pathIssuedCertificate(serialNumber)
274 _, err = kv.Put(ctx, path, string(cert))
275 if err != nil {
276 err = fmt.Errorf("failed to commit new certificate to etcd: %w", err)
277 return
278 }
279 } else {
280 if !c.canBootstrapIssue {
281 err = fmt.Errorf("cannot issue new certificate to memory on existing, etcd-backed CA")
282 return
283 }
284 c.bootstrapIssued = append(c.bootstrapIssued, cert)
285 }
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100286 return
287}
288
Serge Bazanskicb883e22020-07-06 17:47:55 +0200289func (c *CA) makeCRL(revoked []pkix.RevokedCertificate) ([]byte, error) {
290 crl, err := c.CACert.CreateCRL(rand.Reader, c.privateKey, revoked, time.Now(), unknownNotAfter)
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100291 if err != nil {
Serge Bazanskicb883e22020-07-06 17:47:55 +0200292 return nil, fmt.Errorf("failed to generate CRL: %w", err)
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100293 }
Serge Bazanskicb883e22020-07-06 17:47:55 +0200294 return crl, nil
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100295}
296
Serge Bazanskicb883e22020-07-06 17:47:55 +0200297// Revoke revokes a certificate by hostname. The selected hostname will be added to the CRL stored in etcd. This call
298// might fail (safely) if a simultaneous revoke happened that caused the CRL to be bumped. The call can be then retried
299// safely.
300func (c *CA) Revoke(ctx context.Context, kv clientv3.KV, hostname string) error {
301 res, err := kv.Txn(ctx).Then(
302 clientv3.OpGet(pathCACRL),
303 clientv3.OpGet(pathIssuedCertificates, clientv3.WithPrefix())).Commit()
304 if err != nil {
305 return fmt.Errorf("failed to retrieve certificates and CRL from etcd: %w", err)
306 }
307
308 var certs []*x509.Certificate
309 var crlRevision int64
310 var crl *pkix.CertificateList
311 for _, el := range res.Responses {
312 for _, kv := range el.GetResponseRange().GetKvs() {
313 if string(kv.Key) == pathCACRL {
314 crl, err = x509.ParseCRL(kv.Value)
315 if err != nil {
316 return fmt.Errorf("could not parse CRL from etcd: %w", err)
317 }
318 crlRevision = kv.CreateRevision
319 } else {
320 cert, err := x509.ParseCertificate(kv.Value)
321 if err != nil {
322 return fmt.Errorf("could not parse certificate %q from etcd: %w", string(kv.Key), err)
323 }
324 certs = append(certs, cert)
325 }
326 }
327 }
328
329 if crl == nil {
330 return fmt.Errorf("could not find CRL in etcd")
331 }
332 revoked := crl.TBSCertList.RevokedCertificates
333
334 // Find requested hostname in issued certificates.
335 var serial *big.Int
336 for _, cert := range certs {
337 for _, dnsName := range cert.DNSNames {
338 if dnsName == hostname {
339 serial = cert.SerialNumber
340 break
341 }
342 }
343 if serial != nil {
344 break
345 }
346 }
347 if serial == nil {
348 return fmt.Errorf("could not find requested hostname")
349 }
350
351 // Check if certificate has already been revoked.
352 for _, revokedCert := range revoked {
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100353 if revokedCert.SerialNumber.Cmp(serial) == 0 {
354 return nil // Already revoked
355 }
356 }
Serge Bazanskicb883e22020-07-06 17:47:55 +0200357
358 revoked = append(revoked, pkix.RevokedCertificate{
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100359 SerialNumber: serial,
360 RevocationTime: time.Now(),
361 })
Serge Bazanskicb883e22020-07-06 17:47:55 +0200362
363 crlRaw, err := c.makeCRL(revoked)
364 if err != nil {
365 return fmt.Errorf("when generating new CRL for revocation: %w", err)
366 }
367
368 res, err = kv.Txn(ctx).If(
369 clientv3.Compare(clientv3.CreateRevision(pathCACRL), "=", crlRevision),
370 ).Then(
371 clientv3.OpPut(pathCACRL, string(crlRaw)),
372 ).Commit()
373 if err != nil {
374 return fmt.Errorf("when saving new CRL: %w", err)
375 }
376 if !res.Succeeded {
377 return fmt.Errorf("CRL save transaction failed, retry possibly")
378 }
379
380 return nil
381}
382
383// WaitCRLChange returns a channel that will receive a CRLUpdate any time the remote CRL changed. Immediately after
384// calling this method, the current CRL is retrieved from the cluster and put into the channel.
385func (c *CA) WaitCRLChange(ctx context.Context, kv clientv3.KV, w clientv3.Watcher) <-chan CRLUpdate {
386 C := make(chan CRLUpdate)
387
388 go func(ctx context.Context) {
389 ctxC, cancel := context.WithCancel(ctx)
390 defer cancel()
391
392 fail := func(f string, args ...interface{}) {
393 C <- CRLUpdate{Err: fmt.Errorf(f, args...)}
394 close(C)
395 }
396
397 initial, err := kv.Get(ctx, pathCACRL)
398 if err != nil {
399 fail("failed to retrieve initial CRL: %w", err)
400 return
401 }
402
403 C <- CRLUpdate{CRL: initial.Kvs[0].Value}
404
405 for wr := range w.Watch(ctxC, pathCACRL, clientv3.WithRev(initial.Kvs[0].CreateRevision)) {
406 if wr.Err() != nil {
407 fail("failed watching CRL: %w", wr.Err())
408 return
409 }
410
411 for _, e := range wr.Events {
412 if string(e.Kv.Key) != pathCACRL {
413 continue
414 }
415
416 C <- CRLUpdate{CRL: e.Kv.Value}
417 }
418 }
419 }(ctx)
420
421 return C
422}
423
424// CRLUpdate is emitted for every remote CRL change, and spuriously on ever new WaitCRLChange.
425type CRLUpdate struct {
426 // The new (or existing, in the case of the first call) CRL. If nil, Err will be set.
427 CRL []byte
428 // If set, an error occurred and the WaitCRLChange call must be restarted. If set, CRL will be nil.
429 Err error
430}
431
432// GetCurrentCRL returns the current CRL for the CA. This should only be used for one-shot operations like
433// bootstrapping a new node that doesn't yet have access to etcd - otherwise, WaitCRLChange shoulde be used.
434func (c *CA) GetCurrentCRL(ctx context.Context, kv clientv3.KV) ([]byte, error) {
435 initial, err := kv.Get(ctx, pathCACRL)
436 if err != nil {
437 return nil, fmt.Errorf("failed to retrieve initial CRL: %w", err)
438 }
439 return initial.Kvs[0].Value, nil
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100440}