Debian Codegraph @

internal/main.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 // Command mkcert is a simple zero-config tool to make development certificates.
6 package internal
7
8 import (
9 "crypto"
10 "crypto/x509"
11 "flag"
12 "fmt"
13 "log"
14 "net"
15 "net/mail"
16 "net/url"
17 "os"
18 "os/exec"
19 "os/user"
20 "path/filepath"
21 "regexp"
22 "runtime"
23 "runtime/debug"
24 "strings"
25 "sync"
26
27 "golang.org/x/net/idna"
28 )
29
30 const shortUsage = `Usage of mkcert:
31
32 $ hugo server trust
33 Install the local CA in the system trust store.
34
35 $ mkcert example.org
36 Generate "example.org.pem" and "example.org-key.pem".
37
38 $ mkcert example.com myapp.dev localhost 127.0.0.1 ::1
39 Generate "example.com+4.pem" and "example.com+4-key.pem".
40
41 $ mkcert "*.example.it"
42 Generate "_wildcard.example.it.pem" and "_wildcard.example.it-key.pem".
43
44 $ hugo server trust -uninstall
45 Uninstall the local CA (but do not delete it).
46
47 `
48
49 const advancedUsage = `Advanced options:
50
51 -cert-file FILE, -key-file FILE, -p12-file FILE
52 Customize the output paths.
53
54 -client
55 Generate a certificate for client authentication.
56
57 -ecdsa
58 Generate a certificate with an ECDSA key.
59
60 -pkcs12
61 Generate a ".p12" PKCS #12 file, also know as a ".pfx" file,
62 containing certificate and key for legacy applications.
63
64 -csr CSR
65 Generate a certificate based on the supplied CSR. Conflicts with
66 all other flags and arguments except -install and -cert-file.
67
68 -CAROOT
69 Print the CA certificate and key storage location.
70
71 $CAROOT (environment variable)
72 Set the CA certificate and key storage location. (This allows
73 maintaining multiple local CAs in parallel.)
74
75 $TRUST_STORES (environment variable)
76 A comma-separated list of trust stores to install the local
77 root CA into. Options are: "system", "java" and "nss" (includes
78 Firefox). Autodetected by default.
79
80 `
81
82 // Version can be set at link time to override debug.BuildInfo.Main.Version,
83 // which is "(devel)" when building from within the module. See
84 // golang.org/issue/29814 and golang.org/issue/29228.
85 var Version string
86
87 func RunMain() {
88 if len(os.Args) == 1 {
89 fmt.Print(shortUsage)
90 return
91 }
92 log.SetFlags(0)
93 var (
94 installFlag = flag.Bool("install", false, "")
95 uninstallFlag = flag.Bool("uninstall", false, "")
96 pkcs12Flag = flag.Bool("pkcs12", false, "")
97 ecdsaFlag = flag.Bool("ecdsa", false, "")
98 clientFlag = flag.Bool("client", false, "")
99 helpFlag = flag.Bool("help", false, "")
100 carootFlag = flag.Bool("CAROOT", false, "")
101 csrFlag = flag.String("csr", "", "")
102 certFileFlag = flag.String("cert-file", "", "")
103 keyFileFlag = flag.String("key-file", "", "")
104 p12FileFlag = flag.String("p12-file", "", "")
105 versionFlag = flag.Bool("version", false, "")
106 )
107 flag.Usage = func() {
108 fmt.Fprint(flag.CommandLine.Output(), shortUsage)
109 fmt.Fprintln(flag.CommandLine.Output(), `For more options, run "mkcert -help".`)
110 }
111 flag.Parse()
112 if *helpFlag {
113 fmt.Print(shortUsage)
114 fmt.Print(advancedUsage)
115 return
116 }
117 if *versionFlag {
118 if Version != "" {
119 fmt.Println(Version)
120 return
121 }
122 if buildInfo, ok := debug.ReadBuildInfo(); ok {
123 fmt.Println(buildInfo.Main.Version)
124 return
125 }
126 fmt.Println("(unknown)")
127 return
128 }
129 if *carootFlag {
130 if *installFlag || *uninstallFlag {
131 panic(fmt.Sprintln("ERROR: you can't set -[un]install and -CAROOT at the same time"))
132 }
133 fmt.Println(GetCAROOT())
134 return
135 }
136 if *installFlag && *uninstallFlag {
137 panic(fmt.Sprintln("ERROR: you can't set -install and -uninstall at the same time"))
138 }
139 if *csrFlag != "" && (*pkcs12Flag || *ecdsaFlag || *clientFlag) {
140 panic(fmt.Sprintln("ERROR: can only combine -csr with -install and -cert-file"))
141 }
142 if *csrFlag != "" && flag.NArg() != 0 {
143 panic(fmt.Sprintln("ERROR: can't specify extra arguments when using -csr"))
144 }
145 (&mkcert{
146 installMode: *installFlag, uninstallMode: *uninstallFlag, csrPath: *csrFlag,
147 pkcs12: *pkcs12Flag, ecdsa: *ecdsaFlag, client: *clientFlag,
148 certFile: *certFileFlag, keyFile: *keyFileFlag, p12File: *p12FileFlag,
149 }).Run(flag.Args())
150 }
151
152 const rootName = "rootCA.pem"
153 const rootKeyName = "rootCA-key.pem"
154
155 type mkcert struct {
156 installMode, uninstallMode bool
157 pkcs12, ecdsa, client bool
158 keyFile, certFile, p12File string
159 csrPath string
160
161 CAROOT string
162 caCert *x509.Certificate
163 caKey crypto.PrivateKey
164
165 // The system cert pool is only loaded once. After installing the root, checks
166 // will keep failing until the next execution. TODO: maybe execve?
167 // https://github.com/golang/go/issues/24540 (thanks, myself)
168 ignoreCheckFailure bool
169 }
170
171 func (m *mkcert) Run(args []string) {
172 m.CAROOT = GetCAROOT()
173 if m.CAROOT == "" {
174 panic(fmt.Sprintln("ERROR: failed to find the default CA location, set one as the CAROOT env var"))
175 }
176 fatalIfErr(os.MkdirAll(m.CAROOT, 0755), "failed to create the CAROOT")
177 m.loadCA()
178
179 if m.installMode {
180 m.install()
181 if len(args) == 0 {
182 return
183 }
184 } else if m.uninstallMode {
185 m.uninstall()
186 return
187 } else {
188 var warning bool
189 if storeEnabled("system") && !m.checkPlatform() {
190 warning = true
191 log.Println("Note: the local CA is not installed in the system trust store.")
192 }
193 if storeEnabled("nss") && hasNSS && CertutilInstallHelp != "" && !m.checkNSS() {
194 warning = true
195 log.Printf("Note: the local CA is not installed in the %s trust store.", NSSBrowsers)
196 }
197 if storeEnabled("java") && hasJava && !m.checkJava() {
198 warning = true
199 log.Println("Note: the local CA is not installed in the Java trust store.")
200 }
201 if warning {
202 log.Println("Run \"hugo server trust\" for certificates to be trusted automatically")
203 }
204 }
205
206 if m.csrPath != "" {
207 m.makeCertFromCSR()
208 return
209 }
210
211 if len(args) == 0 {
212 flag.Usage()
213 return
214 }
215
216 hostnameRegexp := regexp.MustCompile(`(?i)^(\*\.)?[0-9a-z_-]([0-9a-z._-]*[0-9a-z_-])?$`)
217 for i, name := range args {
218 if ip := net.ParseIP(name); ip != nil {
219 continue
220 }
221 if email, err := mail.ParseAddress(name); err == nil && email.Address == name {
222 continue
223 }
224 if uriName, err := url.Parse(name); err == nil && uriName.Scheme != "" && uriName.Host != "" {
225 continue
226 }
227 punycode, err := idna.ToASCII(name)
228 if err != nil {
229 panic(fmt.Sprintf("ERROR: %q is not a valid hostname, IP, URL or email: %s", name, err))
230 }
231 args[i] = punycode
232 if !hostnameRegexp.MatchString(punycode) {
233 panic(fmt.Sprintf("ERROR: %q is not a valid hostname, IP, URL or email", name))
234 }
235 }
236
237 m.makeCert(args)
238 }
239
240 func GetCAROOT() string {
241 if env := os.Getenv("CAROOT"); env != "" {
242 return env
243 }
244
245 var dir string
246 switch {
247 case runtime.GOOS == "windows":
248 dir = os.Getenv("LocalAppData")
249 case os.Getenv("XDG_DATA_HOME") != "":
250 dir = os.Getenv("XDG_DATA_HOME")
251 case runtime.GOOS == "darwin":
252 dir = os.Getenv("HOME")
253 if dir == "" {
254 return ""
255 }
256 dir = filepath.Join(dir, "Library", "Application Support")
257 default: // Unix
258 dir = os.Getenv("HOME")
259 if dir == "" {
260 return ""
261 }
262 dir = filepath.Join(dir, ".local", "share")
263 }
264 return filepath.Join(dir, "mkcert")
265 }
266
267 func (m *mkcert) install() {
268 if storeEnabled("system") {
269 if m.checkPlatform() {
270 log.Print("The local CA is already installed in the system trust store.")
271 } else {
272 if m.installPlatform() {
273 log.Print("The local CA is now installed in the system trust store.")
274 }
275 m.ignoreCheckFailure = true // TODO: replace with a check for a successful install
276 }
277 }
278 if storeEnabled("nss") && hasNSS {
279 if m.checkNSS() {
280 log.Printf("The local CA is already installed in the %s trust store.", NSSBrowsers)
281 } else {
282 if hasCertutil && m.installNSS() {
283 log.Printf("The local CA is now installed in the %s trust store (requires browser restart).", NSSBrowsers)
284 } else if CertutilInstallHelp == "" {
285 log.Printf(`Note: %s support is not available on your platform.`, NSSBrowsers)
286 } else if !hasCertutil {
287 log.Printf(`Warning: "certutil" is not available, so the CA can't be automatically installed in %s!`, NSSBrowsers)
288 log.Printf(`Install "certutil" with "%s" and re-run "hugo server trust"`, CertutilInstallHelp)
289 }
290 }
291 }
292 if storeEnabled("java") && hasJava {
293 if m.checkJava() {
294 log.Println("The local CA is already installed in Java's trust store.")
295 } else {
296 if hasKeytool {
297 m.installJava()
298 log.Println("The local CA is now installed in Java's trust store! ☕️")
299 } else {
300 log.Println(`Warning: "keytool" is not available, so the CA can't be automatically installed in Java's trust store!`)
301 }
302 }
303 }
304 log.Print("")
305 }
306
307 func (m *mkcert) uninstall() {
308 if storeEnabled("nss") && hasNSS {
309 if hasCertutil {
310 m.uninstallNSS()
311 } else if CertutilInstallHelp != "" {
312 log.Print("")
313 log.Printf(`Warning: "certutil" is not available, so the CA can't be automatically uninstalled from %s (if it was ever installed)!`, NSSBrowsers)
314 log.Printf(`You can install "certutil" with "%s" and re-run "hugo server trust -uninstall"`, CertutilInstallHelp)
315 log.Print("")
316 }
317 }
318 if storeEnabled("java") && hasJava {
319 if hasKeytool {
320 m.uninstallJava()
321 } else {
322 log.Print("")
323 log.Println(`Warning: "keytool" is not available, so the CA can't be automatically uninstalled from Java's trust store (if it was ever installed)!`)
324 log.Print("")
325 }
326 }
327 if storeEnabled("system") && m.uninstallPlatform() {
328 log.Print("The local CA is now uninstalled from the system trust store(s).")
329 log.Print("")
330 } else if storeEnabled("nss") && hasCertutil {
331 log.Printf("The local CA is now uninstalled from the %s trust store(s).", NSSBrowsers)
332 log.Print("")
333 }
334 }
335
336 func (m *mkcert) checkPlatform() bool {
337 if m.ignoreCheckFailure {
338 return true
339 }
340
341 _, err := m.caCert.Verify(x509.VerifyOptions{})
342 return err == nil
343 }
344
345 func storeEnabled(name string) bool {
346 stores := os.Getenv("TRUST_STORES")
347 if stores == "" {
348 return true
349 }
350 for _, store := range strings.Split(stores, ",") {
351 if store == name {
352 return true
353 }
354 }
355 return false
356 }
357
358 func fatalIfErr(err error, msg string) {
359 if err != nil {
360 panic(fmt.Sprintf("ERROR: %s: %s", msg, err))
361 }
362 }
363
364 func fatalIfCmdErr(err error, cmd string, out []byte) {
365 if err != nil {
366 panic(fmt.Sprintf("ERROR: failed to execute \"%s\": %s\n\n%s\n", cmd, err, out))
367 }
368 }
369
370 func pathExists(path string) bool {
371 _, err := os.Stat(path)
372 return err == nil
373 }
374
375 func binaryExists(name string) bool {
376 _, err := exec.LookPath(name)
377 return err == nil
378 }
379
380 var sudoWarningOnce sync.Once
381
382 func commandWithSudo(cmd ...string) *exec.Cmd {
383 if u, err := user.Current(); err == nil && u.Uid == "0" {
384 return exec.Command(cmd[0], cmd[1:]...)
385 }
386 if !binaryExists("sudo") {
387 sudoWarningOnce.Do(func() {
388 log.Println(`Warning: "sudo" is not available, and mkcert is not running as root. The (un)install operation might fail.`)
389 })
390 return exec.Command(cmd[0], cmd[1:]...)
391 }
392 return exec.Command("sudo", append([]string{"--prompt=Sudo password:", "--"}, cmd...)...)
393 }