cert.go 10 KB

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