blob: 20f7c31b12d4fc5d865ad8ece30c07665599611f [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"
Lorenz Brun52f7f292020-06-24 16:42:02 +020038 "net"
Lorenz Bruna4ea9d02019-10-31 11:40:30 +010039 "time"
40)
41
42var (
43 // From RFC 5280 Section 4.1.2.5
44 unknownNotAfter = time.Unix(253402300799, 0)
45)
46
47type CA struct {
48 // TODO: Potentially protect the key with memguard
49 PrivateKey *ed25519.PrivateKey
50 CACert *x509.Certificate
51 CACertRaw []byte
52 CRLRaw []byte
53 Revoked []pkix.RevokedCertificate
54}
55
56// Workaround for https://github.com/golang/go/issues/26676 in Go's crypto/x509. Specifically Go
Lorenz Brun878f5f92020-05-12 16:15:39 +020057// violates Section 4.2.1.2 of RFC 5280 without this.
58// Fixed for 1.15 in https://go-review.googlesource.com/c/go/+/227098/.
Lorenz Bruna4ea9d02019-10-31 11:40:30 +010059//
60// 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 +010061// crypto engineers (BSD 3-clause).
Lorenz Bruna4ea9d02019-10-31 11:40:30 +010062func calculateSKID(pubKey crypto.PublicKey) ([]byte, error) {
63 spkiASN1, err := x509.MarshalPKIXPublicKey(pubKey)
64 if err != nil {
65 return nil, err
66 }
67
68 var spki struct {
69 Algorithm pkix.AlgorithmIdentifier
70 SubjectPublicKey asn1.BitString
71 }
72 _, err = asn1.Unmarshal(spkiASN1, &spki)
73 if err != nil {
74 return nil, err
75 }
76 skid := sha1.Sum(spki.SubjectPublicKey.Bytes)
77 return skid[:], nil
78}
79
Leopold Schabel68c58752019-11-14 21:00:59 +010080// New creates a new certificate authority with the given common name.
Lorenz Bruna4ea9d02019-10-31 11:40:30 +010081func New(name string) (*CA, error) {
82 pubKey, privKey, err := ed25519.GenerateKey(rand.Reader)
83 if err != nil {
84 panic(err)
85 }
86
87 serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 127)
88 serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
89 if err != nil {
Leopold Schabel68c58752019-11-14 21:00:59 +010090 return nil, fmt.Errorf("failed to generate serial number: %w", err)
Lorenz Bruna4ea9d02019-10-31 11:40:30 +010091 }
92
93 skid, err := calculateSKID(pubKey)
94 if err != nil {
95 return nil, err
96 }
97
98 caCert := &x509.Certificate{
99 SerialNumber: serialNumber,
100 Subject: pkix.Name{
101 CommonName: name,
102 },
103 IsCA: true,
104 BasicConstraintsValid: true,
105 NotBefore: time.Now(),
106 NotAfter: unknownNotAfter,
107 KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign | x509.KeyUsageDigitalSignature,
108 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageOCSPSigning},
109 AuthorityKeyId: skid,
110 SubjectKeyId: skid,
111 }
112
113 caCertRaw, err := x509.CreateCertificate(rand.Reader, caCert, caCert, pubKey, privKey)
114 if err != nil {
Leopold Schabel68c58752019-11-14 21:00:59 +0100115 return nil, fmt.Errorf("failed to create root certificate: %w", err)
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100116 }
117
118 ca := &CA{
119 PrivateKey: &privKey,
120 CACertRaw: caCertRaw,
121 CACert: caCert,
122 }
Leopold Schabel68c58752019-11-14 21:00:59 +0100123 if ca.ReissueCRL() != nil {
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100124 return nil, fmt.Errorf("failed to create initial CRL: %w", err)
125 }
126
127 return ca, nil
128}
129
Leopold Schabel68c58752019-11-14 21:00:59 +0100130// FromCertificates restores CA state.
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100131func FromCertificates(caCert []byte, caKey []byte, crl []byte) (*CA, error) {
132 if len(caKey) != ed25519.PrivateKeySize {
Leopold Schabel68c58752019-11-14 21:00:59 +0100133 return nil, errors.New("invalid CA private key size")
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100134 }
135 privateKey := ed25519.PrivateKey(caKey)
136
137 caCertVal, err := x509.ParseCertificate(caCert)
138 if err != nil {
139 return nil, err
140 }
141 crlVal, err := x509.ParseCRL(crl)
142 if err != nil {
143 return nil, err
144 }
145 return &CA{
146 PrivateKey: &privateKey,
147 CACertRaw: caCert,
148 CACert: caCertVal,
149 Revoked: crlVal.TBSCertList.RevokedCertificates,
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100150 }, nil
151}
152
Leopold Schabel68c58752019-11-14 21:00:59 +0100153// IssueCertificate issues a certificate
Lorenz Brun52f7f292020-06-24 16:42:02 +0200154func (ca *CA) IssueCertificate(commonName string, ip net.IP) (cert []byte, privkey []byte, err error) {
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100155 serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 127)
156 serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
157 if err != nil {
158 err = fmt.Errorf("Failed to generate serial number: %w", err)
159 return
160 }
161
162 pubKey, privKeyRaw, err := ed25519.GenerateKey(rand.Reader)
163 if err != nil {
164 return
165 }
166 privkey, err = x509.MarshalPKCS8PrivateKey(privKeyRaw)
167 if err != nil {
168 return
169 }
170
171 etcdCert := &x509.Certificate{
172 SerialNumber: serialNumber,
173 Subject: pkix.Name{
Leopold Schabel68c58752019-11-14 21:00:59 +0100174 CommonName: commonName,
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100175 OrganizationalUnit: []string{"etcd"},
176 },
177 IsCA: false,
178 BasicConstraintsValid: true,
179 NotBefore: time.Now(),
180 NotAfter: unknownNotAfter,
181 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
Leopold Schabel68c58752019-11-14 21:00:59 +0100182 DNSNames: []string{commonName},
Lorenz Brun52f7f292020-06-24 16:42:02 +0200183 IPAddresses: []net.IP{ip},
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100184 }
185 cert, err = x509.CreateCertificate(rand.Reader, etcdCert, ca.CACert, pubKey, ca.PrivateKey)
186 return
187}
188
Leopold Schabel68c58752019-11-14 21:00:59 +0100189func (ca *CA) ReissueCRL() error {
Lorenz Brund3c59d22020-05-11 16:00:22 +0200190 newCRL, err := ca.CACert.CreateCRL(rand.Reader, ca.PrivateKey, ca.Revoked, time.Now(), unknownNotAfter)
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100191 if err != nil {
192 return err
193 }
194 ca.CRLRaw = newCRL
195 return nil
196}
197
198func (ca *CA) Revoke(serial *big.Int) error {
199 for _, revokedCert := range ca.Revoked {
200 if revokedCert.SerialNumber.Cmp(serial) == 0 {
201 return nil // Already revoked
202 }
203 }
204 ca.Revoked = append(ca.Revoked, pkix.RevokedCertificate{
205 SerialNumber: serial,
206 RevocationTime: time.Now(),
207 })
Leopold Schabel68c58752019-11-14 21:00:59 +0100208 return ca.ReissueCRL()
Lorenz Bruna4ea9d02019-10-31 11:40:30 +0100209}