main.go 11 KB

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