blob: ce9a84093e23c8df112a36b11a42f8e19ba738d5 [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//
20// CA and certificates successfully pass https://github.com/zmap/zlint
21// (minus the CA/B rules that a public CA would adhere to, which requires
22// things like OCSP servers, Certificate Policies and ECDSA/RSA-only keys).
Lorenz Bruna4ea9d02019-10-31 11:40:30 +010023package ca
24
Leopold Schabel68c58752019-11-14 21:00:59 +010025// TODO(leo): add zlint test
26
Lorenz Bruna4ea9d02019-10-31 11:40:30 +010027import (
28 "crypto"
29 "crypto/ed25519"
30 "crypto/rand"
31 "crypto/sha1"
32 "crypto/x509"
33 "crypto/x509/pkix"
34 "encoding/asn1"
35 "errors"
36 "fmt"
37 "math/big"
38 "time"
39)
40
41var (
42 // From RFC 5280 Section 4.1.2.5
43 unknownNotAfter = time.Unix(253402300799, 0)
44)
45
46type CA struct {
47 // TODO: Potentially protect the key with memguard
48 PrivateKey *ed25519.PrivateKey
49 CACert *x509.Certificate
50 CACertRaw []byte
51 CRLRaw []byte
52 Revoked []pkix.RevokedCertificate
53}
54
55// Workaround for https://github.com/golang/go/issues/26676 in Go's crypto/x509. Specifically Go
56// violates Section 4.2.1.2 of RFC 5280 without this. Should eventually be redundant.
57//
58// 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 +010059// crypto engineers (BSD 3-clause).
Lorenz Bruna4ea9d02019-10-31 11:40:30 +010060func calculateSKID(pubKey crypto.PublicKey) ([]byte, error) {
61 spkiASN1, err := x509.MarshalPKIXPublicKey(pubKey)
62 if err != nil {
63 return nil, err
64 }
65
66 var spki struct {
67 Algorithm pkix.AlgorithmIdentifier
68 SubjectPublicKey asn1.BitString
69 }
70 _, err = asn1.Unmarshal(spkiASN1, &spki)
71 if err != nil {
72 return nil, err
73 }
74 skid := sha1.Sum(spki.SubjectPublicKey.Bytes)
75 return skid[:], nil
76}
77
Leopold Schabel68c58752019-11-14 21:00:59 +010078// New creates a new certificate authority with the given common name.
Lorenz Bruna4ea9d02019-10-31 11:40:30 +010079func New(name string) (*CA, error) {
80 pubKey, privKey, err := ed25519.GenerateKey(rand.Reader)
81 if err != nil {
82 panic(err)
83 }
84
85 serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 127)
86 serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
87 if err != nil {
Leopold Schabel68c58752019-11-14 21:00:59 +010088 return nil, fmt.Errorf("failed to generate serial number: %w", err)
Lorenz Bruna4ea9d02019-10-31 11:40:30 +010089 }
90
91 skid, err := calculateSKID(pubKey)
92 if err != nil {
93 return nil, err
94 }
95
96 caCert := &x509.Certificate{
97 SerialNumber: serialNumber,
98 Subject: pkix.Name{
99 CommonName: name,
100 },
101 IsCA: true,
102 BasicConstraintsValid: true,
103 NotBefore: time.Now(),
104 NotAfter: unknownNotAfter,
105 KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign | x509.KeyUsageDigitalSignature,
106 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageOCSPSigning},
107 AuthorityKeyId: skid,
108 SubjectKeyId: skid,
109 }
110
111 caCertRaw, err := x509.CreateCertificate(rand.Reader, caCert, caCert, pubKey, privKey)
112 if err != nil {
Leopold Schabel68c58752019-11-14 21:00:59 +0100113 return nil, fmt.Errorf("failed to create root certificate: %w", err)
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100114 }
115
116 ca := &CA{
117 PrivateKey: &privKey,
118 CACertRaw: caCertRaw,
119 CACert: caCert,
120 }
Leopold Schabel68c58752019-11-14 21:00:59 +0100121 if ca.ReissueCRL() != nil {
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100122 return nil, fmt.Errorf("failed to create initial CRL: %w", err)
123 }
124
125 return ca, nil
126}
127
Leopold Schabel68c58752019-11-14 21:00:59 +0100128// FromCertificates restores CA state.
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100129func FromCertificates(caCert []byte, caKey []byte, crl []byte) (*CA, error) {
130 if len(caKey) != ed25519.PrivateKeySize {
Leopold Schabel68c58752019-11-14 21:00:59 +0100131 return nil, errors.New("invalid CA private key size")
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100132 }
133 privateKey := ed25519.PrivateKey(caKey)
134
135 caCertVal, err := x509.ParseCertificate(caCert)
136 if err != nil {
137 return nil, err
138 }
139 crlVal, err := x509.ParseCRL(crl)
140 if err != nil {
141 return nil, err
142 }
143 return &CA{
144 PrivateKey: &privateKey,
145 CACertRaw: caCert,
146 CACert: caCertVal,
147 Revoked: crlVal.TBSCertList.RevokedCertificates,
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100148 }, nil
149}
150
Leopold Schabel68c58752019-11-14 21:00:59 +0100151// IssueCertificate issues a certificate
152func (ca *CA) IssueCertificate(commonName string) (cert []byte, privkey []byte, err error) {
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100153 serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 127)
154 serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
155 if err != nil {
156 err = fmt.Errorf("Failed to generate serial number: %w", err)
157 return
158 }
159
160 pubKey, privKeyRaw, err := ed25519.GenerateKey(rand.Reader)
161 if err != nil {
162 return
163 }
164 privkey, err = x509.MarshalPKCS8PrivateKey(privKeyRaw)
165 if err != nil {
166 return
167 }
168
169 etcdCert := &x509.Certificate{
170 SerialNumber: serialNumber,
171 Subject: pkix.Name{
Leopold Schabel68c58752019-11-14 21:00:59 +0100172 CommonName: commonName,
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100173 OrganizationalUnit: []string{"etcd"},
174 },
175 IsCA: false,
176 BasicConstraintsValid: true,
177 NotBefore: time.Now(),
178 NotAfter: unknownNotAfter,
179 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
Leopold Schabel68c58752019-11-14 21:00:59 +0100180 DNSNames: []string{commonName},
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100181 }
182 cert, err = x509.CreateCertificate(rand.Reader, etcdCert, ca.CACert, pubKey, ca.PrivateKey)
183 return
184}
185
Leopold Schabel68c58752019-11-14 21:00:59 +0100186func (ca *CA) ReissueCRL() error {
Lorenz Brund3c59d22020-05-11 16:00:22 +0200187 newCRL, err := ca.CACert.CreateCRL(rand.Reader, ca.PrivateKey, ca.Revoked, time.Now(), unknownNotAfter)
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100188 if err != nil {
189 return err
190 }
191 ca.CRLRaw = newCRL
192 return nil
193}
194
195func (ca *CA) Revoke(serial *big.Int) error {
196 for _, revokedCert := range ca.Revoked {
197 if revokedCert.SerialNumber.Cmp(serial) == 0 {
198 return nil // Already revoked
199 }
200 }
201 ca.Revoked = append(ca.Revoked, pkix.RevokedCertificate{
202 SerialNumber: serial,
203 RevocationTime: time.Now(),
204 })
Leopold Schabel68c58752019-11-14 21:00:59 +0100205 return ca.ReissueCRL()
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100206}