├── .github ├── PULL_REQUEST_TEMPLATE ├── dependabot.yml └── workflows │ ├── ci.yml │ ├── code-scan-cron.yml │ └── dependabot-auto-merge.yml ├── .gitignore ├── CODEOWNERS ├── LICENSE ├── Makefile ├── README.md ├── cmd └── truststore │ └── main.go ├── errors.go ├── go.mod ├── go.sum ├── truststore.go ├── truststore_darwin.go ├── truststore_freebsd.go ├── truststore_java.go ├── truststore_linux.go ├── truststore_nss.go ├── truststore_others.go └── truststore_windows.go /.github/PULL_REQUEST_TEMPLATE: -------------------------------------------------------------------------------- 1 | 6 | #### Name of feature: 7 | 8 | #### Pain or issue this feature alleviates: 9 | 10 | #### Why is this important to the project (if not answered above): 11 | 12 | #### Is there documentation on how to use this feature? If so, where? 13 | 14 | #### In what environments or workflows is this feature supported? 15 | 16 | #### In what environments or workflows is this feature explicitly NOT supported (if any)? 17 | 18 | #### Supporting links/other PRs/issues: 19 | 20 | 💔Thank you! 21 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "gomod" # See documentation for possible values 9 | directory: "/" # Location of package manifests 10 | schedule: 11 | interval: "weekly" 12 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | tags-ignore: 6 | - 'v*' 7 | branches: 8 | - "master" 9 | pull_request: 10 | workflow_call: 11 | 12 | jobs: 13 | ci: 14 | uses: smallstep/workflows/.github/workflows/goCI.yml@main 15 | with: 16 | only-latest-golang: false 17 | run-codeql: true 18 | secrets: inherit 19 | -------------------------------------------------------------------------------- /.github/workflows/code-scan-cron.yml: -------------------------------------------------------------------------------- 1 | on: 2 | schedule: 3 | - cron: '0 0 * * SUN' 4 | 5 | jobs: 6 | code-scan: 7 | uses: smallstep/workflows/.github/workflows/code-scan.yml@main 8 | -------------------------------------------------------------------------------- /.github/workflows/dependabot-auto-merge.yml: -------------------------------------------------------------------------------- 1 | name: Dependabot auto-merge 2 | on: pull_request 3 | 4 | permissions: 5 | contents: write 6 | pull-requests: write 7 | 8 | jobs: 9 | dependabot: 10 | runs-on: ubuntu-latest 11 | if: ${{ github.actor == 'dependabot[bot]' }} 12 | steps: 13 | - name: Dependabot metadata 14 | id: metadata 15 | uses: dependabot/fetch-metadata@v1.1.1 16 | with: 17 | github-token: "${{ secrets.GITHUB_TOKEN }}" 18 | - name: Enable auto-merge for Dependabot PRs 19 | run: gh pr merge --auto --merge "$PR_URL" 20 | env: 21 | PR_URL: ${{github.event.pull_request.html_url}} 22 | GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}} 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | /bin/truststore 3 | *.exe 4 | *.exe~ 5 | *.dll 6 | *.so 7 | *.dylib 8 | 9 | # Test binary, build with `go test -c` 10 | *.test 11 | 12 | # Output of the go coverage tool, specifically when used with LiteIDE 13 | *.out 14 | 15 | # Others 16 | *.swp 17 | .travis-releases 18 | coverage.txt 19 | output 20 | vendor 21 | step 22 | -------------------------------------------------------------------------------- /CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @maraino @smallstep/core 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # Set V to 1 for verbose output from the Makefile 2 | Q=$(if $V,,@) 3 | SRC=$(shell find . -type f -name '*.go') 4 | 5 | all: lint test build 6 | 7 | ci: test 8 | 9 | .PHONY: all ci 10 | 11 | ######################################### 12 | # Build 13 | ######################################### 14 | 15 | build: 16 | $Q go build -o bin/truststore cmd/truststore/main.go 17 | 18 | .PHONY: build 19 | 20 | ######################################### 21 | # Bootstrapping 22 | ######################################### 23 | 24 | bootstra%: 25 | $Q curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $$(go env GOPATH)/bin v1.49.0 26 | $Q go install golang.org/x/vuln/cmd/govulncheck@latest 27 | $Q go install gotest.tools/gotestsum@v1.8.1 28 | 29 | .PHONY: bootstrap 30 | 31 | ######################################### 32 | # Test 33 | ######################################### 34 | 35 | test: 36 | $Q $(GOFLAGS) gotestsum -- -coverpkg=./... -coverprofile=coverage.out -covermode=atomic ./... 37 | 38 | race: 39 | $Q $(GOFLAGS) gotestsum -- -race ./... 40 | 41 | .PHONY: test race 42 | 43 | ######################################### 44 | # Linting 45 | ######################################### 46 | 47 | fmt: 48 | $Q goimports -local github.com/golangci/golangci-lint -l -w $(SRC) 49 | 50 | lint: golint govulncheck 51 | 52 | golint: SHELL:=/bin/bash 53 | golint: 54 | $Q LOG_LEVEL=error golangci-lint run --config <(curl -s https://raw.githubusercontent.com/smallstep/workflows/master/.golangci.yml) --timeout=30m 55 | 56 | govulncheck: 57 | $Q govulncheck ./... 58 | 59 | .PHONY: fmt lint golint govulncheck 60 | 61 | ######################################### 62 | # Clean 63 | ######################################### 64 | 65 | clean: 66 | rm -rf bin 67 | 68 | .PHONY: all clean 69 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # truststore 2 | 3 | [![GoDoc](https://godoc.org/github.com/smallstep/truststore?status.svg)](https://godoc.org/github.com/smallstep/truststore) 4 | [![Go Report Card](https://goreportcard.com/badge/github.com/smallstep/truststore)](https://goreportcard.com/report/github.com/smallstep/truststore) 5 | 6 | Package to locally install development certificates. 7 | 8 | Based on https://github.com/FiloSottile/mkcert 9 | -------------------------------------------------------------------------------- /cmd/truststore/main.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018 The truststore Authors. All rights reserved. 2 | 3 | package main 4 | 5 | import ( 6 | "flag" 7 | "fmt" 8 | "os" 9 | 10 | "github.com/smallstep/truststore" 11 | ) 12 | 13 | func usage() { 14 | fmt.Fprintf(os.Stderr, "Usage:\n\t%s [-uninstall] rootCA.pem\n", os.Args[0]) 15 | flag.PrintDefaults() 16 | } 17 | 18 | func main() { 19 | var uninstall, help, verbose bool 20 | var java, firefox, noSystem, all bool 21 | flag.Usage = usage 22 | flag.BoolVar(&uninstall, "uninstall", false, "uninstall the given certificate") 23 | flag.BoolVar(&java, "java", false, "install or uninstall on the Java truststore") 24 | flag.BoolVar(&firefox, "firefox", false, "install or uninstall on the Firefox truststore") 25 | flag.BoolVar(&noSystem, "no-system", false, "disables the install or uninstall on the system truststore") 26 | flag.BoolVar(&all, "all", false, "install or uninstall on the system, Firefox and Java truststores") 27 | flag.BoolVar(&verbose, "v", false, "be verbose") 28 | flag.BoolVar(&help, "help", false, "show help") 29 | flag.Parse() 30 | 31 | if help { 32 | flag.Usage() 33 | os.Exit(0) 34 | } 35 | 36 | if len(flag.Args()) != 1 { 37 | flag.Usage() 38 | os.Exit(1) 39 | } 40 | 41 | var opts []truststore.Option 42 | if all { 43 | opts = append(opts, truststore.WithJava(), truststore.WithFirefox()) 44 | } else { 45 | if java { 46 | opts = append(opts, truststore.WithJava()) 47 | } 48 | if firefox { 49 | opts = append(opts, truststore.WithFirefox()) 50 | } 51 | } 52 | if noSystem { 53 | opts = append(opts, truststore.WithNoSystem()) 54 | } 55 | if verbose { 56 | opts = append(opts, truststore.WithDebug()) 57 | } 58 | 59 | if uninstall { 60 | if err := truststore.UninstallFile(flag.Arg(0), opts...); err != nil { 61 | fmt.Fprintln(os.Stderr, err) 62 | os.Exit(2) 63 | } 64 | } else { 65 | if err := truststore.InstallFile(flag.Arg(0), opts...); err != nil { 66 | fmt.Fprintln(os.Stderr, err) 67 | os.Exit(2) 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /errors.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018 The truststore Authors. All rights reserved. 2 | 3 | package truststore 4 | 5 | import ( 6 | "errors" 7 | "fmt" 8 | "os/exec" 9 | "path/filepath" 10 | ) 11 | 12 | var ( 13 | // ErrNotSupported is the error to indicate that the install of the 14 | // certificate is not supported on the system. 15 | ErrNotSupported = errors.New("install is not supported on this system") 16 | 17 | // ErrNotFound is the error to indicate that a cert was not found. 18 | ErrNotFound = errors.New("no certs found") 19 | 20 | // ErrInvalidCertificate is the error to indicate that a cert contains bad data. 21 | ErrInvalidCertificate = errors.New("invalid PEM data") 22 | 23 | // ErrTrustExists is the error returned when a trust already exists. 24 | ErrTrustExists = errors.New("trust already exists") 25 | 26 | // ErrTrustNotFound is the error returned when a trust does not exists. 27 | ErrTrustNotFound = errors.New("trust does not exists") 28 | 29 | // ErrTrustNotSupported is the error returned when a trust is not supported. 30 | ErrTrustNotSupported = errors.New("trust not supported") 31 | ) 32 | 33 | // CmdError is the error used when an executable fails. 34 | type CmdError struct { 35 | err error 36 | cmd *exec.Cmd 37 | out []byte 38 | } 39 | 40 | // NewCmdError creates a new CmdError. 41 | func NewCmdError(err error, cmd *exec.Cmd, out []byte) *CmdError { 42 | return &CmdError{ 43 | err: err, 44 | cmd: cmd, 45 | 46 | out: out, 47 | } 48 | } 49 | 50 | // Error implements the error interface. 51 | func (e *CmdError) Error() string { 52 | name := filepath.Base(e.cmd.Path) 53 | return fmt.Sprintf("failed to execute %s: %v", name, e.err) 54 | } 55 | 56 | // Err returns the internal error. 57 | func (e *CmdError) Err() error { 58 | return e.err 59 | } 60 | 61 | // Cmd returns the command executed. 62 | func (e *CmdError) Cmd() *exec.Cmd { 63 | return e.cmd 64 | } 65 | 66 | // Out returns the output of the command. 67 | func (e *CmdError) Out() []byte { 68 | return e.out 69 | } 70 | 71 | func wrapError(err error, msg string) error { 72 | if err == nil { 73 | return nil 74 | } 75 | return fmt.Errorf("%s: %w", msg, err) 76 | } 77 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/smallstep/truststore 2 | 3 | go 1.18 4 | 5 | require howett.net/plist v1.0.1 6 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= 2 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 3 | gopkg.in/yaml.v1 v1.0.0-20140924161607-9f9df34309c0/go.mod h1:WDnlLJ4WF5VGsH/HVa3CI79GS0ol3YnhVnKP89i0kNg= 4 | howett.net/plist v1.0.1 h1:37GdZ8tP09Q35o9ych3ehygcsL+HqKSwzctveSlarvM= 5 | howett.net/plist v1.0.1/go.mod h1:lqaXoTrLY4hg8tnEzNru53gicrbv7rrk+2xJA/7hw9g= 6 | -------------------------------------------------------------------------------- /truststore.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018 The truststore Authors. All rights reserved. 2 | 3 | package truststore 4 | 5 | import ( 6 | "bytes" 7 | "crypto/x509" 8 | "encoding/pem" 9 | "io" 10 | "log" 11 | "os" 12 | ) 13 | 14 | var prefix = "" 15 | var enableDebug bool 16 | 17 | func debug(format string, args ...interface{}) { 18 | if enableDebug { 19 | log.Printf(format, args...) 20 | } 21 | } 22 | 23 | // Trust is the interface that non-system trustores implement to add and remove 24 | // a certificate on its trustore. Right now we there are two implementations of 25 | // trust NSS (Firefox) and Java. 26 | type Trust interface { 27 | Name() string 28 | Install(filename string, cert *x509.Certificate) error 29 | Uninstall(filename string, cert *x509.Certificate) error 30 | Exists(cert *x509.Certificate) bool 31 | PreCheck() error 32 | } 33 | 34 | // Install installs the given certificate into the system truststore, and 35 | // optionally to the Firefox and Java trustores. 36 | func Install(cert *x509.Certificate, opts ...Option) error { 37 | filename, fn, err := saveTempCert(cert) 38 | defer fn() 39 | if err != nil { 40 | return err 41 | } 42 | return installCertificate(filename, cert, opts) 43 | } 44 | 45 | // InstallFile will read the certificate in the given file and install it to the 46 | // system truststore, and optionally to the Firefox and Java truststores. 47 | func InstallFile(filename string, opts ...Option) error { 48 | cert, err := ReadCertificate(filename) 49 | if err != nil { 50 | return err 51 | } 52 | return installCertificate(filename, cert, opts) 53 | } 54 | 55 | func installCertificate(filename string, cert *x509.Certificate, opts []Option) error { 56 | o := newOptions(opts) 57 | 58 | for _, t := range o.trusts { 59 | if err := t.PreCheck(); err != nil { 60 | debug(err.Error()) 61 | continue 62 | } 63 | if !t.Exists(cert) { 64 | if err := t.Install(filename, cert); err != nil { 65 | return err 66 | } 67 | } 68 | } 69 | 70 | if o.withNoSystem { 71 | return nil 72 | } 73 | 74 | return installPlatform(filename, cert) 75 | } 76 | 77 | // Uninstall removes the given certificate from the system truststore, and 78 | // optionally from the Firefox and Java truststres. 79 | func Uninstall(cert *x509.Certificate, opts ...Option) error { 80 | filename, fn, err := saveTempCert(cert) 81 | defer fn() 82 | if err != nil { 83 | return err 84 | } 85 | return uninstallCertificate(filename, cert, opts) 86 | } 87 | 88 | // UninstallFile reads the certificate in the given file and removes it from the 89 | // system truststore, and optionally to the Firefox and Java truststores. 90 | func UninstallFile(filename string, opts ...Option) error { 91 | cert, err := ReadCertificate(filename) 92 | if err != nil { 93 | return err 94 | } 95 | return uninstallCertificate(filename, cert, opts) 96 | } 97 | 98 | func uninstallCertificate(filename string, cert *x509.Certificate, opts []Option) error { 99 | o := newOptions(opts) 100 | 101 | for _, t := range o.trusts { 102 | if err := t.PreCheck(); err != nil { 103 | debug(err.Error()) 104 | continue 105 | } 106 | if err := t.Uninstall(filename, cert); err != nil { 107 | return err 108 | } 109 | } 110 | 111 | if o.withNoSystem { 112 | return nil 113 | } 114 | 115 | return uninstallPlatform(filename, cert) 116 | } 117 | 118 | // ReadCertificate reads a certificate file and returns a x509.Certificate struct. 119 | func ReadCertificate(filename string) (*x509.Certificate, error) { 120 | b, err := os.ReadFile(filename) 121 | if err != nil { 122 | return nil, err 123 | } 124 | 125 | // PEM format 126 | if bytes.HasPrefix(b, []byte("-----BEGIN ")) { 127 | b, err = os.ReadFile(filename) 128 | if err != nil { 129 | return nil, err 130 | } 131 | 132 | block, _ := pem.Decode(b) 133 | if block == nil || block.Type != "CERTIFICATE" { 134 | return nil, ErrInvalidCertificate 135 | } 136 | b = block.Bytes 137 | } 138 | 139 | // DER format (binary) 140 | crt, err := x509.ParseCertificate(b) 141 | return crt, wrapError(err, "error parsing "+filename) 142 | } 143 | 144 | // SaveCertificate saves the given x509.Certificate with the given filename. 145 | func SaveCertificate(filename string, cert *x509.Certificate) error { 146 | block := &pem.Block{ 147 | Type: "CERTIFICATE", 148 | Bytes: cert.Raw, 149 | } 150 | return os.WriteFile(filename, pem.EncodeToMemory(block), 0600) 151 | } 152 | 153 | type options struct { 154 | withNoSystem bool 155 | trusts map[string]Trust 156 | } 157 | 158 | func newOptions(opts []Option) *options { 159 | o := &options{ 160 | trusts: make(map[string]Trust), 161 | } 162 | 163 | for _, fn := range opts { 164 | fn(o) 165 | } 166 | return o 167 | } 168 | 169 | // Option is the type used to pass custom options. 170 | type Option func(*options) 171 | 172 | // WithTrust enables the given trust. 173 | func WithTrust(t Trust) Option { 174 | return func(o *options) { 175 | o.trusts[t.Name()] = t 176 | } 177 | } 178 | 179 | // WithJava enables the install or uninstall of a certificate in the Java 180 | // truststore. 181 | func WithJava() Option { 182 | t, _ := NewJavaTrust() 183 | return WithTrust(t) 184 | } 185 | 186 | // WithFirefox enables the install or uninstall of a certificate in the Firefox 187 | // truststore. 188 | func WithFirefox() Option { 189 | t, _ := NewNSSTrust() 190 | return WithTrust(t) 191 | } 192 | 193 | // WithNoSystem disables the install or uninstall of a certificate in the system 194 | // truststore. 195 | func WithNoSystem() Option { 196 | return func(o *options) { 197 | o.withNoSystem = true 198 | } 199 | } 200 | 201 | // WithDebug enables debug logging messages. 202 | func WithDebug() Option { 203 | return func(o *options) { 204 | enableDebug = true 205 | } 206 | } 207 | 208 | // WithPrefix sets a custom prefix for the truststore name. 209 | func WithPrefix(s string) Option { 210 | return func(o *options) { 211 | prefix = s 212 | } 213 | } 214 | 215 | func uniqueName(cert *x509.Certificate) string { 216 | switch { 217 | case prefix != "": 218 | return prefix + cert.SerialNumber.String() 219 | case cert.Subject.CommonName != "": 220 | return cert.Subject.CommonName + " " + cert.SerialNumber.String() 221 | default: 222 | return "Truststore Development CA " + cert.SerialNumber.String() 223 | } 224 | } 225 | 226 | func saveTempCert(cert *x509.Certificate) (string, func(), error) { 227 | f, err := os.CreateTemp(os.TempDir(), "truststore.*.pem") 228 | if err != nil { 229 | return "", func() {}, err 230 | } 231 | name := f.Name() 232 | clean := func() { 233 | os.Remove(name) 234 | } 235 | data := pem.EncodeToMemory(&pem.Block{ 236 | Type: "CERTIFICATE", 237 | Bytes: cert.Raw, 238 | }) 239 | n, err := f.Write(data) 240 | if err == nil && n < len(data) { 241 | err = io.ErrShortWrite 242 | } 243 | if err1 := f.Close(); err == nil { 244 | err = err1 245 | } 246 | return name, clean, err 247 | } 248 | -------------------------------------------------------------------------------- /truststore_darwin.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018 The truststore Authors. All rights reserved. 2 | // Copyright (c) 2018 The mkcert Authors. All rights reserved. 3 | 4 | package truststore 5 | 6 | import ( 7 | "bytes" 8 | "crypto/x509" 9 | "encoding/asn1" 10 | "fmt" 11 | "os" 12 | "os/exec" 13 | 14 | plist "howett.net/plist" 15 | ) 16 | 17 | var ( 18 | // NSSProfile is the path of the Firefox profiles. 19 | NSSProfile = os.Getenv("HOME") + "/Library/Application Support/Firefox/Profiles/*" 20 | 21 | // CertutilInstallHelp is the command to run on macOS to add NSS support. 22 | CertutilInstallHelp = "brew install nss" 23 | ) 24 | 25 | // https://github.com/golang/go/issues/24652#issuecomment-399826583 26 | var trustSettings []interface{} 27 | var _, _ = plist.Unmarshal(trustSettingsData, &trustSettings) 28 | var trustSettingsData = []byte(` 29 | 30 | 31 | kSecTrustSettingsPolicy 32 | 33 | KoZIhvdjZAED 34 | 35 | kSecTrustSettingsPolicyName 36 | sslServer 37 | kSecTrustSettingsResult 38 | 1 39 | 40 | 41 | kSecTrustSettingsPolicy 42 | 43 | KoZIhvdjZAEC 44 | 45 | kSecTrustSettingsPolicyName 46 | basicX509 47 | kSecTrustSettingsResult 48 | 1 49 | 50 | 51 | `) 52 | 53 | func installPlatform(filename string, cert *x509.Certificate) error { 54 | cmd := exec.Command("sudo", "security", "add-trusted-cert", "-d", "-k", "/Library/Keychains/System.keychain", filename) 55 | out, err := cmd.CombinedOutput() 56 | if err != nil { 57 | return NewCmdError(err, cmd, out) 58 | } 59 | 60 | // Make trustSettings explicit, as older Go does not know the defaults. 61 | // https://github.com/golang/go/issues/24652 62 | plistFile, err := os.CreateTemp("", "trust-settings") 63 | if err != nil { 64 | return wrapError(err, "failed to create temp file") 65 | } 66 | defer os.Remove(plistFile.Name()) 67 | 68 | //nolint:gosec // tolerable risk necessary for function 69 | cmd = exec.Command("sudo", "security", "trust-settings-export", "-d", plistFile.Name()) 70 | out, err = cmd.CombinedOutput() 71 | if err != nil { 72 | return NewCmdError(err, cmd, out) 73 | } 74 | 75 | plistData, err := os.ReadFile(plistFile.Name()) 76 | if err != nil { 77 | return wrapError(err, "failed to read trust settings") 78 | } 79 | 80 | var plistRoot map[string]interface{} 81 | _, err = plist.Unmarshal(plistData, &plistRoot) 82 | if err != nil { 83 | return wrapError(err, "failed to parse trust settings") 84 | } 85 | if v, ok := plistRoot["trustVersion"].(uint64); v != 1 || !ok { 86 | return fmt.Errorf("unsupported trust settings version: %v", plistRoot["trustVersion"]) 87 | } 88 | 89 | trustList := plistRoot["trustList"].(map[string]interface{}) 90 | rootSubjectASN1, _ := asn1.Marshal(cert.Subject.ToRDNSequence()) 91 | for key := range trustList { 92 | entry := trustList[key].(map[string]interface{}) 93 | if _, ok := entry["issuerName"]; !ok { 94 | continue 95 | } 96 | issuerName := entry["issuerName"].([]byte) 97 | if !bytes.Equal(rootSubjectASN1, issuerName) { 98 | continue 99 | } 100 | entry["trustSettings"] = trustSettings 101 | break 102 | } 103 | 104 | plistData, err = plist.MarshalIndent(plistRoot, plist.XMLFormat, "\t") 105 | if err != nil { 106 | return wrapError(err, "failed to serialize trust settings") 107 | } 108 | 109 | err = os.WriteFile(plistFile.Name(), plistData, 0600) 110 | if err != nil { 111 | return wrapError(err, "failed to write trust settings") 112 | } 113 | 114 | //nolint:gosec // tolerable risk necessary for function 115 | cmd = exec.Command("sudo", "security", "trust-settings-import", "-d", plistFile.Name()) 116 | out, err = cmd.CombinedOutput() 117 | if err != nil { 118 | return NewCmdError(err, cmd, out) 119 | } 120 | 121 | debug("certificate installed properly in macOS keychain") 122 | return nil 123 | } 124 | 125 | func uninstallPlatform(filename string, _ *x509.Certificate) error { 126 | cmd := exec.Command("sudo", "security", "remove-trusted-cert", "-d", filename) 127 | out, err := cmd.CombinedOutput() 128 | if err != nil { 129 | return NewCmdError(err, cmd, out) 130 | } 131 | 132 | debug("certificate uninstalled properly from macOS keychain") 133 | return nil 134 | } 135 | -------------------------------------------------------------------------------- /truststore_freebsd.go: -------------------------------------------------------------------------------- 1 | package truststore 2 | 3 | import ( 4 | "bytes" 5 | "crypto/x509" 6 | "fmt" 7 | "io/ioutil" 8 | "os" 9 | "os/exec" 10 | "strings" 11 | ) 12 | 13 | var ( 14 | // NSSProfile is the path of the Firefox profiles. 15 | NSSProfile = os.Getenv("HOME") + "/.mozilla/firefox/*" 16 | 17 | // CertutilInstallHelp is the command to add NSS support. 18 | CertutilInstallHelp = "" 19 | 20 | // SystemTrustFilename is the format used to name the root certificates. 21 | SystemTrustFilename string 22 | 23 | // SystemTrustCommand is the command used to update the system truststore. 24 | SystemTrustCommand []string 25 | ) 26 | 27 | func init() { 28 | if !pathExists("/usr/local/etc/ssl/certs") { 29 | err := os.Mkdir("/usr/local/etc/ssl/certs", 0755) 30 | if err != nil { 31 | SystemTrustCommand = nil 32 | debug(err.Error()) 33 | return 34 | } 35 | } 36 | SystemTrustCommand = []string{"certctl", "rehash"} 37 | SystemTrustFilename = "/usr/local/etc/ssl/certs/%s.crt" 38 | } 39 | 40 | func pathExists(path string) bool { 41 | _, err := os.Stat(path) 42 | return err == nil 43 | } 44 | 45 | func systemTrustFilename(cert *x509.Certificate) string { 46 | return fmt.Sprintf(SystemTrustFilename, strings.Replace(uniqueName(cert), " ", "_", -1)) 47 | } 48 | 49 | func installPlatform(filename string, cert *x509.Certificate) error { 50 | if SystemTrustCommand == nil { 51 | return ErrNotSupported 52 | } 53 | 54 | data, err := ioutil.ReadFile(filename) 55 | if err != nil { 56 | return err 57 | } 58 | 59 | cmd := CommandWithSudo("tee", systemTrustFilename(cert)) 60 | cmd.Stdin = bytes.NewReader(data) 61 | out, err := cmd.CombinedOutput() 62 | if err != nil { 63 | return NewCmdError(err, cmd, out) 64 | } 65 | 66 | cmd = CommandWithSudo(SystemTrustCommand...) 67 | out, err = cmd.CombinedOutput() 68 | if err != nil { 69 | return NewCmdError(err, cmd, out) 70 | } 71 | 72 | debug("certificate installed properly in FreeBSD trusts") 73 | return nil 74 | } 75 | 76 | func uninstallPlatform(filename string, cert *x509.Certificate) error { 77 | if SystemTrustCommand == nil { 78 | return ErrNotSupported 79 | } 80 | 81 | cmd := CommandWithSudo("rm", "-f", systemTrustFilename(cert)) 82 | out, err := cmd.CombinedOutput() 83 | if err != nil { 84 | return NewCmdError(err, cmd, out) 85 | } 86 | 87 | cmd = CommandWithSudo(SystemTrustCommand...) 88 | out, err = cmd.CombinedOutput() 89 | if err != nil { 90 | return NewCmdError(err, cmd, out) 91 | } 92 | 93 | debug("certificate uninstalled properly from FreeBSD trusts") 94 | return nil 95 | } 96 | 97 | func CommandWithSudo(cmd ...string) *exec.Cmd { 98 | if _, err := exec.LookPath("sudo"); err != nil { 99 | return exec.Command(cmd[0], cmd[1:]...) 100 | } 101 | return exec.Command("sudo", append([]string{"--"}, cmd...)...) 102 | } 103 | -------------------------------------------------------------------------------- /truststore_java.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018 The truststore Authors. All rights reserved. 2 | // Copyright (c) 2018 The mkcert Authors. All rights reserved. 3 | 4 | package truststore 5 | 6 | import ( 7 | "bytes" 8 | "crypto/sha1" //nolint:gosec // not used for cryptographic purposes 9 | "crypto/sha256" 10 | "crypto/x509" 11 | "encoding/hex" 12 | "fmt" 13 | "hash" 14 | "os" 15 | "os/exec" 16 | "path/filepath" 17 | "runtime" 18 | "strings" 19 | ) 20 | 21 | // JavaStorePass is the default store password of the keystore. 22 | var JavaStorePass = "changeit" 23 | 24 | // JavaTrust implements a Trust for the Java runtime. 25 | type JavaTrust struct { 26 | keytoolPath string 27 | cacertsPath string 28 | } 29 | 30 | // NewJavaTrust initializes a new JavaTrust if the environment has java installed. 31 | func NewJavaTrust() (*JavaTrust, error) { 32 | home := os.Getenv("JAVA_HOME") 33 | if home == "" { 34 | return nil, ErrTrustNotFound 35 | } 36 | 37 | var keytoolPath, cacertsPath string 38 | if runtime.GOOS == "windows" { 39 | keytoolPath = filepath.Join(home, "bin", "keytool.exe") 40 | } else { 41 | keytoolPath = filepath.Join(home, "bin", "keytool") 42 | } 43 | 44 | if _, err := os.Stat(keytoolPath); err != nil { 45 | return nil, ErrTrustNotFound 46 | } 47 | 48 | _, err := os.Stat(filepath.Join(home, "lib", "security", "cacerts")) 49 | if err == nil { 50 | cacertsPath = filepath.Join(home, "lib", "security", "cacerts") 51 | } 52 | 53 | _, err = os.Stat(filepath.Join(home, "jre", "lib", "security", "cacerts")) 54 | if err == nil { 55 | cacertsPath = filepath.Join(home, "jre", "lib", "security", "cacerts") 56 | } 57 | 58 | return &JavaTrust{ 59 | keytoolPath: keytoolPath, 60 | cacertsPath: cacertsPath, 61 | }, nil 62 | } 63 | 64 | // Name implement the Trust interface. 65 | func (t *JavaTrust) Name() string { 66 | return "java" 67 | } 68 | 69 | // Install implements the Trust interface. 70 | func (t *JavaTrust) Install(filename string, cert *x509.Certificate) error { 71 | args := []string{ 72 | "-importcert", "-noprompt", 73 | "-keystore", t.cacertsPath, 74 | "-storepass", JavaStorePass, 75 | "-file", filename, 76 | "-alias", uniqueName(cert), 77 | } 78 | 79 | //nolint:gosec // tolerable risk necessary for function 80 | cmd := exec.Command(t.keytoolPath, args...) 81 | if out, err := execKeytool(cmd); err != nil { 82 | return NewCmdError(err, cmd, out) 83 | } 84 | 85 | debug("certificate installed properly in Java keystore") 86 | return nil 87 | } 88 | 89 | // Uninstall implements the Trust interface. 90 | func (t *JavaTrust) Uninstall(_ string, cert *x509.Certificate) error { 91 | args := []string{ 92 | "-delete", 93 | "-alias", uniqueName(cert), 94 | "-keystore", t.cacertsPath, 95 | "-storepass", JavaStorePass, 96 | } 97 | 98 | //nolint:gosec // tolerable risk necessary for function 99 | cmd := exec.Command(t.keytoolPath, args...) 100 | out, err := execKeytool(cmd) 101 | if bytes.Contains(out, []byte("does not exist")) { 102 | return nil 103 | } 104 | if err != nil { 105 | return NewCmdError(err, cmd, out) 106 | } 107 | 108 | debug("certificate uninstalled properly from the Java keystore") 109 | return nil 110 | } 111 | 112 | // Exists implements the Trust interface. 113 | func (t *JavaTrust) Exists(cert *x509.Certificate) bool { 114 | if t == nil { 115 | return false 116 | } 117 | 118 | // exists returns true if the given x509.Certificate's fingerprint 119 | // is in the keytool -list output 120 | exists := func(c *x509.Certificate, h hash.Hash, keytoolOutput []byte) bool { 121 | h.Write(c.Raw) 122 | fp := strings.ToUpper(hex.EncodeToString(h.Sum(nil))) 123 | return bytes.Contains(keytoolOutput, []byte(fp)) 124 | } 125 | 126 | //nolint:gosec // tolerable risk necessary for function 127 | cmd := exec.Command(t.keytoolPath, "-list", "-keystore", t.cacertsPath, "-storepass", JavaStorePass) 128 | keytoolOutput, err := cmd.CombinedOutput() 129 | if err != nil { 130 | debug("failed to execute \"keytool -list\": %s\n\n%s", err, keytoolOutput) 131 | return false 132 | } 133 | 134 | // keytool outputs SHA1 and SHA256 (Java 9+) certificates in uppercase hex 135 | // with each octet pair delimitated by ":". Drop them from the keytool output 136 | keytoolOutput = bytes.ReplaceAll(keytoolOutput, []byte(":"), nil) 137 | 138 | // pre-Java 9 uses SHA1 fingerprints 139 | //nolint:gosec // not used for cryptographic purposes 140 | s1, s256 := sha1.New(), sha256.New() 141 | return exists(cert, s1, keytoolOutput) || exists(cert, s256, keytoolOutput) 142 | } 143 | 144 | // PreCheck implements the Trust interface. 145 | func (t *JavaTrust) PreCheck() error { 146 | if t != nil { 147 | return nil 148 | } 149 | return fmt.Errorf("define JAVA_HOME environment variable to use the Java trust") 150 | } 151 | 152 | // execKeytool will execute a "keytool" command and if needed re-execute 153 | // the command wrapped in 'sudo' to work around file permissions. 154 | func execKeytool(cmd *exec.Cmd) ([]byte, error) { 155 | out, err := cmd.CombinedOutput() 156 | if err != nil && bytes.Contains(out, []byte("java.io.FileNotFoundException")) && runtime.GOOS != "windows" { 157 | origArgs := cmd.Args[1:] 158 | //nolint:gosec // tolerable risk necessary for function 159 | cmd = exec.Command("sudo", cmd.Path) 160 | cmd.Args = append(cmd.Args, origArgs...) 161 | cmd.Env = []string{ 162 | "JAVA_HOME=" + os.Getenv("JAVA_HOME"), 163 | } 164 | out, err = cmd.CombinedOutput() 165 | } 166 | return out, err 167 | } 168 | -------------------------------------------------------------------------------- /truststore_linux.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018 The truststore Authors. All rights reserved. 2 | // Copyright (c) 2018 The mkcert Authors. All rights reserved. 3 | 4 | package truststore 5 | 6 | import ( 7 | "bytes" 8 | "crypto/x509" 9 | "fmt" 10 | "os" 11 | "os/exec" 12 | "strings" 13 | ) 14 | 15 | var ( 16 | // NSSProfile is the path of the Firefox profiles. 17 | NSSProfile = os.Getenv("HOME") + "/.mozilla/firefox/*" 18 | 19 | // CertutilInstallHelp is the command to run on linux to add NSS support. 20 | CertutilInstallHelp = `apt install libnss3-tools" or "yum install nss-tools` 21 | 22 | // SystemTrustFilename is the format used to name the root certificates. 23 | SystemTrustFilename string 24 | 25 | // SystemTrustCommand is the command used to update the system truststore. 26 | SystemTrustCommand []string 27 | ) 28 | 29 | func init() { 30 | switch { 31 | case pathExists("/etc/pki/ca-trust/source/anchors/"): 32 | SystemTrustFilename = "/etc/pki/ca-trust/source/anchors/%s.pem" 33 | SystemTrustCommand = []string{"update-ca-trust", "extract"} 34 | case pathExists("/usr/local/share/ca-certificates/"): 35 | SystemTrustFilename = "/usr/local/share/ca-certificates/%s.crt" 36 | SystemTrustCommand = []string{"update-ca-certificates"} 37 | case pathExists("/usr/share/pki/trust/anchors/"): 38 | SystemTrustFilename = "/usr/share/pki/trust/anchors/%s.crt" 39 | SystemTrustCommand = []string{"update-ca-certificates"} 40 | case pathExists("/etc/ca-certificates/trust-source/anchors/"): 41 | SystemTrustFilename = "/etc/ca-certificates/trust-source/anchors/%s.crt" 42 | SystemTrustCommand = []string{"trust", "extract-compat"} 43 | case pathExists("/etc/ssl/certs/"): 44 | SystemTrustFilename = "/etc/ssl/certs/%s.crt" 45 | SystemTrustCommand = []string{"trust", "extract-compat"} 46 | } 47 | } 48 | 49 | func pathExists(path string) bool { 50 | _, err := os.Stat(path) 51 | return err == nil 52 | } 53 | 54 | func systemTrustFilename(cert *x509.Certificate) string { 55 | return fmt.Sprintf(SystemTrustFilename, strings.ReplaceAll(uniqueName(cert), " ", "_")) 56 | } 57 | 58 | func installPlatform(filename string, cert *x509.Certificate) error { 59 | if SystemTrustCommand == nil { 60 | return ErrNotSupported 61 | } 62 | 63 | data, err := os.ReadFile(filename) 64 | if err != nil { 65 | return err 66 | } 67 | 68 | cmd := CommandWithSudo("tee", systemTrustFilename(cert)) 69 | cmd.Stdin = bytes.NewReader(data) 70 | out, err := cmd.CombinedOutput() 71 | if err != nil { 72 | return NewCmdError(err, cmd, out) 73 | } 74 | 75 | cmd = CommandWithSudo(SystemTrustCommand...) 76 | out, err = cmd.CombinedOutput() 77 | if err != nil { 78 | return NewCmdError(err, cmd, out) 79 | } 80 | 81 | debug("certificate installed properly in linux trusts") 82 | return nil 83 | } 84 | 85 | func uninstallPlatform(_ string, cert *x509.Certificate) error { 86 | if SystemTrustCommand == nil { 87 | return ErrNotSupported 88 | } 89 | 90 | cmd := CommandWithSudo("rm", "-f", systemTrustFilename(cert)) 91 | out, err := cmd.CombinedOutput() 92 | if err != nil { 93 | return NewCmdError(err, cmd, out) 94 | } 95 | 96 | cmd = CommandWithSudo(SystemTrustCommand...) 97 | out, err = cmd.CombinedOutput() 98 | if err != nil { 99 | return NewCmdError(err, cmd, out) 100 | } 101 | 102 | debug("certificate uninstalled properly from linux trusts") 103 | return nil 104 | } 105 | 106 | func CommandWithSudo(cmd ...string) *exec.Cmd { 107 | if _, err := exec.LookPath("sudo"); err != nil { 108 | //nolint:gosec // tolerable risk necessary for function 109 | return exec.Command(cmd[0], cmd[1:]...) 110 | } 111 | //nolint:gosec // tolerable risk necessary for function 112 | return exec.Command("sudo", append([]string{"--"}, cmd...)...) 113 | } 114 | -------------------------------------------------------------------------------- /truststore_nss.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018 The truststore Authors. All rights reserved. 2 | // Copyright (c) 2018 The mkcert Authors. All rights reserved. 3 | 4 | package truststore 5 | 6 | import ( 7 | "crypto/x509" 8 | "fmt" 9 | "os" 10 | "os/exec" 11 | "path/filepath" 12 | "runtime" 13 | "strings" 14 | ) 15 | 16 | var nssDB = filepath.Join(os.Getenv("HOME"), ".pki", "nssdb") 17 | 18 | // NSSTrust implements a Trust for Firefox or other NSS based applications. 19 | type NSSTrust struct { 20 | certutilPath string 21 | } 22 | 23 | // NewNSSTrust creates a new NSSTrust. 24 | func NewNSSTrust() (*NSSTrust, error) { 25 | var err error 26 | var certutilPath string 27 | switch runtime.GOOS { 28 | case "darwin": 29 | certutilPath, err = exec.LookPath("certutil") 30 | if err != nil { 31 | cmd := exec.Command("brew", "--prefix", "nss") 32 | out, err1 := cmd.Output() 33 | if err1 != nil { 34 | return nil, NewCmdError(err1, cmd, out) 35 | } 36 | certutilPath = filepath.Join(strings.TrimSpace(string(out)), "bin", "certutil") 37 | if _, err = os.Stat(certutilPath); err != nil { 38 | return nil, err 39 | } 40 | } 41 | case "linux": 42 | if certutilPath, err = exec.LookPath("certutil"); err != nil { 43 | return nil, err 44 | } 45 | default: 46 | return nil, ErrTrustNotSupported 47 | } 48 | 49 | return &NSSTrust{ 50 | certutilPath: certutilPath, 51 | }, nil 52 | } 53 | 54 | // Name implements the Trust interface. 55 | func (t *NSSTrust) Name() string { 56 | return "nss" 57 | } 58 | 59 | // Install implements the Trust interface. 60 | func (t *NSSTrust) Install(filename string, cert *x509.Certificate) error { 61 | // install certificate in all profiles 62 | if forEachNSSProfile(func(profile string) { 63 | //nolint:gosec // tolerable risk necessary for function 64 | cmd := exec.Command(t.certutilPath, "-A", "-d", profile, "-t", "C,,", "-n", uniqueName(cert), "-i", filename) 65 | out, err := cmd.CombinedOutput() 66 | if err != nil { 67 | debug("failed to execute \"certutil -A\": %s\n\n%s", err, out) 68 | } 69 | }) == 0 { 70 | return fmt.Errorf("not NSS security databases found") 71 | } 72 | 73 | // check for the cert in all profiles 74 | if !t.Exists(cert) { 75 | return fmt.Errorf("certificate cannot be installed in NSS security databases") 76 | } 77 | 78 | debug("certificate installed properly in NSS security databases") 79 | return nil 80 | } 81 | 82 | // Uninstall implements the Trust interface. 83 | func (t *NSSTrust) Uninstall(_ string, cert *x509.Certificate) (err error) { 84 | forEachNSSProfile(func(profile string) { 85 | if err != nil { 86 | return 87 | } 88 | // skip if not found 89 | //nolint:gosec // tolerable risk necessary for function 90 | if err := exec.Command(t.certutilPath, "-V", "-d", profile, "-u", "L", "-n", uniqueName(cert)).Run(); err != nil { 91 | return 92 | } 93 | // delete certificate 94 | //nolint:gosec // tolerable risk necessary for function 95 | cmd := exec.Command(t.certutilPath, "-D", "-d", profile, "-n", uniqueName(cert)) 96 | out, err1 := cmd.CombinedOutput() 97 | if err1 != nil { 98 | err = NewCmdError(err1, cmd, out) 99 | } 100 | }) 101 | if err == nil { 102 | debug("certificate uninstalled properly from NSS security databases") 103 | } 104 | return 105 | } 106 | 107 | // Exists implements the Trust interface. Exists checks if the certificate is 108 | // already installed. 109 | func (t *NSSTrust) Exists(cert *x509.Certificate) bool { 110 | success := true 111 | if forEachNSSProfile(func(profile string) { 112 | //nolint:gosec // tolerable risk necessary for function 113 | err := exec.Command(t.certutilPath, "-V", "-d", profile, "-u", "L", "-n", uniqueName(cert)).Run() 114 | if err != nil { 115 | success = false 116 | } 117 | }) == 0 { 118 | success = false 119 | } 120 | return success 121 | } 122 | 123 | // PreCheck implements the Trust interface. 124 | func (t *NSSTrust) PreCheck() error { 125 | if t != nil { 126 | if forEachNSSProfile(func(_ string) {}) == 0 { 127 | return fmt.Errorf("not NSS security databases found") 128 | } 129 | return nil 130 | } 131 | 132 | if CertutilInstallHelp == "" { 133 | return fmt.Errorf("note: NSS support is not available on your platform") 134 | } 135 | 136 | return fmt.Errorf(`warning: "certutil" is not available, install "certutil" with "%s" and try again`, CertutilInstallHelp) 137 | } 138 | 139 | func forEachNSSProfile(f func(profile string)) (found int) { 140 | profiles, _ := filepath.Glob(NSSProfile) 141 | if _, err := os.Stat(nssDB); err == nil { 142 | profiles = append(profiles, nssDB) 143 | } 144 | if len(profiles) == 0 { 145 | return 146 | } 147 | for _, profile := range profiles { 148 | if stat, err := os.Stat(profile); err != nil || !stat.IsDir() { 149 | continue 150 | } 151 | if _, err := os.Stat(filepath.Join(profile, "cert9.db")); err == nil { 152 | f("sql:" + profile) 153 | found++ 154 | continue 155 | } 156 | if _, err := os.Stat(filepath.Join(profile, "cert8.db")); err == nil { 157 | f("dbm:" + profile) 158 | found++ 159 | } 160 | } 161 | return 162 | } 163 | -------------------------------------------------------------------------------- /truststore_others.go: -------------------------------------------------------------------------------- 1 | //go:build !linux && !darwin && !windows && !freebsd 2 | // +build !linux,!darwin,!windows,!freebsd 3 | 4 | package truststore 5 | 6 | import "crypto/x509" 7 | 8 | var ( 9 | // NSSProfile is the path of the Firefox profiles. 10 | NSSProfile = "" 11 | 12 | // CertutilInstallHelp is the command to add NSS support. 13 | CertutilInstallHelp = "" 14 | ) 15 | 16 | func installPlatform(string, *x509.Certificate) error { 17 | return ErrTrustNotSupported 18 | } 19 | 20 | func uninstallPlatform(string, *x509.Certificate) error { 21 | return ErrTrustNotSupported 22 | } 23 | -------------------------------------------------------------------------------- /truststore_windows.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018 The truststore Authors. All rights reserved. 2 | // Copyright (c) 2018 The mkcert Authors. All rights reserved. 3 | 4 | package truststore 5 | 6 | import ( 7 | "crypto/x509" 8 | "fmt" 9 | "math/big" 10 | "os" 11 | "syscall" 12 | "unsafe" 13 | ) 14 | 15 | var ( 16 | // NSSProfile is the path of the Firefox profiles. 17 | NSSProfile = os.Getenv("USERPROFILE") + "\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles" 18 | 19 | // CertutilInstallHelp is the command to run on windows to add NSS support. 20 | // Certutils is not supported on Windows. 21 | CertutilInstallHelp = "" 22 | ) 23 | 24 | var ( 25 | modcrypt32 = syscall.NewLazyDLL("crypt32.dll") 26 | procCertAddEncodedCertificateToStore = modcrypt32.NewProc("CertAddEncodedCertificateToStore") 27 | procCertCloseStore = modcrypt32.NewProc("CertCloseStore") 28 | procCertDeleteCertificateFromStore = modcrypt32.NewProc("CertDeleteCertificateFromStore") 29 | procCertDuplicateCertificateContext = modcrypt32.NewProc("CertDuplicateCertificateContext") 30 | procCertEnumCertificatesInStore = modcrypt32.NewProc("CertEnumCertificatesInStore") 31 | procCertOpenSystemStoreW = modcrypt32.NewProc("CertOpenSystemStoreW") 32 | ) 33 | 34 | func installPlatform(filename string, cert *x509.Certificate) error { 35 | // Open root store 36 | store, err := openWindowsRootStore() 37 | if err != nil { 38 | return wrapError(err, "open root store failed") 39 | } 40 | defer store.close() 41 | 42 | // Add cert 43 | if err := store.addCert(cert.Raw); err != nil { 44 | return wrapError(err, "add cert failed") 45 | } 46 | 47 | debug("certificate installed properly in windows trusts") 48 | return nil 49 | } 50 | 51 | func uninstallPlatform(filename string, cert *x509.Certificate) error { 52 | // We'll just remove all certs with the same serial number 53 | // Open root store 54 | store, err := openWindowsRootStore() 55 | if err != nil { 56 | return wrapError(err, "open root store failed") 57 | } 58 | defer store.close() 59 | 60 | // Do the deletion 61 | deletedAny, err := store.deleteCertsWithSerial(cert.SerialNumber) 62 | if err != nil { 63 | return wrapError(err, "delete cert failed") 64 | } 65 | if !deletedAny { 66 | return ErrNotFound 67 | } 68 | 69 | debug("certificate uninstalled properly from windows trusts") 70 | return nil 71 | } 72 | 73 | type windowsRootStore uintptr 74 | 75 | func openWindowsRootStore() (windowsRootStore, error) { 76 | store, _, err := procCertOpenSystemStoreW.Call(0, uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr("ROOT")))) 77 | if store != 0 { 78 | return windowsRootStore(store), nil 79 | } 80 | return 0, fmt.Errorf("cannot open windows root store: %v", err) 81 | } 82 | 83 | func (w windowsRootStore) close() error { 84 | ret, _, err := procCertCloseStore.Call(uintptr(w), 0) 85 | if ret != 0 { 86 | return nil 87 | } 88 | return fmt.Errorf("cannot close windows root store: %v", err) 89 | } 90 | 91 | func (w windowsRootStore) addCert(cert []byte) error { 92 | // TODO: ok to always overwrite? 93 | ret, _, err := procCertAddEncodedCertificateToStore.Call( 94 | uintptr(w), // HCERTSTORE hCertStore 95 | uintptr(syscall.X509_ASN_ENCODING|syscall.PKCS_7_ASN_ENCODING), // DWORD dwCertEncodingType 96 | uintptr(unsafe.Pointer(&cert[0])), // const BYTE *pbCertEncoded 97 | uintptr(len(cert)), // DWORD cbCertEncoded 98 | 3, // DWORD dwAddDisposition (CERT_STORE_ADD_REPLACE_EXISTING is 3) 99 | 0, // PCCERT_CONTEXT *ppCertContext 100 | ) 101 | if ret != 0 { 102 | return nil 103 | } 104 | return fmt.Errorf("Failed adding cert: %v", err) 105 | } 106 | 107 | func (w windowsRootStore) deleteCertsWithSerial(serial *big.Int) (bool, error) { 108 | // Go over each, deleting the ones we find 109 | var cert *syscall.CertContext 110 | deletedAny := false 111 | for { 112 | // Next enum 113 | certPtr, _, err := procCertEnumCertificatesInStore.Call(uintptr(w), uintptr(unsafe.Pointer(cert))) 114 | if cert = (*syscall.CertContext)(unsafe.Pointer(certPtr)); cert == nil { 115 | if errno, ok := err.(syscall.Errno); ok && errno == 0x80092004 { 116 | break 117 | } 118 | return deletedAny, fmt.Errorf("Failed enumerating certs: %v", err) 119 | } 120 | // Parse cert 121 | certBytes := (*[1 << 20]byte)(unsafe.Pointer(cert.EncodedCert))[:cert.Length] 122 | parsedCert, err := x509.ParseCertificate(certBytes) 123 | // We'll just ignore parse failures for now 124 | if err == nil && parsedCert.SerialNumber != nil && parsedCert.SerialNumber.Cmp(serial) == 0 { 125 | // Duplicate the context so it doesn't stop the enum when we delete it 126 | dupCertPtr, _, err := procCertDuplicateCertificateContext.Call(uintptr(unsafe.Pointer(cert))) 127 | if dupCertPtr == 0 { 128 | return deletedAny, fmt.Errorf("Failed duplicating context: %v", err) 129 | } 130 | if ret, _, err := procCertDeleteCertificateFromStore.Call(dupCertPtr); ret == 0 { 131 | return deletedAny, fmt.Errorf("Failed deleting certificate: %v", err) 132 | } 133 | deletedAny = true 134 | } 135 | } 136 | return deletedAny, nil 137 | } 138 | --------------------------------------------------------------------------------