github.com/hxx258456/ccgo@v0.0.5-0.20230213014102-48b35f46f66f/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 /* 8 x509/cert_pool.go 证书池实现 9 */ 10 11 import ( 12 "bytes" 13 "encoding/pem" 14 "errors" 15 "runtime" 16 "sync" 17 18 "github.com/hxx258456/ccgo/sm3" 19 ) 20 21 // 将`sha256.Sum224`改为`sm3.Sm3SumArr` 22 type sumSm3 [sm3.Size]byte 23 24 // CertPool is a set of certificates. 25 type CertPool struct { 26 byName map[string][]int // cert.RawSubject => index into lazyCerts 27 28 // lazyCerts contains funcs that return a certificate, 29 // lazily parsing/decompressing it as needed. 30 lazyCerts []lazyCert 31 32 // haveSum maps from sm3.Sm3SumArr(cert.Raw) to true. It's used only 33 // for AddCert duplicate detection, to avoid CertPool.contains 34 // calls in the AddCert path (because the contains method can 35 // call getCert and otherwise negate savings from lazy getCert 36 // funcs). 37 haveSum map[sumSm3]bool 38 } 39 40 // lazyCert is minimal metadata about a Cert and a func to retrieve it 41 // in its normal expanded *Certificate form. 42 type lazyCert struct { 43 // rawSubject is the Certificate.RawSubject value. 44 // It's the same as the CertPool.byName key, but in []byte 45 // form to make CertPool.Subjects (as used by crypto/tls) do 46 // fewer allocations. 47 rawSubject []byte 48 49 // getCert returns the certificate. 50 // 51 // It is not meant to do network operations or anything else 52 // where a failure is likely; the func is meant to lazily 53 // parse/decompress data that is already known to be good. The 54 // error in the signature primarily is meant for use in the 55 // case where a cert file existed on local disk when the program 56 // started up is deleted later before it's read. 57 getCert func() (*Certificate, error) 58 } 59 60 // NewCertPool returns a new, empty CertPool. 61 func NewCertPool() *CertPool { 62 return &CertPool{ 63 byName: make(map[string][]int), 64 haveSum: make(map[sumSm3]bool), 65 } 66 } 67 68 // len returns the number of certs in the set. 69 // A nil set is a valid empty set. 70 func (s *CertPool) len() int { 71 if s == nil { 72 return 0 73 } 74 return len(s.lazyCerts) 75 } 76 77 // cert returns cert index n in s. 78 func (s *CertPool) cert(n int) (*Certificate, error) { 79 return s.lazyCerts[n].getCert() 80 } 81 82 func (s *CertPool) copy() *CertPool { 83 p := &CertPool{ 84 byName: make(map[string][]int, len(s.byName)), 85 lazyCerts: make([]lazyCert, len(s.lazyCerts)), 86 haveSum: make(map[sumSm3]bool, len(s.haveSum)), 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 runtime.GOOS == "windows" { 113 // Issue 16736, 18609: 114 return nil, errors.New("github.com/hxx258456/ccgo/x509: system root pool is not available on Windows") 115 } 116 117 if sysRoots := systemRootsPool(); sysRoots != nil { 118 return sysRoots.copy(), nil 119 } 120 121 return loadSystemRoots() 122 } 123 124 // findPotentialParents returns the indexes of certificates in s which might 125 // have signed cert. 126 func (s *CertPool) findPotentialParents(cert *Certificate) []*Certificate { 127 if s == nil { 128 return nil 129 } 130 131 // consider all candidates where cert.Issuer matches cert.Subject. 132 // when picking possible candidates the list is built in the order 133 // of match plausibility as to save cycles in buildChains: 134 // AKID and SKID match 135 // AKID present, SKID missing / AKID missing, SKID present 136 // AKID and SKID don't match 137 var matchingKeyID, oneKeyID, mismatchKeyID []*Certificate 138 for _, c := range s.byName[string(cert.RawIssuer)] { 139 candidate, err := s.cert(c) 140 if err != nil { 141 continue 142 } 143 kidMatch := bytes.Equal(candidate.SubjectKeyId, cert.AuthorityKeyId) 144 switch { 145 case kidMatch: 146 matchingKeyID = append(matchingKeyID, candidate) 147 case (len(candidate.SubjectKeyId) == 0 && len(cert.AuthorityKeyId) > 0) || 148 (len(candidate.SubjectKeyId) > 0 && len(cert.AuthorityKeyId) == 0): 149 oneKeyID = append(oneKeyID, candidate) 150 default: 151 mismatchKeyID = append(mismatchKeyID, candidate) 152 } 153 } 154 155 found := len(matchingKeyID) + len(oneKeyID) + len(mismatchKeyID) 156 if found == 0 { 157 return nil 158 } 159 candidates := make([]*Certificate, 0, found) 160 candidates = append(candidates, matchingKeyID...) 161 candidates = append(candidates, oneKeyID...) 162 candidates = append(candidates, mismatchKeyID...) 163 return candidates 164 } 165 166 func (s *CertPool) contains(cert *Certificate) bool { 167 if s == nil { 168 return false 169 } 170 return s.haveSum[sm3.Sm3SumArr(cert.Raw)] 171 } 172 173 // AddCert adds a certificate to a pool. 174 func (s *CertPool) AddCert(cert *Certificate) { 175 if cert == nil { 176 panic("adding nil Certificate to CertPool") 177 } 178 s.addCertFunc(sm3.Sm3SumArr(cert.Raw), string(cert.RawSubject), func() (*Certificate, error) { 179 return cert, nil 180 }) 181 } 182 183 // addCertFunc adds metadata about a certificate to a pool, along with 184 // a func to fetch that certificate later when needed. 185 // 186 // The rawSubject is Certificate.RawSubject and must be non-empty. 187 // The getCert func may be called 0 or more times. 188 func (s *CertPool) addCertFunc(rawSumSm3 sumSm3, rawSubject string, getCert func() (*Certificate, error)) { 189 if getCert == nil { 190 panic("getCert can't be nil") 191 } 192 193 // Check that the certificate isn't being added twice. 194 if s.haveSum[rawSumSm3] { 195 return 196 } 197 198 s.haveSum[rawSumSm3] = true 199 s.lazyCerts = append(s.lazyCerts, lazyCert{ 200 rawSubject: []byte(rawSubject), 201 getCert: getCert, 202 }) 203 s.byName[rawSubject] = append(s.byName[rawSubject], len(s.lazyCerts)-1) 204 } 205 206 // AppendCertsFromPEM attempts to parse a series of PEM encoded certificates. 207 // It appends any certificates found to s and reports whether any certificates 208 // were successfully parsed. 209 // 210 // On many Linux systems, /etc/ssl/cert.pem will contain the system wide set 211 // of root CAs in a format suitable for this function. 212 func (s *CertPool) AppendCertsFromPEM(pemCerts []byte) (ok bool) { 213 for len(pemCerts) > 0 { 214 var block *pem.Block 215 block, pemCerts = pem.Decode(pemCerts) 216 if block == nil { 217 break 218 } 219 if block.Type != "CERTIFICATE" || len(block.Headers) != 0 { 220 continue 221 } 222 223 certBytes := block.Bytes 224 cert, err := ParseCertificate(certBytes) 225 if err != nil { 226 continue 227 } 228 var lazyCert struct { 229 sync.Once 230 v *Certificate 231 } 232 s.addCertFunc(sm3.Sm3SumArr(cert.Raw), string(cert.RawSubject), func() (*Certificate, error) { 233 lazyCert.Do(func() { 234 // This can't fail, as the same bytes already parsed above. 235 lazyCert.v, _ = ParseCertificate(certBytes) 236 certBytes = nil 237 }) 238 return lazyCert.v, nil 239 }) 240 ok = true 241 } 242 243 return ok 244 } 245 246 // Subjects returns a list of the DER-encoded subjects of 247 // all of the certificates in the pool. 248 func (s *CertPool) Subjects() [][]byte { 249 res := make([][]byte, s.len()) 250 for i, lc := range s.lazyCerts { 251 res[i] = lc.rawSubject 252 } 253 return res 254 }