pax_global_header00006660000000000000000000000064144371342020014512gustar00rootroot0000000000000052 comment=400520e8d7cde6c9692075f14dc0f4f4d52db995 mclib-1.20400.20402/000077500000000000000000000000001443713420200134145ustar00rootroot00000000000000mclib-1.20400.20402/.github/000077500000000000000000000000001443713420200147545ustar00rootroot00000000000000mclib-1.20400.20402/.github/FUNDING.yml000066400000000000000000000000151443713420200165650ustar00rootroot00000000000000github: [bep]mclib-1.20400.20402/.github/workflows/000077500000000000000000000000001443713420200170115ustar00rootroot00000000000000mclib-1.20400.20402/.github/workflows/test.yml000066400000000000000000000012251443713420200205130ustar00rootroot00000000000000on: push: branches: [ main ] pull_request: name: Test jobs: test: strategy: matrix: go-version: [1.19.x,1.20.x] platform: [ubuntu-latest, macos-latest, windows-latest] runs-on: ${{ matrix.platform }} steps: - name: Install Go uses: actions/setup-go@v3 with: go-version: ${{ matrix.go-version }} - name: Install golint run: go install golang.org/x/lint/golint@latest shell: bash - name: Update PATH run: echo "$(go env GOPATH)/bin" >> $GITHUB_PATH shell: bash - name: Checkout code uses: actions/checkout@v1 - name: Test run: go test -race . mclib-1.20400.20402/.gitignore000066400000000000000000000004151443713420200154040ustar00rootroot00000000000000# Binaries for programs and plugins *.exe *.exe~ *.dll *.so *.dylib # Test binary, built with `go test -c` *.test # Output of the go coverage tool, specifically when used with LiteIDE *.out # Dependency directories (remove the comment below to include it) # vendor/ mclib-1.20400.20402/.gitmodules000066400000000000000000000001251443713420200155670ustar00rootroot00000000000000[submodule "mkcert"] path = mkcert url = https://github.com/FiloSottile/mkcert.git mclib-1.20400.20402/LICENSE000066400000000000000000000020651443713420200144240ustar00rootroot00000000000000MIT License Copyright (c) 2022 BjΓΈrn Erik Pedersen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. mclib-1.20400.20402/README.md000066400000000000000000000021741443713420200146770ustar00rootroot00000000000000[![Tests on Linux, MacOS and Windows](https://github.com/bep/mclib/workflows/Test/badge.svg)](https://github.com/bep/mclib/actions?query=workflow:Test) [![Go Report Card](https://goreportcard.com/badge/github.com/bep/mclib)](https://goreportcard.com/report/github.com/bep/mclib) [![GoDoc](https://godoc.org/github.com/bep/mclib?status.svg)](https://godoc.org/github.com/bep/mclib) This is a simple library to make it possible to run [Mkcert's](https://github.com/FiloSottile/mkcert) `main` method. The script that updates the `internal` package does no logic changes to the source, it simply 1. Renames the `main` package to `internal`. 1. Renames the `main` func to `RunMain` 1. Replaces any `log.Fatal` with `panic` to allow us to handle the errors. 1. Exports getCAROOT(). For more advanced library usage, see [this issue](https://github.com/FiloSottile/mkcert/issues/45). The `mkcert` source code is stored in a Git submodule to a tagged version, so to generate a new version, you need to clone this repo with `--recursive`, and then run: ```bash go generate ./gen ``` We use [semverpair](https://github.com/bep/semverpair) versioning.mclib-1.20400.20402/gen/000077500000000000000000000000001443713420200141655ustar00rootroot00000000000000mclib-1.20400.20402/gen/main.go000066400000000000000000000042561443713420200154470ustar00rootroot00000000000000//go:generate go run main.go package main import ( "io/ioutil" "log" "os" "path/filepath" "regexp" "strings" "github.com/bep/helpers/filehelpers" ) func main() { rootDir := "../" internalDir := filepath.Join(rootDir, "internal") // Remove old files. if err := os.RemoveAll(internalDir); err != nil { log.Fatal(err) } if err := os.MkdirAll(internalDir, 0755); err != nil { log.Fatal(err) } if err := filehelpers.CopyDir(filepath.Join(rootDir, "mkcert"), internalDir, func(path string) bool { return filepath.Ext(path) == ".go" && !strings.HasSuffix(path, "_test.go") }); err != nil { log.Fatal(err) } if err := filehelpers.CopyFile("./truststore_other.go.txt", filepath.Join(internalDir, "truststore_other.go")); err != nil { log.Fatal(err) } fileReplacer := strings.NewReplacer( "getCAROOT()", "GetCAROOT()", "mkcert -install", "hugo server trust", "mkcert -uninstall", "hugo server trust -uninstall", " πŸ‘ˆ", "", " πŸ‘", "", " 🦊", "", " ℹ️", "", " ⚠️", "", " πŸ‘‹", "", " ⚑️", "", ) err := filepath.Walk(filepath.Join(rootDir, "internal"), func(path string, info os.FileInfo, err error) error { if info == nil || info.IsDir() { return nil } b, err := ioutil.ReadFile(path) if err != nil { return err } s := string(b) s = strings.Replace(s, "package main", "package internal", 1) if strings.HasSuffix(path, "main.go") { s = strings.Replace(s, "func main()", "func RunMain()", 1) } s = fileReplacer.Replace(s) s = strings.Replace(s, `!"`, `."`, -1) // We don't want os.Exit(-1) in a library. // E.g. log.Fatalf("ERROR: failed to execute \"%s\": %s\n\n%s\n", cmd, err, out) // Replace with panic. // NOTE: These are currently not perfect, so some edits may be needed (missing imports). fatalFRe := regexp.MustCompile(`log.Fatalf\((.*)\)`) s = fatalFRe.ReplaceAllString(s, "panic(fmt.Sprintf($1))") fatalLnRe := regexp.MustCompile(`log.Fatalln\((.*)\)`) s = fatalLnRe.ReplaceAllString(s, "panic(fmt.Sprintln($1))") // Write to the same file. if err := ioutil.WriteFile(path, []byte(s), info.Mode()); err != nil { return err } return nil }) if err != nil { log.Fatal(err) } } mclib-1.20400.20402/gen/truststore_other.go.txt000066400000000000000000000007651443713420200210010ustar00rootroot00000000000000//go:build dragonfly || freebsd || openbsd || netbsd || solaris package internal import ( "fmt" "runtime" ) var ( FirefoxProfiles = []string{} CertutilInstallHelp = "" NSSBrowsers = "" ) func (m *mkcert) installPlatform() bool { panic(fmt.Sprintf("installing root on %s is currently not supported", runtime.GOOS)) return false } func (m *mkcert) uninstallPlatform() bool { panic(fmt.Sprintf("uninstalling root on %s is currently not supported", runtime.GOOS)) return false } mclib-1.20400.20402/go.mod000066400000000000000000000007761443713420200145340ustar00rootroot00000000000000module github.com/bep/mclib go 1.19 require ( github.com/bep/helpers v0.4.0 github.com/frankban/quicktest v1.14.3 golang.org/x/net v0.10.0 howett.net/plist v1.0.0 software.sslmate.com/src/go-pkcs12 v0.2.0 ) require ( github.com/google/go-cmp v0.5.8 // indirect github.com/kr/pretty v0.3.0 // indirect github.com/kr/text v0.2.0 // indirect github.com/rogpeppe/go-internal v1.8.1 // indirect golang.org/x/crypto v0.0.0-20220331220935-ae2d96664a29 // indirect golang.org/x/text v0.9.0 // indirect ) mclib-1.20400.20402/go.sum000066400000000000000000000073421443713420200145550ustar00rootroot00000000000000github.com/bep/helpers v0.4.0 h1:ab9veaAiWY4ST48Oxp5usaqivDmYdB744fz+tcZ3Ifs= github.com/bep/helpers v0.4.0/go.mod h1:/QpHdmcPagDw7+RjkLFCvnlUc8lQ5kg4KDrEkb2Yyco= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/frankban/quicktest v1.14.3 h1:FJKSZTDHjyhriyC81FLQ0LY93eSai0ZyR/ZIkd3ZUKE= github.com/frankban/quicktest v1.14.3/go.mod h1:mgiwOwqx65TmIk1wJ6Q7wvnVMocbUorkibMOrVTHZps= github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE= github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg= github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= 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/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.8.1 h1:geMPLpDpQOgVyCg5z5GoRwLHepNdb71NXb67XFkP+Eg= github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= golang.org/x/crypto v0.0.0-20220331220935-ae2d96664a29 h1:tkVvjkPTB7pnW3jnid7kNyAMPVWllTNOf/qKDze4p9o= golang.org/x/crypto v0.0.0-20220331220935-ae2d96664a29/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.10.0 h1:X2//UzNDwYmtCLn7To6G58Wr6f5ahEAQgKNzv9Y951M= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE= golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/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.v1 v1.0.0-20140924161607-9f9df34309c0/go.mod h1:WDnlLJ4WF5VGsH/HVa3CI79GS0ol3YnhVnKP89i0kNg= howett.net/plist v1.0.0 h1:7CrbWYbPPO/PyNy38b2EB/+gYbjCe2DXBxgtOOZbSQM= howett.net/plist v1.0.0/go.mod h1:lqaXoTrLY4hg8tnEzNru53gicrbv7rrk+2xJA/7hw9g= software.sslmate.com/src/go-pkcs12 v0.2.0 h1:nlFkj7bTysH6VkC4fGphtjXRbezREPgrHuJG20hBGPE= software.sslmate.com/src/go-pkcs12 v0.2.0/go.mod h1:23rNcYsMabIc1otwLpTkCCPwUq6kQsTyowttG/as0kQ= mclib-1.20400.20402/internal/000077500000000000000000000000001443713420200152305ustar00rootroot00000000000000mclib-1.20400.20402/internal/cert.go000066400000000000000000000265161443713420200165260ustar00rootroot00000000000000// 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 internal import ( "crypto" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/rsa" "crypto/sha1" "crypto/x509" "crypto/x509/pkix" "encoding/asn1" "encoding/pem" "fmt" "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 { panic(fmt.Sprintln("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 { panic(fmt.Sprintln("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 { panic(fmt.Sprintln("ERROR: failed to read the CSR: unexpected content")) } if csrPEM.Type != "CERTIFICATE REQUEST" && csrPEM.Type != "NEW CERTIFICATE REQUEST" { panic(fmt.Sprintln("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") c, err := x509.ParseCertificate(cert) fatalIfErr(err, "failed to parse generated certificate") var hosts []string hosts = append(hosts, c.DNSNames...) hosts = append(hosts, c.EmailAddresses...) for _, ip := range c.IPAddresses { hosts = append(hosts, ip.String()) } for _, uri := range c.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" { panic(fmt.Sprintln("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" { panic(fmt.Sprintln("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 certificate") log.Printf("Created a new local CA πŸ’₯\n") } func (m *mkcert) caUniqueName() string { return "mkcert development CA " + m.caCert.SerialNumber.String() } mclib-1.20400.20402/internal/main.go000066400000000000000000000253561443713420200165160ustar00rootroot00000000000000// 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 internal 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: $ hugo server trust 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". $ hugo server trust -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 RunMain() { if len(os.Args) == 1 { fmt.Print(shortUsage) return } 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 { panic(fmt.Sprintln("ERROR: you can't set -[un]install and -CAROOT at the same time")) } fmt.Println(GetCAROOT()) return } if *installFlag && *uninstallFlag { panic(fmt.Sprintln("ERROR: you can't set -install and -uninstall at the same time")) } if *csrFlag != "" && (*pkcs12Flag || *ecdsaFlag || *clientFlag) { panic(fmt.Sprintln("ERROR: can only combine -csr with -install and -cert-file")) } if *csrFlag != "" && flag.NArg() != 0 { panic(fmt.Sprintln("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 == "" { panic(fmt.Sprintln("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 \"hugo server trust\" 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 { panic(fmt.Sprintf("ERROR: %q is not a valid hostname, IP, URL or email: %s", name, err)) } args[i] = punycode if !hostnameRegexp.MatchString(punycode) { panic(fmt.Sprintf("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 "hugo server trust"`, 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 "hugo server trust -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 { panic(fmt.Sprintf("ERROR: %s: %s", msg, err)) } } func fatalIfCmdErr(err error, cmd string, out []byte) { if err != nil { panic(fmt.Sprintf("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...)...) } mclib-1.20400.20402/internal/truststore_darwin.go000066400000000000000000000064061443713420200213670ustar00rootroot00000000000000// 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 internal import ( "bytes" "encoding/asn1" "fmt" "io/ioutil" "os" "path/filepath" "howett.net/plist" ) var ( FirefoxProfiles = []string{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 { panic(fmt.Sprintln("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 } mclib-1.20400.20402/internal/truststore_java.go000066400000000000000000000063321443713420200210220ustar00rootroot00000000000000// 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 internal 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 } mclib-1.20400.20402/internal/truststore_linux.go000066400000000000000000000061121443713420200212340ustar00rootroot00000000000000// 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 internal import ( "bytes" "fmt" "io/ioutil" "log" "os" "path/filepath" "strings" ) var ( FirefoxProfiles = []string{os.Getenv("HOME") + "/.mozilla/firefox/*", os.Getenv("HOME") + "/snap/firefox/common/.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 } mclib-1.20400.20402/internal/truststore_nss.go000066400000000000000000000102231443713420200206760ustar00rootroot00000000000000// 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 internal 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", "/snap/firefox", "/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) { var profiles []string profiles = append(profiles, nssDBs...) for _, ff := range FirefoxProfiles { pp, _ := filepath.Glob(ff) profiles = append(profiles, pp...) } 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 } mclib-1.20400.20402/internal/truststore_other.go000066400000000000000000000007651443713420200212260ustar00rootroot00000000000000//go:build dragonfly || freebsd || openbsd || netbsd || solaris package internal import ( "fmt" "runtime" ) var ( FirefoxProfiles = []string{} CertutilInstallHelp = "" NSSBrowsers = "" ) func (m *mkcert) installPlatform() bool { panic(fmt.Sprintf("installing root on %s is currently not supported", runtime.GOOS)) return false } func (m *mkcert) uninstallPlatform() bool { panic(fmt.Sprintf("uninstalling root on %s is currently not supported", runtime.GOOS)) return false } mclib-1.20400.20402/internal/truststore_windows.go000066400000000000000000000113071443713420200215710ustar00rootroot00000000000000// 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 internal import ( "crypto/x509" "encoding/pem" "fmt" "io/ioutil" "math/big" "os" "path/filepath" "syscall" "unsafe" ) var ( FirefoxProfiles = []string{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 } mclib-1.20400.20402/mclib.go000066400000000000000000000015621443713420200150350ustar00rootroot00000000000000package mclib import ( "fmt" "os" "strings" "github.com/bep/mclib/internal" ) var errorReplacer = strings.NewReplacer( "ERROR: ", "", ) // RunMain runs mkcert's main function. // // You need to set os.Args before calling this function, e.g. // // os.Args = []string{"-install"} // os.Args = []string{"-cert-file", "cert.pem", "-key-file", "key.pem", "example.com"} func RunMain() (err error) { defer func() { if r := recover(); r != nil { errStr := fmt.Sprintf("%v", r) errStr = errorReplacer.Replace(errStr) err = fmt.Errorf(errStr) } }() const mkcert = "mkcert" if len(os.Args) == 0 || os.Args[0] != mkcert { // All commands needs the "mkcert" as its first argument. os.Args = append([]string{mkcert}, os.Args...) } internal.RunMain() return } // GetCAROOT returns the CA root directory. func GetCAROOT() string { return internal.GetCAROOT() } mclib-1.20400.20402/mclib_test.go000066400000000000000000000005161443713420200160720ustar00rootroot00000000000000package mclib_test import ( "os" "testing" "github.com/bep/mclib" qt "github.com/frankban/quicktest" ) func TestRunMain(t *testing.T) { c := qt.New(t) os.Args = []string{"-help"} c.Assert(mclib.RunMain(), qt.IsNil) } func TestGetCAROOT(t *testing.T) { c := qt.New(t) c.Assert(mclib.GetCAROOT(), qt.Not(qt.Equals), "") } mclib-1.20400.20402/mkcert/000077500000000000000000000000001443713420200147015ustar00rootroot00000000000000