main.go 10 KB

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