blob: 5952b6f07ce216bd4a84b4596035d20643d21eec [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
Lorenz Brun878f5f92020-05-12 16:15:39 +020056// violates Section 4.2.1.2 of RFC 5280 without this.
57// Fixed for 1.15 in https://go-review.googlesource.com/c/go/+/227098/.
Lorenz Bruna4ea9d02019-10-31 11:40:30 +010058//
59// 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 +010060// crypto engineers (BSD 3-clause).
Lorenz Bruna4ea9d02019-10-31 11:40:30 +010061func calculateSKID(pubKey crypto.PublicKey) ([]byte, error) {
62 spkiASN1, err := x509.MarshalPKIXPublicKey(pubKey)
63 if err != nil {
64 return nil, err
65 }
66
67 var spki struct {
68 Algorithm pkix.AlgorithmIdentifier
69 SubjectPublicKey asn1.BitString
70 }
71 _, err = asn1.Unmarshal(spkiASN1, &spki)
72 if err != nil {
73 return nil, err
74 }
75 skid := sha1.Sum(spki.SubjectPublicKey.Bytes)
76 return skid[:], nil
77}
78
Leopold Schabel68c58752019-11-14 21:00:59 +010079// New creates a new certificate authority with the given common name.
Lorenz Bruna4ea9d02019-10-31 11:40:30 +010080func New(name string) (*CA, error) {
81 pubKey, privKey, err := ed25519.GenerateKey(rand.Reader)
82 if err != nil {
83 panic(err)
84 }
85
86 serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 127)
87 serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
88 if err != nil {
Leopold Schabel68c58752019-11-14 21:00:59 +010089 return nil, fmt.Errorf("failed to generate serial number: %w", err)
Lorenz Bruna4ea9d02019-10-31 11:40:30 +010090 }
91
92 skid, err := calculateSKID(pubKey)
93 if err != nil {
94 return nil, err
95 }
96
97 caCert := &x509.Certificate{
98 SerialNumber: serialNumber,
99 Subject: pkix.Name{
100 CommonName: name,
101 },
102 IsCA: true,
103 BasicConstraintsValid: true,
104 NotBefore: time.Now(),
105 NotAfter: unknownNotAfter,
106 KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign | x509.KeyUsageDigitalSignature,
107 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageOCSPSigning},
108 AuthorityKeyId: skid,
109 SubjectKeyId: skid,
110 }
111
112 caCertRaw, err := x509.CreateCertificate(rand.Reader, caCert, caCert, pubKey, privKey)
113 if err != nil {
Leopold Schabel68c58752019-11-14 21:00:59 +0100114 return nil, fmt.Errorf("failed to create root certificate: %w", err)
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100115 }
116
117 ca := &CA{
118 PrivateKey: &privKey,
119 CACertRaw: caCertRaw,
120 CACert: caCert,
121 }
Leopold Schabel68c58752019-11-14 21:00:59 +0100122 if ca.ReissueCRL() != nil {
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100123 return nil, fmt.Errorf("failed to create initial CRL: %w", err)
124 }
125
126 return ca, nil
127}
128
Leopold Schabel68c58752019-11-14 21:00:59 +0100129// FromCertificates restores CA state.
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100130func FromCertificates(caCert []byte, caKey []byte, crl []byte) (*CA, error) {
131 if len(caKey) != ed25519.PrivateKeySize {
Leopold Schabel68c58752019-11-14 21:00:59 +0100132 return nil, errors.New("invalid CA private key size")
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100133 }
134 privateKey := ed25519.PrivateKey(caKey)
135
136 caCertVal, err := x509.ParseCertificate(caCert)
137 if err != nil {
138 return nil, err
139 }
140 crlVal, err := x509.ParseCRL(crl)
141 if err != nil {
142 return nil, err
143 }
144 return &CA{
145 PrivateKey: &privateKey,
146 CACertRaw: caCert,
147 CACert: caCertVal,
148 Revoked: crlVal.TBSCertList.RevokedCertificates,
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100149 }, nil
150}
151
Leopold Schabel68c58752019-11-14 21:00:59 +0100152// IssueCertificate issues a certificate
153func (ca *CA) IssueCertificate(commonName string) (cert []byte, privkey []byte, err error) {
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100154 serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 127)
155 serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
156 if err != nil {
157 err = fmt.Errorf("Failed to generate serial number: %w", err)
158 return
159 }
160
161 pubKey, privKeyRaw, err := ed25519.GenerateKey(rand.Reader)
162 if err != nil {
163 return
164 }
165 privkey, err = x509.MarshalPKCS8PrivateKey(privKeyRaw)
166 if err != nil {
167 return
168 }
169
170 etcdCert := &x509.Certificate{
171 SerialNumber: serialNumber,
172 Subject: pkix.Name{
Leopold Schabel68c58752019-11-14 21:00:59 +0100173 CommonName: commonName,
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100174 OrganizationalUnit: []string{"etcd"},
175 },
176 IsCA: false,
177 BasicConstraintsValid: true,
178 NotBefore: time.Now(),
179 NotAfter: unknownNotAfter,
180 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
Leopold Schabel68c58752019-11-14 21:00:59 +0100181 DNSNames: []string{commonName},
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100182 }
183 cert, err = x509.CreateCertificate(rand.Reader, etcdCert, ca.CACert, pubKey, ca.PrivateKey)
184 return
185}
186
Leopold Schabel68c58752019-11-14 21:00:59 +0100187func (ca *CA) ReissueCRL() error {
Lorenz Brund3c59d22020-05-11 16:00:22 +0200188 newCRL, err := ca.CACert.CreateCRL(rand.Reader, ca.PrivateKey, ca.Revoked, time.Now(), unknownNotAfter)
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100189 if err != nil {
190 return err
191 }
192 ca.CRLRaw = newCRL
193 return nil
194}
195
196func (ca *CA) Revoke(serial *big.Int) error {
197 for _, revokedCert := range ca.Revoked {
198 if revokedCert.SerialNumber.Cmp(serial) == 0 {
199 return nil // Already revoked
200 }
201 }
202 ca.Revoked = append(ca.Revoked, pkix.RevokedCertificate{
203 SerialNumber: serial,
204 RevocationTime: time.Now(),
205 })
Leopold Schabel68c58752019-11-14 21:00:59 +0100206 return ca.ReissueCRL()
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100207}