diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml new file mode 100644 index 0000000000000000000000000000000000000000..c6fc6f2c364e9e4d176656a73d594d85cb06af80 --- /dev/null +++ b/.github/workflows/codeql-analysis.yml @@ -0,0 +1,72 @@ +# For most projects, this workflow file will not need changing; you simply need +# to commit it to your repository. +# +# You may wish to alter this file to override the set of languages analyzed, +# or to provide custom queries or build logic. +# +# ******** NOTE ******** +# We have attempted to detect the languages in your repository. Please check +# the `language` matrix defined below to confirm you have the correct set of +# supported CodeQL languages. +# +name: "CodeQL" + +on: + push: + branches: [ "master" ] + pull_request: + # The branches below must be a subset of the branches above + branches: [ "master" ] + schedule: + - cron: '30 3 * * 3' + +jobs: + analyze: + name: Analyze + runs-on: ubuntu-latest + permissions: + actions: read + contents: read + security-events: write + + strategy: + fail-fast: false + matrix: + language: [ 'go' ] + # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] + # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support + + steps: + - name: Checkout repository + uses: actions/checkout@v3 + + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@v2 + with: + languages: ${{ matrix.language }} + # If you wish to specify custom queries, you can do so here or in a config file. + # By default, queries listed here will override any specified in a config file. + # Prefix the list here with "+" to use these queries and those in the config file. + + # Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs + # queries: security-extended,security-and-quality + + + # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). + # If this step fails, then you should remove it and run the build manually (see below) + - name: Autobuild + uses: github/codeql-action/autobuild@v2 + + # â„¹ï¸ Command-line programs to run using the OS shell. + # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun + + # If the Autobuild fails above, remove it and uncomment the following three lines. + # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance. + + # - run: | + # echo "Run, Build Application using script" + # ./location_of_script_within_repo/buildscript.sh + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v2 diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000000000000000000000000000000000000..d84c028ea42a70851f803017dc4d19a91bf1c8ec --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,15 @@ +name: Continuous Integration + +on: + push: + tags-ignore: + - 'v*' + branches: + - "**" + pull_request: + schedule: + - cron: '0 0 * * SUN' + +jobs: + ci: + uses: smallstep/workflows/.github/workflows/goCI.yml@main diff --git a/Makefile b/Makefile index cb7f82adadb8bc13610b8e304196441f8b5c2fd8..ce711408c5942ea9f73de996d56126d147297e98 100644 --- a/Makefile +++ b/Makefile @@ -1,5 +1,62 @@ -all: - go build -o bin/truststore cmd/truststore/main.go +# Set V to 1 for verbose output from the Makefile +Q=$(if $V,,@) +SRC=$(shell find . -type f -name '*.go') + +all: lint test build + +ci: test + +.PHONY: all ci + +######################################### +# Build +######################################### + +build: + $Q go build -o bin/truststore cmd/truststore/main.go + +.PHONY: build + +######################################### +# Bootstrapping +######################################### + +bootstra%: + $Q curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $$(go env GOPATH)/bin v1.49.0 + $Q go install golang.org/x/vuln/cmd/govulncheck@latest + $Q go install gotest.tools/gotestsum@v1.8.1 + +.PHONY: bootstrap + +######################################### +# Test +######################################### + +test: + $Q $(GOFLAGS) gotestsum -- -coverpkg=./... -coverprofile=coverage.out -covermode=atomic ./... + +race: + $Q $(GOFLAGS) gotestsum -- -race ./... + +.PHONY: test race + +######################################### +# Linting +######################################### + +fmt: + $Q goimports -local github.com/golangci/golangci-lint -l -w $(SRC) + +lint: SHELL:=/bin/bash +lint: + $Q LOG_LEVEL=error golangci-lint run --config <(curl -s https://raw.githubusercontent.com/smallstep/workflows/master/.golangci.yml) --timeout=30m + $Q govulncheck ./... + +.PHONY: fmt lint + +######################################### +# Clean +######################################### clean: rm -rf bin diff --git a/errors.go b/errors.go index 13741bae82279ae3361a8f3a956d8bd40e688801..15b97370e83c85ac8df1163f6b23204b096b77c0 100644 --- a/errors.go +++ b/errors.go @@ -72,5 +72,5 @@ func wrapError(err error, msg string) error { if err == nil { return nil } - return fmt.Errorf("%s: %s", msg, err) + return fmt.Errorf("%s: %w", msg, err) } diff --git a/go.mod b/go.mod index 4b56c6c3c134033cedf79b945b95d1050735115b..c92bcbeef8c38e4cbedac223012bb16fa2396988 100644 --- a/go.mod +++ b/go.mod @@ -1,5 +1,5 @@ module github.com/smallstep/truststore -go 1.13 +go 1.18 require howett.net/plist v0.0.0-20181124034731-591f970eefbb diff --git a/truststore.go b/truststore.go index 714af038c0b39b9f3c65ff0324c011b1a7ca9d74..82571a3f488e72081a4c4fb072029e4e6da4254e 100644 --- a/truststore.go +++ b/truststore.go @@ -7,7 +7,6 @@ import ( "crypto/x509" "encoding/pem" "io" - "io/ioutil" "log" "os" ) @@ -118,14 +117,14 @@ func uninstallCertificate(filename string, cert *x509.Certificate, opts []Option // ReadCertificate reads a certificate file and returns a x509.Certificate struct. func ReadCertificate(filename string) (*x509.Certificate, error) { - b, err := ioutil.ReadFile(filename) + b, err := os.ReadFile(filename) if err != nil { return nil, err } // PEM format if bytes.HasPrefix(b, []byte("-----BEGIN ")) { - b, err = ioutil.ReadFile(filename) + b, err = os.ReadFile(filename) if err != nil { return nil, err } @@ -148,7 +147,7 @@ func SaveCertificate(filename string, cert *x509.Certificate) error { Type: "CERTIFICATE", Bytes: cert.Raw, } - return ioutil.WriteFile(filename, pem.EncodeToMemory(block), 0600) + return os.WriteFile(filename, pem.EncodeToMemory(block), 0600) } type options struct { @@ -225,7 +224,7 @@ func uniqueName(cert *x509.Certificate) string { } func saveTempCert(cert *x509.Certificate) (string, func(), error) { - f, err := ioutil.TempFile(os.TempDir(), "truststore.*.pem") + f, err := os.CreateTemp(os.TempDir(), "truststore.*.pem") if err != nil { return "", func() {}, err } diff --git a/truststore_darwin.go b/truststore_darwin.go index bdc1f6c29b1ec7146a08a651f5163fd50f7e2bf7..9f25654585d37e0f9434a9fc3f1fe666cf1d74bb 100644 --- a/truststore_darwin.go +++ b/truststore_darwin.go @@ -8,7 +8,6 @@ import ( "crypto/x509" "encoding/asn1" "fmt" - "io/ioutil" "os" "os/exec" @@ -60,19 +59,20 @@ func installPlatform(filename string, cert *x509.Certificate) error { // Make trustSettings explicit, as older Go does not know the defaults. // https://github.com/golang/go/issues/24652 - plistFile, err := ioutil.TempFile("", "trust-settings") + plistFile, err := os.CreateTemp("", "trust-settings") if err != nil { return wrapError(err, "failed to create temp file") } defer os.Remove(plistFile.Name()) + //nolint:gosec // tolerable risk necessary for function cmd = exec.Command("sudo", "security", "trust-settings-export", "-d", plistFile.Name()) out, err = cmd.CombinedOutput() if err != nil { return NewCmdError(err, cmd, out) } - plistData, err := ioutil.ReadFile(plistFile.Name()) + plistData, err := os.ReadFile(plistFile.Name()) if err != nil { return wrapError(err, "failed to read trust settings") } @@ -106,11 +106,12 @@ func installPlatform(filename string, cert *x509.Certificate) error { return wrapError(err, "failed to serialize trust settings") } - err = ioutil.WriteFile(plistFile.Name(), plistData, 0600) + err = os.WriteFile(plistFile.Name(), plistData, 0600) if err != nil { return wrapError(err, "failed to write trust settings") } + //nolint:gosec // tolerable risk necessary for function cmd = exec.Command("sudo", "security", "trust-settings-import", "-d", plistFile.Name()) out, err = cmd.CombinedOutput() if err != nil { diff --git a/truststore_java.go b/truststore_java.go index d7bbea6f7ae3755b040f05c5eff26414f3103d42..7051a43d7803bdfcb2353626534a36d68d42dc8f 100644 --- a/truststore_java.go +++ b/truststore_java.go @@ -5,7 +5,7 @@ package truststore import ( "bytes" - "crypto/sha1" + "crypto/sha1" //nolint:gosec // not used for cryptographic purposes "crypto/sha256" "crypto/x509" "encoding/hex" @@ -76,6 +76,7 @@ func (t *JavaTrust) Install(filename string, cert *x509.Certificate) error { "-alias", uniqueName(cert), } + //nolint:gosec // tolerable risk necessary for function cmd := exec.Command(t.keytoolPath, args...) if out, err := execKeytool(cmd); err != nil { return NewCmdError(err, cmd, out) @@ -94,6 +95,7 @@ func (t *JavaTrust) Uninstall(filename string, cert *x509.Certificate) error { "-storepass", JavaStorePass, } + //nolint:gosec // tolerable risk necessary for function cmd := exec.Command(t.keytoolPath, args...) out, err := execKeytool(cmd) if bytes.Contains(out, []byte("does not exist")) { @@ -121,6 +123,7 @@ func (t *JavaTrust) Exists(cert *x509.Certificate) bool { return bytes.Contains(keytoolOutput, []byte(fp)) } + //nolint:gosec // tolerable risk necessary for function cmd := exec.Command(t.keytoolPath, "-list", "-keystore", t.cacertsPath, "-storepass", JavaStorePass) keytoolOutput, err := cmd.CombinedOutput() if err != nil { @@ -130,9 +133,10 @@ func (t *JavaTrust) Exists(cert *x509.Certificate) bool { // 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) + keytoolOutput = bytes.ReplaceAll(keytoolOutput, []byte(":"), nil) // pre-Java 9 uses SHA1 fingerprints + //nolint:gosec // not used for cryptographic purposes s1, s256 := sha1.New(), sha256.New() return exists(cert, s1, keytoolOutput) || exists(cert, s256, keytoolOutput) } @@ -151,6 +155,7 @@ 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:] + //nolint:gosec // tolerable risk necessary for function cmd = exec.Command("sudo", cmd.Path) cmd.Args = append(cmd.Args, origArgs...) cmd.Env = []string{ diff --git a/truststore_linux.go b/truststore_linux.go index 92bbfba44ecff8b5de9e5a72bffe5c4d29fac06b..d01d73e285e031d52dc903e96291455b04425f7b 100644 --- a/truststore_linux.go +++ b/truststore_linux.go @@ -7,7 +7,6 @@ import ( "bytes" "crypto/x509" "fmt" - "io/ioutil" "os" "os/exec" "strings" @@ -28,19 +27,20 @@ var ( ) func init() { - if pathExists("/etc/pki/ca-trust/source/anchors/") { + switch { + case 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/") { + case pathExists("/usr/local/share/ca-certificates/"): SystemTrustFilename = "/usr/local/share/ca-certificates/%s.crt" SystemTrustCommand = []string{"update-ca-certificates"} - } else if pathExists("/usr/shared/pki/trust/anchors/") { + case pathExists("/usr/shared/pki/trust/anchors/"): SystemTrustFilename = "/usr/shared/pki/trust/anchors/%s.crt" SystemTrustCommand = []string{"update-ca-certificates"} - } else if pathExists("/etc/ca-certificates/trust-source/anchors/") { + case pathExists("/etc/ca-certificates/trust-source/anchors/"): SystemTrustFilename = "/etc/ca-certificates/trust-source/anchors/%s.crt" SystemTrustCommand = []string{"trust", "extract-compat"} - } else if pathExists("/etc/ssl/certs/") { + case pathExists("/etc/ssl/certs/"): SystemTrustFilename = "/etc/ssl/certs/%s.crt" SystemTrustCommand = []string{"trust", "extract-compat"} } @@ -58,7 +58,7 @@ func pathExists(path string) bool { } func systemTrustFilename(cert *x509.Certificate) string { - return fmt.Sprintf(SystemTrustFilename, strings.Replace(uniqueName(cert), " ", "_", -1)) + return fmt.Sprintf(SystemTrustFilename, strings.ReplaceAll(uniqueName(cert), " ", "_")) } func installPlatform(filename string, cert *x509.Certificate) error { @@ -66,7 +66,7 @@ func installPlatform(filename string, cert *x509.Certificate) error { return ErrNotSupported } - data, err := ioutil.ReadFile(filename) + data, err := os.ReadFile(filename) if err != nil { return err } @@ -111,7 +111,9 @@ func uninstallPlatform(filename string, cert *x509.Certificate) error { func CommandWithSudo(cmd ...string) *exec.Cmd { if _, err := exec.LookPath("sudo"); err != nil { + //nolint:gosec // tolerable risk necessary for function return exec.Command(cmd[0], cmd[1:]...) } + //nolint:gosec // tolerable risk necessary for function return exec.Command("sudo", append([]string{"--"}, cmd...)...) } diff --git a/truststore_nss.go b/truststore_nss.go index 9bdcbbc8c0986d374968066ad2b4cb160a917ad2..c3c3618be7f1898ef26c72f9f8c2961a8484c9ee 100644 --- a/truststore_nss.go +++ b/truststore_nss.go @@ -13,7 +13,7 @@ import ( "strings" ) -var nssDB = filepath.Join(os.Getenv("HOME"), ".pki/nssdb") +var nssDB = filepath.Join(os.Getenv("HOME"), ".pki", "nssdb") // NSSTrust implements a Trust for Firefox or other NSS based applications. type NSSTrust struct { @@ -60,6 +60,7 @@ func (t *NSSTrust) Name() string { func (t *NSSTrust) Install(filename string, cert *x509.Certificate) error { // install certificate in all profiles if forEachNSSProfile(func(profile string) { + //nolint:gosec // tolerable risk necessary for function cmd := exec.Command(t.certutilPath, "-A", "-d", profile, "-t", "C,,", "-n", uniqueName(cert), "-i", filename) out, err := cmd.CombinedOutput() if err != nil { @@ -85,10 +86,12 @@ func (t *NSSTrust) Uninstall(filename string, cert *x509.Certificate) (err error return } // skip if not found + //nolint:gosec // tolerable risk necessary for function if err := exec.Command(t.certutilPath, "-V", "-d", profile, "-u", "L", "-n", uniqueName(cert)).Run(); err != nil { return } // delete certificate + //nolint:gosec // tolerable risk necessary for function cmd := exec.Command(t.certutilPath, "-D", "-d", profile, "-n", uniqueName(cert)) out, err1 := cmd.CombinedOutput() if err1 != nil { @@ -106,6 +109,7 @@ func (t *NSSTrust) Uninstall(filename string, cert *x509.Certificate) (err error func (t *NSSTrust) Exists(cert *x509.Certificate) bool { success := true if forEachNSSProfile(func(profile string) { + //nolint:gosec // tolerable risk necessary for function err := exec.Command(t.certutilPath, "-V", "-d", profile, "-u", "L", "-n", uniqueName(cert)).Run() if err != nil { success = false @@ -126,10 +130,10 @@ func (t *NSSTrust) PreCheck() error { } if CertutilInstallHelp == "" { - return fmt.Errorf("Note: NSS support is not available on your platform") + return fmt.Errorf("note: NSS support is not available on your platform") } - return fmt.Errorf(`Warning: "certutil" is not available, install "certutil" with "%s" and try again`, CertutilInstallHelp) + return fmt.Errorf(`warning: "certutil" is not available, install "certutil" with "%s" and try again`, CertutilInstallHelp) } func forEachNSSProfile(f func(profile string)) (found int) {