blob: bb68907fe18c40d417f1f133c71a87e27ed6d5c0 [file] [log] [blame]
Serge Bazanskidbfc6382020-06-19 20:35:43 +02001// 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 Bazanski9411f7c2021-03-10 13:12:53 +010017// package pki builds upon metropolis/pkg/pki/ to provide an
18// etcd-backed implementation of all x509 PKI Certificates/CAs required to run
19// Kubernetes.
20// Most elements of the PKI are 'static' long-standing certificates/credentials
21// stored within etcd. However, this package also provides a method to generate
22// 'volatile' (in-memory) certificates/credentials for per-node Kubelets and
23// any client certificates.
Serge Bazanskidbfc6382020-06-19 20:35:43 +020024package pki
25
26import (
27 "context"
28 "crypto/rand"
29 "crypto/rsa"
30 "crypto/x509"
31 "encoding/pem"
32 "fmt"
33 "net"
34
Serge Bazanskidbfc6382020-06-19 20:35:43 +020035 "go.etcd.io/etcd/clientv3"
36 "k8s.io/client-go/tools/clientcmd"
37 configapi "k8s.io/client-go/tools/clientcmd/api"
38
Serge Bazanski31370b02021-01-07 16:31:14 +010039 common "source.monogon.dev/metropolis/node"
40 "source.monogon.dev/metropolis/pkg/logtree"
Serge Bazanski9411f7c2021-03-10 13:12:53 +010041 opki "source.monogon.dev/metropolis/pkg/pki"
Serge Bazanskidbfc6382020-06-19 20:35:43 +020042)
43
Serge Bazanski9411f7c2021-03-10 13:12:53 +010044// KubeCertificateName is an enum-like unique name of a static Kubernetes
45// certificate. The value of the name is used as the unique part of an etcd
46// path where the certificate and key are stored.
Serge Bazanskidbfc6382020-06-19 20:35:43 +020047type KubeCertificateName string
48
49const (
50 // The main Kubernetes CA, used to authenticate API consumers, and servers.
51 IdCA KubeCertificateName = "id-ca"
52
53 // Kubernetes apiserver server certificate.
54 APIServer KubeCertificateName = "apiserver"
55
Serge Bazanski9411f7c2021-03-10 13:12:53 +010056 // APIServer client certificate used to authenticate to kubelets.
57 APIServerKubeletClient KubeCertificateName = "apiserver-kubelet-client"
Serge Bazanskidbfc6382020-06-19 20:35:43 +020058
Serge Bazanski216fe7b2021-05-21 18:36:16 +020059 // Kubernetes Controller manager client certificate, used to authenticate
60 // to the apiserver.
Serge Bazanskidbfc6382020-06-19 20:35:43 +020061 ControllerManagerClient KubeCertificateName = "controller-manager-client"
Serge Bazanski216fe7b2021-05-21 18:36:16 +020062 // Kubernetes Controller manager server certificate, used to run its HTTP
63 // server.
Serge Bazanskidbfc6382020-06-19 20:35:43 +020064 ControllerManager KubeCertificateName = "controller-manager"
65
66 // Kubernetes Scheduler client certificate, used to authenticate to the apiserver.
67 SchedulerClient KubeCertificateName = "scheduler-client"
68 // Kubernetes scheduler server certificate, used to run its HTTP server.
69 Scheduler KubeCertificateName = "scheduler"
70
Serge Bazanski216fe7b2021-05-21 18:36:16 +020071 // Root-on-kube (system:masters) client certificate. Used to control the
72 // apiserver (and resources) by Metropolis internally.
Serge Bazanskidbfc6382020-06-19 20:35:43 +020073 Master KubeCertificateName = "master"
74
75 // OpenAPI Kubernetes Aggregation CA.
Serge Bazanski216fe7b2021-05-21 18:36:16 +020076 // https://kubernetes.io/docs/tasks/extend-kubernetes/configure-aggregation-layer/#ca-reusage-and-conflicts
Serge Bazanskidbfc6382020-06-19 20:35:43 +020077 AggregationCA KubeCertificateName = "aggregation-ca"
78 FrontProxyClient KubeCertificateName = "front-proxy-client"
79)
80
81const (
Serge Bazanski9411f7c2021-03-10 13:12:53 +010082 // etcdPrefix is where all the PKI data is stored in etcd.
83 etcdPrefix = "/kube-pki/"
Serge Bazanski216fe7b2021-05-21 18:36:16 +020084 // serviceAccountKeyName is the etcd path part that is used to store the
85 // ServiceAccount authentication secret. This is not a certificate, just an
86 // RSA key.
Serge Bazanskidbfc6382020-06-19 20:35:43 +020087 serviceAccountKeyName = "service-account-privkey"
88)
89
Serge Bazanski9411f7c2021-03-10 13:12:53 +010090// PKI manages all PKI resources required to run Kubernetes on Metropolis. It
91// contains all static certificates, which can be retrieved, or be used to
92// generate Kubeconfigs from.
93type PKI struct {
94 namespace opki.Namespace
Serge Bazanskic7359672020-10-30 16:38:57 +010095 logger logtree.LeveledLogger
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020096 KV clientv3.KV
Serge Bazanski9411f7c2021-03-10 13:12:53 +010097 Certificates map[KubeCertificateName]*opki.Certificate
Serge Bazanskidbfc6382020-06-19 20:35:43 +020098}
99
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100100func New(l logtree.LeveledLogger, kv clientv3.KV) *PKI {
101 pki := PKI{
102 namespace: opki.Namespaced(etcdPrefix),
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200103 logger: l,
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200104 KV: kv,
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100105 Certificates: make(map[KubeCertificateName]*opki.Certificate),
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200106 }
107
108 make := func(i, name KubeCertificateName, template x509.Certificate) {
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100109 pki.Certificates[name] = pki.namespace.New(pki.Certificates[i], string(name), template)
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200110 }
111
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100112 pki.Certificates[IdCA] = pki.namespace.New(opki.SelfSigned, string(IdCA), opki.CA("Metropolis Kubernetes ID CA"))
113 make(IdCA, APIServer, opki.Server(
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200114 []string{
115 "kubernetes",
116 "kubernetes.default",
117 "kubernetes.default.svc",
118 "kubernetes.default.svc.cluster",
119 "kubernetes.default.svc.cluster.local",
120 "localhost",
121 },
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200122 // TODO(q3k): add service network internal apiserver address
123 []net.IP{{10, 0, 255, 1}, {127, 0, 0, 1}},
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200124 ))
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100125 make(IdCA, APIServerKubeletClient, opki.Client("metropolis:apiserver-kubelet-client", nil))
126 make(IdCA, ControllerManagerClient, opki.Client("system:kube-controller-manager", nil))
127 make(IdCA, ControllerManager, opki.Server([]string{"kube-controller-manager.local"}, nil))
128 make(IdCA, SchedulerClient, opki.Client("system:kube-scheduler", nil))
129 make(IdCA, Scheduler, opki.Server([]string{"kube-scheduler.local"}, nil))
130 make(IdCA, Master, opki.Client("metropolis:master", []string{"system:masters"}))
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200131
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100132 pki.Certificates[AggregationCA] = pki.namespace.New(opki.SelfSigned, string(AggregationCA), opki.CA("Metropolis OpenAPI Aggregation CA"))
133 make(AggregationCA, FrontProxyClient, opki.Client("front-proxy-client", nil))
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200134
135 return &pki
136}
137
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200138// EnsureAll ensures that all static certificates (and the serviceaccount key)
139// are present on etcd.
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100140func (k *PKI) EnsureAll(ctx context.Context) error {
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200141 for n, v := range k.Certificates {
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200142 _, _, err := v.Ensure(ctx, k.KV)
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200143 if err != nil {
144 return fmt.Errorf("could not ensure certificate %q exists: %w", n, err)
145 }
146 }
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200147 _, err := k.ServiceAccountKey(ctx)
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200148 if err != nil {
149 return fmt.Errorf("could not ensure service account key exists: %w", err)
150 }
151 return nil
152}
153
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200154// Kubeconfig generates a kubeconfig blob for a given certificate name. The
155// same lifetime semantics as in .Certificate apply.
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100156func (k *PKI) Kubeconfig(ctx context.Context, name KubeCertificateName) ([]byte, error) {
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200157 c, ok := k.Certificates[name]
158 if !ok {
159 return nil, fmt.Errorf("no certificate %q", name)
160 }
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100161 return Kubeconfig(ctx, k.KV, c)
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200162}
163
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200164// Certificate retrieves an x509 DER-encoded (but not PEM-wrapped) key and
165// certificate for a given certificate name.
166// If the requested certificate is volatile, it will be created on demand.
167// Otherwise it will be created on etcd (if not present), and retrieved from
168// there.
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100169func (k *PKI) Certificate(ctx context.Context, name KubeCertificateName) (cert, key []byte, err error) {
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200170 c, ok := k.Certificates[name]
171 if !ok {
172 return nil, nil, fmt.Errorf("no certificate %q", name)
173 }
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200174 return c.Ensure(ctx, k.KV)
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200175}
176
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200177// Kubeconfig generates a kubeconfig blob for this certificate. The same
178// lifetime semantics as in .Ensure apply.
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100179func Kubeconfig(ctx context.Context, kv clientv3.KV, c *opki.Certificate) ([]byte, error) {
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200180
181 cert, key, err := c.Ensure(ctx, kv)
182 if err != nil {
183 return nil, fmt.Errorf("could not ensure certificate exists: %w", err)
184 }
185
186 kubeconfig := configapi.NewConfig()
187
188 cluster := configapi.NewCluster()
189 cluster.Server = fmt.Sprintf("https://127.0.0.1:%v", common.KubernetesAPIPort)
190
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100191 ca, err := c.Issuer.CACertificate(ctx, kv)
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200192 if err != nil {
193 return nil, fmt.Errorf("could not get CA certificate: %w", err)
194 }
195 if ca != nil {
196 cluster.CertificateAuthorityData = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: ca})
197 }
198 kubeconfig.Clusters["default"] = cluster
199
200 authInfo := configapi.NewAuthInfo()
201 authInfo.ClientCertificateData = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert})
202 authInfo.ClientKeyData = pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: key})
203 kubeconfig.AuthInfos["default"] = authInfo
204
205 ct := configapi.NewContext()
206 ct.Cluster = "default"
207 ct.AuthInfo = "default"
208 kubeconfig.Contexts["default"] = ct
209
210 kubeconfig.CurrentContext = "default"
211 return clientcmd.Write(*kubeconfig)
212}
213
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200214// ServiceAccountKey retrieves (and possibly generates and stores on etcd) the
215// Kubernetes service account key. The returned data is ready to be used by
216// Kubernetes components (in PKIX form).
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100217func (k *PKI) ServiceAccountKey(ctx context.Context) ([]byte, error) {
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200218 // TODO(q3k): this should be abstracted away once we abstract away etcd
219 // access into a library with try-or-create semantics.
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100220 path := fmt.Sprintf("%s%s.der", etcdPrefix, serviceAccountKeyName)
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200221
222 // Try loading key from etcd.
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200223 keyRes, err := k.KV.Get(ctx, path)
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200224 if err != nil {
225 return nil, fmt.Errorf("failed to get key from etcd: %w", err)
226 }
227
228 if len(keyRes.Kvs) == 1 {
229 // Certificate and key exists in etcd, return that.
230 return keyRes.Kvs[0].Value, nil
231 }
232
233 // No key found - generate one.
234 keyRaw, err := rsa.GenerateKey(rand.Reader, 2048)
235 if err != nil {
236 panic(err)
237 }
238 key, err := x509.MarshalPKCS8PrivateKey(keyRaw)
239 if err != nil {
240 panic(err) // Always a programmer error
241 }
242
243 // Save to etcd.
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200244 _, err = k.KV.Put(ctx, path, string(key))
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200245 if err != nil {
246 err = fmt.Errorf("failed to write newly generated key: %w", err)
247 }
248 return key, nil
249}
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100250
251// VolatileKubelet returns a pair of server/client ceritficates for the Kubelet
252// to use. The certificates are volatile, meaning they are not stored in etcd,
253// and instead are regenerated any time this function is called.
254func (k *PKI) VolatileKubelet(ctx context.Context, name string) (server *opki.Certificate, client *opki.Certificate, err error) {
255 name = fmt.Sprintf("system:node:%s", name)
256 err = k.EnsureAll(ctx)
257 if err != nil {
258 err = fmt.Errorf("could not ensure certificates exist: %w", err)
259 }
260 kubeCA := k.Certificates[IdCA]
261 server = k.namespace.New(kubeCA, "", opki.Server([]string{name}, nil))
262 client = k.namespace.New(kubeCA, "", opki.Client(name, []string{"system:nodes"}))
263 return
264}
265
266// VolatileClient returns a client certificate for Kubernetes clients to use.
267// The generated certificate will place the user in the given groups, and with
268// a given identiy as the certificate's CN.
269func (k *PKI) VolatileClient(ctx context.Context, identity string, groups []string) (*opki.Certificate, error) {
270 if err := k.EnsureAll(ctx); err != nil {
271 return nil, fmt.Errorf("could not ensure certificates exist: %w", err)
272 }
273 kubeCA := k.Certificates[IdCA]
274 return k.namespace.New(kubeCA, "", opki.Client(identity, groups)), nil
275}