Serge Bazanski | dbfc638 | 2020-06-19 20:35:43 +0200 | [diff] [blame] | 1 | // 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 | |
| 17 | package pki |
| 18 | |
| 19 | import ( |
| 20 | "context" |
| 21 | "crypto/rand" |
| 22 | "crypto/rsa" |
| 23 | "crypto/x509" |
| 24 | "encoding/pem" |
| 25 | "fmt" |
| 26 | "net" |
| 27 | |
Serge Bazanski | dbfc638 | 2020-06-19 20:35:43 +0200 | [diff] [blame] | 28 | "go.etcd.io/etcd/clientv3" |
| 29 | "k8s.io/client-go/tools/clientcmd" |
| 30 | configapi "k8s.io/client-go/tools/clientcmd/api" |
| 31 | |
Serge Bazanski | 77cb6c5 | 2020-12-19 00:09:22 +0100 | [diff] [blame^] | 32 | common "git.monogon.dev/source/nexantic.git/metropolis/node" |
| 33 | "git.monogon.dev/source/nexantic.git/metropolis/node/core/logtree" |
Serge Bazanski | dbfc638 | 2020-06-19 20:35:43 +0200 | [diff] [blame] | 34 | ) |
| 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. |
| 38 | type KubeCertificateName string |
| 39 | |
| 40 | const ( |
| 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 | |
| 60 | // Root-on-kube (system:masters) client certificate. Used to control the apiserver (and resources) by Smalltown |
| 61 | // 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 | |
| 70 | const ( |
| 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 | |
| 76 | // KubernetesPKI manages all PKI resources required to run Kubernetes on Smalltown. It contains all static certificates, |
| 77 | // which can be retrieved, or be used to generate Kubeconfigs from. |
| 78 | type KubernetesPKI struct { |
Serge Bazanski | c735967 | 2020-10-30 16:38:57 +0100 | [diff] [blame] | 79 | logger logtree.LeveledLogger |
Serge Bazanski | c2c7ad9 | 2020-07-13 17:20:09 +0200 | [diff] [blame] | 80 | KV clientv3.KV |
Serge Bazanski | dbfc638 | 2020-06-19 20:35:43 +0200 | [diff] [blame] | 81 | Certificates map[KubeCertificateName]*Certificate |
| 82 | } |
| 83 | |
Serge Bazanski | c735967 | 2020-10-30 16:38:57 +0100 | [diff] [blame] | 84 | func NewKubernetes(l logtree.LeveledLogger, kv clientv3.KV) *KubernetesPKI { |
Serge Bazanski | dbfc638 | 2020-06-19 20:35:43 +0200 | [diff] [blame] | 85 | pki := KubernetesPKI{ |
| 86 | logger: l, |
Serge Bazanski | c2c7ad9 | 2020-07-13 17:20:09 +0200 | [diff] [blame] | 87 | KV: kv, |
Serge Bazanski | dbfc638 | 2020-06-19 20:35:43 +0200 | [diff] [blame] | 88 | 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 | |
| 95 | pki.Certificates[IdCA] = New(SelfSigned, string(IdCA), CA("Smalltown Kubernetes ID CA")) |
| 96 | 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 Brun | b682ba5 | 2020-07-08 14:51:36 +0200 | [diff] [blame] | 105 | []net.IP{{10, 0, 255, 1}, {127, 0, 0, 1}}, // TODO(q3k): add service network internal apiserver address |
Serge Bazanski | dbfc638 | 2020-06-19 20:35:43 +0200 | [diff] [blame] | 106 | )) |
| 107 | make(IdCA, KubeletClient, Client("smalltown:apiserver-kubelet-client", nil)) |
| 108 | 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)) |
| 112 | make(IdCA, Master, Client("smalltown:master", []string{"system:masters"})) |
| 113 | |
| 114 | pki.Certificates[AggregationCA] = New(SelfSigned, string(AggregationCA), CA("Smalltown OpenAPI Aggregation CA")) |
| 115 | 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 Bazanski | c2c7ad9 | 2020-07-13 17:20:09 +0200 | [diff] [blame] | 121 | func (k *KubernetesPKI) EnsureAll(ctx context.Context) error { |
Serge Bazanski | dbfc638 | 2020-06-19 20:35:43 +0200 | [diff] [blame] | 122 | for n, v := range k.Certificates { |
Serge Bazanski | c735967 | 2020-10-30 16:38:57 +0100 | [diff] [blame] | 123 | k.logger.Infof("Ensuring %s exists", string(n)) |
Serge Bazanski | c2c7ad9 | 2020-07-13 17:20:09 +0200 | [diff] [blame] | 124 | _, _, err := v.Ensure(ctx, k.KV) |
Serge Bazanski | dbfc638 | 2020-06-19 20:35:43 +0200 | [diff] [blame] | 125 | if err != nil { |
| 126 | return fmt.Errorf("could not ensure certificate %q exists: %w", n, err) |
| 127 | } |
| 128 | } |
Serge Bazanski | c2c7ad9 | 2020-07-13 17:20:09 +0200 | [diff] [blame] | 129 | _, err := k.ServiceAccountKey(ctx) |
Serge Bazanski | dbfc638 | 2020-06-19 20:35:43 +0200 | [diff] [blame] | 130 | 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 Bazanski | c2c7ad9 | 2020-07-13 17:20:09 +0200 | [diff] [blame] | 138 | func (k *KubernetesPKI) Kubeconfig(ctx context.Context, name KubeCertificateName) ([]byte, error) { |
Serge Bazanski | dbfc638 | 2020-06-19 20:35:43 +0200 | [diff] [blame] | 139 | c, ok := k.Certificates[name] |
| 140 | if !ok { |
| 141 | return nil, fmt.Errorf("no certificate %q", name) |
| 142 | } |
Serge Bazanski | c2c7ad9 | 2020-07-13 17:20:09 +0200 | [diff] [blame] | 143 | return c.Kubeconfig(ctx, k.KV) |
Serge Bazanski | dbfc638 | 2020-06-19 20:35:43 +0200 | [diff] [blame] | 144 | } |
| 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 Bazanski | c2c7ad9 | 2020-07-13 17:20:09 +0200 | [diff] [blame] | 149 | func (k *KubernetesPKI) Certificate(ctx context.Context, name KubeCertificateName) (cert, key []byte, err error) { |
Serge Bazanski | dbfc638 | 2020-06-19 20:35:43 +0200 | [diff] [blame] | 150 | c, ok := k.Certificates[name] |
| 151 | if !ok { |
| 152 | return nil, nil, fmt.Errorf("no certificate %q", name) |
| 153 | } |
Serge Bazanski | c2c7ad9 | 2020-07-13 17:20:09 +0200 | [diff] [blame] | 154 | return c.Ensure(ctx, k.KV) |
Serge Bazanski | dbfc638 | 2020-06-19 20:35:43 +0200 | [diff] [blame] | 155 | } |
| 156 | |
| 157 | // Kubeconfig generates a kubeconfig blob for this certificate. The same lifetime semantics as in .Ensure apply. |
| 158 | func (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 Bazanski | c2c7ad9 | 2020-07-13 17:20:09 +0200 | [diff] [blame] | 195 | func (k *KubernetesPKI) ServiceAccountKey(ctx context.Context) ([]byte, error) { |
Serge Bazanski | dbfc638 | 2020-06-19 20:35:43 +0200 | [diff] [blame] | 196 | // 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 Bazanski | c2c7ad9 | 2020-07-13 17:20:09 +0200 | [diff] [blame] | 202 | keyRes, err := k.KV.Get(ctx, path) |
Serge Bazanski | dbfc638 | 2020-06-19 20:35:43 +0200 | [diff] [blame] | 203 | 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 Bazanski | c2c7ad9 | 2020-07-13 17:20:09 +0200 | [diff] [blame] | 223 | _, err = k.KV.Put(ctx, path, string(key)) |
Serge Bazanski | dbfc638 | 2020-06-19 20:35:43 +0200 | [diff] [blame] | 224 | if err != nil { |
| 225 | err = fmt.Errorf("failed to write newly generated key: %w", err) |
| 226 | } |
| 227 | return key, nil |
| 228 | } |