main.go 9.4 KB

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