pax_global_header 0000666 0000000 0000000 00000000064 13757453631 0014530 g ustar 00root root 0000000 0000000 52 comment=1a5aaff12e0edb54f32ce187079d05c4a1ffd19b
mkcert-1.4.3/ 0000775 0000000 0000000 00000000000 13757453631 0013022 5 ustar 00root root 0000000 0000000 mkcert-1.4.3/.github/ 0000775 0000000 0000000 00000000000 13757453631 0014362 5 ustar 00root root 0000000 0000000 mkcert-1.4.3/.github/workflows/ 0000775 0000000 0000000 00000000000 13757453631 0016417 5 ustar 00root root 0000000 0000000 mkcert-1.4.3/.github/workflows/release.yml 0000664 0000000 0000000 00000004002 13757453631 0020556 0 ustar 00root root 0000000 0000000 on:
release:
types: [published]
name: Upload Release Asset
jobs:
release:
name: Upload Release Asset
runs-on: ubuntu-latest
steps:
- name: Install Go
uses: actions/setup-go@v2
with:
go-version: 1.x
- name: Checkout repository
uses: actions/checkout@v2
- name: Build binaries
run: |
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o "mkcert-$(git describe --tags)-linux-amd64" -ldflags "-X main.Version=$(git describe --tags)"
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=6 go build -o "mkcert-$(git describe --tags)-linux-arm" -ldflags "-X main.Version=$(git describe --tags)"
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -o "mkcert-$(git describe --tags)-linux-arm64" -ldflags "-X main.Version=$(git describe --tags)"
CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build -o "mkcert-$(git describe --tags)-darwin-amd64" -ldflags "-X main.Version=$(git describe --tags)"
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -o "mkcert-$(git describe --tags)-windows-amd64.exe" -ldflags "-X main.Version=$(git describe --tags)"
- name: Upload release artifacts
uses: actions/github-script@v3
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const fs = require("fs").promises;
const { repo: { owner, repo }, sha } = context;
const release = await github.repos.getReleaseByTag({
owner, repo,
tag: process.env.GITHUB_REF.replace("refs/tags/", ""),
});
console.log("Release:", { release });
for (let file of await fs.readdir(".")) {
if (!file.startsWith("mkcert-")) continue;
console.log("Uploading", file);
await github.repos.uploadReleaseAsset({
owner, repo,
release_id: release.data.id,
name: file,
data: await fs.readFile(file),
});
}
mkcert-1.4.3/.github/workflows/test.yml 0000664 0000000 0000000 00000001064 13757453631 0020122 0 ustar 00root root 0000000 0000000 on: [push, pull_request]
name: Test
jobs:
test:
name: Go tests
strategy:
fail-fast: false
matrix:
go: [1.14.x, 1.x]
os: [ubuntu-latest, macos-latest, windows-latest]
runs-on: ${{ matrix.os }}
steps:
- name: Install Go ${{ matrix.go }}
uses: actions/setup-go@v2
with:
go-version: ${{ matrix.go }}
- name: Checkout repository
uses: actions/checkout@v2
- name: Run analyses
run: go run analysis.go ./...
- name: Run tests
run: go test -race ./...
mkcert-1.4.3/AUTHORS 0000664 0000000 0000000 00000000540 13757453631 0014071 0 ustar 00root root 0000000 0000000 # This is the list of mkcert authors for copyright purposes.
#
# This does not necessarily list everyone who has contributed code, since in
# some cases, their employer may be the copyright holder. To see the full list
# of contributors, see the revision history in source control.
Google LLC
Adam Shannon
Chad Retz
Travis Campbell
Carl Henrik Lunde
mkcert-1.4.3/LICENSE 0000664 0000000 0000000 00000002713 13757453631 0014032 0 ustar 00root root 0000000 0000000 Copyright (c) 2018 The mkcert Authors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
mkcert-1.4.3/README.md 0000664 0000000 0000000 00000014275 13757453631 0014312 0 ustar 00root root 0000000 0000000 # mkcert
mkcert is a simple tool for making locally-trusted development certificates. It requires no configuration.
```
$ mkcert -install
Created a new local CA đĨ
The local CA is now installed in the system trust store! âĄī¸
The local CA is now installed in the Firefox trust store (requires browser restart)! đĻ
$ mkcert example.com "*.example.com" example.test localhost 127.0.0.1 ::1
Created a new certificate valid for the following names đ
- "example.com"
- "*.example.com"
- "example.test"
- "localhost"
- "127.0.0.1"
- "::1"
The certificate is at "./example.com+5.pem" and the key at "./example.com+5-key.pem" â
```

Using certificates from real certificate authorities (CAs) for development can be dangerous or impossible (for hosts like `example.test`, `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.
mkcert automatically creates and installs a local CA in the system root store, and generates locally-trusted certificates. mkcert does not automatically configure servers to use the certificates, though, that's up to you.
## Installation
> **Warning**: the `rootCA-key.pem` file that mkcert automatically generates gives complete power to intercept secure requests from your machine. Do not share it.
### macOS
On macOS, use [Homebrew](https://brew.sh/)
```
brew install mkcert
brew install nss # if you use Firefox
```
or [MacPorts](https://www.macports.org/).
```
sudo port selfupdate
sudo port install mkcert
sudo port install nss # if you use Firefox
```
### Linux
On Linux, first install `certutil`.
```
sudo apt install libnss3-tools
-or-
sudo yum install nss-tools
-or-
sudo pacman -S nss
-or-
sudo zypper install mozilla-nss-tools
```
Then you can install using [Linuxbrew](http://linuxbrew.sh/)
```
brew install mkcert
```
or build from source (requires Go 1.13+)
```
git clone https://github.com/FiloSottile/mkcert && cd mkcert
go build -ldflags "-X main.Version=$(git describe --tags)"
```
or use [the pre-built binaries](https://github.com/FiloSottile/mkcert/releases).
For Arch Linux users, [`mkcert`](https://www.archlinux.org/packages/community/x86_64/mkcert/) is available on the official Arch Linux repository.
```
sudo pacman -Syu mkcert
```
### Windows
On Windows, use [Chocolatey](https://chocolatey.org)
```
choco install mkcert
```
or use Scoop
```
scoop bucket add extras
scoop install mkcert
```
or build from source (requires Go 1.10+), or use [the pre-built binaries](https://github.com/FiloSottile/mkcert/releases).
If you're running into permission problems try running `mkcert` as an Administrator.
## Supported root stores
mkcert supports the following root stores:
* macOS system store
* Windows system store
* Linux variants that provide either
* `update-ca-trust` (Fedora, RHEL, CentOS) or
* `update-ca-certificates` (Ubuntu, Debian, OpenSUSE, SLES) or
* `trust` (Arch)
* Firefox (macOS and Linux only)
* 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.
```
> **Note:** You _must_ place these options before the domain names list.
#### Example
```
mkcert -key-file key.pem -cert-file cert.pem example.com *.example.com
```
### S/MIME
mkcert automatically generates an S/MIME certificate if one of the supplied names is an email address.
```
mkcert filippo@example.com
```
### 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`.
On iOS, you can either use AirDrop, email the CA to yourself, or serve it from an HTTP server. After opening it, you need to [install the profile in Settings > Profile Downloaded](https://github.com/FiloSottile/mkcert/issues/233#issuecomment-690110809) and then [enable full trust in it](https://support.apple.com/en-nz/HT204477).
For Android, you will have to install the CA and then enable user roots in the development build of your app. See [this StackOverflow answer](https://stackoverflow.com/a/22040887/749014).
### Using the root with Node.js
Node does not use the system root store, so it won't accept mkcert certificates automatically. Instead, you will have to set the [`NODE_EXTRA_CA_CERTS`](https://nodejs.org/api/cli.html#cli_node_extra_ca_certs_file) environment variable.
```
export NODE_EXTRA_CA_CERTS="$(mkcert -CAROOT)/rootCA.pem"
```
### Changing the location of the CA files
The CA certificate and its key are stored in an application data folder in the user home. You usually don't have to worry about it, as installation is automated, but the location is printed by `mkcert -CAROOT`.
If you want to manage separate CAs, you can use the environment variable `$CAROOT` to set the folder where mkcert will place and look for the local CA files.
### Installing the CA on other systems
Installing in the trust store does not require the CA key, so you can export the CA certificate and use mkcert to install it in other machines.
* Look for the `rootCA.pem` file in `mkcert -CAROOT`
* copy it to a different machine
* set `$CAROOT` to its directory
* run `mkcert -install`
Remember that mkcert is meant for development purposes, not production, so it should not be used on end users' machines, and that you should *not* export or share `rootCA-key.pem`.
mkcert-1.4.3/analysis.go 0000664 0000000 0000000 00000005177 13757453631 0015206 0 ustar 00root root 0000000 0000000 // Copyright 2018 The mkcert Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build analysis
package main
import (
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/multichecker"
"golang.org/x/tools/go/analysis/passes/asmdecl"
"golang.org/x/tools/go/analysis/passes/assign"
"golang.org/x/tools/go/analysis/passes/atomic"
"golang.org/x/tools/go/analysis/passes/bools"
"golang.org/x/tools/go/analysis/passes/buildtag"
"golang.org/x/tools/go/analysis/passes/cgocall"
"golang.org/x/tools/go/analysis/passes/composite"
"golang.org/x/tools/go/analysis/passes/copylock"
"golang.org/x/tools/go/analysis/passes/errorsas"
"golang.org/x/tools/go/analysis/passes/httpresponse"
"golang.org/x/tools/go/analysis/passes/ifaceassert"
"golang.org/x/tools/go/analysis/passes/loopclosure"
"golang.org/x/tools/go/analysis/passes/lostcancel"
"golang.org/x/tools/go/analysis/passes/nilfunc"
"golang.org/x/tools/go/analysis/passes/printf"
"golang.org/x/tools/go/analysis/passes/shift"
"golang.org/x/tools/go/analysis/passes/stdmethods"
"golang.org/x/tools/go/analysis/passes/stringintconv"
"golang.org/x/tools/go/analysis/passes/structtag"
"golang.org/x/tools/go/analysis/passes/testinggoroutine"
"golang.org/x/tools/go/analysis/passes/tests"
"golang.org/x/tools/go/analysis/passes/unmarshal"
"golang.org/x/tools/go/analysis/passes/unreachable"
"golang.org/x/tools/go/analysis/passes/unusedresult"
"honnef.co/go/tools/simple"
"honnef.co/go/tools/staticcheck"
"honnef.co/go/tools/stylecheck"
)
func main() {
var analyzers []*analysis.Analyzer
// Add all cmd/vet analyzers.
// https://github.com/golang/go/issues/35487
analyzers = append(analyzers,
asmdecl.Analyzer,
assign.Analyzer,
atomic.Analyzer,
bools.Analyzer,
buildtag.Analyzer,
cgocall.Analyzer,
composite.Analyzer,
copylock.Analyzer,
errorsas.Analyzer,
httpresponse.Analyzer,
ifaceassert.Analyzer,
loopclosure.Analyzer,
lostcancel.Analyzer,
nilfunc.Analyzer,
printf.Analyzer,
shift.Analyzer,
stdmethods.Analyzer,
stringintconv.Analyzer,
structtag.Analyzer,
tests.Analyzer,
testinggoroutine.Analyzer,
unmarshal.Analyzer,
unreachable.Analyzer,
// False positives when using Windows DLL procs.
// https://github.com/golang/go/issues/41205
// unsafeptr.Analyzer,
unusedresult.Analyzer)
for _, v := range simple.Analyzers {
analyzers = append(analyzers, v)
}
for _, v := range staticcheck.Analyzers {
analyzers = append(analyzers, v)
}
for _, v := range stylecheck.Analyzers {
analyzers = append(analyzers, v)
}
multichecker.Main(analyzers...)
}
mkcert-1.4.3/cert.go 0000664 0000000 0000000 00000026307 13757453631 0014316 0 ustar 00root root 0000000 0000000 // Copyright 2018 The mkcert Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/sha1"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"encoding/pem"
"io/ioutil"
"log"
"math/big"
"net"
"net/mail"
"net/url"
"os"
"os/user"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
pkcs12 "software.sslmate.com/src/go-pkcs12"
)
var userAndHostname string
func init() {
u, err := user.Current()
if err == nil {
userAndHostname = u.Username + "@"
}
if h, err := os.Hostname(); err == nil {
userAndHostname += h
}
if err == nil && u.Name != "" && u.Name != u.Username {
userAndHostname += " (" + u.Name + ")"
}
}
func (m *mkcert) makeCert(hosts []string) {
if m.caKey == nil {
log.Fatalln("ERROR: can't create new certificates because the CA key (rootCA-key.pem) is missing")
}
priv, err := m.generateKey(false)
fatalIfErr(err, "failed to generate certificate key")
pub := priv.(crypto.Signer).Public()
// Certificates last for 2 years and 3 months, which is always less than
// 825 days, the limit that macOS/iOS apply to all certificates,
// including custom roots. See https://support.apple.com/en-us/HT210176.
expiration := time.Now().AddDate(2, 3, 0)
tpl := &x509.Certificate{
SerialNumber: randomSerialNumber(),
Subject: pkix.Name{
Organization: []string{"mkcert development certificate"},
OrganizationalUnit: []string{userAndHostname},
},
NotBefore: time.Now(), NotAfter: expiration,
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
}
for _, h := range hosts {
if ip := net.ParseIP(h); ip != nil {
tpl.IPAddresses = append(tpl.IPAddresses, ip)
} else if email, err := mail.ParseAddress(h); err == nil && email.Address == h {
tpl.EmailAddresses = append(tpl.EmailAddresses, h)
} else if uriName, err := url.Parse(h); err == nil && uriName.Scheme != "" && uriName.Host != "" {
tpl.URIs = append(tpl.URIs, uriName)
} else {
tpl.DNSNames = append(tpl.DNSNames, h)
}
}
if m.client {
tpl.ExtKeyUsage = append(tpl.ExtKeyUsage, x509.ExtKeyUsageClientAuth)
}
if len(tpl.IPAddresses) > 0 || len(tpl.DNSNames) > 0 || len(tpl.URIs) > 0 {
tpl.ExtKeyUsage = append(tpl.ExtKeyUsage, x509.ExtKeyUsageServerAuth)
}
if len(tpl.EmailAddresses) > 0 {
tpl.ExtKeyUsage = append(tpl.ExtKeyUsage, x509.ExtKeyUsageEmailProtection)
}
// 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)
if !m.pkcs12 {
certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert})
privDER, err := x509.MarshalPKCS8PrivateKey(priv)
fatalIfErr(err, "failed to encode certificate key")
privPEM := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: privDER})
if certFile == keyFile {
err = ioutil.WriteFile(keyFile, append(certPEM, privPEM...), 0600)
fatalIfErr(err, "failed to save certificate and key")
} else {
err = ioutil.WriteFile(certFile, certPEM, 0644)
fatalIfErr(err, "failed to save certificate")
err = ioutil.WriteFile(keyFile, privPEM, 0600)
fatalIfErr(err, "failed to save certificate key")
}
} else {
domainCert, _ := x509.ParseCertificate(cert)
pfxData, err := pkcs12.Encode(rand.Reader, priv, domainCert, []*x509.Certificate{m.caCert}, "changeit")
fatalIfErr(err, "failed to generate PKCS#12")
err = ioutil.WriteFile(p12File, pfxData, 0644)
fatalIfErr(err, "failed to save PKCS#12")
}
m.printHosts(hosts)
if !m.pkcs12 {
if certFile == keyFile {
log.Printf("\nThe certificate and key are at \"%s\" â
\n\n", certFile)
} else {
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")
}
log.Printf("It will expire on %s đ\n\n", expiration.Format("2 January 2006"))
}
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 {
log.Printf(" - %q", h)
if secondLvlWildcardRegexp.MatchString(h) {
log.Printf(" Warning: many browsers don't support second-level wildcards like %q â ī¸", h)
}
}
for _, h := range hosts {
if strings.HasPrefix(h, "*.") {
log.Printf("\nReminder: X.509 wildcards only go one level deep, so this won't match a.b.%s âšī¸", h[2:])
break
}
}
}
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) {
defaultName := strings.Replace(hosts[0], ":", "_", -1)
defaultName = strings.Replace(defaultName, "*", "_wildcard", -1)
if len(hosts) > 1 {
defaultName += "+" + strconv.Itoa(len(hosts)-1)
}
if m.client {
defaultName += "-client"
}
certFile = "./" + defaultName + ".pem"
if m.certFile != "" {
certFile = m.certFile
}
keyFile = "./" + defaultName + "-key.pem"
if m.keyFile != "" {
keyFile = m.keyFile
}
p12File = "./" + defaultName + ".p12"
if m.p12File != "" {
p12File = m.p12File
}
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" &&
csrPEM.Type != "NEW 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")
expiration := time.Now().AddDate(2, 3, 0)
tpl := &x509.Certificate{
SerialNumber: randomSerialNumber(),
Subject: csr.Subject,
ExtraExtensions: csr.Extensions, // includes requested SANs, KUs and EKUs
NotBefore: time.Now(), NotAfter: expiration,
// 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},
// Likewise, if the CSR does not set KUs and EKUs, fix it up as Apple
// platforms require serverAuth for TLS.
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
}
if m.client {
tpl.ExtKeyUsage = append(tpl.ExtKeyUsage, x509.ExtKeyUsageClientAuth)
}
if len(csr.EmailAddresses) > 0 {
tpl.ExtKeyUsage = append(tpl.ExtKeyUsage, x509.ExtKeyUsageEmailProtection)
}
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())
}
for _, uri := range csr.URIs {
hosts = append(hosts, uri.String())
}
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)
log.Printf("It will expire on %s đ\n\n", expiration.Format("2 January 2006"))
}
// loadCA will load or create the CA at CAROOT.
func (m *mkcert) loadCA() {
if !pathExists(filepath.Join(m.CAROOT, rootName)) {
m.newCA()
}
certPEMBlock, err := ioutil.ReadFile(filepath.Join(m.CAROOT, rootName))
fatalIfErr(err, "failed to read the CA certificate")
certDERBlock, _ := pem.Decode(certPEMBlock)
if certDERBlock == nil || certDERBlock.Type != "CERTIFICATE" {
log.Fatalln("ERROR: failed to read the CA certificate: unexpected content")
}
m.caCert, err = x509.ParseCertificate(certDERBlock.Bytes)
fatalIfErr(err, "failed to parse the CA certificate")
if !pathExists(filepath.Join(m.CAROOT, rootKeyName)) {
return // keyless mode, where only -install works
}
keyPEMBlock, err := ioutil.ReadFile(filepath.Join(m.CAROOT, rootKeyName))
fatalIfErr(err, "failed to read the CA key")
keyDERBlock, _ := pem.Decode(keyPEMBlock)
if keyDERBlock == nil || keyDERBlock.Type != "PRIVATE KEY" {
log.Fatalln("ERROR: failed to read the CA key: unexpected content")
}
m.caKey, err = x509.ParsePKCS8PrivateKey(keyDERBlock.Bytes)
fatalIfErr(err, "failed to parse the CA key")
}
func (m *mkcert) newCA() {
priv, err := m.generateKey(true)
fatalIfErr(err, "failed to generate the CA key")
pub := priv.(crypto.Signer).Public()
spkiASN1, err := x509.MarshalPKIXPublicKey(pub)
fatalIfErr(err, "failed to encode public key")
var spki struct {
Algorithm pkix.AlgorithmIdentifier
SubjectPublicKey asn1.BitString
}
_, err = asn1.Unmarshal(spkiASN1, &spki)
fatalIfErr(err, "failed to decode public key")
skid := sha1.Sum(spki.SubjectPublicKey.Bytes)
tpl := &x509.Certificate{
SerialNumber: randomSerialNumber(),
Subject: pkix.Name{
Organization: []string{"mkcert development CA"},
OrganizationalUnit: []string{userAndHostname},
// The CommonName is required by iOS to show the certificate in the
// "Certificate Trust Settings" menu.
// https://github.com/FiloSottile/mkcert/issues/47
CommonName: "mkcert " + userAndHostname,
},
SubjectKeyId: skid[:],
NotAfter: time.Now().AddDate(10, 0, 0),
NotBefore: time.Now(),
KeyUsage: x509.KeyUsageCertSign,
BasicConstraintsValid: true,
IsCA: true,
MaxPathLenZero: true,
}
cert, err := x509.CreateCertificate(rand.Reader, tpl, tpl, pub, priv)
fatalIfErr(err, "failed to generate CA certificate")
privDER, err := x509.MarshalPKCS8PrivateKey(priv)
fatalIfErr(err, "failed to encode CA key")
err = ioutil.WriteFile(filepath.Join(m.CAROOT, rootKeyName), pem.EncodeToMemory(
&pem.Block{Type: "PRIVATE KEY", Bytes: privDER}), 0400)
fatalIfErr(err, "failed to save CA key")
err = ioutil.WriteFile(filepath.Join(m.CAROOT, rootName), pem.EncodeToMemory(
&pem.Block{Type: "CERTIFICATE", Bytes: cert}), 0644)
fatalIfErr(err, "failed to save CA key")
log.Printf("Created a new local CA đĨ\n")
}
func (m *mkcert) caUniqueName() string {
return "mkcert development CA " + m.caCert.SerialNumber.String()
}
mkcert-1.4.3/go.mod 0000664 0000000 0000000 00000000473 13757453631 0014134 0 ustar 00root root 0000000 0000000 module filippo.io/mkcert
go 1.13
require (
golang.org/x/net v0.0.0-20201021035429-f5854403a974
golang.org/x/tools v0.0.0-20201124202034-299f270db459
honnef.co/go/tools v0.0.1-2020.1.6
howett.net/plist v0.0.0-20181124034731-591f970eefbb
software.sslmate.com/src/go-pkcs12 v0.0.0-20180114231543-2291e8f0f237
)
mkcert-1.4.3/go.sum 0000664 0000000 0000000 00000012236 13757453631 0014161 0 ustar 00root root 0000000 0000000 github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.3.0 h1:RM4zey1++hCTbCVQfnWeKs9/IEsaBLA8vTkd0WVtmH4=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859 h1:R/3boaszxrf1GEUWTVDzSKVwLmSJpwZ1yqXm8j0v2QI=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20201021035429-f5854403a974 h1:IX6qOQeG5uLjB/hjjwjedwfjND0hgjPMMyO1RoIXQNI=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20200410194907-79a7a3126eef/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
golang.org/x/tools v0.0.0-20201124202034-299f270db459 h1:XrUnpqJ8xqeZHrgPu3FuYCv9/O3MrxnIKh5/+MLDE8Q=
golang.org/x/tools v0.0.0-20201124202034-299f270db459/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
honnef.co/go/tools v0.0.1-2020.1.6 h1:W18jzjh8mfPez+AwGLxmOImucz/IFjpNlrKVnaj2YVc=
honnef.co/go/tools v0.0.1-2020.1.6/go.mod h1:pyyisuGw24ruLjrr1ddx39WE0y9OooInRzEYLhQB2YY=
howett.net/plist v0.0.0-20181124034731-591f970eefbb h1:jhnBjNi9UFpfpl8YZhA9CrOqpnJdvzuiHsl/dnxl11M=
howett.net/plist v0.0.0-20181124034731-591f970eefbb/go.mod h1:vMygbs4qMhSZSc4lCUl2OEE+rDiIIJAIdR4m7MiMcm0=
software.sslmate.com/src/go-pkcs12 v0.0.0-20180114231543-2291e8f0f237 h1:iAEkCBPbRaflBgZ7o9gjVUuWuvWeV4sytFWg9o+Pj2k=
software.sslmate.com/src/go-pkcs12 v0.0.0-20180114231543-2291e8f0f237/go.mod h1:/xvNRWUqm0+/ZMiF4EX00vrSCMsE4/NHb+Pt3freEeQ=
mkcert-1.4.3/main.go 0000664 0000000 0000000 00000025247 13757453631 0014307 0 ustar 00root root 0000000 0000000 // Copyright 2018 The mkcert Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Command mkcert is a simple zero-config tool to make development certificates.
package main
import (
"crypto"
"crypto/x509"
"flag"
"fmt"
"log"
"net"
"net/mail"
"net/url"
"os"
"os/exec"
"os/user"
"path/filepath"
"regexp"
"runtime"
"runtime/debug"
"strings"
"sync"
"golang.org/x/net/idna"
)
const shortUsage = `Usage of mkcert:
$ mkcert -install
Install the local CA in the system trust store.
$ mkcert example.org
Generate "example.org.pem" and "example.org-key.pem".
$ mkcert example.com myapp.dev localhost 127.0.0.1 ::1
Generate "example.com+4.pem" and "example.com+4-key.pem".
$ 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).
`
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.
`
// Version can be set at link time to override debug.BuildInfo.Main.Version,
// which is "(devel)" when building from within the module. See
// golang.org/issue/29814 and golang.org/issue/29228.
var Version string
func main() {
log.SetFlags(0)
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", "", "")
versionFlag = flag.Bool("version", false, "")
)
flag.Usage = func() {
fmt.Fprint(flag.CommandLine.Output(), shortUsage)
fmt.Fprintln(flag.CommandLine.Output(), `For more options, run "mkcert -help".`)
}
flag.Parse()
if *helpFlag {
fmt.Print(shortUsage)
fmt.Print(advancedUsage)
return
}
if *versionFlag {
if Version != "" {
fmt.Println(Version)
return
}
if buildInfo, ok := debug.ReadBuildInfo(); ok {
fmt.Println(buildInfo.Main.Version)
return
}
fmt.Println("(unknown)")
return
}
if *carootFlag {
if *installFlag || *uninstallFlag {
log.Fatalln("ERROR: you can't set -[un]install and -CAROOT at the same time")
}
fmt.Println(getCAROOT())
return
}
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, csrPath: *csrFlag,
pkcs12: *pkcs12Flag, ecdsa: *ecdsaFlag, client: *clientFlag,
certFile: *certFileFlag, keyFile: *keyFileFlag, p12File: *p12FileFlag,
}).Run(flag.Args())
}
const rootName = "rootCA.pem"
const rootKeyName = "rootCA-key.pem"
type mkcert struct {
installMode, uninstallMode bool
pkcs12, ecdsa, client bool
keyFile, certFile, p12File string
csrPath string
CAROOT string
caCert *x509.Certificate
caKey crypto.PrivateKey
// The system cert pool is only loaded once. After installing the root, checks
// will keep failing until the next execution. TODO: maybe execve?
// https://github.com/golang/go/issues/24540 (thanks, myself)
ignoreCheckFailure bool
}
func (m *mkcert) Run(args []string) {
m.CAROOT = getCAROOT()
if m.CAROOT == "" {
log.Fatalln("ERROR: failed to find the default CA location, set one as the CAROOT env var")
}
fatalIfErr(os.MkdirAll(m.CAROOT, 0755), "failed to create the CAROOT")
m.loadCA()
if m.installMode {
m.install()
if len(args) == 0 {
return
}
} else if m.uninstallMode {
m.uninstall()
return
} else {
var warning bool
if storeEnabled("system") && !m.checkPlatform() {
warning = true
log.Println("Note: the local CA is not installed in the system trust store.")
}
if storeEnabled("nss") && hasNSS && CertutilInstallHelp != "" && !m.checkNSS() {
warning = true
log.Printf("Note: the local CA is not installed in the %s trust store.", NSSBrowsers)
}
if storeEnabled("java") && hasJava && !m.checkJava() {
warning = true
log.Println("Note: the local CA is not installed in the Java trust store.")
}
if warning {
log.Println("Run \"mkcert -install\" for certificates to be trusted automatically â ī¸")
}
}
if m.csrPath != "" {
m.makeCertFromCSR()
return
}
if len(args) == 0 {
flag.Usage()
return
}
hostnameRegexp := regexp.MustCompile(`(?i)^(\*\.)?[0-9a-z_-]([0-9a-z._-]*[0-9a-z_-])?$`)
for i, name := range args {
if ip := net.ParseIP(name); ip != nil {
continue
}
if email, err := mail.ParseAddress(name); err == nil && email.Address == name {
continue
}
if uriName, err := url.Parse(name); err == nil && uriName.Scheme != "" && uriName.Host != "" {
continue
}
punycode, err := idna.ToASCII(name)
if err != nil {
log.Fatalf("ERROR: %q is not a valid hostname, IP, URL or email: %s", name, err)
}
args[i] = punycode
if !hostnameRegexp.MatchString(punycode) {
log.Fatalf("ERROR: %q is not a valid hostname, IP, URL or email", name)
}
}
m.makeCert(args)
}
func getCAROOT() string {
if env := os.Getenv("CAROOT"); env != "" {
return env
}
var dir string
switch {
case runtime.GOOS == "windows":
dir = os.Getenv("LocalAppData")
case os.Getenv("XDG_DATA_HOME") != "":
dir = os.Getenv("XDG_DATA_HOME")
case runtime.GOOS == "darwin":
dir = os.Getenv("HOME")
if dir == "" {
return ""
}
dir = filepath.Join(dir, "Library", "Application Support")
default: // Unix
dir = os.Getenv("HOME")
if dir == "" {
return ""
}
dir = filepath.Join(dir, ".local", "share")
}
return filepath.Join(dir, "mkcert")
}
func (m *mkcert) install() {
if storeEnabled("system") {
if m.checkPlatform() {
log.Print("The local CA is already installed in the system trust store! đ")
} else {
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
}
}
if storeEnabled("nss") && hasNSS {
if m.checkNSS() {
log.Printf("The local CA is already installed in the %s trust store! đ", NSSBrowsers)
} else {
if hasCertutil && m.installNSS() {
log.Printf("The local CA is now installed in the %s trust store (requires browser restart)! đĻ", NSSBrowsers)
} else if CertutilInstallHelp == "" {
log.Printf(`Note: %s support is not available on your platform. âšī¸`, NSSBrowsers)
} else if !hasCertutil {
log.Printf(`Warning: "certutil" is not available, so the CA can't be automatically installed in %s! â ī¸`, NSSBrowsers)
log.Printf(`Install "certutil" with "%s" and re-run "mkcert -install" đ`, CertutilInstallHelp)
}
}
}
if storeEnabled("java") && hasJava {
if m.checkJava() {
log.Println("The local CA is already installed in Java's trust store! đ")
} else {
if hasKeytool {
m.installJava()
log.Println("The local CA is now installed in Java's trust store! âī¸")
} else {
log.Println(`Warning: "keytool" is not available, so the CA can't be automatically installed in Java's trust store! â ī¸`)
}
}
}
log.Print("")
}
func (m *mkcert) uninstall() {
if storeEnabled("nss") && hasNSS {
if hasCertutil {
m.uninstallNSS()
} else if CertutilInstallHelp != "" {
log.Print("")
log.Printf(`Warning: "certutil" is not available, so the CA can't be automatically uninstalled from %s (if it was ever installed)! â ī¸`, NSSBrowsers)
log.Printf(`You can install "certutil" with "%s" and re-run "mkcert -uninstall" đ`, CertutilInstallHelp)
log.Print("")
}
}
if storeEnabled("java") && hasJava {
if hasKeytool {
m.uninstallJava()
} else {
log.Print("")
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)! â ī¸`)
log.Print("")
}
}
if storeEnabled("system") && m.uninstallPlatform() {
log.Print("The local CA is now uninstalled from the system trust store(s)! đ")
log.Print("")
} else if storeEnabled("nss") && hasCertutil {
log.Printf("The local CA is now uninstalled from the %s trust store(s)! đ", NSSBrowsers)
log.Print("")
}
}
func (m *mkcert) checkPlatform() bool {
if m.ignoreCheckFailure {
return true
}
_, err := m.caCert.Verify(x509.VerifyOptions{})
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)
}
}
func fatalIfCmdErr(err error, cmd string, out []byte) {
if err != nil {
log.Fatalf("ERROR: failed to execute \"%s\": %s\n\n%s\n", cmd, err, out)
}
}
func pathExists(path string) bool {
_, err := os.Stat(path)
return err == nil
}
func binaryExists(name string) bool {
_, err := exec.LookPath(name)
return err == nil
}
var sudoWarningOnce sync.Once
func commandWithSudo(cmd ...string) *exec.Cmd {
if u, err := user.Current(); err == nil && u.Uid == "0" {
return exec.Command(cmd[0], cmd[1:]...)
}
if !binaryExists("sudo") {
sudoWarningOnce.Do(func() {
log.Println(`Warning: "sudo" is not available, and mkcert is not running as root. The (un)install operation might fail. â ī¸`)
})
return exec.Command(cmd[0], cmd[1:]...)
}
return exec.Command("sudo", append([]string{"--prompt=Sudo password:", "--"}, cmd...)...)
}
mkcert-1.4.3/truststore_darwin.go 0000664 0000000 0000000 00000006360 13757453631 0017160 0 ustar 00root root 0000000 0000000 // Copyright 2018 The mkcert Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"bytes"
"encoding/asn1"
"io/ioutil"
"log"
"os"
"path/filepath"
"howett.net/plist"
)
var (
FirefoxProfile = os.Getenv("HOME") + "/Library/Application Support/Firefox/Profiles/*"
CertutilInstallHelp = "brew install nss"
NSSBrowsers = "Firefox"
)
// https://github.com/golang/go/issues/24652#issuecomment-399826583
var trustSettings []interface{}
var _, _ = plist.Unmarshal(trustSettingsData, &trustSettings)
var trustSettingsData = []byte(`
kSecTrustSettingsPolicy
KoZIhvdjZAED
kSecTrustSettingsPolicyName
sslServer
kSecTrustSettingsResult
1
kSecTrustSettingsPolicy
KoZIhvdjZAEC
kSecTrustSettingsPolicyName
basicX509
kSecTrustSettingsResult
1
`)
func (m *mkcert) installPlatform() bool {
cmd := commandWithSudo("security", "add-trusted-cert", "-d", "-k", "/Library/Keychains/System.keychain", filepath.Join(m.CAROOT, rootName))
out, err := cmd.CombinedOutput()
fatalIfCmdErr(err, "security add-trusted-cert", out)
// Make trustSettings explicit, as older Go does not know the defaults.
// https://github.com/golang/go/issues/24652
plistFile, err := ioutil.TempFile("", "trust-settings")
fatalIfErr(err, "failed to create temp file")
defer os.Remove(plistFile.Name())
cmd = commandWithSudo("security", "trust-settings-export", "-d", plistFile.Name())
out, err = cmd.CombinedOutput()
fatalIfCmdErr(err, "security trust-settings-export", out)
plistData, err := ioutil.ReadFile(plistFile.Name())
fatalIfErr(err, "failed to read trust settings")
var plistRoot map[string]interface{}
_, err = plist.Unmarshal(plistData, &plistRoot)
fatalIfErr(err, "failed to parse trust settings")
rootSubjectASN1, _ := asn1.Marshal(m.caCert.Subject.ToRDNSequence())
if plistRoot["trustVersion"].(uint64) != 1 {
log.Fatalln("ERROR: unsupported trust settings version:", plistRoot["trustVersion"])
}
trustList := plistRoot["trustList"].(map[string]interface{})
for key := range trustList {
entry := trustList[key].(map[string]interface{})
if _, ok := entry["issuerName"]; !ok {
continue
}
issuerName := entry["issuerName"].([]byte)
if !bytes.Equal(rootSubjectASN1, issuerName) {
continue
}
entry["trustSettings"] = trustSettings
break
}
plistData, err = plist.MarshalIndent(plistRoot, plist.XMLFormat, "\t")
fatalIfErr(err, "failed to serialize trust settings")
err = ioutil.WriteFile(plistFile.Name(), plistData, 0600)
fatalIfErr(err, "failed to write trust settings")
cmd = commandWithSudo("security", "trust-settings-import", "-d", plistFile.Name())
out, err = cmd.CombinedOutput()
fatalIfCmdErr(err, "security trust-settings-import", out)
return true
}
func (m *mkcert) uninstallPlatform() bool {
cmd := commandWithSudo("security", "remove-trusted-cert", "-d", filepath.Join(m.CAROOT, rootName))
out, err := cmd.CombinedOutput()
fatalIfCmdErr(err, "security remove-trusted-cert", out)
return true
}
mkcert-1.4.3/truststore_java.go 0000664 0000000 0000000 00000006326 13757453631 0016617 0 ustar 00root root 0000000 0000000 // Copyright 2018 The mkcert Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"bytes"
"crypto/sha1"
"crypto/sha256"
"crypto/x509"
"encoding/hex"
"hash"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
)
var (
hasJava bool
hasKeytool bool
javaHome string
cacertsPath string
keytoolPath string
storePass string = "changeit"
)
func init() {
if runtime.GOOS == "windows" {
keytoolPath = filepath.Join("bin", "keytool.exe")
} else {
keytoolPath = filepath.Join("bin", "keytool")
}
if v := os.Getenv("JAVA_HOME"); v != "" {
hasJava = true
javaHome = v
if pathExists(filepath.Join(v, keytoolPath)) {
hasKeytool = true
keytoolPath = filepath.Join(v, keytoolPath)
}
if pathExists(filepath.Join(v, "lib", "security", "cacerts")) {
cacertsPath = filepath.Join(v, "lib", "security", "cacerts")
}
if pathExists(filepath.Join(v, "jre", "lib", "security", "cacerts")) {
cacertsPath = filepath.Join(v, "jre", "lib", "security", "cacerts")
}
}
}
func (m *mkcert) checkJava() bool {
if !hasKeytool {
return false
}
// exists returns true if the given x509.Certificate's fingerprint
// is in the keytool -list output
exists := func(c *x509.Certificate, h hash.Hash, keytoolOutput []byte) bool {
h.Write(c.Raw)
fp := strings.ToUpper(hex.EncodeToString(h.Sum(nil)))
return bytes.Contains(keytoolOutput, []byte(fp))
}
keytoolOutput, err := exec.Command(keytoolPath, "-list", "-keystore", cacertsPath, "-storepass", storePass).CombinedOutput()
fatalIfCmdErr(err, "keytool -list", keytoolOutput)
// keytool outputs SHA1 and SHA256 (Java 9+) certificates in uppercase hex
// with each octet pair delimitated by ":". Drop them from the keytool output
keytoolOutput = bytes.Replace(keytoolOutput, []byte(":"), nil, -1)
// pre-Java 9 uses SHA1 fingerprints
s1, s256 := sha1.New(), sha256.New()
return exists(m.caCert, s1, keytoolOutput) || exists(m.caCert, s256, keytoolOutput)
}
func (m *mkcert) installJava() {
args := []string{
"-importcert", "-noprompt",
"-keystore", cacertsPath,
"-storepass", storePass,
"-file", filepath.Join(m.CAROOT, rootName),
"-alias", m.caUniqueName(),
}
out, err := execKeytool(exec.Command(keytoolPath, args...))
fatalIfCmdErr(err, "keytool -importcert", out)
}
func (m *mkcert) uninstallJava() {
args := []string{
"-delete",
"-alias", m.caUniqueName(),
"-keystore", cacertsPath,
"-storepass", storePass,
}
out, err := execKeytool(exec.Command(keytoolPath, args...))
if bytes.Contains(out, []byte("does not exist")) {
return // cert didn't exist
}
fatalIfCmdErr(err, "keytool -delete", out)
}
// execKeytool will execute a "keytool" command and if needed re-execute
// the command with commandWithSudo to work around file permissions.
func execKeytool(cmd *exec.Cmd) ([]byte, error) {
out, err := cmd.CombinedOutput()
if err != nil && bytes.Contains(out, []byte("java.io.FileNotFoundException")) && runtime.GOOS != "windows" {
origArgs := cmd.Args[1:]
cmd = commandWithSudo(cmd.Path)
cmd.Args = append(cmd.Args, origArgs...)
cmd.Env = []string{
"JAVA_HOME=" + javaHome,
}
out, err = cmd.CombinedOutput()
}
return out, err
}
mkcert-1.4.3/truststore_linux.go 0000664 0000000 0000000 00000005775 13757453631 0017044 0 ustar 00root root 0000000 0000000 // Copyright 2018 The mkcert Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
)
var (
FirefoxProfile = os.Getenv("HOME") + "/.mozilla/firefox/*"
NSSBrowsers = "Firefox and/or Chrome/Chromium"
SystemTrustFilename string
SystemTrustCommand []string
CertutilInstallHelp string
)
func init() {
switch {
case binaryExists("apt"):
CertutilInstallHelp = "apt install libnss3-tools"
case binaryExists("yum"):
CertutilInstallHelp = "yum install nss-tools"
case binaryExists("zypper"):
CertutilInstallHelp = "zypper install mozilla-nss-tools"
}
if pathExists("/etc/pki/ca-trust/source/anchors/") {
SystemTrustFilename = "/etc/pki/ca-trust/source/anchors/%s.pem"
SystemTrustCommand = []string{"update-ca-trust", "extract"}
} else if pathExists("/usr/local/share/ca-certificates/") {
SystemTrustFilename = "/usr/local/share/ca-certificates/%s.crt"
SystemTrustCommand = []string{"update-ca-certificates"}
} else if pathExists("/etc/ca-certificates/trust-source/anchors/") {
SystemTrustFilename = "/etc/ca-certificates/trust-source/anchors/%s.crt"
SystemTrustCommand = []string{"trust", "extract-compat"}
} else if pathExists("/usr/share/pki/trust/anchors") {
SystemTrustFilename = "/usr/share/pki/trust/anchors/%s.pem"
SystemTrustCommand = []string{"update-ca-certificates"}
}
}
func (m *mkcert) systemTrustFilename() string {
return fmt.Sprintf(SystemTrustFilename, strings.Replace(m.caUniqueName(), " ", "_", -1))
}
func (m *mkcert) installPlatform() bool {
if SystemTrustCommand == nil {
log.Printf("Installing to the system store is not yet supported on this Linux đŖ but %s will still work.", NSSBrowsers)
log.Printf("You can also manually install the root certificate at %q.", filepath.Join(m.CAROOT, rootName))
return false
}
cert, err := ioutil.ReadFile(filepath.Join(m.CAROOT, rootName))
fatalIfErr(err, "failed to read root certificate")
cmd := commandWithSudo("tee", m.systemTrustFilename())
cmd.Stdin = bytes.NewReader(cert)
out, err := cmd.CombinedOutput()
fatalIfCmdErr(err, "tee", out)
cmd = commandWithSudo(SystemTrustCommand...)
out, err = cmd.CombinedOutput()
fatalIfCmdErr(err, strings.Join(SystemTrustCommand, " "), out)
return true
}
func (m *mkcert) uninstallPlatform() bool {
if SystemTrustCommand == nil {
return false
}
cmd := commandWithSudo("rm", "-f", m.systemTrustFilename())
out, err := cmd.CombinedOutput()
fatalIfCmdErr(err, "rm", out)
// We used to install under non-unique filenames.
legacyFilename := fmt.Sprintf(SystemTrustFilename, "mkcert-rootCA")
if pathExists(legacyFilename) {
cmd := commandWithSudo("rm", "-f", legacyFilename)
out, err := cmd.CombinedOutput()
fatalIfCmdErr(err, "rm (legacy filename)", out)
}
cmd = commandWithSudo(SystemTrustCommand...)
out, err = cmd.CombinedOutput()
fatalIfCmdErr(err, strings.Join(SystemTrustCommand, " "), out)
return true
}
mkcert-1.4.3/truststore_nss.go 0000664 0000000 0000000 00000010050 13757453631 0016466 0 ustar 00root root 0000000 0000000 // Copyright 2018 The mkcert Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"bytes"
"log"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
)
var (
hasNSS bool
hasCertutil bool
certutilPath string
nssDBs = []string{
filepath.Join(os.Getenv("HOME"), ".pki/nssdb"),
filepath.Join(os.Getenv("HOME"), "snap/chromium/current/.pki/nssdb"), // Snapcraft
"/etc/pki/nssdb", // CentOS 7
}
firefoxPaths = []string{
"/usr/bin/firefox",
"/usr/bin/firefox-nightly",
"/usr/bin/firefox-developer-edition",
"/Applications/Firefox.app",
"/Applications/FirefoxDeveloperEdition.app",
"/Applications/Firefox Developer Edition.app",
"/Applications/Firefox Nightly.app",
"C:\\Program Files\\Mozilla Firefox",
}
)
func init() {
allPaths := append(append([]string{}, nssDBs...), firefoxPaths...)
for _, path := range allPaths {
if pathExists(path) {
hasNSS = true
break
}
}
switch runtime.GOOS {
case "darwin":
switch {
case binaryExists("certutil"):
certutilPath, _ = exec.LookPath("certutil")
hasCertutil = true
case binaryExists("/usr/local/opt/nss/bin/certutil"):
// Check the default Homebrew path, to save executing Ruby. #135
certutilPath = "/usr/local/opt/nss/bin/certutil"
hasCertutil = true
default:
out, err := exec.Command("brew", "--prefix", "nss").Output()
if err == nil {
certutilPath = filepath.Join(strings.TrimSpace(string(out)), "bin", "certutil")
hasCertutil = pathExists(certutilPath)
}
}
case "linux":
if hasCertutil = binaryExists("certutil"); hasCertutil {
certutilPath, _ = exec.LookPath("certutil")
}
}
}
func (m *mkcert) checkNSS() bool {
if !hasCertutil {
return false
}
success := true
if m.forEachNSSProfile(func(profile string) {
err := exec.Command(certutilPath, "-V", "-d", profile, "-u", "L", "-n", m.caUniqueName()).Run()
if err != nil {
success = false
}
}) == 0 {
success = false
}
return success
}
func (m *mkcert) installNSS() bool {
if m.forEachNSSProfile(func(profile string) {
cmd := exec.Command(certutilPath, "-A", "-d", profile, "-t", "C,,", "-n", m.caUniqueName(), "-i", filepath.Join(m.CAROOT, rootName))
out, err := execCertutil(cmd)
fatalIfCmdErr(err, "certutil -A -d "+profile, out)
}) == 0 {
log.Printf("ERROR: no %s security databases found", NSSBrowsers)
return false
}
if !m.checkNSS() {
log.Printf("Installing in %s failed. Please report the issue with details about your environment at https://github.com/FiloSottile/mkcert/issues/new đ", NSSBrowsers)
log.Printf("Note that if you never started %s, you need to do that at least once.", NSSBrowsers)
return false
}
return true
}
func (m *mkcert) uninstallNSS() {
m.forEachNSSProfile(func(profile string) {
err := exec.Command(certutilPath, "-V", "-d", profile, "-u", "L", "-n", m.caUniqueName()).Run()
if err != nil {
return
}
cmd := exec.Command(certutilPath, "-D", "-d", profile, "-n", m.caUniqueName())
out, err := execCertutil(cmd)
fatalIfCmdErr(err, "certutil -D -d "+profile, out)
})
}
// execCertutil will execute a "certutil" command and if needed re-execute
// the command with commandWithSudo to work around file permissions.
func execCertutil(cmd *exec.Cmd) ([]byte, error) {
out, err := cmd.CombinedOutput()
if err != nil && bytes.Contains(out, []byte("SEC_ERROR_READ_ONLY")) && runtime.GOOS != "windows" {
origArgs := cmd.Args[1:]
cmd = commandWithSudo(cmd.Path)
cmd.Args = append(cmd.Args, origArgs...)
out, err = cmd.CombinedOutput()
}
return out, err
}
func (m *mkcert) forEachNSSProfile(f func(profile string)) (found int) {
profiles, _ := filepath.Glob(FirefoxProfile)
profiles = append(profiles, nssDBs...)
for _, profile := range profiles {
if stat, err := os.Stat(profile); err != nil || !stat.IsDir() {
continue
}
if pathExists(filepath.Join(profile, "cert9.db")) {
f("sql:" + profile)
found++
} else if pathExists(filepath.Join(profile, "cert8.db")) {
f("dbm:" + profile)
found++
}
}
return
}
mkcert-1.4.3/truststore_windows.go 0000664 0000000 0000000 00000011271 13757453631 0017363 0 ustar 00root root 0000000 0000000 // Copyright 2018 The mkcert Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"crypto/x509"
"encoding/pem"
"fmt"
"io/ioutil"
"math/big"
"os"
"path/filepath"
"syscall"
"unsafe"
)
var (
FirefoxProfile = os.Getenv("USERPROFILE") + "\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles"
CertutilInstallHelp = "" // certutil unsupported on Windows
NSSBrowsers = "Firefox"
)
var (
modcrypt32 = syscall.NewLazyDLL("crypt32.dll")
procCertAddEncodedCertificateToStore = modcrypt32.NewProc("CertAddEncodedCertificateToStore")
procCertCloseStore = modcrypt32.NewProc("CertCloseStore")
procCertDeleteCertificateFromStore = modcrypt32.NewProc("CertDeleteCertificateFromStore")
procCertDuplicateCertificateContext = modcrypt32.NewProc("CertDuplicateCertificateContext")
procCertEnumCertificatesInStore = modcrypt32.NewProc("CertEnumCertificatesInStore")
procCertOpenSystemStoreW = modcrypt32.NewProc("CertOpenSystemStoreW")
)
func (m *mkcert) installPlatform() bool {
// Load cert
cert, err := ioutil.ReadFile(filepath.Join(m.CAROOT, rootName))
fatalIfErr(err, "failed to read root certificate")
// Decode PEM
if certBlock, _ := pem.Decode(cert); certBlock == nil || certBlock.Type != "CERTIFICATE" {
fatalIfErr(fmt.Errorf("invalid PEM data"), "decode pem")
} else {
cert = certBlock.Bytes
}
// Open root store
store, err := openWindowsRootStore()
fatalIfErr(err, "open root store")
defer store.close()
// Add cert
fatalIfErr(store.addCert(cert), "add cert")
return true
}
func (m *mkcert) uninstallPlatform() bool {
// We'll just remove all certs with the same serial number
// Open root store
store, err := openWindowsRootStore()
fatalIfErr(err, "open root store")
defer store.close()
// Do the deletion
deletedAny, err := store.deleteCertsWithSerial(m.caCert.SerialNumber)
if err == nil && !deletedAny {
err = fmt.Errorf("no certs found")
}
fatalIfErr(err, "delete cert")
return true
}
type windowsRootStore uintptr
func openWindowsRootStore() (windowsRootStore, error) {
rootStr, err := syscall.UTF16PtrFromString("ROOT")
if err != nil {
return 0, err
}
store, _, err := procCertOpenSystemStoreW.Call(0, uintptr(unsafe.Pointer(rootStr)))
if store != 0 {
return windowsRootStore(store), nil
}
return 0, fmt.Errorf("failed to open windows root store: %v", err)
}
func (w windowsRootStore) close() error {
ret, _, err := procCertCloseStore.Call(uintptr(w), 0)
if ret != 0 {
return nil
}
return fmt.Errorf("failed to close windows root store: %v", err)
}
func (w windowsRootStore) addCert(cert []byte) error {
// TODO: ok to always overwrite?
ret, _, err := procCertAddEncodedCertificateToStore.Call(
uintptr(w), // HCERTSTORE hCertStore
uintptr(syscall.X509_ASN_ENCODING|syscall.PKCS_7_ASN_ENCODING), // DWORD dwCertEncodingType
uintptr(unsafe.Pointer(&cert[0])), // const BYTE *pbCertEncoded
uintptr(len(cert)), // DWORD cbCertEncoded
3, // DWORD dwAddDisposition (CERT_STORE_ADD_REPLACE_EXISTING is 3)
0, // PCCERT_CONTEXT *ppCertContext
)
if ret != 0 {
return nil
}
return fmt.Errorf("failed adding cert: %v", err)
}
func (w windowsRootStore) deleteCertsWithSerial(serial *big.Int) (bool, error) {
// Go over each, deleting the ones we find
var cert *syscall.CertContext
deletedAny := false
for {
// Next enum
certPtr, _, err := procCertEnumCertificatesInStore.Call(uintptr(w), uintptr(unsafe.Pointer(cert)))
if cert = (*syscall.CertContext)(unsafe.Pointer(certPtr)); cert == nil {
if errno, ok := err.(syscall.Errno); ok && errno == 0x80092004 {
break
}
return deletedAny, fmt.Errorf("failed enumerating certs: %v", err)
}
// Parse cert
certBytes := (*[1 << 20]byte)(unsafe.Pointer(cert.EncodedCert))[:cert.Length]
parsedCert, err := x509.ParseCertificate(certBytes)
// We'll just ignore parse failures for now
if err == nil && parsedCert.SerialNumber != nil && parsedCert.SerialNumber.Cmp(serial) == 0 {
// Duplicate the context so it doesn't stop the enum when we delete it
dupCertPtr, _, err := procCertDuplicateCertificateContext.Call(uintptr(unsafe.Pointer(cert)))
if dupCertPtr == 0 {
return deletedAny, fmt.Errorf("failed duplicating context: %v", err)
}
if ret, _, err := procCertDeleteCertificateFromStore.Call(dupCertPtr); ret == 0 {
return deletedAny, fmt.Errorf("failed deleting certificate: %v", err)
}
deletedAny = true
}
}
return deletedAny, nil
}