blob: ff60f736fe14994aa7ab30a7ea27b12dec91beaf [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/x509"
23 "crypto/x509/pkix"
24 "encoding/pem"
25 "fmt"
26 "net"
27
28 "go.etcd.io/etcd/clientv3"
29
30 "source.monogon.dev/metropolis/pkg/fileargs"
31)
32
33// Namespace represents some path in etcd where certificate/CA data will be
34// stored. Creating a namespace via Namespaced then permits the consumer of
35// this library to start creating certificates within this namespace.
36type Namespace struct {
37 prefix string
38}
39
40// Namespaced creates a namespace for storing certificate data in etcd at a given 'path' prefix.
41func Namespaced(prefix string) Namespace {
42 return Namespace{
43 prefix: prefix,
44 }
45}
46
47// Certificate is the promise of a Certificate being available to the caller.
48// In this case, Certificate refers to a pair of x509 certificate and
49// corresponding private key. Certificates can be stored in etcd, and their
50// issuers might also be store on etcd. As such, this type's methods contain
51// references to an etcd KV client. This Certificate type is agnostic to
52// usage, but mostly geared towards Kubernetes certificates.
53type Certificate struct {
54 namespace *Namespace
55
56 // issuer is the Issuer that will generate this certificate if one doesn't
57 // yet exist or etcd, or the requested certificate is volatile (not to be
58 // stored on etcd).
59 Issuer Issuer
60 // name is a unique key for storing the certificate in etcd. If empty,
61 // certificate is 'volatile', will not be stored on etcd, and every
62 // .Ensure() call will generate a new pair.
63 name string
64 // template is an x509 certificate definition that will be used to generate
65 // the certificate when issuing it.
66 template x509.Certificate
67 // key is the private key for which the certificate should emitted, or nil
68 // if the key should be generated. The private key is required (vs. the
69 // private one) because the Certificate might be attempted to be issued via
70 // self-signing.
71 key ed25519.PrivateKey
72}
73
74func (n *Namespace) etcdPath(f string, args ...interface{}) string {
75 return n.prefix + fmt.Sprintf(f, args...)
76}
77
78// New creates a new Certificate, or to be more precise, a promise that a
79// certificate will exist once Ensure is called. Issuer must be a valid
80// certificate issuer (SelfSigned or another Certificate). Name must be unique
81// among all certificates, or empty (which will cause the certificate to be
82// volatile, ie. not stored in etcd).
83func (n *Namespace) New(issuer Issuer, name string, template x509.Certificate) *Certificate {
84 return &Certificate{
85 namespace: n,
86 Issuer: issuer,
87 name: name,
88 template: template,
89 }
90}
91
92// Client makes a Kubernetes PKI-compatible client certificate template.
93// Directly derived from Kubernetes PKI requirements documented at
94// https://kubernetes.io/docs/setup/best-practices/certificates/#configure-certificates-manually
95func Client(identity string, groups []string) x509.Certificate {
96 return x509.Certificate{
97 Subject: pkix.Name{
98 CommonName: identity,
99 Organization: groups,
100 },
101 KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
102 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
103 }
104}
105
106// Server makes a Kubernetes PKI-compatible server certificate template.
107func Server(dnsNames []string, ips []net.IP) x509.Certificate {
108 return x509.Certificate{
109 Subject: pkix.Name{},
110 KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
111 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
112 DNSNames: dnsNames,
113 IPAddresses: ips,
114 }
115}
116
117// CA makes a Certificate that can sign other certificates.
118func CA(cn string) x509.Certificate {
119 return x509.Certificate{
120 Subject: pkix.Name{
121 CommonName: cn,
122 },
123 IsCA: true,
124 KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign | x509.KeyUsageDigitalSignature,
125 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageOCSPSigning},
126 }
127}
128
129func (c *Certificate) etcdPaths() (cert, key string) {
130 return c.namespace.etcdPath("%s-cert.der", c.name), c.namespace.etcdPath("%s-key.der", c.name)
131}
132
133func (c *Certificate) UseExistingKey(key ed25519.PrivateKey) {
134 c.key = key
135}
136
137// ensure returns a DER-encoded x509 certificate and internally encoded bare
138// ed25519 key for a given Certificate, in memory (if volatile), loading it
139// from etcd, or creating and saving it on etcd if needed.
140// This function is safe to call in parallel from multiple etcd clients
141// (including across machines), but it will error in case a concurrent
142// certificate generation happens. These errors are, however, safe to retry -
143// as long as all the certificate creators (ie., Metropolis nodes) run the same
144// version of this code.
145//
146// TODO(q3k): in the future, this should be handled better - especially as we
147// introduce new certificates, or worse, change the issuance chain. As a
148// stopgap measure, an explicit per-certificate or even global lock can be
149// implemented. And, even before that, we can handle concurrency errors in a
150// smarter way.
151func (c *Certificate) ensure(ctx context.Context, kv clientv3.KV) (cert, key []byte, err error) {
152 if c.name == "" {
153 // Volatile certificate - generate.
154 // TODO(q3k): cache internally?
155 cert, key, err = c.Issuer.Issue(ctx, c, kv)
156 if err != nil {
157 err = fmt.Errorf("failed to issue: %w", err)
158 return
159 }
160 return
161 }
162
163 certPath, keyPath := c.etcdPaths()
164
165 // Try loading certificate and key from etcd.
166 certRes, err := kv.Get(ctx, certPath)
167 if err != nil {
168 err = fmt.Errorf("failed to get certificate from etcd: %w", err)
169 return
170 }
171 keyRes, err := kv.Get(ctx, keyPath)
172 if err != nil {
173 err = fmt.Errorf("failed to get key from etcd: %w", err)
174 return
175 }
176
177 if len(certRes.Kvs) == 1 && len(keyRes.Kvs) == 1 {
178 // Certificate and key exists in etcd, return that.
179 cert = certRes.Kvs[0].Value
180 key = keyRes.Kvs[0].Value
181
182 err = nil
183 // TODO(q3k): check for expiration
184 return
185 }
186
187 // No certificate found - issue one.
188 cert, key, err = c.Issuer.Issue(ctx, c, kv)
189 if err != nil {
190 err = fmt.Errorf("failed to issue: %w", err)
191 return
192 }
193
194 // Save to etcd in transaction. This ensures that no partial writes happen,
195 // and that we haven't been raced to the save.
196 res, err := kv.Txn(ctx).
197 If(
198 clientv3.Compare(clientv3.CreateRevision(certPath), "=", 0),
199 clientv3.Compare(clientv3.CreateRevision(keyPath), "=", 0),
200 ).
201 Then(
202 clientv3.OpPut(certPath, string(cert)),
203 clientv3.OpPut(keyPath, string(key)),
204 ).Commit()
205 if err != nil {
206 err = fmt.Errorf("failed to write newly issued certificate: %w", err)
207 } else if !res.Succeeded {
208 err = fmt.Errorf("certificate issuance transaction failed: concurrent write")
209 }
210
211 return
212}
213
214// Ensure returns an x509 DER-encoded (but not PEM-encoded) certificate and key
215// for a given Certificate. If the certificate is volatile, each call to
216// Ensure will cause a new certificate to be generated. Otherwise, it will be
217// retrieved from etcd, or generated and stored there if needed.
218func (c *Certificate) Ensure(ctx context.Context, kv clientv3.KV) (cert, key []byte, err error) {
219 cert, key, err = c.ensure(ctx, kv)
220 if err != nil {
221 return nil, nil, err
222 }
223 key, err = x509.MarshalPKCS8PrivateKey(ed25519.PrivateKey(key))
224 if err != nil {
225 err = fmt.Errorf("could not marshal private key (data corruption?): %w", err)
226 return
227 }
228 return cert, key, err
229}
230
231// FilesystemCertificate is a fileargs.FileArgs wrapper which will contain PEM
232// encoded certificate material when Mounted. This construct is useful when
233// dealing with services that want to access etcd-backed certificates as files
234// available locally.
235// Paths to the available files are considered opaque and should not be leaked
236// outside of the struct. Further restrictions on access to these files might
237// be imposed in the future.
238type FilesystemCertificate struct {
239 *fileargs.FileArgs
240 // CACertPath is the full path at which the CA certificate is available.
241 // Read only.
242 CACertPath string
243 // CertPath is the full path at which the certificate is available. Read
244 // only.
245 CertPath string
246 // KeyPath is the full path at which the key is available. Read only.
247 KeyPath string
248}
249
250// Mount returns a locally mounted FilesystemCertificate for this Certificate,
251// which allows services to access this Certificate via local filesystem
252// access.
253// The embeded fileargs.FileArgs can also be used to add additional file-backed
254// data under the same mount by calling ArgPath.
255// The returned FilesystemCertificate must be Closed in order to prevent a
256// system mount leak.
257func (c *Certificate) Mount(ctx context.Context, kv clientv3.KV) (*FilesystemCertificate, error) {
258 fa, err := fileargs.New()
259 if err != nil {
260 return nil, fmt.Errorf("when creating fileargs mount: %w", err)
261 }
262 fs := &FilesystemCertificate{FileArgs: fa}
263
264 cert, key, err := c.Ensure(ctx, kv)
265 if err != nil {
266 return nil, fmt.Errorf("when issuing certificate: %w", err)
267 }
268
269 cacert, err := c.Issuer.CACertificate(ctx, kv)
270 if err != nil {
271 return nil, fmt.Errorf("when getting issuer CA: %w", err)
272 }
273 // cacert will be null if this is a self-signed certificate.
274 if cacert == nil {
275 cacert = cert
276 }
277
278 fs.CACertPath = fs.ArgPath("ca.crt", pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cacert}))
279 fs.CertPath = fs.ArgPath("tls.crt", pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert}))
280 fs.KeyPath = fs.ArgPath("tls.key", pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: key}))
281
282 return fs, nil
283}