pki.go 19 KB

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