main.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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. "strings"
  18. "golang.org/x/net/idna"
  19. )
  20. const shortUsage = `Usage of mkcert:
  21. $ mkcert -install
  22. Install the local CA in the system trust store.
  23. $ mkcert example.org
  24. Generate "example.org.pem" and "example.org-key.pem".
  25. $ mkcert example.com myapp.dev localhost 127.0.0.1 ::1
  26. Generate "example.com+4.pem" and "example.com+4-key.pem".
  27. $ mkcert "*.example.it"
  28. Generate "_wildcard.example.it.pem" and "_wildcard.example.it-key.pem".
  29. $ mkcert -uninstall
  30. Uninstall the local CA (but do not delete it).
  31. `
  32. const advancedUsage = `Advanced options:
  33. -cert-file FILE, -key-file FILE, -p12-file FILE
  34. Customize the output paths.
  35. -client
  36. Generate a certificate for client authentication.
  37. -ecdsa
  38. Generate a certificate with an ECDSA key.
  39. -pkcs12
  40. Generate a ".p12" PKCS #12 file, also know as a ".pfx" file,
  41. containing certificate and key for legacy applications.
  42. -csr CSR
  43. Generate a certificate based on the supplied CSR. Conflicts with
  44. all other flags and arguments except -install and -cert-file.
  45. -CAROOT
  46. Print the CA certificate and key storage location.
  47. $CAROOT (environment variable)
  48. Set the CA certificate and key storage location. (This allows
  49. maintaining multiple local CAs in parallel.)
  50. $TRUST_STORES (environment variable)
  51. A comma-separated list of trust stores to install the local
  52. root CA into. Options are: "system", "java" and "nss" (includes
  53. Firefox). Autodetected by default.
  54. `
  55. func main() {
  56. log.SetFlags(0)
  57. var (
  58. installFlag = flag.Bool("install", false, "")
  59. uninstallFlag = flag.Bool("uninstall", false, "")
  60. pkcs12Flag = flag.Bool("pkcs12", false, "")
  61. ecdsaFlag = flag.Bool("ecdsa", false, "")
  62. clientFlag = flag.Bool("client", false, "")
  63. helpFlag = flag.Bool("help", false, "")
  64. carootFlag = flag.Bool("CAROOT", false, "")
  65. csrFlag = flag.String("csr", "", "")
  66. certFileFlag = flag.String("cert-file", "", "")
  67. keyFileFlag = flag.String("key-file", "", "")
  68. p12FileFlag = flag.String("p12-file", "", "")
  69. )
  70. flag.Usage = func() {
  71. fmt.Fprintf(flag.CommandLine.Output(), shortUsage)
  72. fmt.Fprintln(flag.CommandLine.Output(), `For more options, run "mkcert -help".`)
  73. }
  74. flag.Parse()
  75. if *helpFlag {
  76. fmt.Fprintf(flag.CommandLine.Output(), shortUsage)
  77. fmt.Fprintf(flag.CommandLine.Output(), advancedUsage)
  78. return
  79. }
  80. if *carootFlag {
  81. if *installFlag || *uninstallFlag {
  82. log.Fatalln("ERROR: you can't set -[un]install and -CAROOT at the same time")
  83. }
  84. fmt.Println(getCAROOT())
  85. return
  86. }
  87. if *installFlag && *uninstallFlag {
  88. log.Fatalln("ERROR: you can't set -install and -uninstall at the same time")
  89. }
  90. if *csrFlag != "" && (*pkcs12Flag || *ecdsaFlag || *clientFlag) {
  91. log.Fatalln("ERROR: can only combine -csr with -install and -cert-file")
  92. }
  93. if *csrFlag != "" && flag.NArg() != 0 {
  94. log.Fatalln("ERROR: can't specify extra arguments when using -csr")
  95. }
  96. (&mkcert{
  97. installMode: *installFlag, uninstallMode: *uninstallFlag, csrPath: *csrFlag,
  98. pkcs12: *pkcs12Flag, ecdsa: *ecdsaFlag, client: *clientFlag,
  99. certFile: *certFileFlag, keyFile: *keyFileFlag, p12File: *p12FileFlag,
  100. }).Run(flag.Args())
  101. }
  102. const rootName = "rootCA.pem"
  103. const rootKeyName = "rootCA-key.pem"
  104. type mkcert struct {
  105. installMode, uninstallMode bool
  106. pkcs12, ecdsa, client bool
  107. keyFile, certFile, p12File string
  108. csrPath string
  109. CAROOT string
  110. caCert *x509.Certificate
  111. caKey crypto.PrivateKey
  112. // The system cert pool is only loaded once. After installing the root, checks
  113. // will keep failing until the next execution. TODO: maybe execve?
  114. // https://github.com/golang/go/issues/24540 (thanks, myself)
  115. ignoreCheckFailure bool
  116. }
  117. func (m *mkcert) Run(args []string) {
  118. m.CAROOT = getCAROOT()
  119. if m.CAROOT == "" {
  120. log.Fatalln("ERROR: failed to find the default CA location, set one as the CAROOT env var")
  121. }
  122. fatalIfErr(os.MkdirAll(m.CAROOT, 0755), "failed to create the CAROOT")
  123. m.loadCA()
  124. if m.installMode {
  125. m.install()
  126. if len(args) == 0 {
  127. return
  128. }
  129. } else if m.uninstallMode {
  130. m.uninstall()
  131. return
  132. } else {
  133. var warning bool
  134. if storeEnabled("system") && !m.checkPlatform() {
  135. warning = true
  136. log.Println("Warning: the local CA is not installed in the system trust store! ⚠️")
  137. }
  138. if storeEnabled("nss") && hasNSS && CertutilInstallHelp != "" && !m.checkNSS() {
  139. warning = true
  140. log.Printf("Warning: the local CA is not installed in the %s trust store! ⚠️", NSSBrowsers)
  141. }
  142. if storeEnabled("java") && hasJava && !m.checkJava() {
  143. warning = true
  144. log.Println("Warning: the local CA is not installed in the Java trust store! ⚠️")
  145. }
  146. if warning {
  147. log.Println("Run \"mkcert -install\" to avoid verification errors ‼️")
  148. }
  149. }
  150. if m.csrPath != "" {
  151. m.makeCertFromCSR()
  152. return
  153. }
  154. if len(args) == 0 {
  155. flag.Usage()
  156. return
  157. }
  158. hostnameRegexp := regexp.MustCompile(`(?i)^(\*\.)?[0-9a-z_-]([0-9a-z._-]*[0-9a-z_-])?$`)
  159. for i, name := range args {
  160. if ip := net.ParseIP(name); ip != nil {
  161. continue
  162. }
  163. punycode, err := idna.ToASCII(name)
  164. if err != nil {
  165. log.Fatalf("ERROR: %q is not a valid hostname or IP: %s", name, err)
  166. }
  167. args[i] = punycode
  168. if !hostnameRegexp.MatchString(punycode) {
  169. log.Fatalf("ERROR: %q is not a valid hostname or IP", name)
  170. }
  171. }
  172. m.makeCert(args)
  173. }
  174. func getCAROOT() string {
  175. if env := os.Getenv("CAROOT"); env != "" {
  176. return env
  177. }
  178. var dir string
  179. switch {
  180. case runtime.GOOS == "windows":
  181. dir = os.Getenv("LocalAppData")
  182. case os.Getenv("XDG_DATA_HOME") != "":
  183. dir = os.Getenv("XDG_DATA_HOME")
  184. case runtime.GOOS == "darwin":
  185. dir = os.Getenv("HOME")
  186. if dir == "" {
  187. return ""
  188. }
  189. dir = filepath.Join(dir, "Library", "Application Support")
  190. default: // Unix
  191. dir = os.Getenv("HOME")
  192. if dir == "" {
  193. return ""
  194. }
  195. dir = filepath.Join(dir, ".local", "share")
  196. }
  197. return filepath.Join(dir, "mkcert")
  198. }
  199. func (m *mkcert) install() {
  200. var printed bool
  201. if storeEnabled("system") && !m.checkPlatform() {
  202. if m.installPlatform() {
  203. log.Print("The local CA is now installed in the system trust store! ⚡️")
  204. }
  205. m.ignoreCheckFailure = true // TODO: replace with a check for a successful install
  206. printed = true
  207. }
  208. if storeEnabled("nss") && hasNSS && !m.checkNSS() {
  209. if hasCertutil && m.installNSS() {
  210. log.Printf("The local CA is now installed in the %s trust store (requires browser restart)! 🦊", NSSBrowsers)
  211. } else if CertutilInstallHelp == "" {
  212. log.Printf(`Note: %s support is not available on your platform. ℹ️`, NSSBrowsers)
  213. } else if !hasCertutil {
  214. log.Printf(`Warning: "certutil" is not available, so the CA can't be automatically installed in %s! ⚠️`, NSSBrowsers)
  215. log.Printf(`Install "certutil" with "%s" and re-run "mkcert -install" 👈`, CertutilInstallHelp)
  216. }
  217. printed = true
  218. }
  219. if storeEnabled("java") && hasJava && !m.checkJava() {
  220. if hasKeytool {
  221. m.installJava()
  222. log.Println("The local CA is now installed in Java's trust store! ☕️")
  223. } else {
  224. log.Println(`Warning: "keytool" is not available, so the CA can't be automatically installed in Java's trust store! ⚠️`)
  225. }
  226. printed = true
  227. }
  228. if printed {
  229. log.Print("")
  230. }
  231. }
  232. func (m *mkcert) uninstall() {
  233. if storeEnabled("nss") && hasNSS {
  234. if hasCertutil {
  235. m.uninstallNSS()
  236. } else if CertutilInstallHelp != "" {
  237. log.Print("")
  238. log.Printf(`Warning: "certutil" is not available, so the CA can't be automatically uninstalled from %s (if it was ever installed)! ⚠️`, NSSBrowsers)
  239. log.Printf(`You can install "certutil" with "%s" and re-run "mkcert -uninstall" 👈`, CertutilInstallHelp)
  240. log.Print("")
  241. }
  242. }
  243. if storeEnabled("java") && hasJava {
  244. if hasKeytool {
  245. m.uninstallJava()
  246. } else {
  247. log.Print("")
  248. 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)! ⚠️`)
  249. log.Print("")
  250. }
  251. }
  252. if storeEnabled("system") && m.uninstallPlatform() {
  253. log.Print("The local CA is now uninstalled from the system trust store(s)! 👋")
  254. log.Print("")
  255. } else if storeEnabled("nss") && hasCertutil {
  256. log.Printf("The local CA is now uninstalled from the %s trust store(s)! 👋", NSSBrowsers)
  257. log.Print("")
  258. }
  259. }
  260. func (m *mkcert) checkPlatform() bool {
  261. if m.ignoreCheckFailure {
  262. return true
  263. }
  264. _, err := m.caCert.Verify(x509.VerifyOptions{})
  265. return err == nil
  266. }
  267. func storeEnabled(name string) bool {
  268. stores := os.Getenv("TRUST_STORES")
  269. if stores == "" {
  270. return true
  271. }
  272. for _, store := range strings.Split(stores, ",") {
  273. if store == name {
  274. return true
  275. }
  276. }
  277. return false
  278. }
  279. func fatalIfErr(err error, msg string) {
  280. if err != nil {
  281. log.Fatalf("ERROR: %s: %s", msg, err)
  282. }
  283. }
  284. func fatalIfCmdErr(err error, cmd string, out []byte) {
  285. if err != nil {
  286. log.Fatalf("ERROR: failed to execute \"%s\": %s\n\n%s\n", cmd, err, out)
  287. }
  288. }