apirenewer.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. /*
  2. Copyright 2018 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package renewal
  14. import (
  15. "context"
  16. "crypto"
  17. "crypto/x509"
  18. "crypto/x509/pkix"
  19. "fmt"
  20. "time"
  21. "github.com/pkg/errors"
  22. certsapi "k8s.io/api/certificates/v1beta1"
  23. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  24. clientset "k8s.io/client-go/kubernetes"
  25. certstype "k8s.io/client-go/kubernetes/typed/certificates/v1beta1"
  26. certutil "k8s.io/client-go/util/cert"
  27. csrutil "k8s.io/client-go/util/certificate/csr"
  28. pkiutil "k8s.io/kubernetes/cmd/kubeadm/app/util/pkiutil"
  29. )
  30. const certAPIPrefixName = "kubeadm-cert"
  31. var watchTimeout = 5 * time.Minute
  32. // APIRenewer define a certificate renewer implementation that uses the K8s certificate API
  33. type APIRenewer struct {
  34. client certstype.CertificatesV1beta1Interface
  35. }
  36. // NewAPIRenewer a new certificate renewer implementation that uses the K8s certificate API
  37. func NewAPIRenewer(client clientset.Interface) *APIRenewer {
  38. return &APIRenewer{
  39. client: client.CertificatesV1beta1(),
  40. }
  41. }
  42. // Renew a certificate using the K8s certificate API
  43. func (r *APIRenewer) Renew(cfg *pkiutil.CertConfig) (*x509.Certificate, crypto.Signer, error) {
  44. reqTmp := &x509.CertificateRequest{
  45. Subject: pkix.Name{
  46. CommonName: cfg.CommonName,
  47. Organization: cfg.Organization,
  48. },
  49. DNSNames: cfg.AltNames.DNSNames,
  50. IPAddresses: cfg.AltNames.IPs,
  51. }
  52. key, err := pkiutil.NewPrivateKey(cfg.PublicKeyAlgorithm)
  53. if err != nil {
  54. return nil, nil, errors.Wrap(err, "couldn't create new private key")
  55. }
  56. csr, err := certutil.MakeCSRFromTemplate(key, reqTmp)
  57. if err != nil {
  58. return nil, nil, errors.Wrap(err, "couldn't create certificate signing request")
  59. }
  60. usages := make([]certsapi.KeyUsage, len(cfg.Usages))
  61. for i, usage := range cfg.Usages {
  62. certsAPIUsage, ok := usageMap[usage]
  63. if !ok {
  64. return nil, nil, errors.Errorf("unknown key usage: %v", usage)
  65. }
  66. usages[i] = certsAPIUsage
  67. }
  68. k8sCSR := &certsapi.CertificateSigningRequest{
  69. ObjectMeta: metav1.ObjectMeta{
  70. GenerateName: fmt.Sprintf("%s-%s-", certAPIPrefixName, cfg.CommonName),
  71. },
  72. Spec: certsapi.CertificateSigningRequestSpec{
  73. Request: csr,
  74. Usages: usages,
  75. },
  76. }
  77. req, err := r.client.CertificateSigningRequests().Create(context.TODO(), k8sCSR, metav1.CreateOptions{})
  78. if err != nil {
  79. return nil, nil, errors.Wrap(err, "couldn't create certificate signing request")
  80. }
  81. fmt.Printf("[certs] Certificate request %q created\n", req.Name)
  82. ctx, cancel := context.WithTimeout(context.Background(), watchTimeout)
  83. defer cancel()
  84. certData, err := csrutil.WaitForCertificate(ctx, r.client.CertificateSigningRequests(), req)
  85. if err != nil {
  86. return nil, nil, errors.Wrap(err, "certificate failed to appear")
  87. }
  88. cert, err := certutil.ParseCertsPEM(certData)
  89. if err != nil {
  90. return nil, nil, errors.Wrap(err, "couldn't parse issued certificate")
  91. }
  92. if len(cert) != 1 {
  93. return nil, nil, errors.Errorf("certificate request %q has %d certificates, wanted exactly 1", req.Name, len(cert))
  94. }
  95. return cert[0], key, nil
  96. }
  97. var usageMap = map[x509.ExtKeyUsage]certsapi.KeyUsage{
  98. x509.ExtKeyUsageAny: certsapi.UsageAny,
  99. x509.ExtKeyUsageServerAuth: certsapi.UsageServerAuth,
  100. x509.ExtKeyUsageClientAuth: certsapi.UsageClientAuth,
  101. x509.ExtKeyUsageCodeSigning: certsapi.UsageCodeSigning,
  102. x509.ExtKeyUsageEmailProtection: certsapi.UsageEmailProtection,
  103. x509.ExtKeyUsageIPSECEndSystem: certsapi.UsageIPsecEndSystem,
  104. x509.ExtKeyUsageIPSECTunnel: certsapi.UsageIPsecTunnel,
  105. x509.ExtKeyUsageIPSECUser: certsapi.UsageIPsecUser,
  106. x509.ExtKeyUsageTimeStamping: certsapi.UsageTimestamping,
  107. x509.ExtKeyUsageOCSPSigning: certsapi.UsageOCSPSigning,
  108. x509.ExtKeyUsageMicrosoftServerGatedCrypto: certsapi.UsageMicrosoftSGC,
  109. x509.ExtKeyUsageNetscapeServerGatedCrypto: certsapi.UsageNetscapeSGC,
  110. }