blob: 4ec3bf0565cceb244e96702402bb279abc844dc3 [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
Serge Bazanski52538842021-08-11 16:22:41 +020017// package pki implements an x509 PKI (Public Key Infrastructure) system backed
18// on etcd.
Serge Bazanski9411f7c2021-03-10 13:12:53 +010019package pki
20
21import (
Serge Bazanski52538842021-08-11 16:22:41 +020022 "bytes"
Serge Bazanski9411f7c2021-03-10 13:12:53 +010023 "context"
24 "crypto/ed25519"
Serge Bazanski52538842021-08-11 16:22:41 +020025 "crypto/rand"
Serge Bazanski9411f7c2021-03-10 13:12:53 +010026 "crypto/x509"
27 "crypto/x509/pkix"
28 "encoding/pem"
29 "fmt"
30 "net"
31
32 "go.etcd.io/etcd/clientv3"
33
34 "source.monogon.dev/metropolis/pkg/fileargs"
35)
36
37// Namespace represents some path in etcd where certificate/CA data will be
38// stored. Creating a namespace via Namespaced then permits the consumer of
39// this library to start creating certificates within this namespace.
40type Namespace struct {
41 prefix string
42}
43
Serge Bazanski216fe7b2021-05-21 18:36:16 +020044// Namespaced creates a namespace for storing certificate data in etcd at a
45// given 'path' prefix.
Serge Bazanski9411f7c2021-03-10 13:12:53 +010046func Namespaced(prefix string) Namespace {
47 return Namespace{
48 prefix: prefix,
49 }
50}
51
Serge Bazanski52538842021-08-11 16:22:41 +020052type CertificateMode int
53
54const (
55 // CertificateManaged is a certificate whose key material is fully managed by
56 // the Certificate code. When set, PublicKey and PrivateKey must not be set by
57 // the user, and instead will be populated by the Ensure call. Name must be set,
58 // and will be used to store this Certificate and its keys within etcd. After
59 // the initial generation during Ensure, other Certificates with the same Name
60 // will be retrieved (including key material) from etcd.
61 CertificateManaged CertificateMode = iota
62
63 // CertificateExternal is a certificate whose key material is not managed by
64 // Certificate or stored in etcd, but the X509 certificate itself is. PublicKey
65 // must be set while PrivateKey must not be set. Name must be set, and will be
66 // used to store the emitted X509 certificate in etcd on Ensure. After the
67 // initial generation during Ensure, other Certificates with the same Name will
68 // be retrieved (without key material) from etcd.
69 CertificateExternal
70
71 // CertificateEphemeral is a certificate whose data (X509 certificate and
72 // possibly key material) is generated on demand each time Ensure is called.
73 // Nothing is stored in etcd or loaded from etcd. PrivateKey or PublicKey can be
74 // set, if both are nil then a new keypair will be generated. Name is ignored.
75 CertificateEphemeral
76)
77
Serge Bazanski9411f7c2021-03-10 13:12:53 +010078// Certificate is the promise of a Certificate being available to the caller.
79// In this case, Certificate refers to a pair of x509 certificate and
80// corresponding private key. Certificates can be stored in etcd, and their
81// issuers might also be store on etcd. As such, this type's methods contain
Serge Bazanski52538842021-08-11 16:22:41 +020082// references to an etcd KV client.
Serge Bazanski9411f7c2021-03-10 13:12:53 +010083type Certificate struct {
Serge Bazanski52538842021-08-11 16:22:41 +020084 Namespace *Namespace
Serge Bazanski9411f7c2021-03-10 13:12:53 +010085
Serge Bazanski52538842021-08-11 16:22:41 +020086 // Issuer is the Issuer that will generate this certificate if one doesn't
87 // yet exist or etcd, or the requested certificate is ephemeral (not to be
Serge Bazanski9411f7c2021-03-10 13:12:53 +010088 // stored on etcd).
89 Issuer Issuer
Serge Bazanski52538842021-08-11 16:22:41 +020090 // Name is a unique key for storing the certificate in etcd (if the requested
91 // certificate is not ephemeral).
92 Name string
93 // Template is an x509 certificate definition that will be used to generate
Serge Bazanski9411f7c2021-03-10 13:12:53 +010094 // the certificate when issuing it.
Serge Bazanski52538842021-08-11 16:22:41 +020095 Template x509.Certificate
96
97 // Mode in which this Certificate will operate. This influences the behaviour of
98 // the Ensure call.
99 Mode CertificateMode
100
101 // PrivateKey is the private key for this Certificate. It should never be set by
102 // the user, and instead will be populated by the Ensure call for Managed
103 // Certificates.
104 PrivateKey ed25519.PrivateKey
105
106 // PublicKey is the public key for this Certificate. It should only be set by
107 // the user for External or Ephemeral certificates, and will be populated by the
108 // next Ensure call if missing.
109 PublicKey ed25519.PublicKey
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100110}
111
112func (n *Namespace) etcdPath(f string, args ...interface{}) string {
113 return n.prefix + fmt.Sprintf(f, args...)
114}
115
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100116// Client makes a Kubernetes PKI-compatible client certificate template.
117// Directly derived from Kubernetes PKI requirements documented at
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200118// https://kubernetes.io/docs/setup/best-practices/certificates/#configure-certificates-manually
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100119func Client(identity string, groups []string) x509.Certificate {
120 return x509.Certificate{
121 Subject: pkix.Name{
122 CommonName: identity,
123 Organization: groups,
124 },
125 KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
126 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
127 }
128}
129
130// Server makes a Kubernetes PKI-compatible server certificate template.
131func Server(dnsNames []string, ips []net.IP) x509.Certificate {
132 return x509.Certificate{
133 Subject: pkix.Name{},
134 KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
135 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
136 DNSNames: dnsNames,
137 IPAddresses: ips,
138 }
139}
140
141// CA makes a Certificate that can sign other certificates.
142func CA(cn string) x509.Certificate {
143 return x509.Certificate{
144 Subject: pkix.Name{
145 CommonName: cn,
146 },
147 IsCA: true,
148 KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign | x509.KeyUsageDigitalSignature,
149 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageOCSPSigning},
150 }
151}
152
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100153// ensure returns a DER-encoded x509 certificate and internally encoded bare
Serge Bazanski52538842021-08-11 16:22:41 +0200154// ed25519 key for a given Certificate, in memory (if ephemeral), loading it
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100155// from etcd, or creating and saving it on etcd if needed.
156// This function is safe to call in parallel from multiple etcd clients
157// (including across machines), but it will error in case a concurrent
158// certificate generation happens. These errors are, however, safe to retry -
159// as long as all the certificate creators (ie., Metropolis nodes) run the same
160// version of this code.
Serge Bazanski52538842021-08-11 16:22:41 +0200161func (c *Certificate) ensure(ctx context.Context, kv clientv3.KV) (cert []byte, err error) {
162 // Ensure key is available.
163 if err := c.ensureKey(ctx, kv); err != nil {
164 return nil, err
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100165 }
166
Serge Bazanski52538842021-08-11 16:22:41 +0200167 switch c.Mode {
168 case CertificateEphemeral:
169 // TODO(q3k): cache internally?
170 cert, err = c.Issuer.Issue(ctx, c, kv)
171 if err != nil {
172 return nil, fmt.Errorf("failed to issue: %w", err)
173 }
174 return cert, nil
175 case CertificateManaged, CertificateExternal:
176 default:
177 return nil, fmt.Errorf("invalid certificate mode %v", c.Mode)
178 }
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100179
Serge Bazanski52538842021-08-11 16:22:41 +0200180 certPath := c.Namespace.etcdPath("%s-cert.der", c.Name)
181
182 // Try loading certificate from etcd.
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100183 certRes, err := kv.Get(ctx, certPath)
184 if err != nil {
Serge Bazanski52538842021-08-11 16:22:41 +0200185 return nil, fmt.Errorf("failed to get certificate from etcd: %w", err)
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100186 }
Serge Bazanski52538842021-08-11 16:22:41 +0200187
188 if len(certRes.Kvs) == 1 {
189 certBytes := certRes.Kvs[0].Value
190 cert, err := x509.ParseCertificate(certBytes)
191 if err != nil {
192 return nil, fmt.Errorf("failed to parse certificate retrieved from etcd: %w", err)
193 }
194 pk, ok := cert.PublicKey.(ed25519.PublicKey)
195 if !ok {
196 return nil, fmt.Errorf("unexpected non-ed25519 certificate found in etcd")
197 }
198 if !bytes.Equal(pk, c.PublicKey) {
199 return nil, fmt.Errorf("certificate stored in etcd emitted for different public key")
200 }
201 // TODO(q3k): ensure issuer and template haven't changed
202 return certBytes, nil
203 }
204
205 // No certificate found - issue one and save to etcd.
206 cert, err = c.Issuer.Issue(ctx, c, kv)
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100207 if err != nil {
Serge Bazanski52538842021-08-11 16:22:41 +0200208 return nil, fmt.Errorf("failed to issue: %w", err)
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100209 }
210
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100211 res, err := kv.Txn(ctx).
212 If(
213 clientv3.Compare(clientv3.CreateRevision(certPath), "=", 0),
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100214 ).
215 Then(
216 clientv3.OpPut(certPath, string(cert)),
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100217 ).Commit()
218 if err != nil {
219 err = fmt.Errorf("failed to write newly issued certificate: %w", err)
220 } else if !res.Succeeded {
221 err = fmt.Errorf("certificate issuance transaction failed: concurrent write")
222 }
223
224 return
225}
226
Serge Bazanski52538842021-08-11 16:22:41 +0200227// ensureKey retrieves or creates PublicKey as needed based on the Certificate
228// Mode. For Managed Certificates and Ephemeral Certificates with no PrivateKey
229// it will also populate PrivateKay.
230func (c *Certificate) ensureKey(ctx context.Context, kv clientv3.KV) error {
231 // If we have a public key then we're all set.
232 if c.PublicKey != nil {
233 return nil
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100234 }
Serge Bazanski52538842021-08-11 16:22:41 +0200235
236 // For ephemeral keys, we just generate them.
237 // For external keys, we can't do anything - not having the keys set means
238 // a programming error.
239
240 switch c.Mode {
241 case CertificateEphemeral:
242 pub, priv, err := ed25519.GenerateKey(rand.Reader)
243 if err != nil {
244 return fmt.Errorf("when generating ephemeral key: %w", err)
245 }
246 c.PublicKey = pub
247 c.PrivateKey = priv
248 return nil
249 case CertificateExternal:
250 if c.PrivateKey != nil {
251 // We prohibit having PrivateKey set in External Certificates to simplify the
252 // different logic paths this library implements. Being able to assume External
253 // == PublicKey only makes things easier elsewhere.
254 return fmt.Errorf("external certificate must not have PrivateKey set")
255 }
256 return fmt.Errorf("external certificate must have PublicKey set")
257 case CertificateManaged:
258 default:
259 return fmt.Errorf("invalid certificate mode %v", c.Mode)
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100260 }
Serge Bazanski52538842021-08-11 16:22:41 +0200261
262 // For managed keys, synchronize with etcd.
263 if c.Name == "" {
264 return fmt.Errorf("managed certificate must have Name set")
265 }
266
267 // First, try loading.
268 privPath := c.Namespace.etcdPath("%s-privkey.bin", c.Name)
269 privRes, err := kv.Get(ctx, privPath)
270 if err != nil {
271 return fmt.Errorf("failed to get private key from etcd: %w", err)
272 }
273 if len(privRes.Kvs) == 1 {
274 privBytes := privRes.Kvs[0].Value
275 if len(privBytes) != ed25519.PrivateKeySize {
276 return fmt.Errorf("stored private key has invalid size")
277 }
278 c.PrivateKey = privBytes
279 c.PublicKey = c.PrivateKey.Public().(ed25519.PublicKey)
280 return nil
281 }
282
283 // No key in etcd? Generate and save.
284 pub, priv, err := ed25519.GenerateKey(rand.Reader)
285 if err != nil {
286 return fmt.Errorf("while generating keypair: %w", err)
287 }
288
289 res, err := kv.Txn(ctx).
290 If(
291 clientv3.Compare(clientv3.CreateRevision(privPath), "=", 0),
292 ).
293 Then(
294 clientv3.OpPut(privPath, string(priv)),
295 ).Commit()
296 if err != nil {
297 return fmt.Errorf("failed to write newly generated keypair: %w", err)
298 } else if !res.Succeeded {
299 return fmt.Errorf("key generation transaction failed: concurrent write")
300 }
301
302 c.PrivateKey = priv
303 c.PublicKey = pub
304 return nil
305}
306
307// Ensure returns an x509 DER-encoded (but not PEM-encoded) certificate for a
308// given Certificate.
309//
310// If the Certificate is ephemeral, each call to Ensure will cause a new
311// certificate to be generated. Otherwise, it will be retrieved from etcd, or
312// generated and stored there if needed.
313func (c *Certificate) Ensure(ctx context.Context, kv clientv3.KV) (cert []byte, err error) {
314 return c.ensure(ctx, kv)
315}
316
317func (c *Certificate) PrivateKeyX509() ([]byte, error) {
318 if c.PrivateKey == nil {
319 return nil, fmt.Errorf("certificate has no private key")
320 }
321 key, err := x509.MarshalPKCS8PrivateKey(c.PrivateKey)
322 if err != nil {
323 return nil, fmt.Errorf("could not marshal private key (data corruption?): %w", err)
324 }
325 return key, nil
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100326}
327
328// FilesystemCertificate is a fileargs.FileArgs wrapper which will contain PEM
329// encoded certificate material when Mounted. This construct is useful when
330// dealing with services that want to access etcd-backed certificates as files
331// available locally.
332// Paths to the available files are considered opaque and should not be leaked
333// outside of the struct. Further restrictions on access to these files might
334// be imposed in the future.
335type FilesystemCertificate struct {
336 *fileargs.FileArgs
337 // CACertPath is the full path at which the CA certificate is available.
338 // Read only.
339 CACertPath string
340 // CertPath is the full path at which the certificate is available. Read
341 // only.
342 CertPath string
Serge Bazanski52538842021-08-11 16:22:41 +0200343 // KeyPath is the full path at which the private key is available, or an empty
344 // string if the Certificate was created without a private key. Read only.
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100345 KeyPath string
346}
347
348// Mount returns a locally mounted FilesystemCertificate for this Certificate,
349// which allows services to access this Certificate via local filesystem
350// access.
351// The embeded fileargs.FileArgs can also be used to add additional file-backed
352// data under the same mount by calling ArgPath.
353// The returned FilesystemCertificate must be Closed in order to prevent a
354// system mount leak.
355func (c *Certificate) Mount(ctx context.Context, kv clientv3.KV) (*FilesystemCertificate, error) {
356 fa, err := fileargs.New()
357 if err != nil {
358 return nil, fmt.Errorf("when creating fileargs mount: %w", err)
359 }
360 fs := &FilesystemCertificate{FileArgs: fa}
361
Serge Bazanski52538842021-08-11 16:22:41 +0200362 cert, err := c.Ensure(ctx, kv)
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100363 if err != nil {
364 return nil, fmt.Errorf("when issuing certificate: %w", err)
365 }
366
367 cacert, err := c.Issuer.CACertificate(ctx, kv)
368 if err != nil {
369 return nil, fmt.Errorf("when getting issuer CA: %w", err)
370 }
371 // cacert will be null if this is a self-signed certificate.
372 if cacert == nil {
373 cacert = cert
374 }
375
376 fs.CACertPath = fs.ArgPath("ca.crt", pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cacert}))
377 fs.CertPath = fs.ArgPath("tls.crt", pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert}))
Serge Bazanski52538842021-08-11 16:22:41 +0200378 if c.PrivateKey != nil {
379 key, err := c.PrivateKeyX509()
380 if err != nil {
381 return nil, err
382 }
383 fs.KeyPath = fs.ArgPath("tls.key", pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: key}))
384 }
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100385
386 return fs, nil
387}