blob: e11db29c8a9882690493e6abe123132522139d85 [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
17package pki
18
19import (
20 "context"
21 "crypto/rand"
22 "crypto/rsa"
23 "crypto/x509"
24 "encoding/pem"
25 "fmt"
26 "net"
27
Serge Bazanskidbfc6382020-06-19 20:35:43 +020028 "go.etcd.io/etcd/clientv3"
29 "k8s.io/client-go/tools/clientcmd"
30 configapi "k8s.io/client-go/tools/clientcmd/api"
31
Serge Bazanski77cb6c52020-12-19 00:09:22 +010032 common "git.monogon.dev/source/nexantic.git/metropolis/node"
Serge Bazanski549b72b2021-01-07 14:54:19 +010033 "git.monogon.dev/source/nexantic.git/metropolis/pkg/logtree"
Serge Bazanskidbfc6382020-06-19 20:35:43 +020034)
35
36// KubeCertificateName is an enum-like unique name of a static Kubernetes certificate. The value of the name is used
37// as the unique part of an etcd path where the certificate and key are stored.
38type KubeCertificateName string
39
40const (
41 // The main Kubernetes CA, used to authenticate API consumers, and servers.
42 IdCA KubeCertificateName = "id-ca"
43
44 // Kubernetes apiserver server certificate.
45 APIServer KubeCertificateName = "apiserver"
46
47 // Kubelet client certificate, used to authenticate to the apiserver.
48 KubeletClient KubeCertificateName = "kubelet-client"
49
50 // Kubernetes Controller manager client certificate, used to authenticate to the apiserver.
51 ControllerManagerClient KubeCertificateName = "controller-manager-client"
52 // Kubernetes Controller manager server certificate, used to run its HTTP server.
53 ControllerManager KubeCertificateName = "controller-manager"
54
55 // Kubernetes Scheduler client certificate, used to authenticate to the apiserver.
56 SchedulerClient KubeCertificateName = "scheduler-client"
57 // Kubernetes scheduler server certificate, used to run its HTTP server.
58 Scheduler KubeCertificateName = "scheduler"
59
Serge Bazanski662b5b32020-12-21 13:49:00 +010060 // Root-on-kube (system:masters) client certificate. Used to control the apiserver (and resources) by Metropolis
Serge Bazanskidbfc6382020-06-19 20:35:43 +020061 // internally.
62 Master KubeCertificateName = "master"
63
64 // OpenAPI Kubernetes Aggregation CA.
65 // See: https://kubernetes.io/docs/tasks/extend-kubernetes/configure-aggregation-layer/#ca-reusage-and-conflicts
66 AggregationCA KubeCertificateName = "aggregation-ca"
67 FrontProxyClient KubeCertificateName = "front-proxy-client"
68)
69
70const (
71 // serviceAccountKeyName is the etcd path part that is used to store the ServiceAccount authentication secret.
72 // This is not a certificate, just an RSA key.
73 serviceAccountKeyName = "service-account-privkey"
74)
75
Serge Bazanski662b5b32020-12-21 13:49:00 +010076// KubernetesPKI manages all PKI resources required to run Kubernetes on Metropolis. It contains all static certificates,
Serge Bazanskidbfc6382020-06-19 20:35:43 +020077// which can be retrieved, or be used to generate Kubeconfigs from.
78type KubernetesPKI struct {
Serge Bazanskic7359672020-10-30 16:38:57 +010079 logger logtree.LeveledLogger
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020080 KV clientv3.KV
Serge Bazanskidbfc6382020-06-19 20:35:43 +020081 Certificates map[KubeCertificateName]*Certificate
82}
83
Serge Bazanskic7359672020-10-30 16:38:57 +010084func NewKubernetes(l logtree.LeveledLogger, kv clientv3.KV) *KubernetesPKI {
Serge Bazanskidbfc6382020-06-19 20:35:43 +020085 pki := KubernetesPKI{
86 logger: l,
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020087 KV: kv,
Serge Bazanskidbfc6382020-06-19 20:35:43 +020088 Certificates: make(map[KubeCertificateName]*Certificate),
89 }
90
91 make := func(i, name KubeCertificateName, template x509.Certificate) {
92 pki.Certificates[name] = New(pki.Certificates[i], string(name), template)
93 }
94
Serge Bazanski662b5b32020-12-21 13:49:00 +010095 pki.Certificates[IdCA] = New(SelfSigned, string(IdCA), CA("Metropolis Kubernetes ID CA"))
Serge Bazanskidbfc6382020-06-19 20:35:43 +020096 make(IdCA, APIServer, Server(
97 []string{
98 "kubernetes",
99 "kubernetes.default",
100 "kubernetes.default.svc",
101 "kubernetes.default.svc.cluster",
102 "kubernetes.default.svc.cluster.local",
103 "localhost",
104 },
Lorenz Brunb682ba52020-07-08 14:51:36 +0200105 []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 +0200106 ))
Serge Bazanski662b5b32020-12-21 13:49:00 +0100107 make(IdCA, KubeletClient, Client("metropolis:apiserver-kubelet-client", nil))
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200108 make(IdCA, ControllerManagerClient, Client("system:kube-controller-manager", nil))
109 make(IdCA, ControllerManager, Server([]string{"kube-controller-manager.local"}, nil))
110 make(IdCA, SchedulerClient, Client("system:kube-scheduler", nil))
111 make(IdCA, Scheduler, Server([]string{"kube-scheduler.local"}, nil))
Serge Bazanski662b5b32020-12-21 13:49:00 +0100112 make(IdCA, Master, Client("metropolis:master", []string{"system:masters"}))
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200113
Serge Bazanski662b5b32020-12-21 13:49:00 +0100114 pki.Certificates[AggregationCA] = New(SelfSigned, string(AggregationCA), CA("Metropolis OpenAPI Aggregation CA"))
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200115 make(AggregationCA, FrontProxyClient, Client("front-proxy-client", nil))
116
117 return &pki
118}
119
120// EnsureAll ensures that all static certificates (and the serviceaccount key) are present on etcd.
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200121func (k *KubernetesPKI) EnsureAll(ctx context.Context) error {
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200122 for n, v := range k.Certificates {
Serge Bazanskic7359672020-10-30 16:38:57 +0100123 k.logger.Infof("Ensuring %s exists", string(n))
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200124 _, _, err := v.Ensure(ctx, k.KV)
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200125 if err != nil {
126 return fmt.Errorf("could not ensure certificate %q exists: %w", n, err)
127 }
128 }
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200129 _, err := k.ServiceAccountKey(ctx)
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200130 if err != nil {
131 return fmt.Errorf("could not ensure service account key exists: %w", err)
132 }
133 return nil
134}
135
136// Kubeconfig generates a kubeconfig blob for a given certificate name. The same lifetime semantics as in .Certificate
137// apply.
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200138func (k *KubernetesPKI) Kubeconfig(ctx context.Context, name KubeCertificateName) ([]byte, error) {
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200139 c, ok := k.Certificates[name]
140 if !ok {
141 return nil, fmt.Errorf("no certificate %q", name)
142 }
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200143 return c.Kubeconfig(ctx, k.KV)
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200144}
145
146// Certificate retrieves an x509 DER-encoded (but not PEM-wrapped) key and certificate for a given certificate name.
147// If the requested certificate is volatile, it will be created on demand. Otherwise it will be created on etcd (if not
148// present), and retrieved from there.
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200149func (k *KubernetesPKI) Certificate(ctx context.Context, name KubeCertificateName) (cert, key []byte, err error) {
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200150 c, ok := k.Certificates[name]
151 if !ok {
152 return nil, nil, fmt.Errorf("no certificate %q", name)
153 }
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200154 return c.Ensure(ctx, k.KV)
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200155}
156
157// Kubeconfig generates a kubeconfig blob for this certificate. The same lifetime semantics as in .Ensure apply.
158func (c *Certificate) Kubeconfig(ctx context.Context, kv clientv3.KV) ([]byte, error) {
159
160 cert, key, err := c.Ensure(ctx, kv)
161 if err != nil {
162 return nil, fmt.Errorf("could not ensure certificate exists: %w", err)
163 }
164
165 kubeconfig := configapi.NewConfig()
166
167 cluster := configapi.NewCluster()
168 cluster.Server = fmt.Sprintf("https://127.0.0.1:%v", common.KubernetesAPIPort)
169
170 ca, err := c.issuer.CACertificate(ctx, kv)
171 if err != nil {
172 return nil, fmt.Errorf("could not get CA certificate: %w", err)
173 }
174 if ca != nil {
175 cluster.CertificateAuthorityData = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: ca})
176 }
177 kubeconfig.Clusters["default"] = cluster
178
179 authInfo := configapi.NewAuthInfo()
180 authInfo.ClientCertificateData = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert})
181 authInfo.ClientKeyData = pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: key})
182 kubeconfig.AuthInfos["default"] = authInfo
183
184 ct := configapi.NewContext()
185 ct.Cluster = "default"
186 ct.AuthInfo = "default"
187 kubeconfig.Contexts["default"] = ct
188
189 kubeconfig.CurrentContext = "default"
190 return clientcmd.Write(*kubeconfig)
191}
192
193// ServiceAccountKey retrieves (and possible generates and stores on etcd) the Kubernetes service account key. The
194// returned data is ready to be used by Kubernetes components (in PKIX form).
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200195func (k *KubernetesPKI) ServiceAccountKey(ctx context.Context) ([]byte, error) {
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200196 // TODO(q3k): this should be abstracted away once we abstract away etcd access into a library with try-or-create
197 // semantics.
198
199 path := etcdPath("%s.der", serviceAccountKeyName)
200
201 // Try loading key from etcd.
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200202 keyRes, err := k.KV.Get(ctx, path)
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200203 if err != nil {
204 return nil, fmt.Errorf("failed to get key from etcd: %w", err)
205 }
206
207 if len(keyRes.Kvs) == 1 {
208 // Certificate and key exists in etcd, return that.
209 return keyRes.Kvs[0].Value, nil
210 }
211
212 // No key found - generate one.
213 keyRaw, err := rsa.GenerateKey(rand.Reader, 2048)
214 if err != nil {
215 panic(err)
216 }
217 key, err := x509.MarshalPKCS8PrivateKey(keyRaw)
218 if err != nil {
219 panic(err) // Always a programmer error
220 }
221
222 // Save to etcd.
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200223 _, err = k.KV.Put(ctx, path, string(key))
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200224 if err != nil {
225 err = fmt.Errorf("failed to write newly generated key: %w", err)
226 }
227 return key, nil
228}