Debian Codegraph @

internal/cert.go

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