10 Commits

Author SHA1 Message Date
Filippo Valsorda
99e15e29f9 Add support for certificate signing requests with -csr
Closes #55
2019-02-02 18:51:24 -05:00
Filippo Valsorda
592400aab0 Add the TRUST_STORES environment variable
Fixes #95
2019-02-02 16:26:21 -05:00
John Downey
66af5a51f6 Add support for client certificates with -client
Fixes #125
Closes #89
2019-02-02 16:26:21 -05:00
Filippo Valsorda
5bb0c47df7 Add -ecdsa for generating certificates with ECDSA keys
Fixes #118
2019-02-02 16:26:21 -05:00
Filippo Valsorda
821679b01f Split off advanced options docs 2019-02-02 16:26:21 -05:00
Filippo Valsorda
50b8c9f09f Set the CommonName when generating PKCS#12 files
Fixes #115
2019-02-02 16:26:21 -05:00
Filippo Valsorda
3bcdd3721c Update screenshot with Firefox and Chrome 2019-01-11 16:38:47 -08:00
Oxicode
a177c7e2ad Add "scoop bucket add extras" to README (#109)
Fixes #99
2019-01-08 12:42:51 -08:00
Filippo Valsorda
8dca36bc48 Build binaries for linux/arm
Updates #97
2019-01-08 09:37:29 -08:00
graystevens
610df05c5c Add "Firefox Nightly.app" support on macOS (#102) 2019-01-08 09:22:13 -08:00
5 changed files with 232 additions and 55 deletions

View File

@@ -6,6 +6,7 @@ install: "# skip"
script:
- go vet
- GOOS=linux GOARCH=amd64 go build -o "mkcert-$(git describe --tags)-linux-amd64"
- GOOS=linux GOARCH=arm GOARM=6 go build -o "mkcert-$(git describe --tags)-linux-arm"
- GOOS=darwin GOARCH=amd64 go build -o "mkcert-$(git describe --tags)-darwin-amd64"
- GOOS=windows GOARCH=amd64 go build -o "mkcert-$(git describe --tags)-windows-amd64.exe"

View File

@@ -22,7 +22,7 @@ Created a new certificate valid for the following names 📜
The certificate is at "./example.com+5.pem" and the key at "./example.com+5-key.pem" ✅
```
<p align="center"><img width="444" alt="Chrome screenshot" src="https://user-images.githubusercontent.com/1225294/41887838-7acd55ca-78d0-11e8-8a81-139a54faaf87.png"></p>
<p align="center"><img width="498" alt="Chrome and Firefox screenshot" src="https://user-images.githubusercontent.com/1225294/51066373-96d4aa80-15be-11e9-91e2-f4e44a3a4458.png"></p>
Using certificates from real certificate authorities (CAs) for development can be dangerous or impossible (for hosts like `localhost` or `127.0.0.1`), but self-signed certificates cause trust errors. Managing your own CA is the best solution, but usually involves arcane commands, specialized knowledge and manual steps.
@@ -95,6 +95,7 @@ choco install mkcert
or use Scoop
```
scoop bucket add extras
scoop install mkcert
```
@@ -116,8 +117,31 @@ mkcert supports the following root stores:
* Chrome and Chromium
* Java (when `JAVA_HOME` is set)
To only install the local root CA into a subset of them, you can set the `TRUST_STORES` environment variable to a comma-separated list. Options are: "system", "java" and "nss" (includes Firefox).
## Advanced topics
### Advanced options
```
-cert-file FILE, -key-file FILE, -p12-file FILE
Customize the output paths.
-client
Generate a certificate for client authentication.
-ecdsa
Generate a certificate with an ECDSA key.
-pkcs12
Generate a ".p12" PKCS #12 file, also know as a ".pfx" file,
containing certificate and key for legacy applications.
-csr CSR
Generate a certificate based on the supplied CSR. Conflicts with
all other flags and arguments except -install and -cert-file.
```
### Mobile devices
For the certificates to be trusted on mobile devices, you will have to install the root CA. It's the `rootCA.pem` file in the folder printed by `mkcert -CAROOT`.

134
cert.go
View File

@@ -5,6 +5,9 @@
package main
import (
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/sha1"
@@ -25,7 +28,7 @@ import (
"strings"
"time"
"software.sslmate.com/src/go-pkcs12"
pkcs12 "software.sslmate.com/src/go-pkcs12"
)
var userAndHostname string
@@ -44,15 +47,12 @@ func (m *mkcert) makeCert(hosts []string) {
log.Fatalln("ERROR: can't create new certificates because the CA key (rootCA-key.pem) is missing")
}
priv, err := rsa.GenerateKey(rand.Reader, 2048)
priv, err := m.generateKey(false)
fatalIfErr(err, "failed to generate certificate key")
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
fatalIfErr(err, "failed to generate serial number")
pub := priv.(crypto.Signer).Public()
tpl := &x509.Certificate{
SerialNumber: serialNumber,
SerialNumber: randomSerialNumber(),
Subject: pkix.Name{
Organization: []string{"mkcert development certificate"},
OrganizationalUnit: []string{userAndHostname},
@@ -72,9 +72,17 @@ func (m *mkcert) makeCert(hosts []string) {
tpl.DNSNames = append(tpl.DNSNames, h)
}
}
if m.client {
tpl.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}
}
pub := priv.PublicKey
cert, err := x509.CreateCertificate(rand.Reader, tpl, m.caCert, &pub, m.caKey)
// IIS (the main target of PKCS #12 files), only shows the deprecated
// Common Name in the UI. See issue #115.
if m.pkcs12 {
tpl.Subject.CommonName = hosts[0]
}
cert, err := x509.CreateCertificate(rand.Reader, tpl, m.caCert, pub, m.caKey)
fatalIfErr(err, "failed to generate certificate")
certFile, keyFile, p12File := m.fileNames(hosts)
@@ -88,7 +96,7 @@ func (m *mkcert) makeCert(hosts []string) {
err = ioutil.WriteFile(certFile, pem.EncodeToMemory(
&pem.Block{Type: "CERTIFICATE", Bytes: cert}), 0644)
fatalIfErr(err, "failed to save certificate key")
fatalIfErr(err, "failed to save certificate")
} else {
domainCert, _ := x509.ParseCertificate(cert)
pfxData, err := pkcs12.Encode(rand.Reader, priv, domainCert, []*x509.Certificate{m.caCert}, "changeit")
@@ -97,6 +105,17 @@ func (m *mkcert) makeCert(hosts []string) {
fatalIfErr(err, "failed to save PKCS#12")
}
m.printHosts(hosts)
if !m.pkcs12 {
log.Printf("\nThe certificate is at \"%s\" and the key at \"%s\" ✅\n\n", certFile, keyFile)
} else {
log.Printf("\nThe PKCS#12 bundle is at \"%s\" ✅\n", p12File)
log.Printf("\nThe legacy PKCS#12 encryption password is the often hardcoded default \"changeit\" \n\n")
}
}
func (m *mkcert) printHosts(hosts []string) {
secondLvlWildcardRegexp := regexp.MustCompile(`(?i)^\*\.[0-9a-z_-]+$`)
log.Printf("\nCreated a new certificate valid for the following names 📜")
for _, h := range hosts {
@@ -112,13 +131,16 @@ func (m *mkcert) makeCert(hosts []string) {
break
}
}
if !m.pkcs12 {
log.Printf("\nThe certificate is at \"%s\" and the key at \"%s\" ✅\n\n", certFile, keyFile)
} else {
log.Printf("\nThe PKCS#12 bundle is at \"%s\" ✅\n", p12File)
log.Printf("\nThe legacy PKCS#12 encryption password is the often hardcoded default \"changeit\" \n\n")
}
func (m *mkcert) generateKey(rootCA bool) (crypto.PrivateKey, error) {
if m.ecdsa {
return ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
}
if rootCA {
return rsa.GenerateKey(rand.Reader, 3072)
}
return rsa.GenerateKey(rand.Reader, 2048)
}
func (m *mkcert) fileNames(hosts []string) (certFile, keyFile, p12File string) {
@@ -144,6 +166,72 @@ func (m *mkcert) fileNames(hosts []string) (certFile, keyFile, p12File string) {
return
}
func randomSerialNumber() *big.Int {
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
fatalIfErr(err, "failed to generate serial number")
return serialNumber
}
func (m *mkcert) makeCertFromCSR() {
if m.caKey == nil {
log.Fatalln("ERROR: can't create new certificates because the CA key (rootCA-key.pem) is missing")
}
csrPEMBytes, err := ioutil.ReadFile(m.csrPath)
fatalIfErr(err, "failed to read the CSR")
csrPEM, _ := pem.Decode(csrPEMBytes)
if csrPEM == nil {
log.Fatalln("ERROR: failed to read the CSR: unexpected content")
}
if csrPEM.Type != "CERTIFICATE REQUEST" {
log.Fatalln("ERROR: failed to read the CSR: expected CERTIFICATE REQUEST, got " + csrPEM.Type)
}
csr, err := x509.ParseCertificateRequest(csrPEM.Bytes)
fatalIfErr(err, "failed to parse the CSR")
fatalIfErr(csr.CheckSignature(), "invalid CSR signature")
tpl := &x509.Certificate{
SerialNumber: randomSerialNumber(),
Subject: csr.Subject,
ExtraExtensions: csr.Extensions, // includes requested SANs
NotAfter: time.Now().AddDate(10, 0, 0),
NotBefore: time.Now(),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
// If the CSR does not request a SAN extension, fix it up for them as
// the Common Name field does not work in modern browsers. Otherwise,
// this will get overridden.
DNSNames: []string{csr.Subject.CommonName},
}
cert, err := x509.CreateCertificate(rand.Reader, tpl, m.caCert, csr.PublicKey, m.caKey)
fatalIfErr(err, "failed to generate certificate")
var hosts []string
hosts = append(hosts, csr.DNSNames...)
hosts = append(hosts, csr.EmailAddresses...)
for _, ip := range csr.IPAddresses {
hosts = append(hosts, ip.String())
}
if len(hosts) == 0 {
hosts = []string{csr.Subject.CommonName}
}
certFile, _, _ := m.fileNames(hosts)
err = ioutil.WriteFile(certFile, pem.EncodeToMemory(
&pem.Block{Type: "CERTIFICATE", Bytes: cert}), 0644)
fatalIfErr(err, "failed to save certificate")
m.printHosts(hosts)
log.Printf("\nThe certificate is at \"%s\" ✅\n\n", certFile)
}
// loadCA will load or create the CA at CAROOT.
func (m *mkcert) loadCA() {
if _, err := os.Stat(filepath.Join(m.CAROOT, rootName)); os.IsNotExist(err) {
@@ -176,15 +264,11 @@ func (m *mkcert) loadCA() {
}
func (m *mkcert) newCA() {
priv, err := rsa.GenerateKey(rand.Reader, 3072)
priv, err := m.generateKey(true)
fatalIfErr(err, "failed to generate the CA key")
pub := priv.PublicKey
pub := priv.(crypto.Signer).Public()
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
fatalIfErr(err, "failed to generate serial number")
spkiASN1, err := x509.MarshalPKIXPublicKey(&pub)
spkiASN1, err := x509.MarshalPKIXPublicKey(pub)
fatalIfErr(err, "failed to encode public key")
var spki struct {
@@ -197,7 +281,7 @@ func (m *mkcert) newCA() {
skid := sha1.Sum(spki.SubjectPublicKey.Bytes)
tpl := &x509.Certificate{
SerialNumber: serialNumber,
SerialNumber: randomSerialNumber(),
Subject: pkix.Name{
Organization: []string{"mkcert development CA"},
OrganizationalUnit: []string{userAndHostname},
@@ -219,7 +303,7 @@ func (m *mkcert) newCA() {
MaxPathLenZero: true,
}
cert, err := x509.CreateCertificate(rand.Reader, tpl, tpl, &pub, priv)
cert, err := x509.CreateCertificate(rand.Reader, tpl, tpl, pub, priv)
fatalIfErr(err, "failed to generate CA certificate")
privDER, err := x509.MarshalPKCS8PrivateKey(priv)

127
main.go
View File

@@ -16,11 +16,12 @@ import (
"path/filepath"
"regexp"
"runtime"
"strings"
"golang.org/x/net/idna"
)
const usage = `Usage of mkcert:
const shortUsage = `Usage of mkcert:
$ mkcert -install
Install the local CA in the system trust store.
@@ -31,32 +32,72 @@ const usage = `Usage of mkcert:
$ mkcert example.com myapp.dev localhost 127.0.0.1 ::1
Generate "example.com+4.pem" and "example.com+4-key.pem".
$ mkcert "*.example.com"
Generate "_wildcard.example.com.pem" and "_wildcard.example.com-key.pem".
$ mkcert -pkcs12 example.com
Generate "example.com.p12" instead of a PEM file.
$ mkcert "*.example.it"
Generate "_wildcard.example.it.pem" and "_wildcard.example.it-key.pem".
$ mkcert -uninstall
Uninstall the local CA (but do not delete it).
Use -cert-file, -key-file and -p12-file to customize the output paths.
`
const advancedUsage = `Advanced options:
-cert-file FILE, -key-file FILE, -p12-file FILE
Customize the output paths.
-client
Generate a certificate for client authentication.
-ecdsa
Generate a certificate with an ECDSA key.
-pkcs12
Generate a ".p12" PKCS #12 file, also know as a ".pfx" file,
containing certificate and key for legacy applications.
-csr CSR
Generate a certificate based on the supplied CSR. Conflicts with
all other flags and arguments except -install and -cert-file.
-CAROOT
Print the CA certificate and key storage location.
$CAROOT (environment variable)
Set the CA certificate and key storage location. (This allows
maintaining multiple local CAs in parallel.)
$TRUST_STORES (environment variable)
A comma-separated list of trust stores to install the local
root CA into. Options are: "system", "java" and "nss" (includes
Firefox). Autodetected by default.
Change the CA certificate and key storage location by setting $CAROOT,
print it with "mkcert -CAROOT".
`
func main() {
log.SetFlags(0)
var installFlag = flag.Bool("install", false, "install the local root CA in the system trust store")
var uninstallFlag = flag.Bool("uninstall", false, "uninstall the local root CA from the system trust store")
var pkcs12Flag = flag.Bool("pkcs12", false, "generate PKCS#12 instead of PEM")
var carootFlag = flag.Bool("CAROOT", false, "print the CAROOT path")
var certFileFlag = flag.String("cert-file", "", "output certificate file path")
var keyFileFlag = flag.String("key-file", "", "output key file path")
var p12FileFlag = flag.String("p12-file", "", "output PKCS#12 file path")
flag.Usage = func() { fmt.Fprintf(flag.CommandLine.Output(), usage) }
var (
installFlag = flag.Bool("install", false, "")
uninstallFlag = flag.Bool("uninstall", false, "")
pkcs12Flag = flag.Bool("pkcs12", false, "")
ecdsaFlag = flag.Bool("ecdsa", false, "")
clientFlag = flag.Bool("client", false, "")
helpFlag = flag.Bool("help", false, "")
carootFlag = flag.Bool("CAROOT", false, "")
csrFlag = flag.String("csr", "", "")
certFileFlag = flag.String("cert-file", "", "")
keyFileFlag = flag.String("key-file", "", "")
p12FileFlag = flag.String("p12-file", "", "")
)
flag.Usage = func() {
fmt.Fprintf(flag.CommandLine.Output(), shortUsage)
fmt.Fprintln(flag.CommandLine.Output(), `For more options, run "mkcert -help".`)
}
flag.Parse()
if *helpFlag {
fmt.Fprintf(flag.CommandLine.Output(), shortUsage)
fmt.Fprintf(flag.CommandLine.Output(), advancedUsage)
return
}
if *carootFlag {
if *installFlag || *uninstallFlag {
log.Fatalln("ERROR: you can't set -[un]install and -CAROOT at the same time")
@@ -67,8 +108,15 @@ func main() {
if *installFlag && *uninstallFlag {
log.Fatalln("ERROR: you can't set -install and -uninstall at the same time")
}
if *csrFlag != "" && (*pkcs12Flag || *ecdsaFlag || *clientFlag) {
log.Fatalln("ERROR: can only combine -csr with -install and -cert-file")
}
if *csrFlag != "" && flag.NArg() != 0 {
log.Fatalln("ERROR: can't specify extra arguments when using -csr")
}
(&mkcert{
installMode: *installFlag, uninstallMode: *uninstallFlag, pkcs12: *pkcs12Flag,
installMode: *installFlag, uninstallMode: *uninstallFlag, csrPath: *csrFlag,
pkcs12: *pkcs12Flag, ecdsa: *ecdsaFlag, client: *clientFlag,
certFile: *certFileFlag, keyFile: *keyFileFlag, p12File: *p12FileFlag,
}).Run(flag.Args())
}
@@ -78,8 +126,9 @@ const rootKeyName = "rootCA-key.pem"
type mkcert struct {
installMode, uninstallMode bool
pkcs12 bool
pkcs12, ecdsa, client bool
keyFile, certFile, p12File string
csrPath string
CAROOT string
caCert *x509.Certificate
@@ -109,15 +158,15 @@ func (m *mkcert) Run(args []string) {
return
} else {
var warning bool
if !m.checkPlatform() {
if storeEnabled("system") && !m.checkPlatform() {
warning = true
log.Println("Warning: the local CA is not installed in the system trust store! ⚠️")
}
if hasNSS && CertutilInstallHelp != "" && !m.checkNSS() {
if storeEnabled("nss") && hasNSS && CertutilInstallHelp != "" && !m.checkNSS() {
warning = true
log.Printf("Warning: the local CA is not installed in the %s trust store! ⚠️", NSSBrowsers)
}
if hasJava && !m.checkJava() {
if storeEnabled("java") && hasJava && !m.checkJava() {
warning = true
log.Println("Warning: the local CA is not installed in the Java trust store! ⚠️")
}
@@ -126,8 +175,13 @@ func (m *mkcert) Run(args []string) {
}
}
if m.csrPath != "" {
m.makeCertFromCSR()
return
}
if len(args) == 0 {
log.Printf("\n%s", usage)
flag.Usage()
return
}
@@ -178,14 +232,14 @@ func getCAROOT() string {
func (m *mkcert) install() {
var printed bool
if !m.checkPlatform() {
if storeEnabled("system") && !m.checkPlatform() {
if m.installPlatform() {
log.Print("The local CA is now installed in the system trust store! ⚡️")
}
m.ignoreCheckFailure = true // TODO: replace with a check for a successful install
printed = true
}
if hasNSS && !m.checkNSS() {
if storeEnabled("nss") && hasNSS && !m.checkNSS() {
if hasCertutil && m.installNSS() {
log.Printf("The local CA is now installed in the %s trust store (requires browser restart)! 🦊", NSSBrowsers)
} else if CertutilInstallHelp == "" {
@@ -196,7 +250,7 @@ func (m *mkcert) install() {
}
printed = true
}
if hasJava && !m.checkJava() {
if storeEnabled("java") && hasJava && !m.checkJava() {
if hasKeytool {
m.installJava()
log.Println("The local CA is now installed in Java's trust store! ☕️")
@@ -211,7 +265,7 @@ func (m *mkcert) install() {
}
func (m *mkcert) uninstall() {
if hasNSS {
if storeEnabled("nss") && hasNSS {
if hasCertutil {
m.uninstallNSS()
} else if CertutilInstallHelp != "" {
@@ -221,7 +275,7 @@ func (m *mkcert) uninstall() {
log.Print("")
}
}
if hasJava {
if storeEnabled("java") && hasJava {
if hasKeytool {
m.uninstallJava()
} else {
@@ -230,10 +284,10 @@ func (m *mkcert) uninstall() {
log.Print("")
}
}
if m.uninstallPlatform() {
if storeEnabled("system") && m.uninstallPlatform() {
log.Print("The local CA is now uninstalled from the system trust store(s)! 👋")
log.Print("")
} else if hasCertutil {
} else if storeEnabled("nss") && hasCertutil {
log.Printf("The local CA is now uninstalled from the %s trust store(s)! 👋", NSSBrowsers)
log.Print("")
}
@@ -248,6 +302,19 @@ func (m *mkcert) checkPlatform() bool {
return err == nil
}
func storeEnabled(name string) bool {
stores := os.Getenv("TRUST_STORES")
if stores == "" {
return true
}
for _, store := range strings.Split(stores, ",") {
if store == name {
return true
}
}
return false
}
func fatalIfErr(err error, msg string) {
if err != nil {
log.Fatalf("ERROR: %s: %s", msg, err)

View File

@@ -20,6 +20,7 @@ func init() {
for _, path := range []string{
"/usr/bin/firefox", nssDB, "/Applications/Firefox.app",
"/Applications/Firefox Developer Edition.app",
"/Applications/Firefox Nightly.app",
"C:\\Program Files\\Mozilla Firefox",
} {
_, err := os.Stat(path)