cert.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. // Copyright 2018 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package main
  5. import (
  6. "crypto/rand"
  7. "crypto/rsa"
  8. "crypto/sha1"
  9. "crypto/x509"
  10. "crypto/x509/pkix"
  11. "encoding/asn1"
  12. "encoding/pem"
  13. "io/ioutil"
  14. "log"
  15. "math/big"
  16. "net"
  17. "os"
  18. "os/exec"
  19. "os/user"
  20. "path/filepath"
  21. "regexp"
  22. "strconv"
  23. "strings"
  24. "time"
  25. "software.sslmate.com/src/go-pkcs12"
  26. )
  27. var userAndHostname string
  28. func init() {
  29. u, _ := user.Current()
  30. if u != nil {
  31. userAndHostname = u.Username + "@"
  32. }
  33. out, _ := exec.Command("hostname").Output()
  34. userAndHostname += strings.TrimSpace(string(out))
  35. }
  36. func (m *mkcert) makeCert(hosts []string) {
  37. if m.caKey == nil {
  38. log.Fatalln("ERROR: can't create new certificates because the CA key (rootCA-key.pem) is missing")
  39. }
  40. priv, err := rsa.GenerateKey(rand.Reader, 2048)
  41. fatalIfErr(err, "failed to generate certificate key")
  42. serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
  43. serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
  44. fatalIfErr(err, "failed to generate serial number")
  45. tpl := &x509.Certificate{
  46. SerialNumber: serialNumber,
  47. Subject: pkix.Name{
  48. Organization: []string{"mkcert development certificate"},
  49. OrganizationalUnit: []string{userAndHostname},
  50. },
  51. NotAfter: time.Now().AddDate(10, 0, 0),
  52. NotBefore: time.Now(),
  53. KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
  54. ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
  55. BasicConstraintsValid: true,
  56. }
  57. for _, h := range hosts {
  58. if ip := net.ParseIP(h); ip != nil {
  59. tpl.IPAddresses = append(tpl.IPAddresses, ip)
  60. } else {
  61. tpl.DNSNames = append(tpl.DNSNames, h)
  62. }
  63. }
  64. pub := priv.PublicKey
  65. cert, err := x509.CreateCertificate(rand.Reader, tpl, m.caCert, &pub, m.caKey)
  66. fatalIfErr(err, "failed to generate certificate")
  67. filename := strings.Replace(hosts[0], ":", "_", -1)
  68. filename = strings.Replace(filename, "*", "_wildcard", -1)
  69. if len(hosts) > 1 {
  70. filename += "+" + strconv.Itoa(len(hosts)-1)
  71. }
  72. if !m.pkcs12 {
  73. privDER, err := x509.MarshalPKCS8PrivateKey(priv)
  74. fatalIfErr(err, "failed to encode certificate key")
  75. err = ioutil.WriteFile(filename+"-key.pem", pem.EncodeToMemory(
  76. &pem.Block{Type: "PRIVATE KEY", Bytes: privDER}), 0600)
  77. fatalIfErr(err, "failed to save certificate key")
  78. err = ioutil.WriteFile(filename+".pem", pem.EncodeToMemory(
  79. &pem.Block{Type: "CERTIFICATE", Bytes: cert}), 0644)
  80. fatalIfErr(err, "failed to save certificate key")
  81. } else {
  82. domainCert, _ := x509.ParseCertificate(cert)
  83. pfxData, err := pkcs12.Encode(rand.Reader, priv, domainCert, []*x509.Certificate{m.caCert}, "changeit")
  84. fatalIfErr(err, "failed to generate PKCS#12")
  85. err = ioutil.WriteFile(filename+".p12", pfxData, 0644)
  86. fatalIfErr(err, "failed to save PKCS#12")
  87. }
  88. secondLvlWildcardRegexp := regexp.MustCompile(`(?i)^\*\.[0-9a-z_-]+$`)
  89. log.Printf("\nCreated a new certificate valid for the following names 📜")
  90. for _, h := range hosts {
  91. log.Printf(" - %q", h)
  92. if secondLvlWildcardRegexp.MatchString(h) {
  93. log.Printf(" Warning: many browsers don't support second-level wildcards like %q ⚠️", h)
  94. }
  95. }
  96. if !m.pkcs12 {
  97. log.Printf("\nThe certificate is at \"./%s.pem\" and the key at \"./%s-key.pem\" ✅\n\n", filename, filename)
  98. } else {
  99. log.Printf("\nThe PKCS#12 bundle is at \"./%s.p12\" ✅\n\n", filename)
  100. }
  101. }
  102. // loadCA will load or create the CA at CAROOT.
  103. func (m *mkcert) loadCA() {
  104. if _, err := os.Stat(filepath.Join(m.CAROOT, rootName)); os.IsNotExist(err) {
  105. m.newCA()
  106. } else {
  107. log.Printf("Using the local CA at \"%s\" ✨\n", m.CAROOT)
  108. }
  109. certPEMBlock, err := ioutil.ReadFile(filepath.Join(m.CAROOT, rootName))
  110. fatalIfErr(err, "failed to read the CA certificate")
  111. certDERBlock, _ := pem.Decode(certPEMBlock)
  112. if certDERBlock == nil || certDERBlock.Type != "CERTIFICATE" {
  113. log.Fatalln("ERROR: failed to read the CA certificate: unexpected content")
  114. }
  115. m.caCert, err = x509.ParseCertificate(certDERBlock.Bytes)
  116. fatalIfErr(err, "failed to parse the CA certificate")
  117. if _, err := os.Stat(filepath.Join(m.CAROOT, keyName)); os.IsNotExist(err) {
  118. return // keyless mode, where only -install works
  119. }
  120. keyPEMBlock, err := ioutil.ReadFile(filepath.Join(m.CAROOT, keyName))
  121. fatalIfErr(err, "failed to read the CA key")
  122. keyDERBlock, _ := pem.Decode(keyPEMBlock)
  123. if keyDERBlock == nil || keyDERBlock.Type != "PRIVATE KEY" {
  124. log.Fatalln("ERROR: failed to read the CA key: unexpected content")
  125. }
  126. m.caKey, err = x509.ParsePKCS8PrivateKey(keyDERBlock.Bytes)
  127. fatalIfErr(err, "failed to parse the CA key")
  128. }
  129. func (m *mkcert) newCA() {
  130. priv, err := rsa.GenerateKey(rand.Reader, 3072)
  131. fatalIfErr(err, "failed to generate the CA key")
  132. pub := priv.PublicKey
  133. serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
  134. serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
  135. fatalIfErr(err, "failed to generate serial number")
  136. spkiASN1, err := x509.MarshalPKIXPublicKey(&pub)
  137. fatalIfErr(err, "failed to encode public key")
  138. var spki struct {
  139. Algorithm pkix.AlgorithmIdentifier
  140. SubjectPublicKey asn1.BitString
  141. }
  142. _, err = asn1.Unmarshal(spkiASN1, &spki)
  143. fatalIfErr(err, "failed to decode public key")
  144. skid := sha1.Sum(spki.SubjectPublicKey.Bytes)
  145. tpl := &x509.Certificate{
  146. SerialNumber: serialNumber,
  147. Subject: pkix.Name{
  148. Organization: []string{"mkcert development CA"},
  149. OrganizationalUnit: []string{userAndHostname},
  150. // The CommonName is required by iOS to show the certificate in the
  151. // "Certificate Trust Settings" menu.
  152. // https://github.com/FiloSottile/mkcert/issues/47
  153. CommonName: "mkcert " + userAndHostname,
  154. },
  155. SubjectKeyId: skid[:],
  156. NotAfter: time.Now().AddDate(10, 0, 0),
  157. NotBefore: time.Now(),
  158. KeyUsage: x509.KeyUsageCertSign,
  159. BasicConstraintsValid: true,
  160. IsCA: true,
  161. MaxPathLenZero: true,
  162. }
  163. cert, err := x509.CreateCertificate(rand.Reader, tpl, tpl, &pub, priv)
  164. fatalIfErr(err, "failed to generate CA certificate")
  165. privDER, err := x509.MarshalPKCS8PrivateKey(priv)
  166. fatalIfErr(err, "failed to encode CA key")
  167. err = ioutil.WriteFile(filepath.Join(m.CAROOT, keyName), pem.EncodeToMemory(
  168. &pem.Block{Type: "PRIVATE KEY", Bytes: privDER}), 0400)
  169. fatalIfErr(err, "failed to save CA key")
  170. err = ioutil.WriteFile(filepath.Join(m.CAROOT, rootName), pem.EncodeToMemory(
  171. &pem.Block{Type: "CERTIFICATE", Bytes: cert}), 0644)
  172. fatalIfErr(err, "failed to save CA key")
  173. log.Printf("Created a new local CA at \"%s\" 💥\n", m.CAROOT)
  174. }
  175. func (m *mkcert) caUniqueName() string {
  176. return "mkcert development CA " + m.caCert.SerialNumber.String()
  177. }