cert.go 11 KB

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