Lorenz Brun | 6e8f69c | 2019-11-18 10:44:24 +0100 | [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 kubernetes |
| 18 | |
| 19 | import ( |
| 20 | "context" |
| 21 | "crypto" |
| 22 | "crypto/ed25519" |
| 23 | "crypto/rand" |
| 24 | "crypto/rsa" |
| 25 | "crypto/sha1" |
| 26 | "crypto/x509" |
| 27 | "crypto/x509/pkix" |
| 28 | "encoding/asn1" |
| 29 | "encoding/pem" |
| 30 | "fmt" |
| 31 | "math/big" |
| 32 | "net" |
| 33 | "path" |
| 34 | "time" |
| 35 | |
| 36 | "go.etcd.io/etcd/clientv3" |
| 37 | "k8s.io/client-go/tools/clientcmd" |
| 38 | configapi "k8s.io/client-go/tools/clientcmd/api" |
| 39 | ) |
| 40 | |
| 41 | const ( |
| 42 | etcdPath = "/kube-pki/" |
| 43 | ) |
| 44 | |
| 45 | var ( |
| 46 | // From RFC 5280 Section 4.1.2.5 |
| 47 | unknownNotAfter = time.Unix(253402300799, 0) |
| 48 | ) |
| 49 | |
| 50 | // Directly derived from Kubernetes PKI requirements documented at |
| 51 | // https://kubernetes.io/docs/setup/best-practices/certificates/#configure-certificates-manually |
| 52 | func clientCertTemplate(identity string, groups []string) x509.Certificate { |
| 53 | return x509.Certificate{ |
| 54 | Subject: pkix.Name{ |
| 55 | CommonName: identity, |
| 56 | Organization: groups, |
| 57 | }, |
| 58 | KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment, |
| 59 | ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}, |
| 60 | } |
| 61 | } |
| 62 | func serverCertTemplate(dnsNames []string, ips []net.IP) x509.Certificate { |
| 63 | return x509.Certificate{ |
| 64 | Subject: pkix.Name{}, |
| 65 | KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment, |
| 66 | ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, |
| 67 | DNSNames: dnsNames, |
| 68 | IPAddresses: ips, |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | // Workaround for https://github.com/golang/go/issues/26676 in Go's crypto/x509. Specifically Go |
| 73 | // violates Section 4.2.1.2 of RFC 5280 without this. Should eventually be redundant. |
| 74 | // |
| 75 | // Taken from https://github.com/FiloSottile/mkcert/blob/master/cert.go#L295 written by one of Go's |
| 76 | // crypto engineers |
| 77 | func calculateSKID(pubKey crypto.PublicKey) ([]byte, error) { |
| 78 | spkiASN1, err := x509.MarshalPKIXPublicKey(pubKey) |
| 79 | if err != nil { |
| 80 | return nil, err |
| 81 | } |
| 82 | |
| 83 | var spki struct { |
| 84 | Algorithm pkix.AlgorithmIdentifier |
| 85 | SubjectPublicKey asn1.BitString |
| 86 | } |
| 87 | _, err = asn1.Unmarshal(spkiASN1, &spki) |
| 88 | if err != nil { |
| 89 | return nil, err |
| 90 | } |
| 91 | skid := sha1.Sum(spki.SubjectPublicKey.Bytes) |
| 92 | return skid[:], nil |
| 93 | } |
| 94 | |
| 95 | func newCA(name string) ([]byte, ed25519.PrivateKey, error) { |
| 96 | pubKey, privKey, err := ed25519.GenerateKey(rand.Reader) |
| 97 | if err != nil { |
| 98 | panic(err) |
| 99 | } |
| 100 | |
| 101 | serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 127) |
| 102 | serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) |
| 103 | if err != nil { |
| 104 | return []byte{}, privKey, fmt.Errorf("Failed to generate serial number: %w", err) |
| 105 | } |
| 106 | |
| 107 | skid, err := calculateSKID(pubKey) |
| 108 | if err != nil { |
| 109 | return []byte{}, privKey, err |
| 110 | } |
| 111 | |
| 112 | caCert := &x509.Certificate{ |
| 113 | SerialNumber: serialNumber, |
| 114 | Subject: pkix.Name{ |
| 115 | CommonName: name, |
| 116 | }, |
| 117 | IsCA: true, |
| 118 | BasicConstraintsValid: true, |
| 119 | NotBefore: time.Now(), |
| 120 | NotAfter: unknownNotAfter, |
| 121 | KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign | x509.KeyUsageDigitalSignature, |
| 122 | ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageOCSPSigning}, |
| 123 | AuthorityKeyId: skid, |
| 124 | SubjectKeyId: skid, |
| 125 | } |
| 126 | |
| 127 | caCertRaw, err := x509.CreateCertificate(rand.Reader, caCert, caCert, pubKey, privKey) |
| 128 | return caCertRaw, privKey, err |
| 129 | } |
| 130 | |
| 131 | func storeCert(consensusKV clientv3.KV, name string, cert []byte, key []byte) error { |
| 132 | certPath := path.Join(etcdPath, fmt.Sprintf("%v-cert.der", name)) |
| 133 | keyPath := path.Join(etcdPath, fmt.Sprintf("%v-key.der", name)) |
| 134 | if _, err := consensusKV.Put(context.Background(), certPath, string(cert)); err != nil { |
| 135 | return fmt.Errorf("failed to store certificate: %w", err) |
| 136 | } |
| 137 | if _, err := consensusKV.Put(context.Background(), keyPath, string(key)); err != nil { |
| 138 | return fmt.Errorf("failed to store key: %w", err) |
| 139 | } |
| 140 | return nil |
| 141 | } |
| 142 | |
| 143 | func getCert(consensusKV clientv3.KV, name string) (cert []byte, key []byte, err error) { |
| 144 | certPath := path.Join(etcdPath, fmt.Sprintf("%v-cert.der", name)) |
| 145 | keyPath := path.Join(etcdPath, fmt.Sprintf("%v-key.der", name)) |
| 146 | certRes, err := consensusKV.Get(context.Background(), certPath) |
| 147 | if err != nil { |
| 148 | err = fmt.Errorf("failed to get certificate: %w", err) |
| 149 | return |
| 150 | } |
| 151 | keyRes, err := consensusKV.Get(context.Background(), keyPath) |
| 152 | if err != nil { |
| 153 | err = fmt.Errorf("failed to get certificate: %w", err) |
| 154 | return |
| 155 | } |
| 156 | if len(certRes.Kvs) != 1 || len(keyRes.Kvs) != 1 { |
| 157 | err = fmt.Errorf("failed to find certificate %v", name) |
| 158 | return |
| 159 | } |
| 160 | cert = certRes.Kvs[0].Value |
| 161 | key = keyRes.Kvs[0].Value |
| 162 | return |
| 163 | } |
| 164 | |
| 165 | func getSingle(consensusKV clientv3.KV, name string) ([]byte, error) { |
| 166 | res, err := consensusKV.Get(context.Background(), path.Join(etcdPath, name)) |
| 167 | if err != nil { |
| 168 | return []byte{}, fmt.Errorf("failed to get PKI item: %w", err) |
| 169 | } |
| 170 | if len(res.Kvs) != 1 { |
| 171 | return []byte{}, fmt.Errorf("failed to find PKI item %v", name) |
| 172 | } |
| 173 | return res.Kvs[0].Value, nil |
| 174 | } |
| 175 | |
| 176 | // newCluster initializes the whole PKI for Kubernetes. It issues a single certificate per control |
| 177 | // plane service since it assumes that etcd is already a secure place to store data. This removes |
| 178 | // the need for revocation and makes the logic much simpler. Thus PKI data can NEVER be stored |
| 179 | // outside of etcd or other secure storage locations. All PKI data is stored in DER form and not |
| 180 | // PEM encoded since that would require more logic to deal with it. |
| 181 | func newCluster(consensusKV clientv3.KV) error { |
| 182 | // This whole issuance procedure is pretty repetitive, but abstracts badly because a lot of it |
| 183 | // is subtly different. |
| 184 | idCA, idKey, err := newCA("Smalltown Kubernetes ID CA") |
| 185 | if err != nil { |
| 186 | return fmt.Errorf("failed to create Kubernetes ID CA: %w", err) |
| 187 | } |
| 188 | if err := storeCert(consensusKV, "id-ca", idCA, idKey); err != nil { |
| 189 | return err |
| 190 | } |
| 191 | aggregationCA, aggregationKey, err := newCA("Smalltown OpenAPI Aggregation CA") |
| 192 | if err != nil { |
| 193 | return fmt.Errorf("failed to create OpenAPI Aggregation CA: %w", err) |
| 194 | } |
| 195 | if err := storeCert(consensusKV, "aggregation-ca", aggregationCA, aggregationKey); err != nil { |
| 196 | return err |
| 197 | } |
| 198 | |
| 199 | // ServiceAccounts don't support ed25519 yet, so use RSA (better side-channel resistance than ECDSA) |
| 200 | serviceAccountPrivKeyRaw, err := rsa.GenerateKey(rand.Reader, 2048) |
| 201 | if err != nil { |
| 202 | panic(err) |
| 203 | } |
| 204 | serviceAccountPrivKey, err := x509.MarshalPKCS8PrivateKey(serviceAccountPrivKeyRaw) |
| 205 | if err != nil { |
| 206 | panic(err) // Always a programmer error |
| 207 | } |
| 208 | _, err = consensusKV.Put(context.Background(), path.Join(etcdPath, "service-account-privkey.der"), |
| 209 | string(serviceAccountPrivKey)) |
| 210 | if err != nil { |
| 211 | return fmt.Errorf("failed to store service-account-privkey.der: %w", err) |
| 212 | } |
| 213 | |
| 214 | apiserverCert, apiserverKey, err := issueCertificate( |
| 215 | serverCertTemplate([]string{ |
| 216 | "kubernetes", |
| 217 | "kubernetes.default", |
| 218 | "kubernetes.default.svc", |
| 219 | "kubernetes.default.svc.cluster", |
| 220 | "kubernetes.default.svc.cluster.local", |
| 221 | "localhost", |
| 222 | }, []net.IP{{127, 0, 0, 1}}, // TODO: Add service internal IP |
| 223 | ), |
| 224 | idCA, idKey, |
| 225 | ) |
| 226 | if err != nil { |
| 227 | return fmt.Errorf("failed to issue certificate for apiserver: %w", err) |
| 228 | } |
| 229 | if err := storeCert(consensusKV, "apiserver", apiserverCert, apiserverKey); err != nil { |
| 230 | return err |
| 231 | } |
| 232 | |
| 233 | kubeletClientCert, kubeletClientKey, err := issueCertificate( |
| 234 | clientCertTemplate("kube-apiserver-kubelet-client", []string{"system:masters"}), |
| 235 | idCA, idKey, |
| 236 | ) |
| 237 | if err != nil { |
| 238 | return fmt.Errorf("failed to issue certificate for kubelet client: %w", err) |
| 239 | } |
| 240 | if err := storeCert(consensusKV, "kubelet-client", kubeletClientCert, kubeletClientKey); err != nil { |
| 241 | return err |
| 242 | } |
| 243 | |
| 244 | frontProxyClientCert, frontProxyClientKey, err := issueCertificate( |
| 245 | clientCertTemplate("front-proxy-client", []string{}), |
| 246 | aggregationCA, aggregationKey, |
| 247 | ) |
| 248 | if err != nil { |
| 249 | return fmt.Errorf("failed to issue certificate for OpenAPI frontend: %w", err) |
| 250 | } |
| 251 | if err := storeCert(consensusKV, "front-proxy-client", frontProxyClientCert, frontProxyClientKey); err != nil { |
| 252 | return err |
| 253 | } |
| 254 | |
| 255 | controllerManagerClientCert, controllerManagerClientKey, err := issueCertificate( |
| 256 | clientCertTemplate("system:kube-controller-manager", []string{}), |
| 257 | idCA, idKey, |
| 258 | ) |
| 259 | if err != nil { |
| 260 | return fmt.Errorf("failed to issue certificate for controller-manager client: %w", err) |
| 261 | } |
| 262 | |
| 263 | controllerManagerKubeconfig, err := makeLocalKubeconfig(idCA, controllerManagerClientCert, |
| 264 | controllerManagerClientKey) |
| 265 | if err != nil { |
| 266 | return fmt.Errorf("failed to create kubeconfig for controller-manager: %w", err) |
| 267 | } |
| 268 | |
| 269 | _, err = consensusKV.Put(context.Background(), path.Join(etcdPath, "controller-manager.kubeconfig"), |
| 270 | string(controllerManagerKubeconfig)) |
| 271 | if err != nil { |
| 272 | return fmt.Errorf("failed to store controller-manager kubeconfig: %w", err) |
| 273 | } |
| 274 | |
| 275 | controllerManagerCert, controllerManagerKey, err := issueCertificate( |
| 276 | serverCertTemplate([]string{"kube-controller-manager.local"}, []net.IP{}), |
| 277 | idCA, idKey, |
| 278 | ) |
| 279 | if err != nil { |
| 280 | return fmt.Errorf("failed to issue certificate for controller-manager: %w", err) |
| 281 | } |
| 282 | if err := storeCert(consensusKV, "controller-manager", controllerManagerCert, controllerManagerKey); err != nil { |
| 283 | return err |
| 284 | } |
| 285 | |
| 286 | schedulerClientCert, schedulerClientKey, err := issueCertificate( |
| 287 | clientCertTemplate("system:kube-scheduler", []string{}), |
| 288 | idCA, idKey, |
| 289 | ) |
| 290 | if err != nil { |
| 291 | return fmt.Errorf("failed to issue certificate for scheduler client: %w", err) |
| 292 | } |
| 293 | |
| 294 | schedulerKubeconfig, err := makeLocalKubeconfig(idCA, schedulerClientCert, schedulerClientKey) |
| 295 | if err != nil { |
| 296 | return fmt.Errorf("failed to create kubeconfig for scheduler: %w", err) |
| 297 | } |
| 298 | |
| 299 | _, err = consensusKV.Put(context.Background(), path.Join(etcdPath, "scheduler.kubeconfig"), |
| 300 | string(schedulerKubeconfig)) |
| 301 | if err != nil { |
| 302 | return fmt.Errorf("failed to store controller-manager kubeconfig: %w", err) |
| 303 | } |
| 304 | |
| 305 | schedulerCert, schedulerKey, err := issueCertificate( |
| 306 | serverCertTemplate([]string{"kube-scheduler.local"}, []net.IP{}), |
| 307 | idCA, idKey, |
| 308 | ) |
| 309 | if err != nil { |
| 310 | return fmt.Errorf("failed to issue certificate for scheduler: %w", err) |
| 311 | } |
| 312 | if err := storeCert(consensusKV, "scheduler", schedulerCert, schedulerKey); err != nil { |
| 313 | return err |
| 314 | } |
| 315 | |
| 316 | return nil |
| 317 | } |
| 318 | |
| 319 | func issueCertificate(template x509.Certificate, caCert []byte, privateKey interface{}) (cert []byte, privkey []byte, err error) { |
| 320 | serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 127) |
| 321 | serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) |
| 322 | if err != nil { |
| 323 | err = fmt.Errorf("Failed to generate serial number: %w", err) |
| 324 | return |
| 325 | } |
| 326 | |
| 327 | caCertObj, err := x509.ParseCertificate(caCert) |
| 328 | if err != nil { |
| 329 | err = fmt.Errorf("failed to parse CA certificate: %w", err) |
| 330 | } |
| 331 | |
| 332 | pubKey, privKeyRaw, err := ed25519.GenerateKey(rand.Reader) |
| 333 | if err != nil { |
| 334 | return |
| 335 | } |
| 336 | privkey, err = x509.MarshalPKCS8PrivateKey(privKeyRaw) |
| 337 | if err != nil { |
| 338 | return |
| 339 | } |
| 340 | |
| 341 | template.SerialNumber = serialNumber |
| 342 | template.IsCA = false |
| 343 | template.BasicConstraintsValid = true |
| 344 | template.NotBefore = time.Now() |
| 345 | template.NotAfter = unknownNotAfter |
| 346 | |
| 347 | cert, err = x509.CreateCertificate(rand.Reader, &template, caCertObj, pubKey, privateKey) |
| 348 | return |
| 349 | } |
| 350 | |
| 351 | func makeLocalKubeconfig(ca, cert, key []byte) ([]byte, error) { |
| 352 | kubeconfig := configapi.NewConfig() |
| 353 | cluster := configapi.NewCluster() |
| 354 | cluster.Server = "https://localhost:6443" |
| 355 | cluster.CertificateAuthorityData = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: ca}) |
| 356 | kubeconfig.Clusters["default"] = cluster |
| 357 | authInfo := configapi.NewAuthInfo() |
| 358 | authInfo.ClientCertificateData = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert}) |
| 359 | authInfo.ClientKeyData = pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: key}) |
| 360 | kubeconfig.AuthInfos["default"] = authInfo |
| 361 | ctx := configapi.NewContext() |
| 362 | ctx.Cluster = "default" |
| 363 | ctx.AuthInfo = "default" |
| 364 | kubeconfig.Contexts["default"] = ctx |
| 365 | kubeconfig.CurrentContext = "default" |
| 366 | return clientcmd.Write(*kubeconfig) |
| 367 | } |