main.go 6.9 KB

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