cert.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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. "software.sslmate.com/src/go-pkcs12"
  23. "strconv"
  24. "strings"
  25. "time"
  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. privDER, err := x509.MarshalPKCS8PrivateKey(priv)
  73. fatalIfErr(err, "failed to encode certificate key")
  74. err = ioutil.WriteFile(filename+"-key.pem", pem.EncodeToMemory(
  75. &pem.Block{Type: "PRIVATE KEY", Bytes: privDER}), 0600)
  76. fatalIfErr(err, "failed to save certificate key")
  77. err = ioutil.WriteFile(filename+".pem", pem.EncodeToMemory(
  78. &pem.Block{Type: "CERTIFICATE", Bytes: cert}), 0644)
  79. fatalIfErr(err, "failed to save certificate key")
  80. // generate PKCS#12
  81. domainCert, _ := x509.ParseCertificate(cert)
  82. pfxData, _ := pkcs12.Encode(rand.Reader, priv, domainCert, []*x509.Certificate{m.caCert}, "changeit")
  83. err = ioutil.WriteFile(filename+".p12", pfxData, 0644)
  84. fatalIfErr(err, "failed to save PKCS#12")
  85. secondLvlWildcardRegexp := regexp.MustCompile(`(?i)^\*\.[0-9a-z_-]+$`)
  86. log.Printf("\nCreated a new certificate valid for the following names 📜")
  87. for _, h := range hosts {
  88. log.Printf(" - %q", h)
  89. if secondLvlWildcardRegexp.MatchString(h) {
  90. log.Printf(" Warning: many browsers don't support second-level wildcards like %q ⚠️", h)
  91. }
  92. }
  93. log.Printf("\nThe certificate is at \"./%s.pem\", and the key at \"./%s-key.pem\", and the PKCS#12 at \"./%s.p12\" ✅\n\n", filename, filename, filename)
  94. }
  95. // loadCA will load or create the CA at CAROOT.
  96. func (m *mkcert) loadCA() {
  97. if _, err := os.Stat(filepath.Join(m.CAROOT, rootName)); os.IsNotExist(err) {
  98. m.newCA()
  99. } else {
  100. log.Printf("Using the local CA at \"%s\" ✨\n", m.CAROOT)
  101. }
  102. certPEMBlock, err := ioutil.ReadFile(filepath.Join(m.CAROOT, rootName))
  103. fatalIfErr(err, "failed to read the CA certificate")
  104. certDERBlock, _ := pem.Decode(certPEMBlock)
  105. if certDERBlock == nil || certDERBlock.Type != "CERTIFICATE" {
  106. log.Fatalln("ERROR: failed to read the CA certificate: unexpected content")
  107. }
  108. m.caCert, err = x509.ParseCertificate(certDERBlock.Bytes)
  109. fatalIfErr(err, "failed to parse the CA certificate")
  110. if _, err := os.Stat(filepath.Join(m.CAROOT, keyName)); os.IsNotExist(err) {
  111. return // keyless mode, where only -install works
  112. }
  113. keyPEMBlock, err := ioutil.ReadFile(filepath.Join(m.CAROOT, keyName))
  114. fatalIfErr(err, "failed to read the CA key")
  115. keyDERBlock, _ := pem.Decode(keyPEMBlock)
  116. if keyDERBlock == nil || keyDERBlock.Type != "PRIVATE KEY" {
  117. log.Fatalln("ERROR: failed to read the CA key: unexpected content")
  118. }
  119. m.caKey, err = x509.ParsePKCS8PrivateKey(keyDERBlock.Bytes)
  120. fatalIfErr(err, "failed to parse the CA key")
  121. }
  122. func (m *mkcert) newCA() {
  123. priv, err := rsa.GenerateKey(rand.Reader, 3072)
  124. fatalIfErr(err, "failed to generate the CA key")
  125. pub := priv.PublicKey
  126. serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
  127. serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
  128. fatalIfErr(err, "failed to generate serial number")
  129. spkiASN1, err := x509.MarshalPKIXPublicKey(&pub)
  130. fatalIfErr(err, "failed to encode public key")
  131. var spki struct {
  132. Algorithm pkix.AlgorithmIdentifier
  133. SubjectPublicKey asn1.BitString
  134. }
  135. _, err = asn1.Unmarshal(spkiASN1, &spki)
  136. fatalIfErr(err, "failed to decode public key")
  137. skid := sha1.Sum(spki.SubjectPublicKey.Bytes)
  138. tpl := &x509.Certificate{
  139. SerialNumber: serialNumber,
  140. Subject: pkix.Name{
  141. Organization: []string{"mkcert development CA"},
  142. OrganizationalUnit: []string{userAndHostname},
  143. // The CommonName is required by iOS to show the certificate in the
  144. // "Certificate Trust Settings" menu.
  145. // https://github.com/FiloSottile/mkcert/issues/47
  146. CommonName: "mkcert " + userAndHostname,
  147. },
  148. SubjectKeyId: skid[:],
  149. NotAfter: time.Now().AddDate(10, 0, 0),
  150. NotBefore: time.Now(),
  151. KeyUsage: x509.KeyUsageCertSign,
  152. BasicConstraintsValid: true,
  153. IsCA: true,
  154. MaxPathLenZero: true,
  155. }
  156. cert, err := x509.CreateCertificate(rand.Reader, tpl, tpl, &pub, priv)
  157. fatalIfErr(err, "failed to generate CA certificate")
  158. privDER, err := x509.MarshalPKCS8PrivateKey(priv)
  159. fatalIfErr(err, "failed to encode CA key")
  160. err = ioutil.WriteFile(filepath.Join(m.CAROOT, keyName), pem.EncodeToMemory(
  161. &pem.Block{Type: "PRIVATE KEY", Bytes: privDER}), 0400)
  162. fatalIfErr(err, "failed to save CA key")
  163. err = ioutil.WriteFile(filepath.Join(m.CAROOT, rootName), pem.EncodeToMemory(
  164. &pem.Block{Type: "CERTIFICATE", Bytes: cert}), 0644)
  165. fatalIfErr(err, "failed to save CA key")
  166. log.Printf("Created a new local CA at \"%s\" 💥\n", m.CAROOT)
  167. }
  168. func (m *mkcert) caUniqueName() string {
  169. return "mkcert development CA " + m.caCert.SerialNumber.String()
  170. }