main.go 11 KB

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