|
| 1 | +/* |
| 2 | +Copyright 2018 The Kubernetes Authors. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +package certprovisioner |
| 18 | + |
| 19 | +import ( |
| 20 | + "crypto/x509" |
| 21 | + "fmt" |
| 22 | + |
| 23 | + "k8s.io/client-go/util/cert" |
| 24 | +) |
| 25 | + |
| 26 | +// SelfSignedCertProvisioner implements the CertProvisioner interface. |
| 27 | +// It provisions self-signed certificates. |
| 28 | +type SelfSignedCertProvisioner struct { |
| 29 | + // Required Common Name |
| 30 | + CommonName string |
| 31 | +} |
| 32 | + |
| 33 | +var _ CertProvisioner = &SelfSignedCertProvisioner{} |
| 34 | + |
| 35 | +// ProvisionServingCert creates and returns a CA certificate and certificate and |
| 36 | +// key for the server. serverKey and serverCert are used by the server |
| 37 | +// to establish trust for clients, CA certificate is used by the |
| 38 | +// client to verify the server authentication chain. |
| 39 | +// The cert will be valid for 365 days. |
| 40 | +func (cp *SelfSignedCertProvisioner) ProvisionServingCert() (serverKey, serverCert, caCert []byte, err error) { |
| 41 | + signingKey, err := cert.NewPrivateKey() |
| 42 | + if err != nil { |
| 43 | + return nil, nil, nil, |
| 44 | + fmt.Errorf("failed to create the CA private key: %v", err) |
| 45 | + } |
| 46 | + signingCert, err := cert.NewSelfSignedCACert(cert.Config{CommonName: "webhook-cert-ca"}, signingKey) |
| 47 | + if err != nil { |
| 48 | + return nil, nil, nil, |
| 49 | + fmt.Errorf("failed to create the CA cert: %v", err) |
| 50 | + } |
| 51 | + key, err := cert.NewPrivateKey() |
| 52 | + if err != nil { |
| 53 | + return nil, nil, nil, |
| 54 | + fmt.Errorf("failed to create the private key: %v", err) |
| 55 | + } |
| 56 | + signedCert, err := cert.NewSignedCert( |
| 57 | + cert.Config{ |
| 58 | + CommonName: cp.CommonName, |
| 59 | + Usages: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, |
| 60 | + }, |
| 61 | + key, signingCert, signingKey, |
| 62 | + ) |
| 63 | + if err != nil { |
| 64 | + return nil, nil, nil, |
| 65 | + fmt.Errorf("failed to create the cert: %v", err) |
| 66 | + } |
| 67 | + return cert.EncodePrivateKeyPEM(key), cert.EncodeCertPEM(signedCert), cert.EncodeCertPEM(signingCert), nil |
| 68 | +} |
0 commit comments