cert.go 6.7 KB

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