cert.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. /*
  2. Copyright 2014 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 cert
  14. import (
  15. "bytes"
  16. "crypto"
  17. cryptorand "crypto/rand"
  18. "crypto/rsa"
  19. "crypto/x509"
  20. "crypto/x509/pkix"
  21. "encoding/pem"
  22. "fmt"
  23. "math/big"
  24. "net"
  25. "os"
  26. "path/filepath"
  27. "strings"
  28. "time"
  29. "k8s.io/client-go/util/keyutil"
  30. netutils "k8s.io/utils/net"
  31. )
  32. const duration365d = time.Hour * 24 * 365
  33. // Config contains the basic fields required for creating a certificate
  34. type Config struct {
  35. CommonName string
  36. Organization []string
  37. AltNames AltNames
  38. Usages []x509.ExtKeyUsage
  39. }
  40. // AltNames contains the domain names and IP addresses that will be added
  41. // to the API Server's x509 certificate SubAltNames field. The values will
  42. // be passed directly to the x509.Certificate object.
  43. type AltNames struct {
  44. DNSNames []string
  45. IPs []net.IP
  46. }
  47. // NewSelfSignedCACert creates a CA certificate
  48. func NewSelfSignedCACert(cfg Config, key crypto.Signer) (*x509.Certificate, error) {
  49. now := time.Now()
  50. tmpl := x509.Certificate{
  51. SerialNumber: new(big.Int).SetInt64(0),
  52. Subject: pkix.Name{
  53. CommonName: cfg.CommonName,
  54. Organization: cfg.Organization,
  55. },
  56. DNSNames: []string{cfg.CommonName},
  57. NotBefore: now.UTC(),
  58. NotAfter: now.Add(duration365d * 10).UTC(),
  59. KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
  60. BasicConstraintsValid: true,
  61. IsCA: true,
  62. }
  63. certDERBytes, err := x509.CreateCertificate(cryptorand.Reader, &tmpl, &tmpl, key.Public(), key)
  64. if err != nil {
  65. return nil, err
  66. }
  67. return x509.ParseCertificate(certDERBytes)
  68. }
  69. // GenerateSelfSignedCertKey creates a self-signed certificate and key for the given host.
  70. // Host may be an IP or a DNS name
  71. // You may also specify additional subject alt names (either ip or dns names) for the certificate.
  72. func GenerateSelfSignedCertKey(host string, alternateIPs []net.IP, alternateDNS []string) ([]byte, []byte, error) {
  73. return GenerateSelfSignedCertKeyWithFixtures(host, alternateIPs, alternateDNS, "")
  74. }
  75. // GenerateSelfSignedCertKeyWithFixtures creates a self-signed certificate and key for the given host.
  76. // Host may be an IP or a DNS name. You may also specify additional subject alt names (either ip or dns names)
  77. // for the certificate.
  78. //
  79. // If fixtureDirectory is non-empty, it is a directory path which can contain pre-generated certs. The format is:
  80. // <host>_<ip>-<ip>_<alternateDNS>-<alternateDNS>.crt
  81. // <host>_<ip>-<ip>_<alternateDNS>-<alternateDNS>.key
  82. // Certs/keys not existing in that directory are created.
  83. func GenerateSelfSignedCertKeyWithFixtures(host string, alternateIPs []net.IP, alternateDNS []string, fixtureDirectory string) ([]byte, []byte, error) {
  84. validFrom := time.Now().Add(-time.Hour) // valid an hour earlier to avoid flakes due to clock skew
  85. maxAge := time.Hour * 24 * 365 // one year self-signed certs
  86. baseName := fmt.Sprintf("%s_%s_%s", host, strings.Join(ipsToStrings(alternateIPs), "-"), strings.Join(alternateDNS, "-"))
  87. certFixturePath := filepath.Join(fixtureDirectory, baseName+".crt")
  88. keyFixturePath := filepath.Join(fixtureDirectory, baseName+".key")
  89. if len(fixtureDirectory) > 0 {
  90. cert, err := os.ReadFile(certFixturePath)
  91. if err == nil {
  92. key, err := os.ReadFile(keyFixturePath)
  93. if err == nil {
  94. return cert, key, nil
  95. }
  96. return nil, nil, fmt.Errorf("cert %s can be read, but key %s cannot: %v", certFixturePath, keyFixturePath, err)
  97. }
  98. maxAge = 100 * time.Hour * 24 * 365 // 100 years fixtures
  99. }
  100. caKey, err := rsa.GenerateKey(cryptorand.Reader, 2048)
  101. if err != nil {
  102. return nil, nil, err
  103. }
  104. caTemplate := x509.Certificate{
  105. SerialNumber: big.NewInt(1),
  106. Subject: pkix.Name{
  107. CommonName: fmt.Sprintf("%s-ca@%d", host, time.Now().Unix()),
  108. },
  109. NotBefore: validFrom,
  110. NotAfter: validFrom.Add(maxAge),
  111. KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
  112. BasicConstraintsValid: true,
  113. IsCA: true,
  114. }
  115. caDERBytes, err := x509.CreateCertificate(cryptorand.Reader, &caTemplate, &caTemplate, &caKey.PublicKey, caKey)
  116. if err != nil {
  117. return nil, nil, err
  118. }
  119. caCertificate, err := x509.ParseCertificate(caDERBytes)
  120. if err != nil {
  121. return nil, nil, err
  122. }
  123. priv, err := rsa.GenerateKey(cryptorand.Reader, 2048)
  124. if err != nil {
  125. return nil, nil, err
  126. }
  127. template := x509.Certificate{
  128. SerialNumber: big.NewInt(2),
  129. Subject: pkix.Name{
  130. CommonName: fmt.Sprintf("%s@%d", host, time.Now().Unix()),
  131. },
  132. NotBefore: validFrom,
  133. NotAfter: validFrom.Add(maxAge),
  134. KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
  135. ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
  136. BasicConstraintsValid: true,
  137. }
  138. if ip := netutils.ParseIPSloppy(host); ip != nil {
  139. template.IPAddresses = append(template.IPAddresses, ip)
  140. } else {
  141. template.DNSNames = append(template.DNSNames, host)
  142. }
  143. template.IPAddresses = append(template.IPAddresses, alternateIPs...)
  144. template.DNSNames = append(template.DNSNames, alternateDNS...)
  145. derBytes, err := x509.CreateCertificate(cryptorand.Reader, &template, caCertificate, &priv.PublicKey, caKey)
  146. if err != nil {
  147. return nil, nil, err
  148. }
  149. // Generate cert, followed by ca
  150. certBuffer := bytes.Buffer{}
  151. if err := pem.Encode(&certBuffer, &pem.Block{Type: CertificateBlockType, Bytes: derBytes}); err != nil {
  152. return nil, nil, err
  153. }
  154. if err := pem.Encode(&certBuffer, &pem.Block{Type: CertificateBlockType, Bytes: caDERBytes}); err != nil {
  155. return nil, nil, err
  156. }
  157. // Generate key
  158. keyBuffer := bytes.Buffer{}
  159. if err := pem.Encode(&keyBuffer, &pem.Block{Type: keyutil.RSAPrivateKeyBlockType, Bytes: x509.MarshalPKCS1PrivateKey(priv)}); err != nil {
  160. return nil, nil, err
  161. }
  162. if len(fixtureDirectory) > 0 {
  163. if err := os.WriteFile(certFixturePath, certBuffer.Bytes(), 0644); err != nil {
  164. return nil, nil, fmt.Errorf("failed to write cert fixture to %s: %v", certFixturePath, err)
  165. }
  166. if err := os.WriteFile(keyFixturePath, keyBuffer.Bytes(), 0644); err != nil {
  167. return nil, nil, fmt.Errorf("failed to write key fixture to %s: %v", certFixturePath, err)
  168. }
  169. }
  170. return certBuffer.Bytes(), keyBuffer.Bytes(), nil
  171. }
  172. func ipsToStrings(ips []net.IP) []string {
  173. ss := make([]string, 0, len(ips))
  174. for _, ip := range ips {
  175. ss = append(ss, ip.String())
  176. }
  177. return ss
  178. }