Debian Codegraph @

pki.go

raw
1 package nebula
2
3 import (
4 "encoding/binary"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "io"
9 "log/slog"
10 "net"
11 "net/netip"
12 "os"
13 "slices"
14 "strings"
15 "sync/atomic"
16 "time"
17
18 "github.com/flynn/noise"
19 "github.com/gaissmai/bart"
20 "github.com/slackhq/nebula/cert"
21 "github.com/slackhq/nebula/config"
22 "github.com/slackhq/nebula/handshake"
23 "github.com/slackhq/nebula/noiseutil"
24 "github.com/slackhq/nebula/util"
25 )
26
27 type PKI struct {
28 cs atomic.Pointer[CertState]
29 caPool atomic.Pointer[cert.CAPool]
30 l *slog.Logger
31 }
32
33 type CertState struct {
34 v1Cert cert.Certificate
35 v1Credential *handshake.Credential
36
37 v2Cert cert.Certificate
38 v2Credential *handshake.Credential
39
40 initiatingVersion cert.Version
41 privateKey []byte
42 pkcs11Backed bool
43 cipher string
44
45 myVpnNetworks []netip.Prefix
46 myVpnNetworksTable *bart.Lite
47 myVpnAddrs []netip.Addr
48 myVpnAddrsTable *bart.Lite
49 myVpnBroadcastAddrsTable *bart.Lite
50 }
51
52 func NewPKIFromConfig(l *slog.Logger, c *config.C) (*PKI, error) {
53 pki := &PKI{l: l}
54 err := pki.reload(c, true)
55 if err != nil {
56 return nil, err
57 }
58
59 c.RegisterReloadCallback(func(c *config.C) {
60 rErr := pki.reload(c, false)
61 if rErr != nil {
62 util.LogWithContextIfNeeded("Failed to reload PKI from config", rErr, l)
63 }
64 })
65
66 return pki, nil
67 }
68
69 func (p *PKI) GetCAPool() *cert.CAPool {
70 return p.caPool.Load()
71 }
72
73 func (p *PKI) getCertState() *CertState {
74 return p.cs.Load()
75 }
76
77 func (p *PKI) reload(c *config.C, initial bool) error {
78 err := p.reloadCerts(c, initial)
79 if err != nil {
80 if initial {
81 return err
82 }
83 err.Log(p.l)
84 }
85
86 err = p.reloadCAPool(c)
87 if err != nil {
88 if initial {
89 return err
90 }
91 err.Log(p.l)
92 }
93
94 return nil
95 }
96
97 func (p *PKI) reloadCerts(c *config.C, initial bool) *util.ContextualError {
98 var cipher string
99 var currentState *CertState
100 if initial {
101 cipher = c.GetString("cipher", "aes")
102 switch cipher {
103 case "aes", "chachapoly":
104 // Each post-handshake CipherState in noiseutil hardcodes its own
105 // nonce endianness now, so there's nothing to set up here.
106 default:
107 return util.NewContextualError(
108 "unknown cipher",
109 m{"cipher": cipher},
110 nil,
111 )
112 }
113 } else {
114 // Cipher cant be hot swapped so just leave it at what it was before
115 currentState = p.cs.Load()
116 cipher = currentState.cipher
117 }
118
119 newState, err := newCertStateFromConfig(c, cipher)
120 if err != nil {
121 return util.NewContextualError("Could not load client cert", nil, err)
122 }
123
124 if currentState != nil {
125 if newState.v1Cert != nil {
126 if currentState.v1Cert == nil {
127 //adding certs is fine, actually. Networks-in-common confirmed in newCertState().
128 } else {
129 // did IP in cert change? if so, don't set
130 if !slices.Equal(currentState.v1Cert.Networks(), newState.v1Cert.Networks()) {
131 return util.NewContextualError(
132 "Networks in new cert was different from old",
133 m{"new_networks": newState.v1Cert.Networks(), "old_networks": currentState.v1Cert.Networks(), "cert_version": cert.Version1},
134 nil,
135 )
136 }
137
138 if currentState.v1Cert.Curve() != newState.v1Cert.Curve() {
139 return util.NewContextualError(
140 "Curve in new v1 cert was different from old",
141 m{"new_curve": newState.v1Cert.Curve(), "old_curve": currentState.v1Cert.Curve(), "cert_version": cert.Version1},
142 nil,
143 )
144 }
145 }
146 }
147
148 if newState.v2Cert != nil {
149 if currentState.v2Cert == nil {
150 //adding certs is fine, actually
151 } else {
152 // did IP in cert change? if so, don't set
153 if !slices.Equal(currentState.v2Cert.Networks(), newState.v2Cert.Networks()) {
154 return util.NewContextualError(
155 "Networks in new cert was different from old",
156 m{"new_networks": newState.v2Cert.Networks(), "old_networks": currentState.v2Cert.Networks(), "cert_version": cert.Version2},
157 nil,
158 )
159 }
160
161 if currentState.v2Cert.Curve() != newState.v2Cert.Curve() {
162 return util.NewContextualError(
163 "Curve in new cert was different from old",
164 m{"new_curve": newState.v2Cert.Curve(), "old_curve": currentState.v2Cert.Curve(), "cert_version": cert.Version2},
165 nil,
166 )
167 }
168 }
169
170 } else if currentState.v2Cert != nil {
171 //newState.v1Cert is non-nil bc empty certstates aren't permitted
172 if newState.v1Cert == nil {
173 return util.NewContextualError("v1 and v2 certs are nil, this should be impossible", nil, err)
174 }
175 //if we're going to v1-only, we need to make sure we didn't orphan any v2-cert vpnaddrs
176 if !slices.Equal(currentState.v2Cert.Networks(), newState.v1Cert.Networks()) {
177 return util.NewContextualError(
178 "Removing a V2 cert is not permitted unless it has identical networks to the new V1 cert",
179 m{"new_v1_networks": newState.v1Cert.Networks(), "old_v2_networks": currentState.v2Cert.Networks()},
180 nil,
181 )
182 }
183 }
184 }
185
186 p.cs.Store(newState)
187
188 if initial {
189 p.l.Debug("Client nebula certificate(s)", "cert", newState)
190 } else {
191 p.l.Info("Client certificate(s) refreshed from disk", "cert", newState)
192 }
193 return nil
194 }
195
196 func (p *PKI) reloadCAPool(c *config.C) *util.ContextualError {
197 caPool, err := loadCAPoolFromConfig(p.l, c)
198 if err != nil {
199 return util.NewContextualError("Failed to load ca from config", nil, err)
200 }
201
202 p.caPool.Store(caPool)
203 p.l.Debug("Trusted CA fingerprints", "fingerprints", caPool.GetFingerprints())
204 return nil
205 }
206
207 func (cs *CertState) GetDefaultCertificate() cert.Certificate {
208 c := cs.getCertificate(cs.initiatingVersion)
209 if c == nil {
210 panic("No default certificate found")
211 }
212 return c
213 }
214
215 // DefaultVersion returns the preferred cert version for initiating handshakes.
216 func (cs *CertState) DefaultVersion() cert.Version { return cs.initiatingVersion }
217
218 // GetCredential returns the pre-computed handshake credential for the given version, or nil.
219 func (cs *CertState) GetCredential(v cert.Version) *handshake.Credential {
220 switch v {
221 case cert.Version1:
222 return cs.v1Credential
223 case cert.Version2:
224 return cs.v2Credential
225 }
226 return nil
227 }
228
229 func (cs *CertState) getCertificate(v cert.Version) cert.Certificate {
230 switch v {
231 case cert.Version1:
232 return cs.v1Cert
233 case cert.Version2:
234 return cs.v2Cert
235 }
236
237 return nil
238 }
239
240 func newCipherSuite(curve cert.Curve, pkcs11backed bool, cipher string) (noise.CipherSuite, error) {
241 var dhFunc noise.DHFunc
242 switch curve {
243 case cert.Curve_CURVE25519:
244 dhFunc = noise.DH25519
245 case cert.Curve_P256:
246 if pkcs11backed {
247 dhFunc = noiseutil.DHP256PKCS11
248 } else {
249 dhFunc = noiseutil.DHP256
250 }
251 default:
252 return nil, fmt.Errorf("unsupported curve: %s", curve)
253 }
254
255 if cipher == "chachapoly" {
256 return noise.NewCipherSuite(dhFunc, noise.CipherChaChaPoly, noise.HashSHA256), nil
257 }
258 return noise.NewCipherSuite(dhFunc, noiseutil.CipherAESGCM, noise.HashSHA256), nil
259 }
260
261 func (cs *CertState) String() string {
262 b, err := cs.MarshalJSON()
263 if err != nil {
264 return fmt.Sprintf("error marshaling certificate state: %v", err)
265 }
266 return string(b)
267 }
268
269 func (cs *CertState) MarshalJSON() ([]byte, error) {
270 msg := []json.RawMessage{}
271 if cs.v1Cert != nil {
272 b, err := cs.v1Cert.MarshalJSON()
273 if err != nil {
274 return nil, err
275 }
276 msg = append(msg, b)
277 }
278
279 if cs.v2Cert != nil {
280 b, err := cs.v2Cert.MarshalJSON()
281 if err != nil {
282 return nil, err
283 }
284 msg = append(msg, b)
285 }
286
287 return json.Marshal(msg)
288 }
289
290 func newCertStateFromConfig(c *config.C, cipher string) (*CertState, error) {
291 var err error
292
293 privPathOrPEM := c.GetString("pki.key", "")
294 if privPathOrPEM == "" {
295 return nil, errors.New("no pki.key path or PEM data provided")
296 }
297
298 rawKey, curve, isPkcs11, err := loadPrivateKey(privPathOrPEM)
299 if err != nil {
300 return nil, err
301 }
302
303 var rawCert []byte
304
305 pubPathOrPEM := c.GetString("pki.cert", "")
306 if pubPathOrPEM == "" {
307 return nil, errors.New("no pki.cert path or PEM data provided")
308 }
309
310 if strings.Contains(pubPathOrPEM, "-----BEGIN") {
311 rawCert = []byte(pubPathOrPEM)
312 pubPathOrPEM = "<inline>"
313
314 } else {
315 rawCert, err = os.ReadFile(pubPathOrPEM)
316 if err != nil {
317 return nil, fmt.Errorf("unable to read pki.cert file %s: %s", pubPathOrPEM, err)
318 }
319 }
320
321 var crt, v1, v2 cert.Certificate
322 for {
323 // Load the certificate
324 crt, rawCert, err = loadCertificate(rawCert)
325 if err != nil {
326 return nil, err
327 }
328
329 switch crt.Version() {
330 case cert.Version1:
331 if v1 != nil {
332 return nil, fmt.Errorf("v1 certificate already found in pki.cert")
333 }
334 v1 = crt
335 case cert.Version2:
336 if v2 != nil {
337 return nil, fmt.Errorf("v2 certificate already found in pki.cert")
338 }
339 v2 = crt
340 default:
341 return nil, fmt.Errorf("unknown certificate version %v", crt.Version())
342 }
343
344 if len(rawCert) == 0 || strings.TrimSpace(string(rawCert)) == "" {
345 break
346 }
347 }
348
349 if v1 == nil && v2 == nil {
350 return nil, errors.New("no certificates found in pki.cert")
351 }
352
353 useInitiatingVersion := uint32(1)
354 if v1 == nil {
355 // The only condition that requires v2 as the default is if only a v2 certificate is present
356 // We do this to avoid having to configure it specifically in the config file
357 useInitiatingVersion = 2
358 }
359
360 rawInitiatingVersion := c.GetUint32("pki.initiating_version", useInitiatingVersion)
361 var initiatingVersion cert.Version
362 switch rawInitiatingVersion {
363 case 1:
364 if v1 == nil {
365 return nil, fmt.Errorf("can not use pki.initiating_version 1 without a v1 certificate in pki.cert")
366 }
367 initiatingVersion = cert.Version1
368 case 2:
369 initiatingVersion = cert.Version2
370 default:
371 return nil, fmt.Errorf("unknown pki.initiating_version: %v", rawInitiatingVersion)
372 }
373
374 return newCertState(initiatingVersion, v1, v2, isPkcs11, curve, rawKey, cipher)
375 }
376
377 func newCertState(dv cert.Version, v1, v2 cert.Certificate, pkcs11backed bool, privateKeyCurve cert.Curve, privateKey []byte, cipher string) (*CertState, error) {
378 cs := CertState{
379 privateKey: privateKey,
380 pkcs11Backed: pkcs11backed,
381 cipher: cipher,
382 myVpnNetworksTable: new(bart.Lite),
383 myVpnAddrsTable: new(bart.Lite),
384 myVpnBroadcastAddrsTable: new(bart.Lite),
385 }
386
387 if v1 != nil && v2 != nil {
388 if !slices.Equal(v1.PublicKey(), v2.PublicKey()) {
389 return nil, util.NewContextualError("v1 and v2 public keys are not the same, ignoring", nil, nil)
390 }
391
392 if v1.Curve() != v2.Curve() {
393 return nil, util.NewContextualError("v1 and v2 curve are not the same, ignoring", nil, nil)
394 }
395
396 if v1.Networks()[0] != v2.Networks()[0] {
397 return nil, util.NewContextualError("v1 and v2 networks are not the same", nil, nil)
398 }
399
400 cs.initiatingVersion = dv
401 }
402
403 if v1 != nil {
404 if pkcs11backed {
405 //NOTE: We do not currently have a method to verify a public private key pair when the private key is in an hsm
406 } else {
407 if err := v1.VerifyPrivateKey(privateKeyCurve, privateKey); err != nil {
408 return nil, fmt.Errorf("private key is not a pair with public key in nebula cert")
409 }
410 }
411
412 v1hs, err := v1.MarshalForHandshakes()
413 if err != nil {
414 return nil, fmt.Errorf("error marshalling v1 certificate for handshake: %w", err)
415 }
416 ncs, err := newCipherSuite(v1.Curve(), pkcs11backed, cipher)
417 if err != nil {
418 return nil, err
419 }
420 cs.v1Cert = v1
421 cs.v1Credential = handshake.NewCredential(v1, v1hs, privateKey, ncs)
422
423 if cs.initiatingVersion == 0 {
424 cs.initiatingVersion = cert.Version1
425 }
426 }
427
428 if v2 != nil {
429 if pkcs11backed {
430 //NOTE: We do not currently have a method to verify a public private key pair when the private key is in an hsm
431 } else {
432 if err := v2.VerifyPrivateKey(privateKeyCurve, privateKey); err != nil {
433 return nil, fmt.Errorf("private key is not a pair with public key in nebula cert")
434 }
435 }
436
437 v2hs, err := v2.MarshalForHandshakes()
438 if err != nil {
439 return nil, fmt.Errorf("error marshalling v2 certificate for handshake: %w", err)
440 }
441 ncs, err := newCipherSuite(v2.Curve(), pkcs11backed, cipher)
442 if err != nil {
443 return nil, err
444 }
445 cs.v2Cert = v2
446 cs.v2Credential = handshake.NewCredential(v2, v2hs, privateKey, ncs)
447
448 if cs.initiatingVersion == 0 {
449 cs.initiatingVersion = cert.Version2
450 }
451 }
452
453 var crt cert.Certificate
454 crt = cs.getCertificate(cert.Version2)
455 if crt == nil {
456 // v2 certificates are a superset, only look at v1 if its all we have
457 crt = cs.getCertificate(cert.Version1)
458 }
459
460 for _, network := range crt.Networks() {
461 cs.myVpnNetworks = append(cs.myVpnNetworks, network)
462 cs.myVpnNetworksTable.Insert(network)
463
464 cs.myVpnAddrs = append(cs.myVpnAddrs, network.Addr())
465 cs.myVpnAddrsTable.Insert(netip.PrefixFrom(network.Addr(), network.Addr().BitLen()))
466
467 if network.Addr().Is4() {
468 addr := network.Masked().Addr().As4()
469 mask := net.CIDRMask(network.Bits(), network.Addr().BitLen())
470 binary.BigEndian.PutUint32(addr[:], binary.BigEndian.Uint32(addr[:])|^binary.BigEndian.Uint32(mask))
471 cs.myVpnBroadcastAddrsTable.Insert(netip.PrefixFrom(netip.AddrFrom4(addr), network.Addr().BitLen()))
472 }
473 }
474
475 return &cs, nil
476 }
477
478 func loadPrivateKey(privPathOrPEM string) (rawKey []byte, curve cert.Curve, isPkcs11 bool, err error) {
479 var pemPrivateKey []byte
480 if strings.Contains(privPathOrPEM, "-----BEGIN") {
481 pemPrivateKey = []byte(privPathOrPEM)
482 privPathOrPEM = "<inline>"
483 rawKey, _, curve, err = cert.UnmarshalPrivateKeyFromPEM(pemPrivateKey)
484 if err != nil {
485 return nil, curve, false, fmt.Errorf("error while unmarshaling pki.key %s: %s", privPathOrPEM, err)
486 }
487 } else if strings.HasPrefix(privPathOrPEM, "pkcs11:") {
488 rawKey = []byte(privPathOrPEM)
489 return rawKey, cert.Curve_P256, true, nil
490 } else {
491 pemPrivateKey, err = os.ReadFile(privPathOrPEM)
492 if err != nil {
493 return nil, curve, false, fmt.Errorf("unable to read pki.key file %s: %s", privPathOrPEM, err)
494 }
495 rawKey, _, curve, err = cert.UnmarshalPrivateKeyFromPEM(pemPrivateKey)
496 if err != nil {
497 return nil, curve, false, fmt.Errorf("error while unmarshaling pki.key %s: %s", privPathOrPEM, err)
498 }
499 }
500
501 return
502 }
503
504 func loadCertificate(b []byte) (cert.Certificate, []byte, error) {
505 c, b, err := cert.UnmarshalCertificateFromPEM(b)
506 if err != nil {
507 return nil, b, fmt.Errorf("error while unmarshaling pki.cert: %w", err)
508 }
509
510 if c.Expired(time.Now()) {
511 return nil, b, fmt.Errorf("nebula certificate for this host is expired")
512 }
513
514 if len(c.Networks()) == 0 {
515 return nil, b, fmt.Errorf("no networks encoded in certificate")
516 }
517
518 if c.IsCA() {
519 return nil, b, fmt.Errorf("host certificate is a CA certificate")
520 }
521
522 return c, b, nil
523 }
524
525 func loadCAPoolFromConfig(l *slog.Logger, c *config.C) (*cert.CAPool, error) {
526 caPathOrPEM := c.GetString("pki.ca", "")
527 if caPathOrPEM == "" {
528 return nil, errors.New("no pki.ca path or PEM data provided")
529 }
530
531 var caReader io.ReadCloser
532 var err error
533
534 if strings.Contains(caPathOrPEM, "-----BEGIN") {
535 caReader = io.NopCloser(strings.NewReader(caPathOrPEM))
536 } else {
537 caReader, err = os.Open(caPathOrPEM)
538 if err != nil {
539 return nil, fmt.Errorf("unable to read pki.ca file %s: %s", caPathOrPEM, err)
540 }
541 }
542 defer caReader.Close()
543
544 caPool, err := cert.NewCAPoolFromPEMReader(caReader)
545 if errors.Is(err, cert.ErrExpired) {
546 var expired int
547 for _, crt := range caPool.CAs {
548 if crt.Certificate.Expired(time.Now()) {
549 expired++
550 l.Warn("expired certificate present in CA pool", "cert", crt)
551 }
552 }
553
554 if expired >= len(caPool.CAs) {
555 return nil, errors.New("no valid CA certificates present")
556 }
557
558 } else if err != nil {
559 return nil, fmt.Errorf("error while adding CA certificate to CA trust store: %s", err)
560 }
561
562 bl := c.GetStringSlice("pki.blocklist", []string{})
563 if len(bl) > 0 {
564 for _, fp := range bl {
565 caPool.BlocklistFingerprint(fp)
566 }
567
568 l.Info("Blocklisted certificates", "fingerprintCount", len(bl))
569 }
570
571 return caPool, nil
572 }