main.go 5.3 KB

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