Debian Codegraph @

cert/ca_pool.go

raw
1 package cert
2
3 import (
4 "bufio"
5 "bytes"
6 "encoding/pem"
7 "errors"
8 "fmt"
9 "io"
10 "net/netip"
11 "slices"
12 "time"
13 )
14
15 type CAPool struct {
16 CAs map[string]*CachedCertificate
17 certBlocklist map[string]struct{}
18 }
19
20 // NewCAPool creates an empty CAPool
21 func NewCAPool() *CAPool {
22 ca := CAPool{
23 CAs: make(map[string]*CachedCertificate),
24 certBlocklist: make(map[string]struct{}),
25 }
26
27 return &ca
28 }
29
30 // NewCAPoolFromPEM will create a new CA pool from the provided
31 // input bytes, which must be a PEM-encoded set of nebula certificates.
32 // If the pool contains any expired certificates, an ErrExpired will be
33 // returned along with the pool. The caller must handle any such errors.
34 func NewCAPoolFromPEM(caPEMs []byte) (*CAPool, error) {
35 return NewCAPoolFromPEMReader(bytes.NewReader(caPEMs))
36 }
37
38 // NewCAPoolFromPEMReader will create a new CA pool from the provided reader.
39 // The reader must contain a PEM-encoded set of nebula certificates.
40 func NewCAPoolFromPEMReader(r io.Reader) (*CAPool, error) {
41 pool := NewCAPool()
42
43 var expired bool
44
45 scanner := bufio.NewScanner(r)
46 scanner.Split(SplitPEM)
47
48 for scanner.Scan() {
49 pemBytes := scanner.Bytes()
50
51 block, rest := pem.Decode(pemBytes)
52 if len(bytes.TrimSpace(rest)) > 0 {
53 return nil, ErrInvalidPEMBlock
54 }
55 if block == nil {
56 return nil, ErrInvalidPEMBlock
57 }
58
59 c, err := unmarshalCertificateBlock(block)
60 if err != nil {
61 return nil, err
62 }
63
64 err = pool.AddCA(c)
65 if errors.Is(err, ErrExpired) {
66 expired = true
67 continue
68 } else if err != nil {
69 return nil, err
70 }
71 }
72 if err := scanner.Err(); err != nil {
73 return nil, ErrInvalidPEMBlock
74 }
75
76 if expired {
77 return pool, ErrExpired
78 }
79
80 return pool, nil
81 }
82
83 // AddCAFromPEM verifies a Nebula CA certificate and adds it to the pool.
84 // Only the first pem encoded object will be consumed, any remaining bytes are returned.
85 // Parsed certificates will be verified and must be a CA
86 func (ncp *CAPool) AddCAFromPEM(pemBytes []byte) ([]byte, error) {
87 c, pemBytes, err := UnmarshalCertificateFromPEM(pemBytes)
88 if err != nil {
89 return pemBytes, err
90 }
91
92 err = ncp.AddCA(c)
93 if err != nil {
94 return pemBytes, err
95 }
96
97 return pemBytes, nil
98 }
99
100 // AddCA verifies a Nebula CA certificate and adds it to the pool.
101 func (ncp *CAPool) AddCA(c Certificate) error {
102 if !c.IsCA() {
103 return fmt.Errorf("%s: %w", c.Name(), ErrNotCA)
104 }
105
106 if !c.CheckSignature(c.PublicKey()) {
107 return fmt.Errorf("%s: %w", c.Name(), ErrNotSelfSigned)
108 }
109
110 sum, err := c.Fingerprint()
111 if err != nil {
112 return fmt.Errorf("could not calculate fingerprint for provided CA; error: %w; %s", err, c.Name())
113 }
114
115 cc := &CachedCertificate{
116 Certificate: c,
117 Fingerprint: sum,
118 InvertedGroups: make(map[string]struct{}),
119 }
120
121 for _, g := range c.Groups() {
122 cc.InvertedGroups[g] = struct{}{}
123 }
124
125 ncp.CAs[sum] = cc
126
127 if c.Expired(time.Now()) {
128 return fmt.Errorf("%s: %w", c.Name(), ErrExpired)
129 }
130
131 return nil
132 }
133
134 // BlocklistFingerprint adds a cert fingerprint to the blocklist
135 func (ncp *CAPool) BlocklistFingerprint(f string) {
136 ncp.certBlocklist[f] = struct{}{}
137 }
138
139 // ResetCertBlocklist removes all previously blocklisted cert fingerprints
140 func (ncp *CAPool) ResetCertBlocklist() {
141 ncp.certBlocklist = make(map[string]struct{})
142 }
143
144 // IsBlocklisted tests the provided fingerprint against the pools blocklist.
145 // Returns true if the fingerprint is blocked.
146 func (ncp *CAPool) IsBlocklisted(fingerprint string) bool {
147 if _, ok := ncp.certBlocklist[fingerprint]; ok {
148 return true
149 }
150
151 return false
152 }
153
154 // VerifyCertificate verifies the certificate is valid and is signed by a trusted CA in the pool.
155 // If the certificate is valid then the returned CachedCertificate can be used in subsequent verification attempts
156 // to increase performance.
157 func (ncp *CAPool) VerifyCertificate(now time.Time, c Certificate) (*CachedCertificate, error) {
158 if c == nil {
159 return nil, fmt.Errorf("no certificate")
160 }
161 fp, err := c.Fingerprint()
162 if err != nil {
163 return nil, fmt.Errorf("could not calculate fingerprint to verify: %w", err)
164 }
165
166 signer, err := ncp.verify(c, now, fp, "")
167 if err != nil {
168 return nil, err
169 }
170
171 // Pre nebula v1.10.3 could generate signatures in either high or low s form and validation
172 // of signatures allowed for either. Nebula v1.10.3 and beyond clamps signature generation to low-s form
173 // but validation still allows for either. Since a change in the signature bytes affects the fingerprint, we
174 // need to test both forms until such a time comes that we enforce low-s form on signature validation.
175 fp2, err := CalculateAlternateFingerprint(c)
176 if err != nil {
177 return nil, fmt.Errorf("could not calculate alternate fingerprint to verify: %w", err)
178 }
179 if fp2 != "" && ncp.IsBlocklisted(fp2) {
180 return nil, ErrBlockListed
181 }
182
183 cc := CachedCertificate{
184 Certificate: c,
185 InvertedGroups: make(map[string]struct{}),
186 Fingerprint: fp,
187 fingerprint2: fp2,
188 signerFingerprint: signer.Fingerprint,
189 }
190
191 for _, g := range c.Groups() {
192 cc.InvertedGroups[g] = struct{}{}
193 }
194
195 return &cc, nil
196 }
197
198 // VerifyCachedCertificate is the same as VerifyCertificate other than it operates on a pre-verified structure and
199 // is a cheaper operation to perform as a result.
200 func (ncp *CAPool) VerifyCachedCertificate(now time.Time, c *CachedCertificate) error {
201 // Check any available alternate fingerprint forms for this certificate, re P256 high-s/low-s
202 if c.fingerprint2 != "" && ncp.IsBlocklisted(c.fingerprint2) {
203 return ErrBlockListed
204 }
205
206 _, err := ncp.verify(c.Certificate, now, c.Fingerprint, c.signerFingerprint)
207 return err
208 }
209
210 func (ncp *CAPool) verify(c Certificate, now time.Time, certFp string, signerFp string) (*CachedCertificate, error) {
211 if ncp.IsBlocklisted(certFp) {
212 return nil, ErrBlockListed
213 }
214
215 signer, err := ncp.GetCAForCert(c)
216 if err != nil {
217 return nil, err
218 }
219
220 if signer.Certificate.Curve() != c.Curve() {
221 return nil, ErrCurveMismatch
222 }
223
224 if signer.Certificate.Expired(now) {
225 return nil, ErrRootExpired
226 }
227
228 if c.Expired(now) {
229 return nil, ErrExpired
230 }
231
232 // If we are checking a cached certificate then we can bail early here
233 // Either the root is no longer trusted or everything is fine
234 if len(signerFp) > 0 {
235 if signerFp != signer.Fingerprint {
236 return nil, ErrFingerprintMismatch
237 }
238 return signer, nil
239 }
240 if !c.CheckSignature(signer.Certificate.PublicKey()) {
241 return nil, ErrSignatureMismatch
242 }
243
244 err = CheckCAConstraints(signer.Certificate, c)
245 if err != nil {
246 return nil, err
247 }
248
249 return signer, nil
250 }
251
252 // GetCAForCert attempts to return the signing certificate for the provided certificate.
253 // No signature validation is performed
254 func (ncp *CAPool) GetCAForCert(c Certificate) (*CachedCertificate, error) {
255 issuer := c.Issuer()
256 if issuer == "" {
257 return nil, fmt.Errorf("no issuer in certificate")
258 }
259
260 signer, ok := ncp.CAs[issuer]
261 if ok {
262 return signer, nil
263 }
264
265 return nil, ErrCaNotFound
266 }
267
268 // GetFingerprints returns an array of trusted CA fingerprints
269 func (ncp *CAPool) GetFingerprints() []string {
270 fp := make([]string, len(ncp.CAs))
271
272 i := 0
273 for k := range ncp.CAs {
274 fp[i] = k
275 i++
276 }
277
278 return fp
279 }
280
281 // CheckCAConstraints returns an error if the sub certificate violates constraints present in the signer certificate.
282 func CheckCAConstraints(signer Certificate, sub Certificate) error {
283 return checkCAConstraints(signer, sub.NotBefore(), sub.NotAfter(), sub.Groups(), sub.Networks(), sub.UnsafeNetworks())
284 }
285
286 // checkCAConstraints is a very generic function allowing both Certificates and TBSCertificates to be tested.
287 func checkCAConstraints(signer Certificate, notBefore, notAfter time.Time, groups []string, networks, unsafeNetworks []netip.Prefix) error {
288 // Make sure this cert isn't valid after the root
289 if notAfter.After(signer.NotAfter()) {
290 return fmt.Errorf("certificate expires after signing certificate")
291 }
292
293 // Make sure this cert wasn't valid before the root
294 if notBefore.Before(signer.NotBefore()) {
295 return fmt.Errorf("certificate is valid before the signing certificate")
296 }
297
298 // If the signer has a limited set of groups make sure the cert only contains a subset
299 signerGroups := signer.Groups()
300 if len(signerGroups) > 0 {
301 for _, g := range groups {
302 if !slices.Contains(signerGroups, g) {
303 return fmt.Errorf("certificate contained a group not present on the signing ca: %s", g)
304 }
305 }
306 }
307
308 // If the signer has a limited set of ip ranges to issue from make sure the cert only contains a subset
309 signingNetworks := signer.Networks()
310 if len(signingNetworks) > 0 {
311 for _, certNetwork := range networks {
312 found := false
313 for _, signingNetwork := range signingNetworks {
314 if signingNetwork.Contains(certNetwork.Addr()) && signingNetwork.Bits() <= certNetwork.Bits() {
315 found = true
316 break
317 }
318 }
319
320 if !found {
321 return fmt.Errorf("certificate contained a network assignment outside the limitations of the signing ca: %s", certNetwork.String())
322 }
323 }
324 }
325
326 // If the signer has a limited set of subnet ranges to issue from make sure the cert only contains a subset
327 signingUnsafeNetworks := signer.UnsafeNetworks()
328 if len(signingUnsafeNetworks) > 0 {
329 for _, certUnsafeNetwork := range unsafeNetworks {
330 found := false
331 for _, caNetwork := range signingUnsafeNetworks {
332 if caNetwork.Contains(certUnsafeNetwork.Addr()) && caNetwork.Bits() <= certUnsafeNetwork.Bits() {
333 found = true
334 break
335 }
336 }
337
338 if !found {
339 return fmt.Errorf("certificate contained an unsafe network assignment outside the limitations of the signing ca: %s", certUnsafeNetwork.String())
340 }
341 }
342 }
343
344 return nil
345 }