main.go 11 KB

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