summaryrefslogtreecommitdiff
path: root/src/mongo/gotools/common/db/tlsgo/rootcerts_darwin.go
blob: 72c7a9116adae6d4b6e7e5d577a5dbe4b25559de (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// Copyright (C) MongoDB, Inc. 2018-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
//
// Based on https://github.com/hashicorp/go-rootcerts by HashiCorp
// See THIRD-PARTY-NOTICES for original license terms.

package tlsgo

import (
	"crypto/x509"
	"os/exec"
	"os/user"
	"path"
)

// loadSystemCAs has special behavior on Darwin systems to work around
// bugs loading certs from keychains.  See this GitHub issues query:
// https://github.com/golang/go/issues?utf8=%E2%9C%93&q=is%3Aissue+darwin+keychain
func loadSystemCAs() (*x509.CertPool, error) {
	pool := x509.NewCertPool()

	for _, keychain := range certKeychains() {
		err := addCertsFromKeychain(pool, keychain)
		if err != nil {
			return nil, err
		}
	}

	return pool, nil
}

func addCertsFromKeychain(pool *x509.CertPool, keychain string) error {
	cmd := exec.Command("/usr/bin/security", "find-certificate", "-a", "-p", keychain)
	data, err := cmd.Output()
	if err != nil {
		return err
	}

	pool.AppendCertsFromPEM(data)

	return nil
}

func certKeychains() []string {
	keychains := []string{
		"/System/Library/Keychains/SystemRootCertificates.keychain",
		"/Library/Keychains/System.keychain",
	}
	user, err := user.Current()
	if err == nil {
		loginKeychain := path.Join(user.HomeDir, "Library", "Keychains", "login.keychain")
		keychains = append(keychains, loginKeychain)
	}
	return keychains
}