main.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. // Copyright 2018 The Go 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. // Command mkcert is a simple zero-config tool to make development certificates.
  5. package main
  6. import (
  7. "crypto"
  8. "crypto/x509"
  9. "flag"
  10. "fmt"
  11. "log"
  12. "net"
  13. "os"
  14. "path/filepath"
  15. "regexp"
  16. "runtime"
  17. "golang.org/x/net/idna"
  18. )
  19. const usage = `Usage of mkcert:
  20. $ mkcert -install
  21. Install the local CA in the system trust store.
  22. $ mkcert example.org
  23. Generate "example.org.pem" and "example.org-key.pem".
  24. $ mkcert example.com myapp.dev localhost 127.0.0.1 ::1
  25. Generate "example.com+4.pem" and "example.com+4-key.pem".
  26. $ mkcert '*.example.com'
  27. Generate "_wildcard.example.com.pem" and "_wildcard.example.com-key.pem".
  28. $ mkcert -uninstall
  29. Uninstall the local CA (but do not delete it).
  30. Change the CA certificate and key storage location by setting $CAROOT,
  31. print it with "mkcert -CAROOT".
  32. `
  33. func main() {
  34. log.SetFlags(0)
  35. var installFlag = flag.Bool("install", false, "install the local root CA in the system trust store")
  36. var uninstallFlag = flag.Bool("uninstall", false, "uninstall the local root CA from the system trust store")
  37. var carootFlag = flag.Bool("CAROOT", false, "print the CAROOT path")
  38. flag.Usage = func() { fmt.Fprintf(flag.CommandLine.Output(), usage) }
  39. flag.Parse()
  40. if *carootFlag {
  41. if *installFlag || *uninstallFlag {
  42. log.Fatalln("ERROR: you can't set -[un]install and -CAROOT at the same time")
  43. }
  44. fmt.Println(getCAROOT())
  45. return
  46. }
  47. if *installFlag && *uninstallFlag {
  48. log.Fatalln("ERROR: you can't set -install and -uninstall at the same time")
  49. }
  50. (&mkcert{
  51. installMode: *installFlag, uninstallMode: *uninstallFlag,
  52. }).Run(flag.Args())
  53. }
  54. const rootName = "rootCA.pem"
  55. const keyName = "rootCA-key.pem"
  56. type mkcert struct {
  57. installMode, uninstallMode bool
  58. CAROOT string
  59. caCert *x509.Certificate
  60. caKey crypto.PrivateKey
  61. // The system cert pool is only loaded once. After installing the root, checks
  62. // will keep failing until the next execution. TODO: maybe execve?
  63. // https://github.com/golang/go/issues/24540 (thanks, myself)
  64. ignoreCheckFailure bool
  65. }
  66. func (m *mkcert) Run(args []string) {
  67. m.CAROOT = getCAROOT()
  68. if m.CAROOT == "" {
  69. log.Fatalln("ERROR: failed to find the default CA location, set one as the CAROOT env var")
  70. }
  71. fatalIfErr(os.MkdirAll(m.CAROOT, 0755), "failed to create the CAROOT")
  72. m.loadCA()
  73. if m.installMode {
  74. m.install()
  75. if len(args) == 0 {
  76. return
  77. }
  78. } else if m.uninstallMode {
  79. m.uninstall()
  80. return
  81. } else {
  82. var warning bool
  83. if !m.checkPlatform() {
  84. warning = true
  85. log.Println("Warning: the local CA is not installed in the system trust store! ⚠️")
  86. }
  87. if hasNSS && !m.checkNSS() {
  88. warning = true
  89. log.Printf("Warning: the local CA is not installed in the %s trust store! ⚠️", NSSBrowsers)
  90. }
  91. if warning {
  92. log.Println("Run \"mkcert -install\" to avoid verification errors ‼️")
  93. }
  94. }
  95. if len(args) == 0 {
  96. log.Printf("\n%s", usage)
  97. return
  98. }
  99. hostnameRegexp := regexp.MustCompile(`(?i)^(\*\.)?[0-9a-z_-]([0-9a-z._-]*[0-9a-z_-])?$`)
  100. for i, name := range args {
  101. if ip := net.ParseIP(name); ip != nil {
  102. continue
  103. }
  104. punycode, err := idna.ToASCII(name)
  105. if err != nil {
  106. log.Fatalf("ERROR: %q is not a valid hostname or IP: %s", name, err)
  107. }
  108. args[i] = punycode
  109. if !hostnameRegexp.MatchString(punycode) {
  110. log.Fatalf("ERROR: %q is not a valid hostname or IP", name)
  111. }
  112. }
  113. m.makeCert(args)
  114. }
  115. func getCAROOT() string {
  116. if env := os.Getenv("CAROOT"); env != "" {
  117. return env
  118. }
  119. var dir string
  120. switch {
  121. case runtime.GOOS == "windows":
  122. dir = os.Getenv("LocalAppData")
  123. case os.Getenv("XDG_DATA_HOME") != "":
  124. dir = os.Getenv("XDG_DATA_HOME")
  125. case runtime.GOOS == "darwin":
  126. dir = os.Getenv("HOME")
  127. if dir == "" {
  128. return ""
  129. }
  130. dir = filepath.Join(dir, "Library", "Application Support")
  131. default: // Unix
  132. dir = os.Getenv("HOME")
  133. if dir == "" {
  134. return ""
  135. }
  136. dir = filepath.Join(dir, ".local", "share")
  137. }
  138. return filepath.Join(dir, "mkcert")
  139. }
  140. func (m *mkcert) install() {
  141. var printed bool
  142. if !m.checkPlatform() {
  143. if m.installPlatform() {
  144. log.Print("The local CA is now installed in the system trust store! ⚡️")
  145. }
  146. m.ignoreCheckFailure = true // TODO: replace with a check for a successful install
  147. printed = true
  148. }
  149. if hasNSS && !m.checkNSS() {
  150. if hasCertutil {
  151. m.installNSS()
  152. log.Printf("The local CA is now installed in the %s trust store (requires browser restart)! 🦊", NSSBrowsers)
  153. } else {
  154. log.Printf(`Warning: "certutil" is not available, so the CA can't be automatically installed in %s! ⚠️`, NSSBrowsers)
  155. log.Printf(`Install "certutil" with "%s" and re-run "mkcert -install" 👈`, CertutilInstallHelp)
  156. }
  157. printed = true
  158. }
  159. if printed {
  160. log.Print("")
  161. }
  162. }
  163. func (m *mkcert) uninstall() {
  164. if hasNSS {
  165. if hasCertutil {
  166. m.uninstallNSS()
  167. } else {
  168. log.Print("")
  169. log.Printf(`Warning: "certutil" is not available, so the CA can't be automatically uninstalled from %s (if it was ever installed)! ⚠️`, NSSBrowsers)
  170. log.Printf(`You can install "certutil" with "%s" and re-run "mkcert -uninstall" 👈`, CertutilInstallHelp)
  171. log.Print("")
  172. }
  173. }
  174. if m.uninstallPlatform() {
  175. log.Print("The local CA is now uninstalled from the system trust store(s)! 👋")
  176. log.Print("")
  177. } else if hasCertutil {
  178. log.Printf("The local CA is now uninstalled from the %s trust store(s)! 👋", NSSBrowsers)
  179. log.Print("")
  180. }
  181. }
  182. func (m *mkcert) checkPlatform() bool {
  183. if m.ignoreCheckFailure {
  184. return true
  185. }
  186. _, err := m.caCert.Verify(x509.VerifyOptions{})
  187. return err == nil
  188. }
  189. func fatalIfErr(err error, msg string) {
  190. if err != nil {
  191. log.Fatalf("ERROR: %s: %s", msg, err)
  192. }
  193. }
  194. func fatalIfCmdErr(err error, cmd string, out []byte) {
  195. if err != nil {
  196. log.Fatalf("ERROR: failed to execute \"%s\": %s\n\n%s\n", cmd, err, out)
  197. }
  198. }