main.go 9.2 KB

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