main.go 5.1 KB

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