github.com/mtsmfm/go/src@v0.0.0-20221020090648-44bdcb9f8fde/crypto/x509/cert_pool.go (about) 1 // Copyright 2011 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package x509 6 7 import ( 8 "bytes" 9 "crypto/sha256" 10 "encoding/pem" 11 "sync" 12 ) 13 14 type sum224 [sha256.Size224]byte 15 16 // CertPool is a set of certificates. 17 type CertPool struct { 18 byName map[string][]int // cert.RawSubject => index into lazyCerts 19 20 // lazyCerts contains funcs that return a certificate, 21 // lazily parsing/decompressing it as needed. 22 lazyCerts []lazyCert 23 24 // haveSum maps from sum224(cert.Raw) to true. It's used only 25 // for AddCert duplicate detection, to avoid CertPool.contains 26 // calls in the AddCert path (because the contains method can 27 // call getCert and otherwise negate savings from lazy getCert 28 // funcs). 29 haveSum map[sum224]bool 30 31 // systemPool indicates whether this is a special pool derived from the 32 // system roots. If it includes additional roots, it requires doing two 33 // verifications, one using the roots provided by the caller, and one using 34 // the system platform verifier. 35 systemPool bool 36 } 37 38 // lazyCert is minimal metadata about a Cert and a func to retrieve it 39 // in its normal expanded *Certificate form. 40 type lazyCert struct { 41 // rawSubject is the Certificate.RawSubject value. 42 // It's the same as the CertPool.byName key, but in []byte 43 // form to make CertPool.Subjects (as used by crypto/tls) do 44 // fewer allocations. 45 rawSubject []byte 46 47 // getCert returns the certificate. 48 // 49 // It is not meant to do network operations or anything else 50 // where a failure is likely; the func is meant to lazily 51 // parse/decompress data that is already known to be good. The 52 // error in the signature primarily is meant for use in the 53 // case where a cert file existed on local disk when the program 54 // started up is deleted later before it's read. 55 getCert func() (*Certificate, error) 56 } 57 58 // NewCertPool returns a new, empty CertPool. 59 func NewCertPool() *CertPool { 60 return &CertPool{ 61 byName: make(map[string][]int), 62 haveSum: make(map[sum224]bool), 63 } 64 } 65 66 // len returns the number of certs in the set. 67 // A nil set is a valid empty set. 68 func (s *CertPool) len() int { 69 if s == nil { 70 return 0 71 } 72 return len(s.lazyCerts) 73 } 74 75 // cert returns cert index n in s. 76 func (s *CertPool) cert(n int) (*Certificate, error) { 77 return s.lazyCerts[n].getCert() 78 } 79 80 // Clone returns a copy of s. 81 func (s *CertPool) Clone() *CertPool { 82 p := &CertPool{ 83 byName: make(map[string][]int, len(s.byName)), 84 lazyCerts: make([]lazyCert, len(s.lazyCerts)), 85 haveSum: make(map[sum224]bool, len(s.haveSum)), 86 systemPool: s.systemPool, 87 } 88 for k, v := range s.byName { 89 indexes := make([]int, len(v)) 90 copy(indexes, v) 91 p.byName[k] = indexes 92 } 93 for k := range s.haveSum { 94 p.haveSum[k] = true 95 } 96 copy(p.lazyCerts, s.lazyCerts) 97 return p 98 } 99 100 // SystemCertPool returns a copy of the system cert pool. 101 // 102 // On Unix systems other than macOS the environment variables SSL_CERT_FILE and 103 // SSL_CERT_DIR can be used to override the system default locations for the SSL 104 // certificate file and SSL certificate files directory, respectively. The 105 // latter can be a colon-separated list. 106 // 107 // Any mutations to the returned pool are not written to disk and do not affect 108 // any other pool returned by SystemCertPool. 109 // 110 // New changes in the system cert pool might not be reflected in subsequent calls. 111 func SystemCertPool() (*CertPool, error) { 112 if sysRoots := systemRootsPool(); sysRoots != nil { 113 return sysRoots.Clone(), nil 114 } 115 116 return loadSystemRoots() 117 } 118 119 // findPotentialParents returns the indexes of certificates in s which might 120 // have signed cert. 121 func (s *CertPool) findPotentialParents(cert *Certificate) []*Certificate { 122 if s == nil { 123 return nil 124 } 125 126 // consider all candidates where cert.Issuer matches cert.Subject. 127 // when picking possible candidates the list is built in the order 128 // of match plausibility as to save cycles in buildChains: 129 // AKID and SKID match 130 // AKID present, SKID missing / AKID missing, SKID present 131 // AKID and SKID don't match 132 var matchingKeyID, oneKeyID, mismatchKeyID []*Certificate 133 for _, c := range s.byName[string(cert.RawIssuer)] { 134 candidate, err := s.cert(c) 135 if err != nil { 136 continue 137 } 138 kidMatch := bytes.Equal(candidate.SubjectKeyId, cert.AuthorityKeyId) 139 switch { 140 case kidMatch: 141 matchingKeyID = append(matchingKeyID, candidate) 142 case (len(candidate.SubjectKeyId) == 0 && len(cert.AuthorityKeyId) > 0) || 143 (len(candidate.SubjectKeyId) > 0 && len(cert.AuthorityKeyId) == 0): 144 oneKeyID = append(oneKeyID, candidate) 145 default: 146 mismatchKeyID = append(mismatchKeyID, candidate) 147 } 148 } 149 150 found := len(matchingKeyID) + len(oneKeyID) + len(mismatchKeyID) 151 if found == 0 { 152 return nil 153 } 154 candidates := make([]*Certificate, 0, found) 155 candidates = append(candidates, matchingKeyID...) 156 candidates = append(candidates, oneKeyID...) 157 candidates = append(candidates, mismatchKeyID...) 158 return candidates 159 } 160 161 func (s *CertPool) contains(cert *Certificate) bool { 162 if s == nil { 163 return false 164 } 165 return s.haveSum[sha256.Sum224(cert.Raw)] 166 } 167 168 // AddCert adds a certificate to a pool. 169 func (s *CertPool) AddCert(cert *Certificate) { 170 if cert == nil { 171 panic("adding nil Certificate to CertPool") 172 } 173 s.addCertFunc(sha256.Sum224(cert.Raw), string(cert.RawSubject), func() (*Certificate, error) { 174 return cert, nil 175 }) 176 } 177 178 // addCertFunc adds metadata about a certificate to a pool, along with 179 // a func to fetch that certificate later when needed. 180 // 181 // The rawSubject is Certificate.RawSubject and must be non-empty. 182 // The getCert func may be called 0 or more times. 183 func (s *CertPool) addCertFunc(rawSum224 sum224, rawSubject string, getCert func() (*Certificate, error)) { 184 if getCert == nil { 185 panic("getCert can't be nil") 186 } 187 188 // Check that the certificate isn't being added twice. 189 if s.haveSum[rawSum224] { 190 return 191 } 192 193 s.haveSum[rawSum224] = true 194 s.lazyCerts = append(s.lazyCerts, lazyCert{ 195 rawSubject: []byte(rawSubject), 196 getCert: getCert, 197 }) 198 s.byName[rawSubject] = append(s.byName[rawSubject], len(s.lazyCerts)-1) 199 } 200 201 // AppendCertsFromPEM attempts to parse a series of PEM encoded certificates. 202 // It appends any certificates found to s and reports whether any certificates 203 // were successfully parsed. 204 // 205 // On many Linux systems, /etc/ssl/cert.pem will contain the system wide set 206 // of root CAs in a format suitable for this function. 207 func (s *CertPool) AppendCertsFromPEM(pemCerts []byte) (ok bool) { 208 for len(pemCerts) > 0 { 209 var block *pem.Block 210 block, pemCerts = pem.Decode(pemCerts) 211 if block == nil { 212 break 213 } 214 if block.Type != "CERTIFICATE" || len(block.Headers) != 0 { 215 continue 216 } 217 218 certBytes := block.Bytes 219 cert, err := ParseCertificate(certBytes) 220 if err != nil { 221 continue 222 } 223 var lazyCert struct { 224 sync.Once 225 v *Certificate 226 } 227 s.addCertFunc(sha256.Sum224(cert.Raw), string(cert.RawSubject), func() (*Certificate, error) { 228 lazyCert.Do(func() { 229 // This can't fail, as the same bytes already parsed above. 230 lazyCert.v, _ = ParseCertificate(certBytes) 231 certBytes = nil 232 }) 233 return lazyCert.v, nil 234 }) 235 ok = true 236 } 237 238 return ok 239 } 240 241 // Subjects returns a list of the DER-encoded subjects of 242 // all of the certificates in the pool. 243 // 244 // Deprecated: if s was returned by SystemCertPool, Subjects 245 // will not include the system roots. 246 func (s *CertPool) Subjects() [][]byte { 247 res := make([][]byte, s.len()) 248 for i, lc := range s.lazyCerts { 249 res[i] = lc.rawSubject 250 } 251 return res 252 } 253 254 // Equal reports whether s and other are equal. 255 func (s *CertPool) Equal(other *CertPool) bool { 256 if s == nil || other == nil { 257 return s == other 258 } 259 if s.systemPool != other.systemPool || len(s.haveSum) != len(other.haveSum) { 260 return false 261 } 262 for h := range s.haveSum { 263 if !other.haveSum[h] { 264 return false 265 } 266 } 267 return true 268 }