cert.go 11 KB

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