main.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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. func main() {
  20. log.SetFlags(0)
  21. var installFlag = flag.Bool("install", false, "install the local root CA in the system trust store")
  22. var uninstallFlag = flag.Bool("uninstall", false, "uninstall the local root CA from the system trust store")
  23. var carootFlag = flag.Bool("CAROOT", false, "print the CAROOT path")
  24. flag.Parse()
  25. if *carootFlag {
  26. if *installFlag || *uninstallFlag {
  27. log.Fatalln("ERROR: you can't set -[un]install and -CAROOT at the same time")
  28. }
  29. fmt.Println(getCAROOT())
  30. return
  31. }
  32. if *installFlag && *uninstallFlag {
  33. log.Fatalln("ERROR: you can't set -install and -uninstall at the same time")
  34. }
  35. (&mkcert{
  36. installMode: *installFlag, uninstallMode: *uninstallFlag,
  37. }).Run(flag.Args())
  38. }
  39. const rootName = "rootCA.pem"
  40. const keyName = "rootCA-key.pem"
  41. type mkcert struct {
  42. installMode, uninstallMode bool
  43. CAROOT string
  44. caCert *x509.Certificate
  45. caKey crypto.PrivateKey
  46. // The system cert pool is only loaded once. After installing the root, checks
  47. // will keep failing until the next execution. TODO: maybe execve?
  48. // https://github.com/golang/go/issues/24540 (thanks, myself)
  49. ignoreCheckFailure bool
  50. }
  51. func (m *mkcert) Run(args []string) {
  52. m.CAROOT = getCAROOT()
  53. if m.CAROOT == "" {
  54. log.Fatalln("ERROR: failed to find the default CA location, set one as the CAROOT env var")
  55. }
  56. fatalIfErr(os.MkdirAll(m.CAROOT, 0755), "failed to create the CAROOT")
  57. m.loadCA()
  58. if m.installMode {
  59. m.install()
  60. if len(args) == 0 {
  61. return
  62. }
  63. } else if m.uninstallMode {
  64. m.uninstall()
  65. return
  66. } else {
  67. var warning bool
  68. if !m.checkPlatform() {
  69. warning = true
  70. log.Println("Warning: the local CA is not installed in the system trust store! ⚠️")
  71. }
  72. if hasNSS && !m.checkNSS() {
  73. warning = true
  74. log.Printf("Warning: the local CA is not installed in the %s trust store! ⚠️", NSSBrowsers)
  75. }
  76. if warning {
  77. log.Println("Run \"mkcert -install\" to avoid verification errors ‼️")
  78. }
  79. }
  80. if len(args) == 0 {
  81. log.Printf(`
  82. Usage:
  83. $ mkcert -install
  84. Install the local CA in the system trust store.
  85. $ mkcert example.org
  86. Generate "example.org.pem" and "example.org-key.pem".
  87. $ mkcert example.com myapp.dev localhost 127.0.0.1 ::1
  88. Generate "example.com+4.pem" and "example.com+4-key.pem".
  89. $ mkcert '*.example.com'
  90. Generate "_wildcard.example.com.pem" and "_wildcard.example.com-key.pem".
  91. $ mkcert -uninstall
  92. Uninstall the local CA (but do not delete it).
  93. Change the CA certificate and key storage location by setting $CAROOT,
  94. print it with "mkcert -CAROOT".
  95. `)
  96. return
  97. }
  98. hostnameRegexp := regexp.MustCompile(`(?i)^(\*\.)?[0-9a-z_-]([0-9a-z._-]*[0-9a-z_-])?$`)
  99. for i, name := range args {
  100. if ip := net.ParseIP(name); ip != nil {
  101. continue
  102. }
  103. punycode, err := idna.ToASCII(name)
  104. if err != nil {
  105. log.Fatalf("ERROR: %q is not a valid hostname or IP: %s", name, err)
  106. }
  107. args[i] = punycode
  108. if !hostnameRegexp.MatchString(punycode) {
  109. log.Fatalf("ERROR: %q is not a valid hostname or IP", name)
  110. }
  111. }
  112. m.makeCert(args)
  113. }
  114. func getCAROOT() string {
  115. if env := os.Getenv("CAROOT"); env != "" {
  116. return env
  117. }
  118. var dir string
  119. switch runtime.GOOS {
  120. case "windows":
  121. dir = os.Getenv("LocalAppData")
  122. case "darwin":
  123. dir = os.Getenv("HOME")
  124. if dir == "" {
  125. return ""
  126. }
  127. dir = filepath.Join(dir, "Library", "Application Support")
  128. default: // Unix
  129. dir = os.Getenv("XDG_DATA_HOME")
  130. if dir == "" {
  131. dir = os.Getenv("HOME")
  132. if dir == "" {
  133. return ""
  134. }
  135. dir = filepath.Join(dir, ".local", "share")
  136. }
  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. }