Debian Codegraph @

lib/x509tools/certpool.go

raw symbols SCIP
1 //
2 // Copyright (c) SAS Institute Inc.
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16
17 package x509tools
18
19 import (
20 "crypto/tls"
21 "crypto/x509"
22 "fmt"
23 "io/ioutil"
24 "strings"
25 )
26
27 // Load a certificate pool from a file and set it as the root CA for a TLS
28 // config. If path is empty then the system pool will be used. If the filename
29 // starts with + then both the system pool and the contents of the file will be
30 // used.
31 func LoadCertPool(path string, tconf *tls.Config) error {
32 if path == "" {
33 return nil
34 } else if path[0] == '+' {
35 pool, err := x509.SystemCertPool()
36 if err != nil {
37 return err
38 }
39 tconf.RootCAs = pool
40 path = path[1:]
41 } else {
42 tconf.RootCAs = x509.NewCertPool()
43 }
44 var contents []byte
45 if strings.Contains(path, "-----BEGIN") {
46 contents = []byte(path)
47 } else {
48 var err error
49 contents, err = ioutil.ReadFile(path)
50 if err != nil {
51 return err
52 }
53 }
54 if !tconf.RootCAs.AppendCertsFromPEM(contents) {
55 return fmt.Errorf("no CA certificates in %s", path)
56 }
57 return nil
58 }