blob: 48ce6e9d222245fd75f48fc9bd0c171e2d5dd5d9 [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
28 "go.uber.org/zap"
29
30 "go.etcd.io/etcd/clientv3"
31 "k8s.io/client-go/tools/clientcmd"
32 configapi "k8s.io/client-go/tools/clientcmd/api"
33
34 "git.monogon.dev/source/nexantic.git/core/internal/common"
35)
36
37// KubeCertificateName is an enum-like unique name of a static Kubernetes certificate. The value of the name is used
38// as the unique part of an etcd path where the certificate and key are stored.
39type KubeCertificateName string
40
41const (
42 // The main Kubernetes CA, used to authenticate API consumers, and servers.
43 IdCA KubeCertificateName = "id-ca"
44
45 // Kubernetes apiserver server certificate.
46 APIServer KubeCertificateName = "apiserver"
47
48 // Kubelet client certificate, used to authenticate to the apiserver.
49 KubeletClient KubeCertificateName = "kubelet-client"
50
51 // Kubernetes Controller manager client certificate, used to authenticate to the apiserver.
52 ControllerManagerClient KubeCertificateName = "controller-manager-client"
53 // Kubernetes Controller manager server certificate, used to run its HTTP server.
54 ControllerManager KubeCertificateName = "controller-manager"
55
56 // Kubernetes Scheduler client certificate, used to authenticate to the apiserver.
57 SchedulerClient KubeCertificateName = "scheduler-client"
58 // Kubernetes scheduler server certificate, used to run its HTTP server.
59 Scheduler KubeCertificateName = "scheduler"
60
61 // Root-on-kube (system:masters) client certificate. Used to control the apiserver (and resources) by Smalltown
62 // internally.
63 Master KubeCertificateName = "master"
64
65 // OpenAPI Kubernetes Aggregation CA.
66 // See: https://kubernetes.io/docs/tasks/extend-kubernetes/configure-aggregation-layer/#ca-reusage-and-conflicts
67 AggregationCA KubeCertificateName = "aggregation-ca"
68 FrontProxyClient KubeCertificateName = "front-proxy-client"
69)
70
71const (
72 // serviceAccountKeyName is the etcd path part that is used to store the ServiceAccount authentication secret.
73 // This is not a certificate, just an RSA key.
74 serviceAccountKeyName = "service-account-privkey"
75)
76
77// KubernetesPKI manages all PKI resources required to run Kubernetes on Smalltown. It contains all static certificates,
78// which can be retrieved, or be used to generate Kubeconfigs from.
79type KubernetesPKI struct {
80 logger *zap.Logger
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020081 KV clientv3.KV
Serge Bazanskidbfc6382020-06-19 20:35:43 +020082 Certificates map[KubeCertificateName]*Certificate
83}
84
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020085func NewKubernetes(l *zap.Logger, kv clientv3.KV) *KubernetesPKI {
Serge Bazanskidbfc6382020-06-19 20:35:43 +020086 pki := KubernetesPKI{
87 logger: l,
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020088 KV: kv,
Serge Bazanskidbfc6382020-06-19 20:35:43 +020089 Certificates: make(map[KubeCertificateName]*Certificate),
90 }
91
92 make := func(i, name KubeCertificateName, template x509.Certificate) {
93 pki.Certificates[name] = New(pki.Certificates[i], string(name), template)
94 }
95
96 pki.Certificates[IdCA] = New(SelfSigned, string(IdCA), CA("Smalltown Kubernetes ID CA"))
97 make(IdCA, APIServer, Server(
98 []string{
99 "kubernetes",
100 "kubernetes.default",
101 "kubernetes.default.svc",
102 "kubernetes.default.svc.cluster",
103 "kubernetes.default.svc.cluster.local",
104 "localhost",
105 },
106 []net.IP{{127, 0, 0, 1}}, // TODO(q3k): add service network internal apiserver address
107 ))
108 make(IdCA, KubeletClient, Client("smalltown:apiserver-kubelet-client", nil))
109 make(IdCA, ControllerManagerClient, Client("system:kube-controller-manager", nil))
110 make(IdCA, ControllerManager, Server([]string{"kube-controller-manager.local"}, nil))
111 make(IdCA, SchedulerClient, Client("system:kube-scheduler", nil))
112 make(IdCA, Scheduler, Server([]string{"kube-scheduler.local"}, nil))
113 make(IdCA, Master, Client("smalltown:master", []string{"system:masters"}))
114
115 pki.Certificates[AggregationCA] = New(SelfSigned, string(AggregationCA), CA("Smalltown OpenAPI Aggregation CA"))
116 make(AggregationCA, FrontProxyClient, Client("front-proxy-client", nil))
117
118 return &pki
119}
120
121// EnsureAll ensures that all static certificates (and the serviceaccount key) are present on etcd.
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200122func (k *KubernetesPKI) EnsureAll(ctx context.Context) error {
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200123 for n, v := range k.Certificates {
124 k.logger.Info("ensureing certificate existence", zap.String("name", string(n)))
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200125 _, _, err := v.Ensure(ctx, k.KV)
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200126 if err != nil {
127 return fmt.Errorf("could not ensure certificate %q exists: %w", n, err)
128 }
129 }
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200130 _, err := k.ServiceAccountKey(ctx)
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200131 if err != nil {
132 return fmt.Errorf("could not ensure service account key exists: %w", err)
133 }
134 return nil
135}
136
137// Kubeconfig generates a kubeconfig blob for a given certificate name. The same lifetime semantics as in .Certificate
138// apply.
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200139func (k *KubernetesPKI) Kubeconfig(ctx context.Context, name KubeCertificateName) ([]byte, error) {
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200140 c, ok := k.Certificates[name]
141 if !ok {
142 return nil, fmt.Errorf("no certificate %q", name)
143 }
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200144 return c.Kubeconfig(ctx, k.KV)
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200145}
146
147// Certificate retrieves an x509 DER-encoded (but not PEM-wrapped) key and certificate for a given certificate name.
148// If the requested certificate is volatile, it will be created on demand. Otherwise it will be created on etcd (if not
149// present), and retrieved from there.
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200150func (k *KubernetesPKI) Certificate(ctx context.Context, name KubeCertificateName) (cert, key []byte, err error) {
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200151 c, ok := k.Certificates[name]
152 if !ok {
153 return nil, nil, fmt.Errorf("no certificate %q", name)
154 }
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200155 return c.Ensure(ctx, k.KV)
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200156}
157
158// Kubeconfig generates a kubeconfig blob for this certificate. The same lifetime semantics as in .Ensure apply.
159func (c *Certificate) Kubeconfig(ctx context.Context, kv clientv3.KV) ([]byte, error) {
160
161 cert, key, err := c.Ensure(ctx, kv)
162 if err != nil {
163 return nil, fmt.Errorf("could not ensure certificate exists: %w", err)
164 }
165
166 kubeconfig := configapi.NewConfig()
167
168 cluster := configapi.NewCluster()
169 cluster.Server = fmt.Sprintf("https://127.0.0.1:%v", common.KubernetesAPIPort)
170
171 ca, err := c.issuer.CACertificate(ctx, kv)
172 if err != nil {
173 return nil, fmt.Errorf("could not get CA certificate: %w", err)
174 }
175 if ca != nil {
176 cluster.CertificateAuthorityData = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: ca})
177 }
178 kubeconfig.Clusters["default"] = cluster
179
180 authInfo := configapi.NewAuthInfo()
181 authInfo.ClientCertificateData = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert})
182 authInfo.ClientKeyData = pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: key})
183 kubeconfig.AuthInfos["default"] = authInfo
184
185 ct := configapi.NewContext()
186 ct.Cluster = "default"
187 ct.AuthInfo = "default"
188 kubeconfig.Contexts["default"] = ct
189
190 kubeconfig.CurrentContext = "default"
191 return clientcmd.Write(*kubeconfig)
192}
193
194// ServiceAccountKey retrieves (and possible generates and stores on etcd) the Kubernetes service account key. The
195// returned data is ready to be used by Kubernetes components (in PKIX form).
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200196func (k *KubernetesPKI) ServiceAccountKey(ctx context.Context) ([]byte, error) {
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200197 // TODO(q3k): this should be abstracted away once we abstract away etcd access into a library with try-or-create
198 // semantics.
199
200 path := etcdPath("%s.der", serviceAccountKeyName)
201
202 // Try loading key from etcd.
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200203 keyRes, err := k.KV.Get(ctx, path)
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200204 if err != nil {
205 return nil, fmt.Errorf("failed to get key from etcd: %w", err)
206 }
207
208 if len(keyRes.Kvs) == 1 {
209 // Certificate and key exists in etcd, return that.
210 return keyRes.Kvs[0].Value, nil
211 }
212
213 // No key found - generate one.
214 keyRaw, err := rsa.GenerateKey(rand.Reader, 2048)
215 if err != nil {
216 panic(err)
217 }
218 key, err := x509.MarshalPKCS8PrivateKey(keyRaw)
219 if err != nil {
220 panic(err) // Always a programmer error
221 }
222
223 // Save to etcd.
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200224 _, err = k.KV.Put(ctx, path, string(key))
Serge Bazanskidbfc6382020-06-19 20:35:43 +0200225 if err != nil {
226 err = fmt.Errorf("failed to write newly generated key: %w", err)
227 }
228 return key, nil
229}