main.go 9.5 KB

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