pki.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. package nebula
  2. import (
  3. "encoding/binary"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "net"
  8. "net/netip"
  9. "os"
  10. "slices"
  11. "strings"
  12. "sync/atomic"
  13. "time"
  14. "github.com/gaissmai/bart"
  15. "github.com/sirupsen/logrus"
  16. "github.com/slackhq/nebula/cert"
  17. "github.com/slackhq/nebula/config"
  18. "github.com/slackhq/nebula/util"
  19. )
  20. type PKI struct {
  21. cs atomic.Pointer[CertState]
  22. caPool atomic.Pointer[cert.CAPool]
  23. l *logrus.Logger
  24. }
  25. type CertState struct {
  26. v1Cert cert.Certificate
  27. v1HandshakeBytes []byte
  28. v2Cert cert.Certificate
  29. v2HandshakeBytes []byte
  30. initiatingVersion cert.Version
  31. privateKey []byte
  32. pkcs11Backed bool
  33. cipher string
  34. myVpnNetworks []netip.Prefix
  35. myVpnNetworksTable *bart.Lite
  36. myVpnAddrs []netip.Addr
  37. myVpnAddrsTable *bart.Lite
  38. myVpnBroadcastAddrsTable *bart.Lite
  39. }
  40. func NewPKIFromConfig(l *logrus.Logger, c *config.C) (*PKI, error) {
  41. pki := &PKI{l: l}
  42. err := pki.reload(c, true)
  43. if err != nil {
  44. return nil, err
  45. }
  46. c.RegisterReloadCallback(func(c *config.C) {
  47. rErr := pki.reload(c, false)
  48. if rErr != nil {
  49. util.LogWithContextIfNeeded("Failed to reload PKI from config", rErr, l)
  50. }
  51. })
  52. return pki, nil
  53. }
  54. func (p *PKI) GetCAPool() *cert.CAPool {
  55. return p.caPool.Load()
  56. }
  57. func (p *PKI) getCertState() *CertState {
  58. return p.cs.Load()
  59. }
  60. func (p *PKI) reload(c *config.C, initial bool) error {
  61. err := p.reloadCerts(c, initial)
  62. if err != nil {
  63. if initial {
  64. return err
  65. }
  66. err.Log(p.l)
  67. }
  68. err = p.reloadCAPool(c)
  69. if err != nil {
  70. if initial {
  71. return err
  72. }
  73. err.Log(p.l)
  74. }
  75. return nil
  76. }
  77. func (p *PKI) reloadCerts(c *config.C, initial bool) *util.ContextualError {
  78. newState, err := newCertStateFromConfig(c, p.l)
  79. if err != nil {
  80. return util.NewContextualError("Could not load client cert", nil, err)
  81. }
  82. if !initial {
  83. currentState := p.cs.Load()
  84. if newState.v1Cert != nil {
  85. if currentState.v1Cert == nil {
  86. //adding certs is fine, actually. Networks-in-common confirmed in newCertState().
  87. } else {
  88. // did IP in cert change? if so, don't set. If we ever allow this, need to set p.firewallReloadNeeded
  89. if !slices.Equal(currentState.v1Cert.Networks(), newState.v1Cert.Networks()) {
  90. return util.NewContextualError(
  91. "Networks in new cert was different from old",
  92. m{"new_networks": newState.v1Cert.Networks(), "old_networks": currentState.v1Cert.Networks(), "cert_version": cert.Version1},
  93. nil,
  94. )
  95. }
  96. if currentState.v1Cert.Curve() != newState.v1Cert.Curve() {
  97. return util.NewContextualError(
  98. "Curve in new v1 cert was different from old",
  99. m{"new_curve": newState.v1Cert.Curve(), "old_curve": currentState.v1Cert.Curve(), "cert_version": cert.Version1},
  100. nil,
  101. )
  102. }
  103. }
  104. }
  105. if newState.v2Cert != nil {
  106. if currentState.v2Cert == nil {
  107. //adding certs is fine, actually
  108. } else {
  109. // did IP in cert change? if so, don't set
  110. if !slices.Equal(currentState.v2Cert.Networks(), newState.v2Cert.Networks()) {
  111. return util.NewContextualError(
  112. "Networks in new cert was different from old",
  113. m{"new_networks": newState.v2Cert.Networks(), "old_networks": currentState.v2Cert.Networks(), "cert_version": cert.Version2},
  114. nil,
  115. )
  116. }
  117. if currentState.v2Cert.Curve() != newState.v2Cert.Curve() {
  118. return util.NewContextualError(
  119. "Curve in new cert was different from old",
  120. m{"new_curve": newState.v2Cert.Curve(), "old_curve": currentState.v2Cert.Curve(), "cert_version": cert.Version2},
  121. nil,
  122. )
  123. }
  124. }
  125. } else if currentState.v2Cert != nil {
  126. //newState.v1Cert is non-nil bc empty certstates aren't permitted
  127. if newState.v1Cert == nil {
  128. return util.NewContextualError("v1 and v2 certs are nil, this should be impossible", nil, err)
  129. }
  130. //if we're going to v1-only, we need to make sure we didn't orphan any v2-cert vpnaddrs
  131. if !slices.Equal(currentState.v2Cert.Networks(), newState.v1Cert.Networks()) {
  132. return util.NewContextualError(
  133. "Removing a V2 cert is not permitted unless it has identical networks to the new V1 cert",
  134. m{"new_v1_networks": newState.v1Cert.Networks(), "old_v2_networks": currentState.v2Cert.Networks()},
  135. nil,
  136. )
  137. }
  138. }
  139. newUN := newState.GetDefaultCertificate().UnsafeNetworks()
  140. oldUN := currentState.GetDefaultCertificate().UnsafeNetworks()
  141. if !slices.Equal(newUN, oldUN) {
  142. //todo I don't love this, because other clients will see the new assignments and act on them, but we will not be able to.
  143. //I think we need to wire this into the firewall reload.
  144. p.l.WithFields(m{"previous": oldUN, "new": newUN}).Warning("UnsafeNetworks assignments differ. A restart is required in order for this to take effect.")
  145. }
  146. // Cipher cant be hot swapped so just leave it at what it was before
  147. newState.cipher = currentState.cipher
  148. } else {
  149. newState.cipher = c.GetString("cipher", "aes")
  150. //TODO: this sucks and we should make it not a global
  151. switch newState.cipher {
  152. case "aes":
  153. noiseEndianness = binary.BigEndian
  154. case "chachapoly":
  155. noiseEndianness = binary.LittleEndian
  156. default:
  157. return util.NewContextualError(
  158. "unknown cipher",
  159. m{"cipher": newState.cipher},
  160. nil,
  161. )
  162. }
  163. }
  164. p.cs.Store(newState)
  165. if initial {
  166. p.l.WithField("cert", newState).Debug("Client nebula certificate(s)")
  167. } else {
  168. p.l.WithField("cert", newState).Info("Client certificate(s) refreshed from disk")
  169. }
  170. return nil
  171. }
  172. func (p *PKI) reloadCAPool(c *config.C) *util.ContextualError {
  173. caPool, err := loadCAPoolFromConfig(p.l, c)
  174. if err != nil {
  175. return util.NewContextualError("Failed to load ca from config", nil, err)
  176. }
  177. p.caPool.Store(caPool)
  178. p.l.WithField("fingerprints", caPool.GetFingerprints()).Debug("Trusted CA fingerprints")
  179. return nil
  180. }
  181. func (cs *CertState) GetDefaultCertificate() cert.Certificate {
  182. c := cs.getCertificate(cs.initiatingVersion)
  183. if c == nil {
  184. panic("No default certificate found")
  185. }
  186. return c
  187. }
  188. func (cs *CertState) getCertificate(v cert.Version) cert.Certificate {
  189. switch v {
  190. case cert.Version1:
  191. return cs.v1Cert
  192. case cert.Version2:
  193. return cs.v2Cert
  194. }
  195. return nil
  196. }
  197. // getHandshakeBytes returns the cached bytes to be used in a handshake message for the requested version.
  198. // Callers must check if the return []byte is nil.
  199. func (cs *CertState) getHandshakeBytes(v cert.Version) []byte {
  200. switch v {
  201. case cert.Version1:
  202. return cs.v1HandshakeBytes
  203. case cert.Version2:
  204. return cs.v2HandshakeBytes
  205. default:
  206. return nil
  207. }
  208. }
  209. func (cs *CertState) String() string {
  210. b, err := cs.MarshalJSON()
  211. if err != nil {
  212. return fmt.Sprintf("error marshaling certificate state: %v", err)
  213. }
  214. return string(b)
  215. }
  216. func (cs *CertState) MarshalJSON() ([]byte, error) {
  217. msg := []json.RawMessage{}
  218. if cs.v1Cert != nil {
  219. b, err := cs.v1Cert.MarshalJSON()
  220. if err != nil {
  221. return nil, err
  222. }
  223. msg = append(msg, b)
  224. }
  225. if cs.v2Cert != nil {
  226. b, err := cs.v2Cert.MarshalJSON()
  227. if err != nil {
  228. return nil, err
  229. }
  230. msg = append(msg, b)
  231. }
  232. return json.Marshal(msg)
  233. }
  234. func newCertStateFromConfig(c *config.C, l *logrus.Logger) (*CertState, error) {
  235. var err error
  236. privPathOrPEM := c.GetString("pki.key", "")
  237. if privPathOrPEM == "" {
  238. return nil, errors.New("no pki.key path or PEM data provided")
  239. }
  240. rawKey, curve, isPkcs11, err := loadPrivateKey(privPathOrPEM)
  241. if err != nil {
  242. return nil, err
  243. }
  244. var rawCert []byte
  245. pubPathOrPEM := c.GetString("pki.cert", "")
  246. if pubPathOrPEM == "" {
  247. return nil, errors.New("no pki.cert path or PEM data provided")
  248. }
  249. if strings.Contains(pubPathOrPEM, "-----BEGIN") {
  250. rawCert = []byte(pubPathOrPEM)
  251. pubPathOrPEM = "<inline>"
  252. } else {
  253. rawCert, err = os.ReadFile(pubPathOrPEM)
  254. if err != nil {
  255. return nil, fmt.Errorf("unable to read pki.cert file %s: %s", pubPathOrPEM, err)
  256. }
  257. }
  258. var crt, v1, v2 cert.Certificate
  259. for {
  260. // Load the certificate
  261. crt, rawCert, err = loadCertificate(rawCert)
  262. if err != nil {
  263. return nil, err
  264. }
  265. switch crt.Version() {
  266. case cert.Version1:
  267. if v1 != nil {
  268. return nil, fmt.Errorf("v1 certificate already found in pki.cert")
  269. }
  270. v1 = crt
  271. case cert.Version2:
  272. if v2 != nil {
  273. return nil, fmt.Errorf("v2 certificate already found in pki.cert")
  274. }
  275. v2 = crt
  276. default:
  277. return nil, fmt.Errorf("unknown certificate version %v", crt.Version())
  278. }
  279. if len(rawCert) == 0 || strings.TrimSpace(string(rawCert)) == "" {
  280. break
  281. }
  282. }
  283. if v1 == nil && v2 == nil {
  284. return nil, errors.New("no certificates found in pki.cert")
  285. }
  286. useInitiatingVersion := uint32(1)
  287. if v1 == nil {
  288. // The only condition that requires v2 as the default is if only a v2 certificate is present
  289. // We do this to avoid having to configure it specifically in the config file
  290. useInitiatingVersion = 2
  291. }
  292. rawInitiatingVersion := c.GetUint32("pki.initiating_version", useInitiatingVersion)
  293. var initiatingVersion cert.Version
  294. switch rawInitiatingVersion {
  295. case 1:
  296. if v1 == nil {
  297. return nil, fmt.Errorf("can not use pki.initiating_version 1 without a v1 certificate in pki.cert")
  298. }
  299. initiatingVersion = cert.Version1
  300. case 2:
  301. initiatingVersion = cert.Version2
  302. default:
  303. return nil, fmt.Errorf("unknown pki.initiating_version: %v", rawInitiatingVersion)
  304. }
  305. return newCertState(l, initiatingVersion, v1, v2, isPkcs11, curve, rawKey)
  306. }
  307. func compareUnsafeNetworksAcrossCertVersions(v1, v2 cert.Certificate) error {
  308. if v1 == nil || v2 == nil {
  309. return nil //can't be a problem if we don't have one of the kinds of cert
  310. }
  311. v4UnsafeNets := 0
  312. for _, n := range v2.UnsafeNetworks() {
  313. if n.Addr().Is6() {
  314. continue // V1 certs can't have IPv6 unsafe networks
  315. } else {
  316. v4UnsafeNets++
  317. }
  318. if !slices.Contains(v1.UnsafeNetworks(), n) {
  319. return errors.New("UnsafeNetworks mismatch")
  320. }
  321. }
  322. if len(v1.UnsafeNetworks()) != v4UnsafeNets {
  323. return errors.New("UnsafeNetworks mismatch")
  324. }
  325. return nil
  326. }
  327. func newCertState(l *logrus.Logger, dv cert.Version, v1, v2 cert.Certificate, pkcs11backed bool, privateKeyCurve cert.Curve, privateKey []byte) (*CertState, error) {
  328. cs := CertState{
  329. privateKey: privateKey,
  330. pkcs11Backed: pkcs11backed,
  331. myVpnNetworksTable: new(bart.Lite),
  332. myVpnAddrsTable: new(bart.Lite),
  333. myVpnBroadcastAddrsTable: new(bart.Lite),
  334. }
  335. if v1 != nil && v2 != nil {
  336. if !slices.Equal(v1.PublicKey(), v2.PublicKey()) {
  337. return nil, util.NewContextualError("v1 and v2 public keys are not the same, ignoring", nil, nil)
  338. }
  339. if v1.Curve() != v2.Curve() {
  340. return nil, util.NewContextualError("v1 and v2 curve are not the same, ignoring", nil, nil)
  341. }
  342. if v1.Networks()[0] != v2.Networks()[0] {
  343. return nil, util.NewContextualError("v1 and v2 networks are not the same", nil, nil)
  344. }
  345. cs.initiatingVersion = dv
  346. warn := compareUnsafeNetworksAcrossCertVersions(v1, v2)
  347. if warn != nil {
  348. l.WithFields(m{"UnsafeNetworksV1": v1.UnsafeNetworks(), "UnsafeNetworksV2": v2.UnsafeNetworks()}).
  349. Warning("the IPv4 UnsafeNetworks assigned in the V1 certificate do not match the ones in V2")
  350. }
  351. }
  352. if v1 != nil {
  353. if pkcs11backed {
  354. //NOTE: We do not currently have a method to verify a public private key pair when the private key is in an hsm
  355. } else {
  356. if err := v1.VerifyPrivateKey(privateKeyCurve, privateKey); err != nil {
  357. return nil, fmt.Errorf("private key is not a pair with public key in nebula cert")
  358. }
  359. }
  360. v1hs, err := v1.MarshalForHandshakes()
  361. if err != nil {
  362. return nil, fmt.Errorf("error marshalling certificate for handshake: %w", err)
  363. }
  364. cs.v1Cert = v1
  365. cs.v1HandshakeBytes = v1hs
  366. if cs.initiatingVersion == 0 {
  367. cs.initiatingVersion = cert.Version1
  368. }
  369. }
  370. if v2 != nil {
  371. if pkcs11backed {
  372. //NOTE: We do not currently have a method to verify a public private key pair when the private key is in an hsm
  373. } else {
  374. if err := v2.VerifyPrivateKey(privateKeyCurve, privateKey); err != nil {
  375. return nil, fmt.Errorf("private key is not a pair with public key in nebula cert")
  376. }
  377. }
  378. v2hs, err := v2.MarshalForHandshakes()
  379. if err != nil {
  380. return nil, fmt.Errorf("error marshalling certificate for handshake: %w", err)
  381. }
  382. cs.v2Cert = v2
  383. cs.v2HandshakeBytes = v2hs
  384. if cs.initiatingVersion == 0 {
  385. cs.initiatingVersion = cert.Version2
  386. }
  387. }
  388. var crt cert.Certificate
  389. crt = cs.getCertificate(cert.Version2)
  390. if crt == nil {
  391. // v2 certificates are a superset, only look at v1 if its all we have
  392. crt = cs.getCertificate(cert.Version1)
  393. }
  394. for _, network := range crt.Networks() {
  395. cs.myVpnNetworks = append(cs.myVpnNetworks, network)
  396. cs.myVpnNetworksTable.Insert(network)
  397. cs.myVpnAddrs = append(cs.myVpnAddrs, network.Addr())
  398. cs.myVpnAddrsTable.Insert(netip.PrefixFrom(network.Addr(), network.Addr().BitLen()))
  399. if network.Addr().Is4() {
  400. addr := network.Masked().Addr().As4()
  401. mask := net.CIDRMask(network.Bits(), network.Addr().BitLen())
  402. binary.BigEndian.PutUint32(addr[:], binary.BigEndian.Uint32(addr[:])|^binary.BigEndian.Uint32(mask))
  403. cs.myVpnBroadcastAddrsTable.Insert(netip.PrefixFrom(netip.AddrFrom4(addr), network.Addr().BitLen()))
  404. }
  405. }
  406. return &cs, nil
  407. }
  408. func loadPrivateKey(privPathOrPEM string) (rawKey []byte, curve cert.Curve, isPkcs11 bool, err error) {
  409. var pemPrivateKey []byte
  410. if strings.Contains(privPathOrPEM, "-----BEGIN") {
  411. pemPrivateKey = []byte(privPathOrPEM)
  412. privPathOrPEM = "<inline>"
  413. rawKey, _, curve, err = cert.UnmarshalPrivateKeyFromPEM(pemPrivateKey)
  414. if err != nil {
  415. return nil, curve, false, fmt.Errorf("error while unmarshaling pki.key %s: %s", privPathOrPEM, err)
  416. }
  417. } else if strings.HasPrefix(privPathOrPEM, "pkcs11:") {
  418. rawKey = []byte(privPathOrPEM)
  419. return rawKey, cert.Curve_P256, true, nil
  420. } else {
  421. pemPrivateKey, err = os.ReadFile(privPathOrPEM)
  422. if err != nil {
  423. return nil, curve, false, fmt.Errorf("unable to read pki.key file %s: %s", privPathOrPEM, err)
  424. }
  425. rawKey, _, curve, err = cert.UnmarshalPrivateKeyFromPEM(pemPrivateKey)
  426. if err != nil {
  427. return nil, curve, false, fmt.Errorf("error while unmarshaling pki.key %s: %s", privPathOrPEM, err)
  428. }
  429. }
  430. return
  431. }
  432. func loadCertificate(b []byte) (cert.Certificate, []byte, error) {
  433. c, b, err := cert.UnmarshalCertificateFromPEM(b)
  434. if err != nil {
  435. return nil, b, fmt.Errorf("error while unmarshaling pki.cert: %w", err)
  436. }
  437. if c.Expired(time.Now()) {
  438. return nil, b, fmt.Errorf("nebula certificate for this host is expired")
  439. }
  440. if len(c.Networks()) == 0 {
  441. return nil, b, fmt.Errorf("no networks encoded in certificate")
  442. }
  443. if c.IsCA() {
  444. return nil, b, fmt.Errorf("host certificate is a CA certificate")
  445. }
  446. return c, b, nil
  447. }
  448. func loadCAPoolFromConfig(l *logrus.Logger, c *config.C) (*cert.CAPool, error) {
  449. var rawCA []byte
  450. var err error
  451. caPathOrPEM := c.GetString("pki.ca", "")
  452. if caPathOrPEM == "" {
  453. return nil, errors.New("no pki.ca path or PEM data provided")
  454. }
  455. if strings.Contains(caPathOrPEM, "-----BEGIN") {
  456. rawCA = []byte(caPathOrPEM)
  457. } else {
  458. rawCA, err = os.ReadFile(caPathOrPEM)
  459. if err != nil {
  460. return nil, fmt.Errorf("unable to read pki.ca file %s: %s", caPathOrPEM, err)
  461. }
  462. }
  463. caPool, err := cert.NewCAPoolFromPEM(rawCA)
  464. if errors.Is(err, cert.ErrExpired) {
  465. var expired int
  466. for _, crt := range caPool.CAs {
  467. if crt.Certificate.Expired(time.Now()) {
  468. expired++
  469. l.WithField("cert", crt).Warn("expired certificate present in CA pool")
  470. }
  471. }
  472. if expired >= len(caPool.CAs) {
  473. return nil, errors.New("no valid CA certificates present")
  474. }
  475. } else if err != nil {
  476. return nil, fmt.Errorf("error while adding CA certificate to CA trust store: %s", err)
  477. }
  478. bl := c.GetStringSlice("pki.blocklist", []string{})
  479. if len(bl) > 0 {
  480. for _, fp := range bl {
  481. caPool.BlocklistFingerprint(fp)
  482. }
  483. l.WithField("fingerprintCount", len(bl)).Info("Blocklisted certificates")
  484. }
  485. return caPool, nil
  486. }