main.go 7.3 KB

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