main.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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 && CertutilInstallHelp != "" && !m.checkNSS() {
  88. warning = true
  89. log.Printf("Warning: the local CA is not installed in the %s trust store! ⚠️", NSSBrowsers)
  90. }
  91. if hasJava && !m.checkJava() {
  92. warning = true
  93. log.Println("Warning: the local CA is not installed in the Java trust store! ⚠️")
  94. }
  95. if warning {
  96. log.Println("Run \"mkcert -install\" to avoid verification errors ‼️")
  97. }
  98. }
  99. if len(args) == 0 {
  100. log.Printf("\n%s", usage)
  101. return
  102. }
  103. hostnameRegexp := regexp.MustCompile(`(?i)^(\*\.)?[0-9a-z_-]([0-9a-z._-]*[0-9a-z_-])?$`)
  104. for i, name := range args {
  105. if ip := net.ParseIP(name); ip != nil {
  106. continue
  107. }
  108. punycode, err := idna.ToASCII(name)
  109. if err != nil {
  110. log.Fatalf("ERROR: %q is not a valid hostname or IP: %s", name, err)
  111. }
  112. args[i] = punycode
  113. if !hostnameRegexp.MatchString(punycode) {
  114. log.Fatalf("ERROR: %q is not a valid hostname or IP", name)
  115. }
  116. }
  117. m.makeCert(args)
  118. }
  119. func getCAROOT() string {
  120. if env := os.Getenv("CAROOT"); env != "" {
  121. return env
  122. }
  123. var dir string
  124. switch {
  125. case runtime.GOOS == "windows":
  126. dir = os.Getenv("LocalAppData")
  127. case os.Getenv("XDG_DATA_HOME") != "":
  128. dir = os.Getenv("XDG_DATA_HOME")
  129. case runtime.GOOS == "darwin":
  130. dir = os.Getenv("HOME")
  131. if dir == "" {
  132. return ""
  133. }
  134. dir = filepath.Join(dir, "Library", "Application Support")
  135. default: // Unix
  136. dir = os.Getenv("HOME")
  137. if dir == "" {
  138. return ""
  139. }
  140. dir = filepath.Join(dir, ".local", "share")
  141. }
  142. return filepath.Join(dir, "mkcert")
  143. }
  144. func (m *mkcert) install() {
  145. var printed bool
  146. if !m.checkPlatform() {
  147. if m.installPlatform() {
  148. log.Print("The local CA is now installed in the system trust store! ⚡️")
  149. }
  150. m.ignoreCheckFailure = true // TODO: replace with a check for a successful install
  151. printed = true
  152. }
  153. if hasNSS && !m.checkNSS() {
  154. if hasCertutil && m.installNSS() {
  155. log.Printf("The local CA is now installed in the %s trust store (requires browser restart)! 🦊", NSSBrowsers)
  156. } else if CertutilInstallHelp == "" {
  157. log.Printf(`Note: %s support is not available on your platform. ℹ️`, NSSBrowsers)
  158. } else if !hasCertutil {
  159. log.Printf(`Warning: "certutil" is not available, so the CA can't be automatically installed in %s! ⚠️`, NSSBrowsers)
  160. log.Printf(`Install "certutil" with "%s" and re-run "mkcert -install" 👈`, CertutilInstallHelp)
  161. }
  162. printed = true
  163. }
  164. if hasJava && !m.checkJava() {
  165. if hasKeytool {
  166. m.installJava()
  167. log.Println("The local CA is now installed in Java's trust store! ☕️")
  168. } else {
  169. log.Println(`Warning: "keytool" is not available, so the CA can't be automatically installed in Java's trust store! ⚠️`)
  170. }
  171. printed = true
  172. }
  173. if printed {
  174. log.Print("")
  175. }
  176. }
  177. func (m *mkcert) uninstall() {
  178. if hasNSS {
  179. if hasCertutil {
  180. m.uninstallNSS()
  181. } else if CertutilInstallHelp != "" {
  182. log.Print("")
  183. log.Printf(`Warning: "certutil" is not available, so the CA can't be automatically uninstalled from %s (if it was ever installed)! ⚠️`, NSSBrowsers)
  184. log.Printf(`You can install "certutil" with "%s" and re-run "mkcert -uninstall" 👈`, CertutilInstallHelp)
  185. log.Print("")
  186. }
  187. }
  188. if hasJava {
  189. if hasKeytool {
  190. m.uninstallJava()
  191. } else {
  192. log.Print("")
  193. 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)! ⚠️`)
  194. log.Print("")
  195. }
  196. }
  197. if m.uninstallPlatform() {
  198. log.Print("The local CA is now uninstalled from the system trust store(s)! 👋")
  199. log.Print("")
  200. } else if hasCertutil {
  201. log.Printf("The local CA is now uninstalled from the %s trust store(s)! 👋", NSSBrowsers)
  202. log.Print("")
  203. }
  204. }
  205. func (m *mkcert) checkPlatform() bool {
  206. if m.ignoreCheckFailure {
  207. return true
  208. }
  209. _, err := m.caCert.Verify(x509.VerifyOptions{})
  210. return err == nil
  211. }
  212. func fatalIfErr(err error, msg string) {
  213. if err != nil {
  214. log.Fatalf("ERROR: %s: %s", msg, err)
  215. }
  216. }
  217. func fatalIfCmdErr(err error, cmd string, out []byte) {
  218. if err != nil {
  219. log.Fatalf("ERROR: failed to execute \"%s\": %s\n\n%s\n", cmd, err, out)
  220. }
  221. }