cert.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. // Copyright 2018 The mkcert 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"
  7. "crypto/ecdsa"
  8. "crypto/elliptic"
  9. "crypto/rand"
  10. "crypto/rsa"
  11. "crypto/sha1"
  12. "crypto/x509"
  13. "crypto/x509/pkix"
  14. "encoding/asn1"
  15. "encoding/pem"
  16. "io/ioutil"
  17. "log"
  18. "math/big"
  19. "net"
  20. "net/mail"
  21. "os"
  22. "os/user"
  23. "path/filepath"
  24. "regexp"
  25. "strconv"
  26. "strings"
  27. "time"
  28. pkcs12 "software.sslmate.com/src/go-pkcs12"
  29. )
  30. var userAndHostname string
  31. func init() {
  32. u, _ := user.Current()
  33. if u != nil {
  34. userAndHostname = u.Username + "@"
  35. }
  36. hostname, _ := os.Hostname()
  37. userAndHostname += hostname
  38. }
  39. func (m *mkcert) makeCert(hosts []string) {
  40. if m.caKey == nil {
  41. log.Fatalln("ERROR: can't create new certificates because the CA key (rootCA-key.pem) is missing")
  42. }
  43. priv, err := m.generateKey(false)
  44. fatalIfErr(err, "failed to generate certificate key")
  45. pub := priv.(crypto.Signer).Public()
  46. tpl := &x509.Certificate{
  47. SerialNumber: randomSerialNumber(),
  48. Subject: pkix.Name{
  49. Organization: []string{"mkcert development certificate"},
  50. OrganizationalUnit: []string{userAndHostname},
  51. },
  52. NotAfter: time.Now().AddDate(10, 0, 0),
  53. NotBefore: time.Now(),
  54. KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
  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 if email, err := mail.ParseAddress(h); err == nil && email.Address == h {
  61. tpl.EmailAddresses = append(tpl.EmailAddresses, h)
  62. } else {
  63. tpl.DNSNames = append(tpl.DNSNames, h)
  64. }
  65. }
  66. if m.client {
  67. tpl.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}
  68. } else if len(tpl.IPAddresses) > 0 || len(tpl.DNSNames) > 0 {
  69. tpl.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}
  70. }
  71. if len(tpl.EmailAddresses) > 0 {
  72. tpl.ExtKeyUsage = append(tpl.ExtKeyUsage, x509.ExtKeyUsageCodeSigning, x509.ExtKeyUsageEmailProtection)
  73. }
  74. // IIS (the main target of PKCS #12 files), only shows the deprecated
  75. // Common Name in the UI. See issue #115.
  76. if m.pkcs12 {
  77. tpl.Subject.CommonName = hosts[0]
  78. }
  79. cert, err := x509.CreateCertificate(rand.Reader, tpl, m.caCert, pub, m.caKey)
  80. fatalIfErr(err, "failed to generate certificate")
  81. certFile, keyFile, p12File := m.fileNames(hosts)
  82. if !m.pkcs12 {
  83. privDER, err := x509.MarshalPKCS8PrivateKey(priv)
  84. fatalIfErr(err, "failed to encode certificate key")
  85. err = ioutil.WriteFile(keyFile, pem.EncodeToMemory(
  86. &pem.Block{Type: "PRIVATE KEY", Bytes: privDER}), 0600)
  87. fatalIfErr(err, "failed to save certificate key")
  88. err = ioutil.WriteFile(certFile, pem.EncodeToMemory(
  89. &pem.Block{Type: "CERTIFICATE", Bytes: cert}), 0644)
  90. fatalIfErr(err, "failed to save certificate")
  91. } else {
  92. domainCert, _ := x509.ParseCertificate(cert)
  93. pfxData, err := pkcs12.Encode(rand.Reader, priv, domainCert, []*x509.Certificate{m.caCert}, "changeit")
  94. fatalIfErr(err, "failed to generate PKCS#12")
  95. err = ioutil.WriteFile(p12File, pfxData, 0644)
  96. fatalIfErr(err, "failed to save PKCS#12")
  97. }
  98. m.printHosts(hosts)
  99. if !m.pkcs12 {
  100. log.Printf("\nThe certificate is at \"%s\" and the key at \"%s\" ✅\n\n", certFile, keyFile)
  101. } else {
  102. log.Printf("\nThe PKCS#12 bundle is at \"%s\" ✅\n", p12File)
  103. log.Printf("\nThe legacy PKCS#12 encryption password is the often hardcoded default \"changeit\" ℹ️\n\n")
  104. }
  105. }
  106. func (m *mkcert) printHosts(hosts []string) {
  107. secondLvlWildcardRegexp := regexp.MustCompile(`(?i)^\*\.[0-9a-z_-]+$`)
  108. log.Printf("\nCreated a new certificate valid for the following names 📜")
  109. for _, h := range hosts {
  110. log.Printf(" - %q", h)
  111. if secondLvlWildcardRegexp.MatchString(h) {
  112. log.Printf(" Warning: many browsers don't support second-level wildcards like %q ⚠️", h)
  113. }
  114. }
  115. for _, h := range hosts {
  116. if strings.HasPrefix(h, "*.") {
  117. log.Printf("\nReminder: X.509 wildcards only go one level deep, so this won't match a.b.%s ℹ️", h[2:])
  118. break
  119. }
  120. }
  121. }
  122. func (m *mkcert) generateKey(rootCA bool) (crypto.PrivateKey, error) {
  123. if m.ecdsa {
  124. return ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  125. }
  126. if rootCA {
  127. return rsa.GenerateKey(rand.Reader, 3072)
  128. }
  129. return rsa.GenerateKey(rand.Reader, 2048)
  130. }
  131. func (m *mkcert) fileNames(hosts []string) (certFile, keyFile, p12File string) {
  132. defaultName := strings.Replace(hosts[0], ":", "_", -1)
  133. defaultName = strings.Replace(defaultName, "*", "_wildcard", -1)
  134. if len(hosts) > 1 {
  135. defaultName += "+" + strconv.Itoa(len(hosts)-1)
  136. }
  137. if m.client {
  138. defaultName += "-client"
  139. }
  140. certFile = "./" + defaultName + ".pem"
  141. if m.certFile != "" {
  142. certFile = m.certFile
  143. }
  144. keyFile = "./" + defaultName + "-key.pem"
  145. if m.keyFile != "" {
  146. keyFile = m.keyFile
  147. }
  148. p12File = "./" + defaultName + ".p12"
  149. if m.p12File != "" {
  150. p12File = m.p12File
  151. }
  152. return
  153. }
  154. func randomSerialNumber() *big.Int {
  155. serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
  156. serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
  157. fatalIfErr(err, "failed to generate serial number")
  158. return serialNumber
  159. }
  160. func (m *mkcert) makeCertFromCSR() {
  161. if m.caKey == nil {
  162. log.Fatalln("ERROR: can't create new certificates because the CA key (rootCA-key.pem) is missing")
  163. }
  164. csrPEMBytes, err := ioutil.ReadFile(m.csrPath)
  165. fatalIfErr(err, "failed to read the CSR")
  166. csrPEM, _ := pem.Decode(csrPEMBytes)
  167. if csrPEM == nil {
  168. log.Fatalln("ERROR: failed to read the CSR: unexpected content")
  169. }
  170. if csrPEM.Type != "CERTIFICATE REQUEST" {
  171. log.Fatalln("ERROR: failed to read the CSR: expected CERTIFICATE REQUEST, got " + csrPEM.Type)
  172. }
  173. csr, err := x509.ParseCertificateRequest(csrPEM.Bytes)
  174. fatalIfErr(err, "failed to parse the CSR")
  175. fatalIfErr(csr.CheckSignature(), "invalid CSR signature")
  176. tpl := &x509.Certificate{
  177. SerialNumber: randomSerialNumber(),
  178. Subject: csr.Subject,
  179. ExtraExtensions: csr.Extensions, // includes requested SANs
  180. NotAfter: time.Now().AddDate(10, 0, 0),
  181. NotBefore: time.Now(),
  182. KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
  183. ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
  184. BasicConstraintsValid: true,
  185. // If the CSR does not request a SAN extension, fix it up for them as
  186. // the Common Name field does not work in modern browsers. Otherwise,
  187. // this will get overridden.
  188. DNSNames: []string{csr.Subject.CommonName},
  189. }
  190. cert, err := x509.CreateCertificate(rand.Reader, tpl, m.caCert, csr.PublicKey, m.caKey)
  191. fatalIfErr(err, "failed to generate certificate")
  192. var hosts []string
  193. hosts = append(hosts, csr.DNSNames...)
  194. hosts = append(hosts, csr.EmailAddresses...)
  195. for _, ip := range csr.IPAddresses {
  196. hosts = append(hosts, ip.String())
  197. }
  198. if len(hosts) == 0 {
  199. hosts = []string{csr.Subject.CommonName}
  200. }
  201. certFile, _, _ := m.fileNames(hosts)
  202. err = ioutil.WriteFile(certFile, pem.EncodeToMemory(
  203. &pem.Block{Type: "CERTIFICATE", Bytes: cert}), 0644)
  204. fatalIfErr(err, "failed to save certificate")
  205. m.printHosts(hosts)
  206. log.Printf("\nThe certificate is at \"%s\" ✅\n\n", certFile)
  207. }
  208. // loadCA will load or create the CA at CAROOT.
  209. func (m *mkcert) loadCA() {
  210. if !pathExists(filepath.Join(m.CAROOT, rootName)) {
  211. m.newCA()
  212. } else {
  213. log.Printf("Using the local CA at \"%s\" ✨\n", m.CAROOT)
  214. }
  215. certPEMBlock, err := ioutil.ReadFile(filepath.Join(m.CAROOT, rootName))
  216. fatalIfErr(err, "failed to read the CA certificate")
  217. certDERBlock, _ := pem.Decode(certPEMBlock)
  218. if certDERBlock == nil || certDERBlock.Type != "CERTIFICATE" {
  219. log.Fatalln("ERROR: failed to read the CA certificate: unexpected content")
  220. }
  221. m.caCert, err = x509.ParseCertificate(certDERBlock.Bytes)
  222. fatalIfErr(err, "failed to parse the CA certificate")
  223. if !pathExists(filepath.Join(m.CAROOT, rootKeyName)) {
  224. return // keyless mode, where only -install works
  225. }
  226. keyPEMBlock, err := ioutil.ReadFile(filepath.Join(m.CAROOT, rootKeyName))
  227. fatalIfErr(err, "failed to read the CA key")
  228. keyDERBlock, _ := pem.Decode(keyPEMBlock)
  229. if keyDERBlock == nil || keyDERBlock.Type != "PRIVATE KEY" {
  230. log.Fatalln("ERROR: failed to read the CA key: unexpected content")
  231. }
  232. m.caKey, err = x509.ParsePKCS8PrivateKey(keyDERBlock.Bytes)
  233. fatalIfErr(err, "failed to parse the CA key")
  234. }
  235. func (m *mkcert) newCA() {
  236. priv, err := m.generateKey(true)
  237. fatalIfErr(err, "failed to generate the CA key")
  238. pub := priv.(crypto.Signer).Public()
  239. spkiASN1, err := x509.MarshalPKIXPublicKey(pub)
  240. fatalIfErr(err, "failed to encode public key")
  241. var spki struct {
  242. Algorithm pkix.AlgorithmIdentifier
  243. SubjectPublicKey asn1.BitString
  244. }
  245. _, err = asn1.Unmarshal(spkiASN1, &spki)
  246. fatalIfErr(err, "failed to decode public key")
  247. skid := sha1.Sum(spki.SubjectPublicKey.Bytes)
  248. tpl := &x509.Certificate{
  249. SerialNumber: randomSerialNumber(),
  250. Subject: pkix.Name{
  251. Organization: []string{"mkcert development CA"},
  252. OrganizationalUnit: []string{userAndHostname},
  253. // The CommonName is required by iOS to show the certificate in the
  254. // "Certificate Trust Settings" menu.
  255. // https://github.com/FiloSottile/mkcert/issues/47
  256. CommonName: "mkcert " + userAndHostname,
  257. },
  258. SubjectKeyId: skid[:],
  259. NotAfter: time.Now().AddDate(10, 0, 0),
  260. NotBefore: time.Now(),
  261. KeyUsage: x509.KeyUsageCertSign,
  262. BasicConstraintsValid: true,
  263. IsCA: true,
  264. MaxPathLenZero: true,
  265. }
  266. cert, err := x509.CreateCertificate(rand.Reader, tpl, tpl, pub, priv)
  267. fatalIfErr(err, "failed to generate CA certificate")
  268. privDER, err := x509.MarshalPKCS8PrivateKey(priv)
  269. fatalIfErr(err, "failed to encode CA key")
  270. err = ioutil.WriteFile(filepath.Join(m.CAROOT, rootKeyName), pem.EncodeToMemory(
  271. &pem.Block{Type: "PRIVATE KEY", Bytes: privDER}), 0400)
  272. fatalIfErr(err, "failed to save CA key")
  273. err = ioutil.WriteFile(filepath.Join(m.CAROOT, rootName), pem.EncodeToMemory(
  274. &pem.Block{Type: "CERTIFICATE", Bytes: cert}), 0644)
  275. fatalIfErr(err, "failed to save CA key")
  276. log.Printf("Created a new local CA at \"%s\" 💥\n", m.CAROOT)
  277. }
  278. func (m *mkcert) caUniqueName() string {
  279. return "mkcert development CA " + m.caCert.SerialNumber.String()
  280. }