cert.go 10 KB

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