├── .go-version ├── test-fixtures ├── capath-with-symlinks │ ├── thawte.pem │ └── securetrust.pem ├── capath │ ├── securetrust.pem │ └── thawte.pem └── cafile │ └── cacert.pem ├── CHANGELOG.md ├── go.mod ├── go.sum ├── Makefile ├── .travis.yml ├── .golangci.yml ├── rootcerts_base.go ├── doc.go ├── rootcerts_darwin_test.go ├── .github ├── pull_request_template.md ├── CODEOWNERS ├── dependabot.yaml └── workflows │ └── build_test.yml ├── rootcerts_darwin.go ├── README.md ├── rootcerts_test.go ├── rootcerts.go └── LICENSE /.go-version: -------------------------------------------------------------------------------- 1 | 1.23 2 | -------------------------------------------------------------------------------- /test-fixtures/capath-with-symlinks/thawte.pem: -------------------------------------------------------------------------------- 1 | ../capath/thawte.pem -------------------------------------------------------------------------------- /test-fixtures/capath-with-symlinks/securetrust.pem: -------------------------------------------------------------------------------- 1 | ../capath/securetrust.pem -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## Unreleased 2 | 3 | ### Improvements 4 | 5 | ### Changes 6 | 7 | ### Fixed 8 | 9 | ### Security 10 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/hashicorp/go-rootcerts 2 | 3 | go 1.23 4 | 5 | require github.com/mitchellh/go-homedir v1.1.0 6 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= 2 | github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= 3 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | TEST?=./... 2 | 3 | test: 4 | go test $(TEST) $(TESTARGS) -timeout=3s -parallel=4 5 | go vet $(TEST) 6 | go test $(TEST) -race 7 | go test $(TEST) -v -coverprofile=coverage.out 8 | 9 | .PHONY: test 10 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | # Copyright IBM Corp. 2016, 2025 2 | # SPDX-License-Identifier: MPL-2.0 3 | 4 | sudo: false 5 | 6 | language: go 7 | 8 | go: 9 | - 1.6 10 | 11 | branches: 12 | only: 13 | - master 14 | 15 | script: make test 16 | -------------------------------------------------------------------------------- /.golangci.yml: -------------------------------------------------------------------------------- 1 | # Copyright IBM Corp. 2016, 2025 2 | # SPDX-License-Identifier: MPL-2.0 3 | 4 | linters: 5 | disable-all: true 6 | enable: 7 | - errcheck 8 | - gosimple 9 | - unused 10 | - govet 11 | output_format: colored-line-number 12 | -------------------------------------------------------------------------------- /rootcerts_base.go: -------------------------------------------------------------------------------- 1 | // Copyright IBM Corp. 2016, 2025 2 | // SPDX-License-Identifier: MPL-2.0 3 | 4 | // +build !darwin 5 | 6 | package rootcerts 7 | 8 | import "crypto/x509" 9 | 10 | // LoadSystemCAs does nothing on non-Darwin systems. We return nil so that 11 | // default behavior of standard TLS config libraries is triggered, which is to 12 | // load system certs. 13 | func LoadSystemCAs() (*x509.CertPool, error) { 14 | return nil, nil 15 | } 16 | -------------------------------------------------------------------------------- /doc.go: -------------------------------------------------------------------------------- 1 | // Copyright IBM Corp. 2016, 2025 2 | // SPDX-License-Identifier: MPL-2.0 3 | 4 | // Package rootcerts contains functions to aid in loading CA certificates for 5 | // TLS connections. 6 | // 7 | // In addition, its default behavior on Darwin works around an open issue [1] 8 | // in Go's crypto/x509 that prevents certicates from being loaded from the 9 | // System or Login keychains. 10 | // 11 | // [1] https://github.com/golang/go/issues/14514 12 | package rootcerts 13 | -------------------------------------------------------------------------------- /rootcerts_darwin_test.go: -------------------------------------------------------------------------------- 1 | // Copyright IBM Corp. 2016, 2025 2 | // SPDX-License-Identifier: MPL-2.0 3 | 4 | package rootcerts 5 | 6 | import "testing" 7 | 8 | func TestSystemCAsOnDarwin(t *testing.T) { 9 | _, err := LoadSystemCAs() 10 | if err != nil { 11 | t.Fatalf("Got error: %s", err) 12 | } 13 | } 14 | 15 | func TestCertKeychains(t *testing.T) { 16 | keychains := certKeychains() 17 | if len(keychains) != 3 { 18 | t.Fatalf("Expected 3 keychains, got %#v", keychains) 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | 2 | ## Description 3 | 4 | 5 | 6 | ## Related Issue 7 | 8 | 9 | 10 | ## How Has This Been Tested? 11 | 12 | 13 | -------------------------------------------------------------------------------- /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | # Each line is a file pattern followed by one or more owners. 2 | # More on CODEOWNERS files: https://help.github.com/en/github/creating-cloning-and-archiving-repositories/about-code-owners 3 | 4 | # Default owner 5 | * @hashicorp/team-ip-compliance 6 | 7 | # Add override rules below. Each line is a file/folder pattern followed by one or more owners. 8 | # Being an owner means those groups or individuals will be added as reviewers to PRs affecting 9 | # those areas of the code. 10 | # Examples: 11 | # /docs/ @docs-team 12 | # *.js @js-team 13 | # *.go @go-team 14 | -------------------------------------------------------------------------------- /.github/dependabot.yaml: -------------------------------------------------------------------------------- 1 | # Copyright IBM Corp. 2016, 2025 2 | # SPDX-License-Identifier: MPL-2.0 3 | 4 | version: 2 5 | 6 | updates: 7 | - package-ecosystem: "github-actions" 8 | directory: "/" 9 | schedule: 10 | interval: "weekly" 11 | day: "sunday" 12 | commit-message: 13 | prefix: "[chore] : " 14 | groups: 15 | actions: 16 | patterns: 17 | - "*" 18 | 19 | - package-ecosystem: "gomod" 20 | directory: "/" 21 | schedule: 22 | interval: "weekly" 23 | day: "sunday" 24 | commit-message: 25 | prefix: "[chore] : " 26 | groups: 27 | go: 28 | patterns: 29 | - "*" 30 | applies-to: "version-updates" 31 | go-security: 32 | patterns: 33 | - "*" 34 | applies-to: "security-updates" -------------------------------------------------------------------------------- /.github/workflows/build_test.yml: -------------------------------------------------------------------------------- 1 | name: Build and Test Workflow 2 | 3 | on: 4 | pull_request: 5 | branches: [master] 6 | 7 | jobs: 8 | build: 9 | runs-on: ubuntu-latest 10 | 11 | steps: 12 | - name: Checkout Code 13 | uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 14 | - name: Setup Go 15 | uses: actions/setup-go@d35c59abb061a4a6fb18e82ac0862c26744d6ab5 # v5.5.0 16 | with: 17 | go-version: '1.23' 18 | - name: Run golangci-lint 19 | uses: golangci/golangci-lint-action@08e2f20817b15149a52b5b3ebe7de50aff2ba8c5 20 | - name: Test Go 21 | run: make test 22 | - name: Upload coverage report 23 | uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 24 | with: 25 | path: coverage.out 26 | name: Coverage-report 27 | - name: Display coverage report 28 | run: go tool cover -func=coverage.out 29 | - name: Build Go 30 | run: go build ./... 31 | -------------------------------------------------------------------------------- /rootcerts_darwin.go: -------------------------------------------------------------------------------- 1 | // Copyright IBM Corp. 2016, 2025 2 | // SPDX-License-Identifier: MPL-2.0 3 | 4 | package rootcerts 5 | 6 | import ( 7 | "crypto/x509" 8 | "os/exec" 9 | "path" 10 | 11 | "github.com/mitchellh/go-homedir" 12 | ) 13 | 14 | // LoadSystemCAs has special behavior on Darwin systems to work around 15 | func LoadSystemCAs() (*x509.CertPool, error) { 16 | pool := x509.NewCertPool() 17 | 18 | for _, keychain := range certKeychains() { 19 | err := addCertsFromKeychain(pool, keychain) 20 | if err != nil { 21 | return nil, err 22 | } 23 | } 24 | 25 | return pool, nil 26 | } 27 | 28 | func addCertsFromKeychain(pool *x509.CertPool, keychain string) error { 29 | cmd := exec.Command("/usr/bin/security", "find-certificate", "-a", "-p", keychain) 30 | data, err := cmd.Output() 31 | if err != nil { 32 | return err 33 | } 34 | 35 | pool.AppendCertsFromPEM(data) 36 | 37 | return nil 38 | } 39 | 40 | func certKeychains() []string { 41 | keychains := []string{ 42 | "/System/Library/Keychains/SystemRootCertificates.keychain", 43 | "/Library/Keychains/System.keychain", 44 | } 45 | home, err := homedir.Dir() 46 | if err == nil { 47 | loginKeychain := path.Join(home, "Library", "Keychains", "login.keychain") 48 | keychains = append(keychains, loginKeychain) 49 | } 50 | return keychains 51 | } 52 | -------------------------------------------------------------------------------- /test-fixtures/capath/securetrust.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIDuDCCAqCgAwIBAgIQDPCOXAgWpa1Cf/DrJxhZ0DANBgkqhkiG9w0BAQUFADBI 3 | MQswCQYDVQQGEwJVUzEgMB4GA1UEChMXU2VjdXJlVHJ1c3QgQ29ycG9yYXRpb24x 4 | FzAVBgNVBAMTDlNlY3VyZVRydXN0IENBMB4XDTA2MTEwNzE5MzExOFoXDTI5MTIz 5 | MTE5NDA1NVowSDELMAkGA1UEBhMCVVMxIDAeBgNVBAoTF1NlY3VyZVRydXN0IENv 6 | cnBvcmF0aW9uMRcwFQYDVQQDEw5TZWN1cmVUcnVzdCBDQTCCASIwDQYJKoZIhvcN 7 | AQEBBQADggEPADCCAQoCggEBAKukgeWVzfX2FI7CT8rU4niVWJxB4Q2ZQCQXOZEz 8 | Zum+4YOvYlyJ0fwkW2Gz4BERQRwdbvC4u/jep4G6pkjGnx29vo6pQT64lO0pGtSO 9 | 0gMdA+9tDWccV9cGrcrI9f4Or2YlSASWC12juhbDCE/RRvgUXPLIXgGZbf2IzIao 10 | wW8xQmxSPmjL8xk037uHGFaAJsTQ3MBv396gwpEWoGQRS0S8Hvbn+mPeZqx2pHGj 11 | 7DaUaHp3pLHnDi+BeuK1cobvomuL8A/b01k/unK8RCSc43Oz969XL0Imnal0ugBS 12 | 8kvNU3xHCzaFDmapCJcWNFfBZveA4+1wVMeT4C4oFVmHursCAwEAAaOBnTCBmjAT 13 | BgkrBgEEAYI3FAIEBh4EAEMAQTALBgNVHQ8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB 14 | /zAdBgNVHQ4EFgQUQjK2FvoE/f5dS3rD/fdMQB1aQ68wNAYDVR0fBC0wKzApoCeg 15 | JYYjaHR0cDovL2NybC5zZWN1cmV0cnVzdC5jb20vU1RDQS5jcmwwEAYJKwYBBAGC 16 | NxUBBAMCAQAwDQYJKoZIhvcNAQEFBQADggEBADDtT0rhWDpSclu1pqNlGKa7UTt3 17 | 6Z3q059c4EVlew3KW+JwULKUBRSuSceNQQcSc5R+DCMh/bwQf2AQWnL1mA6s7Ll/ 18 | 3XpvXdMc9P+IBWlCqQVxyLesJugutIxq/3HcuLHfmbx8IVQr5Fiiu1cprp6poxkm 19 | D5kuCLDv/WnPmRoJjeOnnyvJNjR7JLN4TJUXpAYmHrZkUjZfYGfZnMUFdAvnZyPS 20 | CPyI6a6Lf+Ew9Dd+/cYy2i2eRDAwbO4H3tI0/NL/QPZL9GZGBlSm8jIKYyYwa5vR 21 | 3ItHuuG51WLQoqD0ZwV4KWMabwTW+MZMo5qxN7SN5ShLHZ4swrhovO0C7jE= 22 | -----END CERTIFICATE----- 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # rootcerts 2 | 3 | Functions for loading root certificates for TLS connections. 4 | 5 | ----- 6 | 7 | Go's standard library `crypto/tls` provides a common mechanism for configuring 8 | TLS connections in `tls.Config`. The `RootCAs` field on this struct is a pool 9 | of certificates for the client to use as a trust store when verifying server 10 | certificates. 11 | 12 | This library contains utility functions for loading certificates destined for 13 | that field, as well as one other important thing: 14 | 15 | When the `RootCAs` field is `nil`, the standard library attempts to load the 16 | host's root CA set. This behavior is OS-specific, and the Darwin 17 | implementation contains [a bug that prevents trusted certificates from the 18 | System and Login keychains from being loaded][1]. This library contains 19 | Darwin-specific behavior that works around that bug. 20 | 21 | [1]: https://github.com/golang/go/issues/14514 22 | 23 | ## Example Usage 24 | 25 | Here's a snippet demonstrating how this library is meant to be used: 26 | 27 | ```go 28 | func httpClient() (*http.Client, error) 29 | tlsConfig := &tls.Config{} 30 | err := rootcerts.ConfigureTLS(tlsConfig, &rootcerts.Config{ 31 | CAFile: os.Getenv("MYAPP_CAFILE"), 32 | CAPath: os.Getenv("MYAPP_CAPATH"), 33 | CACertificate: []byte(os.Getenv("MYAPP_CERTIFICATE")), 34 | }) 35 | if err != nil { 36 | return nil, err 37 | } 38 | c := cleanhttp.DefaultClient() 39 | t := cleanhttp.DefaultTransport() 40 | t.TLSClientConfig = tlsConfig 41 | c.Transport = t 42 | return c, nil 43 | } 44 | ``` 45 | -------------------------------------------------------------------------------- /test-fixtures/capath/thawte.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIEIDCCAwigAwIBAgIQNE7VVyDV7exJ9C/ON9srbTANBgkqhkiG9w0BAQUFADCB 3 | qTELMAkGA1UEBhMCVVMxFTATBgNVBAoTDHRoYXd0ZSwgSW5jLjEoMCYGA1UECxMf 4 | Q2VydGlmaWNhdGlvbiBTZXJ2aWNlcyBEaXZpc2lvbjE4MDYGA1UECxMvKGMpIDIw 5 | MDYgdGhhd3RlLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxHzAdBgNV 6 | BAMTFnRoYXd0ZSBQcmltYXJ5IFJvb3QgQ0EwHhcNMDYxMTE3MDAwMDAwWhcNMzYw 7 | NzE2MjM1OTU5WjCBqTELMAkGA1UEBhMCVVMxFTATBgNVBAoTDHRoYXd0ZSwgSW5j 8 | LjEoMCYGA1UECxMfQ2VydGlmaWNhdGlvbiBTZXJ2aWNlcyBEaXZpc2lvbjE4MDYG 9 | A1UECxMvKGMpIDIwMDYgdGhhd3RlLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNl 10 | IG9ubHkxHzAdBgNVBAMTFnRoYXd0ZSBQcmltYXJ5IFJvb3QgQ0EwggEiMA0GCSqG 11 | SIb3DQEBAQUAA4IBDwAwggEKAoIBAQCsoPD7gFnUnMekz52hWXMJEEUMDSxuaPFs 12 | W0hoSVk3/AszGcJ3f8wQLZU0HObrTQmnHNK4yZc2AreJ1CRfBsDMRJSUjQJib+ta 13 | 3RGNKJpchJAQeg29dGYvajig4tVUROsdB58Hum/u6f1OCyn1PoSgAfGcq/gcfomk 14 | 6KHYcWUNo1F77rzSImANuVud37r8UVsLr5iy6S7pBOhih94ryNdOwUxkHt3Ph1i6 15 | Sk/KaAcdHJ1KxtUvkcx8cXIcxcBn6zL9yZJclNqFwJu/U30rCfSMnZEfl2pSy94J 16 | NqR32HuHUETVPm4pafs5SSYeCaWAe0At6+gnhcn+Yf1+5nyXHdWdAgMBAAGjQjBA 17 | MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBR7W0XP 18 | r87Lev0xkhpqtvNG61dIUDANBgkqhkiG9w0BAQUFAAOCAQEAeRHAS7ORtvzw6WfU 19 | DW5FvlXok9LOAz/t2iWwHVfLHjp2oEzsUHboZHIMpKnxuIvW1oeEuzLlQRHAd9mz 20 | YJ3rG9XRbkREqaYB7FViHXe4XI5ISXycO1cRrK1zN44veFyQaEfZYGDm/Ac9IiAX 21 | xPcW6cTYcvnIc3zfFi8VqT79aie2oetaupgf1eNNZAqdE8hhuvU5HIe6uL17In/2 22 | /qxAeeWsEG89jxt5dovEN7MhGITlNgDrYyCZuen+MwS7QcjBAvlEYyCegc5C09Y/ 23 | LHbTY5xZ3Y+m4Q6gLkH3LpVHz7z9M/P2C2F+fpErgUfCJzDupxBdN49cOSvkBPB7 24 | jVaMaA== 25 | -----END CERTIFICATE----- 26 | -------------------------------------------------------------------------------- /test-fixtures/cafile/cacert.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIExDCCA6ygAwIBAgIJAJ7PV+3kJZqZMA0GCSqGSIb3DQEBBQUAMIGcMQswCQYD 3 | VQQGEwJVUzERMA8GA1UECBMISWxsaW5vaXMxEDAOBgNVBAcTB0NoaWNhZ28xEjAQ 4 | BgNVBAoTCUhhc2hpQ29ycDEUMBIGA1UECxMLRW5naW5lZXJpbmcxGzAZBgNVBAMU 5 | EiouYXRsYXMucGhpbnplLmNvbTEhMB8GCSqGSIb3DQEJARYScGF1bEBoYXNoaWNv 6 | cnAuY29tMB4XDTE2MDQyNzE1MjYyMVoXDTE3MDQyNzE1MjYyMVowgZwxCzAJBgNV 7 | BAYTAlVTMREwDwYDVQQIEwhJbGxpbm9pczEQMA4GA1UEBxMHQ2hpY2FnbzESMBAG 8 | A1UEChMJSGFzaGlDb3JwMRQwEgYDVQQLEwtFbmdpbmVlcmluZzEbMBkGA1UEAxQS 9 | Ki5hdGxhcy5waGluemUuY29tMSEwHwYJKoZIhvcNAQkBFhJwYXVsQGhhc2hpY29y 10 | cC5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDWRXdMnsTpxpwZ 11 | D2olsun9WO7SnMQ/SIR3DV/fttPIDHSQm2ad4r2pKEuiV+TKEFUgj/Id9bCAfQYs 12 | jsa1qX1GmieXz+83OnK3MDEcDczpjGhSplTYGOjlxKLMhMBAOtdV5hJAYz3nwV3c 13 | R+IQu/4213+em40shZAQRNZ2apnyE3+QB+gPlEs9Nw0OcbSKLmAiuKPbJpO+94ou 14 | n1h0/w/+DPz6yO/fFPoA3vlisGM6B4R9U2JVwWjXrU71fU1i82ulFQdApdfUs1FP 15 | wRrZxgX5ldUrRvFr8lJiMehdX8khO7Ue4rT6yxbI6KVM04Q5mNt1ARRLI69rN9My 16 | pGXiItcxAgMBAAGjggEFMIIBATAdBgNVHQ4EFgQUjwsj8l0Y9HFQLH0GaJAsOHof 17 | PhwwgdEGA1UdIwSByTCBxoAUjwsj8l0Y9HFQLH0GaJAsOHofPhyhgaKkgZ8wgZwx 18 | CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhJbGxpbm9pczEQMA4GA1UEBxMHQ2hpY2Fn 19 | bzESMBAGA1UEChMJSGFzaGlDb3JwMRQwEgYDVQQLEwtFbmdpbmVlcmluZzEbMBkG 20 | A1UEAxQSKi5hdGxhcy5waGluemUuY29tMSEwHwYJKoZIhvcNAQkBFhJwYXVsQGhh 21 | c2hpY29ycC5jb22CCQCez1ft5CWamTAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEB 22 | BQUAA4IBAQC4tFfxpB8xEk9ewb5CNhhac4oKwGths+oq45DjoNtlagDMmIs2bl18 23 | q45PIB7fuFkAz/YHcOL0UEOAiw4jbuROp9jacHxBV21lRLLmNlK1Llc3eNVvLJ38 24 | ud6/Skilv9XyC4JNk0P5KrghxR6SOGwRuYZNqF+tthf+Bp9wJvLyfqDuJfGBal7C 25 | ezobMoh4tp8Dh1JeQlwvJcVt2k0UFJpa57MNr78c684Bq55ow+jd6wFG0XM0MMmy 26 | u+QRgJEGfYuYDPFEO8C8IfRyrHuV7Ll9P6eyEEFCneznXY0yJc/Gn3ZcX7ANqJsc 27 | ueMOWw/vUnonzxAFKW+I9U9ptyVSNMLY 28 | -----END CERTIFICATE----- 29 | -------------------------------------------------------------------------------- /rootcerts_test.go: -------------------------------------------------------------------------------- 1 | // Copyright IBM Corp. 2016, 2025 2 | // SPDX-License-Identifier: MPL-2.0 3 | 4 | package rootcerts 5 | 6 | import ( 7 | "crypto/sha256" 8 | "crypto/x509" 9 | "fmt" 10 | "os" 11 | "path/filepath" 12 | "testing" 13 | ) 14 | 15 | const fixturesDir = "./test-fixtures" 16 | const caCertSHA256Sum = "e85d9f94f730878cc1a516d9486fdb0255452b37961f325af9fc851cc4689311" 17 | 18 | func TestConfigureTLSHandlesNil(t *testing.T) { 19 | err := ConfigureTLS(nil, nil) 20 | if err != nil { 21 | t.Fatalf("err: %s", err) 22 | } 23 | } 24 | 25 | func TestLoadCACertsHandlesNil(t *testing.T) { 26 | _, err := LoadCACerts(nil) 27 | if err != nil { 28 | t.Fatalf("err: %s", err) 29 | } 30 | } 31 | 32 | func TestLoadCACertsFromFile(t *testing.T) { 33 | path := testFixture("cafile", "cacert.pem") 34 | p, err := LoadCACerts(&Config{CAFile: path}) 35 | if err != nil { 36 | t.Fatalf("err: %s", err) 37 | } 38 | testCertLoaded(t, p) 39 | } 40 | 41 | func TestLoadCACertsInMem(t *testing.T) { 42 | path := testFixture("cafile", "cacert.pem") 43 | pem, err := os.ReadFile(path) 44 | if err != nil { 45 | t.Fatalf("err : %s", err) 46 | } 47 | p, err := LoadCACerts(&Config{CACertificate: pem}) 48 | if err != nil { 49 | t.Fatalf("err: %s", err) 50 | } 51 | testCertLoaded(t, p) 52 | } 53 | 54 | func TestLoadCACertsFromDir(t *testing.T) { 55 | path := testFixture("capath") 56 | p, err := LoadCACerts(&Config{CAPath: path}) 57 | if err != nil { 58 | t.Fatalf("err: %s", err) 59 | } 60 | testCertLoaded(t, p) 61 | } 62 | 63 | func TestLoadCACertsFromDirWithSymlinks(t *testing.T) { 64 | path := testFixture("capath-with-symlinks") 65 | p, err := LoadCACerts(&Config{CAPath: path}) 66 | if err != nil { 67 | t.Fatalf("err: %s", err) 68 | } 69 | testCertLoaded(t, p) 70 | } 71 | 72 | func testFixture(n ...string) string { 73 | parts := []string{fixturesDir} 74 | parts = append(parts, n...) 75 | return filepath.Join(parts...) 76 | } 77 | 78 | func testCertLoaded(t *testing.T, p *x509.CertPool) { 79 | switch len(p.Subjects()) { 80 | case 0: 81 | t.Fatal("expected a certificate in the pool") 82 | case 1: 83 | h := sha256.New() 84 | h.Write(p.Subjects()[0]) 85 | sha256Sum := fmt.Sprintf("%x", h.Sum(nil)) 86 | if caCertSHA256Sum != sha256Sum { 87 | t.Fatalf("sha256 sum mismatch; got '%x'; expected '%s'", sha256Sum, caCertSHA256Sum) 88 | } 89 | default: 90 | // Check if length is not zero 91 | for _, subj := range p.Subjects() { 92 | if len(subj) == 0 { 93 | t.Fatal("expected certificate with data included") 94 | } 95 | } 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /rootcerts.go: -------------------------------------------------------------------------------- 1 | // Copyright IBM Corp. 2016, 2025 2 | // SPDX-License-Identifier: MPL-2.0 3 | 4 | package rootcerts 5 | 6 | import ( 7 | "crypto/tls" 8 | "crypto/x509" 9 | "errors" 10 | "fmt" 11 | "os" 12 | "path/filepath" 13 | ) 14 | 15 | // Config determines where LoadCACerts will load certificates from. When CAFile, 16 | // CACertificate and CAPath are blank, this library's functions will either load 17 | // system roots explicitly and return them, or set the CertPool to nil to allow 18 | // Go's standard library to load system certs. 19 | type Config struct { 20 | // CAFile is a path to a PEM-encoded certificate file or bundle. Takes 21 | // precedence over CACertificate and CAPath. 22 | CAFile string 23 | 24 | // CACertificate is a PEM-encoded certificate or bundle. Takes precedence 25 | // over CAPath. 26 | CACertificate []byte 27 | 28 | // CAPath is a path to a directory populated with PEM-encoded certificates. 29 | CAPath string 30 | } 31 | 32 | // ConfigureTLS sets up the RootCAs on the provided tls.Config based on the 33 | // Config specified. 34 | func ConfigureTLS(t *tls.Config, c *Config) error { 35 | if t == nil { 36 | return nil 37 | } 38 | pool, err := LoadCACerts(c) 39 | if err != nil { 40 | return err 41 | } 42 | t.RootCAs = pool 43 | return nil 44 | } 45 | 46 | // LoadCACerts loads a CertPool based on the Config specified. 47 | func LoadCACerts(c *Config) (*x509.CertPool, error) { 48 | if c == nil { 49 | c = &Config{} 50 | } 51 | if c.CAFile != "" { 52 | return LoadCAFile(c.CAFile) 53 | } 54 | if len(c.CACertificate) != 0 { 55 | return AppendCertificate(c.CACertificate) 56 | } 57 | if c.CAPath != "" { 58 | return LoadCAPath(c.CAPath) 59 | } 60 | 61 | return LoadSystemCAs() 62 | } 63 | 64 | // LoadCAFile loads a single PEM-encoded file from the path specified. 65 | func LoadCAFile(caFile string) (*x509.CertPool, error) { 66 | pool := x509.NewCertPool() 67 | 68 | pem, err := os.ReadFile(caFile) 69 | if err != nil { 70 | return nil, fmt.Errorf("Error loading CA File: %s", err) 71 | } 72 | 73 | ok := pool.AppendCertsFromPEM(pem) 74 | if !ok { 75 | return nil, fmt.Errorf("Error loading CA File: Couldn't parse PEM in: %s", caFile) 76 | } 77 | 78 | return pool, nil 79 | } 80 | 81 | // AppendCertificate appends an in-memory PEM-encoded certificate or bundle and returns a pool. 82 | func AppendCertificate(ca []byte) (*x509.CertPool, error) { 83 | pool := x509.NewCertPool() 84 | 85 | ok := pool.AppendCertsFromPEM(ca) 86 | if !ok { 87 | return nil, errors.New("Error appending CA: Couldn't parse PEM") 88 | } 89 | 90 | return pool, nil 91 | } 92 | 93 | // LoadCAPath walks the provided path and loads all certificates encounted into 94 | // a pool. 95 | func LoadCAPath(caPath string) (*x509.CertPool, error) { 96 | pool := x509.NewCertPool() 97 | walkFn := func(path string, info os.FileInfo, err error) error { 98 | if err != nil { 99 | return err 100 | } 101 | 102 | if info.IsDir() { 103 | return nil 104 | } 105 | 106 | pem, err := os.ReadFile(path) 107 | if err != nil { 108 | return fmt.Errorf("Error loading file from CAPath: %s", err) 109 | } 110 | 111 | ok := pool.AppendCertsFromPEM(pem) 112 | if !ok { 113 | return fmt.Errorf("Error loading CA Path: Couldn't parse PEM in: %s", path) 114 | } 115 | 116 | return nil 117 | } 118 | 119 | err := filepath.Walk(caPath, walkFn) 120 | if err != nil { 121 | return nil, err 122 | } 123 | 124 | return pool, nil 125 | } 126 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright IBM Corp. 2016, 2025 2 | 3 | Mozilla Public License, version 2.0 4 | 5 | 1. Definitions 6 | 7 | 1.1. "Contributor" 8 | 9 | means each individual or legal entity that creates, contributes to the 10 | creation of, or owns Covered Software. 11 | 12 | 1.2. "Contributor Version" 13 | 14 | means the combination of the Contributions of others (if any) used by a 15 | Contributor and that particular Contributor's Contribution. 16 | 17 | 1.3. "Contribution" 18 | 19 | means Covered Software of a particular Contributor. 20 | 21 | 1.4. "Covered Software" 22 | 23 | means Source Code Form to which the initial Contributor has attached the 24 | notice in Exhibit A, the Executable Form of such Source Code Form, and 25 | Modifications of such Source Code Form, in each case including portions 26 | thereof. 27 | 28 | 1.5. "Incompatible With Secondary Licenses" 29 | means 30 | 31 | a. that the initial Contributor has attached the notice described in 32 | Exhibit B to the Covered Software; or 33 | 34 | b. that the Covered Software was made available under the terms of 35 | version 1.1 or earlier of the License, but not also under the terms of 36 | a Secondary License. 37 | 38 | 1.6. "Executable Form" 39 | 40 | means any form of the work other than Source Code Form. 41 | 42 | 1.7. "Larger Work" 43 | 44 | means a work that combines Covered Software with other material, in a 45 | separate file or files, that is not Covered Software. 46 | 47 | 1.8. "License" 48 | 49 | means this document. 50 | 51 | 1.9. "Licensable" 52 | 53 | means having the right to grant, to the maximum extent possible, whether 54 | at the time of the initial grant or subsequently, any and all of the 55 | rights conveyed by this License. 56 | 57 | 1.10. "Modifications" 58 | 59 | means any of the following: 60 | 61 | a. any file in Source Code Form that results from an addition to, 62 | deletion from, or modification of the contents of Covered Software; or 63 | 64 | b. any new file in Source Code Form that contains any Covered Software. 65 | 66 | 1.11. "Patent Claims" of a Contributor 67 | 68 | means any patent claim(s), including without limitation, method, 69 | process, and apparatus claims, in any patent Licensable by such 70 | Contributor that would be infringed, but for the grant of the License, 71 | by the making, using, selling, offering for sale, having made, import, 72 | or transfer of either its Contributions or its Contributor Version. 73 | 74 | 1.12. "Secondary License" 75 | 76 | means either the GNU General Public License, Version 2.0, the GNU Lesser 77 | General Public License, Version 2.1, the GNU Affero General Public 78 | License, Version 3.0, or any later versions of those licenses. 79 | 80 | 1.13. "Source Code Form" 81 | 82 | means the form of the work preferred for making modifications. 83 | 84 | 1.14. "You" (or "Your") 85 | 86 | means an individual or a legal entity exercising rights under this 87 | License. For legal entities, "You" includes any entity that controls, is 88 | controlled by, or is under common control with You. For purposes of this 89 | definition, "control" means (a) the power, direct or indirect, to cause 90 | the direction or management of such entity, whether by contract or 91 | otherwise, or (b) ownership of more than fifty percent (50%) of the 92 | outstanding shares or beneficial ownership of such entity. 93 | 94 | 95 | 2. License Grants and Conditions 96 | 97 | 2.1. Grants 98 | 99 | Each Contributor hereby grants You a world-wide, royalty-free, 100 | non-exclusive license: 101 | 102 | a. under intellectual property rights (other than patent or trademark) 103 | Licensable by such Contributor to use, reproduce, make available, 104 | modify, display, perform, distribute, and otherwise exploit its 105 | Contributions, either on an unmodified basis, with Modifications, or 106 | as part of a Larger Work; and 107 | 108 | b. under Patent Claims of such Contributor to make, use, sell, offer for 109 | sale, have made, import, and otherwise transfer either its 110 | Contributions or its Contributor Version. 111 | 112 | 2.2. Effective Date 113 | 114 | The licenses granted in Section 2.1 with respect to any Contribution 115 | become effective for each Contribution on the date the Contributor first 116 | distributes such Contribution. 117 | 118 | 2.3. Limitations on Grant Scope 119 | 120 | The licenses granted in this Section 2 are the only rights granted under 121 | this License. No additional rights or licenses will be implied from the 122 | distribution or licensing of Covered Software under this License. 123 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 124 | Contributor: 125 | 126 | a. for any code that a Contributor has removed from Covered Software; or 127 | 128 | b. for infringements caused by: (i) Your and any other third party's 129 | modifications of Covered Software, or (ii) the combination of its 130 | Contributions with other software (except as part of its Contributor 131 | Version); or 132 | 133 | c. under Patent Claims infringed by Covered Software in the absence of 134 | its Contributions. 135 | 136 | This License does not grant any rights in the trademarks, service marks, 137 | or logos of any Contributor (except as may be necessary to comply with 138 | the notice requirements in Section 3.4). 139 | 140 | 2.4. Subsequent Licenses 141 | 142 | No Contributor makes additional grants as a result of Your choice to 143 | distribute the Covered Software under a subsequent version of this 144 | License (see Section 10.2) or under the terms of a Secondary License (if 145 | permitted under the terms of Section 3.3). 146 | 147 | 2.5. Representation 148 | 149 | Each Contributor represents that the Contributor believes its 150 | Contributions are its original creation(s) or it has sufficient rights to 151 | grant the rights to its Contributions conveyed by this License. 152 | 153 | 2.6. Fair Use 154 | 155 | This License is not intended to limit any rights You have under 156 | applicable copyright doctrines of fair use, fair dealing, or other 157 | equivalents. 158 | 159 | 2.7. Conditions 160 | 161 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in 162 | Section 2.1. 163 | 164 | 165 | 3. Responsibilities 166 | 167 | 3.1. Distribution of Source Form 168 | 169 | All distribution of Covered Software in Source Code Form, including any 170 | Modifications that You create or to which You contribute, must be under 171 | the terms of this License. You must inform recipients that the Source 172 | Code Form of the Covered Software is governed by the terms of this 173 | License, and how they can obtain a copy of this License. You may not 174 | attempt to alter or restrict the recipients' rights in the Source Code 175 | Form. 176 | 177 | 3.2. Distribution of Executable Form 178 | 179 | If You distribute Covered Software in Executable Form then: 180 | 181 | a. such Covered Software must also be made available in Source Code Form, 182 | as described in Section 3.1, and You must inform recipients of the 183 | Executable Form how they can obtain a copy of such Source Code Form by 184 | reasonable means in a timely manner, at a charge no more than the cost 185 | of distribution to the recipient; and 186 | 187 | b. You may distribute such Executable Form under the terms of this 188 | License, or sublicense it under different terms, provided that the 189 | license for the Executable Form does not attempt to limit or alter the 190 | recipients' rights in the Source Code Form under this License. 191 | 192 | 3.3. Distribution of a Larger Work 193 | 194 | You may create and distribute a Larger Work under terms of Your choice, 195 | provided that You also comply with the requirements of this License for 196 | the Covered Software. If the Larger Work is a combination of Covered 197 | Software with a work governed by one or more Secondary Licenses, and the 198 | Covered Software is not Incompatible With Secondary Licenses, this 199 | License permits You to additionally distribute such Covered Software 200 | under the terms of such Secondary License(s), so that the recipient of 201 | the Larger Work may, at their option, further distribute the Covered 202 | Software under the terms of either this License or such Secondary 203 | License(s). 204 | 205 | 3.4. Notices 206 | 207 | You may not remove or alter the substance of any license notices 208 | (including copyright notices, patent notices, disclaimers of warranty, or 209 | limitations of liability) contained within the Source Code Form of the 210 | Covered Software, except that You may alter any license notices to the 211 | extent required to remedy known factual inaccuracies. 212 | 213 | 3.5. Application of Additional Terms 214 | 215 | You may choose to offer, and to charge a fee for, warranty, support, 216 | indemnity or liability obligations to one or more recipients of Covered 217 | Software. However, You may do so only on Your own behalf, and not on 218 | behalf of any Contributor. You must make it absolutely clear that any 219 | such warranty, support, indemnity, or liability obligation is offered by 220 | You alone, and You hereby agree to indemnify every Contributor for any 221 | liability incurred by such Contributor as a result of warranty, support, 222 | indemnity or liability terms You offer. You may include additional 223 | disclaimers of warranty and limitations of liability specific to any 224 | jurisdiction. 225 | 226 | 4. Inability to Comply Due to Statute or Regulation 227 | 228 | If it is impossible for You to comply with any of the terms of this License 229 | with respect to some or all of the Covered Software due to statute, 230 | judicial order, or regulation then You must: (a) comply with the terms of 231 | this License to the maximum extent possible; and (b) describe the 232 | limitations and the code they affect. Such description must be placed in a 233 | text file included with all distributions of the Covered Software under 234 | this License. Except to the extent prohibited by statute or regulation, 235 | such description must be sufficiently detailed for a recipient of ordinary 236 | skill to be able to understand it. 237 | 238 | 5. Termination 239 | 240 | 5.1. The rights granted under this License will terminate automatically if You 241 | fail to comply with any of its terms. However, if You become compliant, 242 | then the rights granted under this License from a particular Contributor 243 | are reinstated (a) provisionally, unless and until such Contributor 244 | explicitly and finally terminates Your grants, and (b) on an ongoing 245 | basis, if such Contributor fails to notify You of the non-compliance by 246 | some reasonable means prior to 60 days after You have come back into 247 | compliance. Moreover, Your grants from a particular Contributor are 248 | reinstated on an ongoing basis if such Contributor notifies You of the 249 | non-compliance by some reasonable means, this is the first time You have 250 | received notice of non-compliance with this License from such 251 | Contributor, and You become compliant prior to 30 days after Your receipt 252 | of the notice. 253 | 254 | 5.2. If You initiate litigation against any entity by asserting a patent 255 | infringement claim (excluding declaratory judgment actions, 256 | counter-claims, and cross-claims) alleging that a Contributor Version 257 | directly or indirectly infringes any patent, then the rights granted to 258 | You by any and all Contributors for the Covered Software under Section 259 | 2.1 of this License shall terminate. 260 | 261 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user 262 | license agreements (excluding distributors and resellers) which have been 263 | validly granted by You or Your distributors under this License prior to 264 | termination shall survive termination. 265 | 266 | 6. Disclaimer of Warranty 267 | 268 | Covered Software is provided under this License on an "as is" basis, 269 | without warranty of any kind, either expressed, implied, or statutory, 270 | including, without limitation, warranties that the Covered Software is free 271 | of defects, merchantable, fit for a particular purpose or non-infringing. 272 | The entire risk as to the quality and performance of the Covered Software 273 | is with You. Should any Covered Software prove defective in any respect, 274 | You (not any Contributor) assume the cost of any necessary servicing, 275 | repair, or correction. This disclaimer of warranty constitutes an essential 276 | part of this License. No use of any Covered Software is authorized under 277 | this License except under this disclaimer. 278 | 279 | 7. Limitation of Liability 280 | 281 | Under no circumstances and under no legal theory, whether tort (including 282 | negligence), contract, or otherwise, shall any Contributor, or anyone who 283 | distributes Covered Software as permitted above, be liable to You for any 284 | direct, indirect, special, incidental, or consequential damages of any 285 | character including, without limitation, damages for lost profits, loss of 286 | goodwill, work stoppage, computer failure or malfunction, or any and all 287 | other commercial damages or losses, even if such party shall have been 288 | informed of the possibility of such damages. This limitation of liability 289 | shall not apply to liability for death or personal injury resulting from 290 | such party's negligence to the extent applicable law prohibits such 291 | limitation. Some jurisdictions do not allow the exclusion or limitation of 292 | incidental or consequential damages, so this exclusion and limitation may 293 | not apply to You. 294 | 295 | 8. Litigation 296 | 297 | Any litigation relating to this License may be brought only in the courts 298 | of a jurisdiction where the defendant maintains its principal place of 299 | business and such litigation shall be governed by laws of that 300 | jurisdiction, without reference to its conflict-of-law provisions. Nothing 301 | in this Section shall prevent a party's ability to bring cross-claims or 302 | counter-claims. 303 | 304 | 9. Miscellaneous 305 | 306 | This License represents the complete agreement concerning the subject 307 | matter hereof. If any provision of this License is held to be 308 | unenforceable, such provision shall be reformed only to the extent 309 | necessary to make it enforceable. Any law or regulation which provides that 310 | the language of a contract shall be construed against the drafter shall not 311 | be used to construe this License against a Contributor. 312 | 313 | 314 | 10. Versions of the License 315 | 316 | 10.1. New Versions 317 | 318 | Mozilla Foundation is the license steward. Except as provided in Section 319 | 10.3, no one other than the license steward has the right to modify or 320 | publish new versions of this License. Each version will be given a 321 | distinguishing version number. 322 | 323 | 10.2. Effect of New Versions 324 | 325 | You may distribute the Covered Software under the terms of the version 326 | of the License under which You originally received the Covered Software, 327 | or under the terms of any subsequent version published by the license 328 | steward. 329 | 330 | 10.3. Modified Versions 331 | 332 | If you create software not governed by this License, and you want to 333 | create a new license for such software, you may create and use a 334 | modified version of this License if you rename the license and remove 335 | any references to the name of the license steward (except to note that 336 | such modified license differs from this License). 337 | 338 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 339 | Licenses If You choose to distribute Source Code Form that is 340 | Incompatible With Secondary Licenses under the terms of this version of 341 | the License, the notice described in Exhibit B of this License must be 342 | attached. 343 | 344 | Exhibit A - Source Code Form License Notice 345 | 346 | This Source Code Form is subject to the 347 | terms of the Mozilla Public License, v. 348 | 2.0. If a copy of the MPL was not 349 | distributed with this file, You can 350 | obtain one at 351 | http://mozilla.org/MPL/2.0/. 352 | 353 | If it is not possible or desirable to put the notice in a particular file, 354 | then You may include the notice in a location (such as a LICENSE file in a 355 | relevant directory) where a recipient would be likely to look for such a 356 | notice. 357 | 358 | You may add additional accurate notices of copyright ownership. 359 | 360 | Exhibit B - "Incompatible With Secondary Licenses" Notice 361 | 362 | This Source Code Form is "Incompatible 363 | With Secondary Licenses", as defined by 364 | the Mozilla Public License, v. 2.0. 365 | 366 | --------------------------------------------------------------------------------