cert.go 11 KB

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