cert.go 7.3 KB

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