blob: bbed085a49090ae0733c40b07eb93cb8bafb8044 [file] [log] [blame]
Serge Bazanski9411f7c2021-03-10 13:12:53 +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
17package pki
18
19import (
20 "context"
21 "crypto/ed25519"
22 "crypto/rand"
23 "crypto/x509"
24 "fmt"
25 "math/big"
26 "time"
27
28 "go.etcd.io/etcd/clientv3"
29)
30
31// Issuer is an entity that can issue certificates. This interface is
32// implemented by SelfSigned, which is an issuer that emits self-signed
33// certificates, and any other Certificate that has been created with CA(),
34// which makes this Certificate act as a CA and issue (sign) ceritficates.
35type Issuer interface {
36 // CACertificate returns the DER-encoded x509 certificate of the CA that will sign certificates when Issue is
37 // called, or nil if this is self-signing issuer.
38 CACertificate(ctx context.Context, kv clientv3.KV) ([]byte, error)
39 // Issue will generate a key and certificate signed by the Issuer. The returned certificate is x509 DER-encoded,
40 // while the key is a bare ed25519 key.
41 Issue(ctx context.Context, req *Certificate, kv clientv3.KV) (cert, key []byte, err error)
42}
43
44// issueCertificate is a generic low level certificate-and-key issuance function. If ca or cakey is null, the
45// certificate will be self-signed. The returned certificate is DER-encoded, while the returned key is internal.
46func issueCertificate(req *Certificate, ca *x509.Certificate, caKey interface{}) (cert, key []byte, err error) {
47 var privKey ed25519.PrivateKey
48 var pubKey ed25519.PublicKey
49 if req.key != nil {
50 privKey = req.key
51 pubKey = privKey.Public().(ed25519.PublicKey)
52 } else {
53 var err error
54 pubKey, privKey, err = ed25519.GenerateKey(rand.Reader)
55 if err != nil {
56 panic(err)
57 }
58 }
59
60 serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 127)
61 serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
62 if err != nil {
63 err = fmt.Errorf("failed to generate serial number: %w", err)
64 return
65 }
66
67 skid, err := calculateSKID(pubKey)
68 if err != nil {
69 return []byte{}, privKey, err
70 }
71
72 req.template.SerialNumber = serialNumber
73 req.template.NotBefore = time.Now()
74 req.template.NotAfter = unknownNotAfter
75 req.template.BasicConstraintsValid = true
76 req.template.SubjectKeyId = skid
77
78 // Set the AuthorityKeyID to the SKID of the signing certificate (or self, if self-signing).
79 if ca != nil && caKey != nil {
80 req.template.AuthorityKeyId = ca.AuthorityKeyId
81 } else {
82 req.template.AuthorityKeyId = req.template.SubjectKeyId
83 }
84
85 if ca == nil || caKey == nil {
86 ca = &req.template
87 caKey = privKey
88 }
89
90 caCertRaw, err := x509.CreateCertificate(rand.Reader, &req.template, ca, pubKey, caKey)
91 return caCertRaw, privKey, err
92}
93
94type selfSigned struct{}
95
96var (
97 // SelfSigned is an Issuer that generates self-signed certificates.
98 SelfSigned = &selfSigned{}
99)
100
101// Issue will generate a key and certificate that is self-signed.
102func (s *selfSigned) Issue(ctx context.Context, req *Certificate, kv clientv3.KV) (cert, key []byte, err error) {
103 return issueCertificate(req, nil, nil)
104}
105
106// CACertificate returns nil for self-signed issuers.
107func (s *selfSigned) CACertificate(ctx context.Context, kv clientv3.KV) ([]byte, error) {
108 return nil, nil
109}
110
111// Issue will generate a key and certificate that is signed by this
112// Certificate, if the Certificate is a CA.
113func (c *Certificate) Issue(ctx context.Context, req *Certificate, kv clientv3.KV) (cert, key []byte, err error) {
114 caCert, caKey, err := c.ensure(ctx, kv)
115 if err != nil {
116 return nil, nil, fmt.Errorf("could not ensure CA certificate %q exists: %w", c.name, err)
117 }
118
119 ca, err := x509.ParseCertificate(caCert)
120 if err != nil {
121 return nil, nil, fmt.Errorf("could not parse CA certificate: %w", err)
122 }
123 // Ensure only one level of CAs exist, and that they are created explicitly.
124 req.template.IsCA = false
125 return issueCertificate(req, ca, ed25519.PrivateKey(caKey))
126}
127
128// CACertificate returns the DER encoded x509 form of this Certificate that
129// will be the used to issue child certificates.
130func (c *Certificate) CACertificate(ctx context.Context, kv clientv3.KV) ([]byte, error) {
131 cert, _, err := c.ensure(ctx, kv)
132 return cert, err
133}