main.go 10 KB

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