blob: 467f7187a97eb94f6cba57d0c3019d92781ed4fa [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
59 // Kubernetes Controller manager client certificate, used to authenticate to the apiserver.
60 ControllerManagerClient KubeCertificateName = "controller-manager-client"
61 // Kubernetes Controller manager server certificate, used to run its HTTP server.
62 ControllerManager KubeCertificateName = "controller-manager"
63
64 // Kubernetes Scheduler client certificate, used to authenticate to the apiserver.
65 SchedulerClient KubeCertificateName = "scheduler-client"
66 // Kubernetes scheduler server certificate, used to run its HTTP server.
67 Scheduler KubeCertificateName = "scheduler"
68
Serge Bazanski662b5b32020-12-21 13:49:00 +010069 // Root-on-kube (system:masters) client certificate. Used to control the apiserver (and resources) by Metropolis
Serge Bazanskidbfc6382020-06-19 20:35:43 +020070 // internally.
71 Master KubeCertificateName = "master"
72
73 // OpenAPI Kubernetes Aggregation CA.
74 // See: https://kubernetes.io/docs/tasks/extend-kubernetes/configure-aggregation-layer/#ca-reusage-and-conflicts
75 AggregationCA KubeCertificateName = "aggregation-ca"
76 FrontProxyClient KubeCertificateName = "front-proxy-client"
77)
78
79const (
Serge Bazanski9411f7c2021-03-10 13:12:53 +010080 // etcdPrefix is where all the PKI data is stored in etcd.
81 etcdPrefix = "/kube-pki/"
Serge Bazanskidbfc6382020-06-19 20:35:43 +020082 // serviceAccountKeyName is the etcd path part that is used to store the ServiceAccount authentication secret.
83 // This is not a certificate, just an RSA key.
84 serviceAccountKeyName = "service-account-privkey"
85)
86
Serge Bazanski9411f7c2021-03-10 13:12:53 +010087// PKI manages all PKI resources required to run Kubernetes on Metropolis. It
88// contains all static certificates, which can be retrieved, or be used to
89// generate Kubeconfigs from.
90type PKI struct {
91 namespace opki.Namespace
Serge Bazanskic7359672020-10-30 16:38:57 +010092 logger logtree.LeveledLogger
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020093 KV clientv3.KV
Serge Bazanski9411f7c2021-03-10 13:12:53 +010094 Certificates map[KubeCertificateName]*opki.Certificate
Serge Bazanskidbfc6382020-06-19 20:35:43 +020095}
96
Serge Bazanski9411f7c2021-03-10 13:12:53 +010097func New(l logtree.LeveledLogger, kv clientv3.KV) *PKI {
98 pki := PKI{
99 namespace: opki.Namespaced(etcdPrefix),
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200100 logger: l,
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200101 KV: kv,
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100102 Certificates: make(map[KubeCertificateName]*opki.Certificate),
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200103 }
104
105 make := func(i, name KubeCertificateName, template x509.Certificate) {
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100106 pki.Certificates[name] = pki.namespace.New(pki.Certificates[i], string(name), template)
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200107 }
108
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100109 pki.Certificates[IdCA] = pki.namespace.New(opki.SelfSigned, string(IdCA), opki.CA("Metropolis Kubernetes ID CA"))
110 make(IdCA, APIServer, opki.Server(
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200111 []string{
112 "kubernetes",
113 "kubernetes.default",
114 "kubernetes.default.svc",
115 "kubernetes.default.svc.cluster",
116 "kubernetes.default.svc.cluster.local",
117 "localhost",
118 },
Lorenz Brunb682ba52020-07-08 14:51:36 +0200119 []net.IP{{10, 0, 255, 1}, {127, 0, 0, 1}}, // TODO(q3k): add service network internal apiserver address
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200120 ))
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100121 make(IdCA, APIServerKubeletClient, opki.Client("metropolis:apiserver-kubelet-client", nil))
122 make(IdCA, ControllerManagerClient, opki.Client("system:kube-controller-manager", nil))
123 make(IdCA, ControllerManager, opki.Server([]string{"kube-controller-manager.local"}, nil))
124 make(IdCA, SchedulerClient, opki.Client("system:kube-scheduler", nil))
125 make(IdCA, Scheduler, opki.Server([]string{"kube-scheduler.local"}, nil))
126 make(IdCA, Master, opki.Client("metropolis:master", []string{"system:masters"}))
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200127
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100128 pki.Certificates[AggregationCA] = pki.namespace.New(opki.SelfSigned, string(AggregationCA), opki.CA("Metropolis OpenAPI Aggregation CA"))
129 make(AggregationCA, FrontProxyClient, opki.Client("front-proxy-client", nil))
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200130
131 return &pki
132}
133
134// EnsureAll ensures that all static certificates (and the serviceaccount key) are present on etcd.
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100135func (k *PKI) EnsureAll(ctx context.Context) error {
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200136 for n, v := range k.Certificates {
Serge Bazanskic7359672020-10-30 16:38:57 +0100137 k.logger.Infof("Ensuring %s exists", string(n))
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200138 _, _, err := v.Ensure(ctx, k.KV)
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200139 if err != nil {
140 return fmt.Errorf("could not ensure certificate %q exists: %w", n, err)
141 }
142 }
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200143 _, err := k.ServiceAccountKey(ctx)
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200144 if err != nil {
145 return fmt.Errorf("could not ensure service account key exists: %w", err)
146 }
147 return nil
148}
149
150// Kubeconfig generates a kubeconfig blob for a given certificate name. The same lifetime semantics as in .Certificate
151// apply.
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100152func (k *PKI) Kubeconfig(ctx context.Context, name KubeCertificateName) ([]byte, error) {
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200153 c, ok := k.Certificates[name]
154 if !ok {
155 return nil, fmt.Errorf("no certificate %q", name)
156 }
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100157 return Kubeconfig(ctx, k.KV, c)
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200158}
159
160// Certificate retrieves an x509 DER-encoded (but not PEM-wrapped) key and certificate for a given certificate name.
161// If the requested certificate is volatile, it will be created on demand. Otherwise it will be created on etcd (if not
162// present), and retrieved from there.
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100163func (k *PKI) Certificate(ctx context.Context, name KubeCertificateName) (cert, key []byte, err error) {
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200164 c, ok := k.Certificates[name]
165 if !ok {
166 return nil, nil, fmt.Errorf("no certificate %q", name)
167 }
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200168 return c.Ensure(ctx, k.KV)
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200169}
170
171// Kubeconfig generates a kubeconfig blob for this certificate. The same lifetime semantics as in .Ensure apply.
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100172func Kubeconfig(ctx context.Context, kv clientv3.KV, c *opki.Certificate) ([]byte, error) {
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200173
174 cert, key, err := c.Ensure(ctx, kv)
175 if err != nil {
176 return nil, fmt.Errorf("could not ensure certificate exists: %w", err)
177 }
178
179 kubeconfig := configapi.NewConfig()
180
181 cluster := configapi.NewCluster()
182 cluster.Server = fmt.Sprintf("https://127.0.0.1:%v", common.KubernetesAPIPort)
183
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100184 ca, err := c.Issuer.CACertificate(ctx, kv)
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200185 if err != nil {
186 return nil, fmt.Errorf("could not get CA certificate: %w", err)
187 }
188 if ca != nil {
189 cluster.CertificateAuthorityData = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: ca})
190 }
191 kubeconfig.Clusters["default"] = cluster
192
193 authInfo := configapi.NewAuthInfo()
194 authInfo.ClientCertificateData = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert})
195 authInfo.ClientKeyData = pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: key})
196 kubeconfig.AuthInfos["default"] = authInfo
197
198 ct := configapi.NewContext()
199 ct.Cluster = "default"
200 ct.AuthInfo = "default"
201 kubeconfig.Contexts["default"] = ct
202
203 kubeconfig.CurrentContext = "default"
204 return clientcmd.Write(*kubeconfig)
205}
206
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100207// ServiceAccountKey retrieves (and possibly generates and stores on etcd) the Kubernetes service account key. The
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200208// returned data is ready to be used by Kubernetes components (in PKIX form).
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100209func (k *PKI) ServiceAccountKey(ctx context.Context) ([]byte, error) {
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200210 // TODO(q3k): this should be abstracted away once we abstract away etcd access into a library with try-or-create
211 // semantics.
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100212 path := fmt.Sprintf("%s%s.der", etcdPrefix, serviceAccountKeyName)
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200213
214 // Try loading key from etcd.
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200215 keyRes, err := k.KV.Get(ctx, path)
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200216 if err != nil {
217 return nil, fmt.Errorf("failed to get key from etcd: %w", err)
218 }
219
220 if len(keyRes.Kvs) == 1 {
221 // Certificate and key exists in etcd, return that.
222 return keyRes.Kvs[0].Value, nil
223 }
224
225 // No key found - generate one.
226 keyRaw, err := rsa.GenerateKey(rand.Reader, 2048)
227 if err != nil {
228 panic(err)
229 }
230 key, err := x509.MarshalPKCS8PrivateKey(keyRaw)
231 if err != nil {
232 panic(err) // Always a programmer error
233 }
234
235 // Save to etcd.
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200236 _, err = k.KV.Put(ctx, path, string(key))
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200237 if err != nil {
238 err = fmt.Errorf("failed to write newly generated key: %w", err)
239 }
240 return key, nil
241}
Serge Bazanski9411f7c2021-03-10 13:12:53 +0100242
243// VolatileKubelet returns a pair of server/client ceritficates for the Kubelet
244// to use. The certificates are volatile, meaning they are not stored in etcd,
245// and instead are regenerated any time this function is called.
246func (k *PKI) VolatileKubelet(ctx context.Context, name string) (server *opki.Certificate, client *opki.Certificate, err error) {
247 name = fmt.Sprintf("system:node:%s", name)
248 err = k.EnsureAll(ctx)
249 if err != nil {
250 err = fmt.Errorf("could not ensure certificates exist: %w", err)
251 }
252 kubeCA := k.Certificates[IdCA]
253 server = k.namespace.New(kubeCA, "", opki.Server([]string{name}, nil))
254 client = k.namespace.New(kubeCA, "", opki.Client(name, []string{"system:nodes"}))
255 return
256}
257
258// VolatileClient returns a client certificate for Kubernetes clients to use.
259// The generated certificate will place the user in the given groups, and with
260// a given identiy as the certificate's CN.
261func (k *PKI) VolatileClient(ctx context.Context, identity string, groups []string) (*opki.Certificate, error) {
262 if err := k.EnsureAll(ctx); err != nil {
263 return nil, fmt.Errorf("could not ensure certificates exist: %w", err)
264 }
265 kubeCA := k.Certificates[IdCA]
266 return k.namespace.New(kubeCA, "", opki.Client(identity, groups)), nil
267}