blob: ed70b8749698c90e79f18b5ba8dbc1e8ab481cd2 [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
81 Certificates map[KubeCertificateName]*Certificate
82}
83
84func NewKubernetes(l *zap.Logger) *KubernetesPKI {
85 pki := KubernetesPKI{
86 logger: l,
87 Certificates: make(map[KubeCertificateName]*Certificate),
88 }
89
90 make := func(i, name KubeCertificateName, template x509.Certificate) {
91 pki.Certificates[name] = New(pki.Certificates[i], string(name), template)
92 }
93
94 pki.Certificates[IdCA] = New(SelfSigned, string(IdCA), CA("Smalltown Kubernetes ID CA"))
95 make(IdCA, APIServer, Server(
96 []string{
97 "kubernetes",
98 "kubernetes.default",
99 "kubernetes.default.svc",
100 "kubernetes.default.svc.cluster",
101 "kubernetes.default.svc.cluster.local",
102 "localhost",
103 },
104 []net.IP{{127, 0, 0, 1}}, // TODO(q3k): add service network internal apiserver address
105 ))
106 make(IdCA, KubeletClient, Client("smalltown:apiserver-kubelet-client", nil))
107 make(IdCA, ControllerManagerClient, Client("system:kube-controller-manager", nil))
108 make(IdCA, ControllerManager, Server([]string{"kube-controller-manager.local"}, nil))
109 make(IdCA, SchedulerClient, Client("system:kube-scheduler", nil))
110 make(IdCA, Scheduler, Server([]string{"kube-scheduler.local"}, nil))
111 make(IdCA, Master, Client("smalltown:master", []string{"system:masters"}))
112
113 pki.Certificates[AggregationCA] = New(SelfSigned, string(AggregationCA), CA("Smalltown OpenAPI Aggregation CA"))
114 make(AggregationCA, FrontProxyClient, Client("front-proxy-client", nil))
115
116 return &pki
117}
118
119// EnsureAll ensures that all static certificates (and the serviceaccount key) are present on etcd.
120func (k *KubernetesPKI) EnsureAll(ctx context.Context, kv clientv3.KV) error {
121 for n, v := range k.Certificates {
122 k.logger.Info("ensureing certificate existence", zap.String("name", string(n)))
123 _, _, err := v.Ensure(ctx, kv)
124 if err != nil {
125 return fmt.Errorf("could not ensure certificate %q exists: %w", n, err)
126 }
127 }
128 _, err := k.ServiceAccountKey(ctx, kv)
129 if err != nil {
130 return fmt.Errorf("could not ensure service account key exists: %w", err)
131 }
132 return nil
133}
134
135// Kubeconfig generates a kubeconfig blob for a given certificate name. The same lifetime semantics as in .Certificate
136// apply.
137func (k *KubernetesPKI) Kubeconfig(ctx context.Context, name KubeCertificateName, kv clientv3.KV) ([]byte, error) {
138 c, ok := k.Certificates[name]
139 if !ok {
140 return nil, fmt.Errorf("no certificate %q", name)
141 }
142 return c.Kubeconfig(ctx, kv)
143}
144
145// Certificate retrieves an x509 DER-encoded (but not PEM-wrapped) key and certificate for a given certificate name.
146// If the requested certificate is volatile, it will be created on demand. Otherwise it will be created on etcd (if not
147// present), and retrieved from there.
148func (k *KubernetesPKI) Certificate(ctx context.Context, name KubeCertificateName, kv clientv3.KV) (cert, key []byte, err error) {
149 c, ok := k.Certificates[name]
150 if !ok {
151 return nil, nil, fmt.Errorf("no certificate %q", name)
152 }
153 return c.Ensure(ctx, kv)
154}
155
156// Kubeconfig generates a kubeconfig blob for this certificate. The same lifetime semantics as in .Ensure apply.
157func (c *Certificate) Kubeconfig(ctx context.Context, kv clientv3.KV) ([]byte, error) {
158
159 cert, key, err := c.Ensure(ctx, kv)
160 if err != nil {
161 return nil, fmt.Errorf("could not ensure certificate exists: %w", err)
162 }
163
164 kubeconfig := configapi.NewConfig()
165
166 cluster := configapi.NewCluster()
167 cluster.Server = fmt.Sprintf("https://127.0.0.1:%v", common.KubernetesAPIPort)
168
169 ca, err := c.issuer.CACertificate(ctx, kv)
170 if err != nil {
171 return nil, fmt.Errorf("could not get CA certificate: %w", err)
172 }
173 if ca != nil {
174 cluster.CertificateAuthorityData = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: ca})
175 }
176 kubeconfig.Clusters["default"] = cluster
177
178 authInfo := configapi.NewAuthInfo()
179 authInfo.ClientCertificateData = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert})
180 authInfo.ClientKeyData = pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: key})
181 kubeconfig.AuthInfos["default"] = authInfo
182
183 ct := configapi.NewContext()
184 ct.Cluster = "default"
185 ct.AuthInfo = "default"
186 kubeconfig.Contexts["default"] = ct
187
188 kubeconfig.CurrentContext = "default"
189 return clientcmd.Write(*kubeconfig)
190}
191
192// ServiceAccountKey retrieves (and possible generates and stores on etcd) the Kubernetes service account key. The
193// returned data is ready to be used by Kubernetes components (in PKIX form).
194func (k *KubernetesPKI) ServiceAccountKey(ctx context.Context, kv clientv3.KV) ([]byte, error) {
195 // TODO(q3k): this should be abstracted away once we abstract away etcd access into a library with try-or-create
196 // semantics.
197
198 path := etcdPath("%s.der", serviceAccountKeyName)
199
200 // Try loading key from etcd.
201 keyRes, err := kv.Get(ctx, path)
202 if err != nil {
203 return nil, fmt.Errorf("failed to get key from etcd: %w", err)
204 }
205
206 if len(keyRes.Kvs) == 1 {
207 // Certificate and key exists in etcd, return that.
208 return keyRes.Kvs[0].Value, nil
209 }
210
211 // No key found - generate one.
212 keyRaw, err := rsa.GenerateKey(rand.Reader, 2048)
213 if err != nil {
214 panic(err)
215 }
216 key, err := x509.MarshalPKCS8PrivateKey(keyRaw)
217 if err != nil {
218 panic(err) // Always a programmer error
219 }
220
221 // Save to etcd.
222 _, err = kv.Put(ctx, path, string(key))
223 if err != nil {
224 err = fmt.Errorf("failed to write newly generated key: %w", err)
225 }
226 return key, nil
227}