pki.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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)
  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
  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. // Cipher cant be hot swapped so just leave it at what it was before
  140. newState.cipher = currentState.cipher
  141. } else {
  142. newState.cipher = c.GetString("cipher", "aes")
  143. //TODO: this sucks and we should make it not a global
  144. switch newState.cipher {
  145. case "aes":
  146. noiseEndianness = binary.BigEndian
  147. case "chachapoly":
  148. noiseEndianness = binary.LittleEndian
  149. default:
  150. return util.NewContextualError(
  151. "unknown cipher",
  152. m{"cipher": newState.cipher},
  153. nil,
  154. )
  155. }
  156. }
  157. p.cs.Store(newState)
  158. if initial {
  159. p.l.WithField("cert", newState).Debug("Client nebula certificate(s)")
  160. } else {
  161. p.l.WithField("cert", newState).Info("Client certificate(s) refreshed from disk")
  162. }
  163. return nil
  164. }
  165. func (p *PKI) reloadCAPool(c *config.C) *util.ContextualError {
  166. caPool, err := loadCAPoolFromConfig(p.l, c)
  167. if err != nil {
  168. return util.NewContextualError("Failed to load ca from config", nil, err)
  169. }
  170. p.caPool.Store(caPool)
  171. p.l.WithField("fingerprints", caPool.GetFingerprints()).Debug("Trusted CA fingerprints")
  172. return nil
  173. }
  174. func (cs *CertState) GetDefaultCertificate() cert.Certificate {
  175. c := cs.getCertificate(cs.initiatingVersion)
  176. if c == nil {
  177. panic("No default certificate found")
  178. }
  179. return c
  180. }
  181. func (cs *CertState) getCertificate(v cert.Version) cert.Certificate {
  182. switch v {
  183. case cert.Version1:
  184. return cs.v1Cert
  185. case cert.Version2:
  186. return cs.v2Cert
  187. }
  188. return nil
  189. }
  190. // getHandshakeBytes returns the cached bytes to be used in a handshake message for the requested version.
  191. // Callers must check if the return []byte is nil.
  192. func (cs *CertState) getHandshakeBytes(v cert.Version) []byte {
  193. switch v {
  194. case cert.Version1:
  195. return cs.v1HandshakeBytes
  196. case cert.Version2:
  197. return cs.v2HandshakeBytes
  198. default:
  199. return nil
  200. }
  201. }
  202. func (cs *CertState) String() string {
  203. b, err := cs.MarshalJSON()
  204. if err != nil {
  205. return fmt.Sprintf("error marshaling certificate state: %v", err)
  206. }
  207. return string(b)
  208. }
  209. func (cs *CertState) MarshalJSON() ([]byte, error) {
  210. msg := []json.RawMessage{}
  211. if cs.v1Cert != nil {
  212. b, err := cs.v1Cert.MarshalJSON()
  213. if err != nil {
  214. return nil, err
  215. }
  216. msg = append(msg, b)
  217. }
  218. if cs.v2Cert != nil {
  219. b, err := cs.v2Cert.MarshalJSON()
  220. if err != nil {
  221. return nil, err
  222. }
  223. msg = append(msg, b)
  224. }
  225. return json.Marshal(msg)
  226. }
  227. func newCertStateFromConfig(c *config.C) (*CertState, error) {
  228. var err error
  229. privPathOrPEM := c.GetString("pki.key", "")
  230. if privPathOrPEM == "" {
  231. return nil, errors.New("no pki.key path or PEM data provided")
  232. }
  233. rawKey, curve, isPkcs11, err := loadPrivateKey(privPathOrPEM)
  234. if err != nil {
  235. return nil, err
  236. }
  237. var rawCert []byte
  238. pubPathOrPEM := c.GetString("pki.cert", "")
  239. if pubPathOrPEM == "" {
  240. return nil, errors.New("no pki.cert path or PEM data provided")
  241. }
  242. if strings.Contains(pubPathOrPEM, "-----BEGIN") {
  243. rawCert = []byte(pubPathOrPEM)
  244. pubPathOrPEM = "<inline>"
  245. } else {
  246. rawCert, err = os.ReadFile(pubPathOrPEM)
  247. if err != nil {
  248. return nil, fmt.Errorf("unable to read pki.cert file %s: %s", pubPathOrPEM, err)
  249. }
  250. }
  251. var crt, v1, v2 cert.Certificate
  252. for {
  253. // Load the certificate
  254. crt, rawCert, err = loadCertificate(rawCert)
  255. if err != nil {
  256. return nil, err
  257. }
  258. switch crt.Version() {
  259. case cert.Version1:
  260. if v1 != nil {
  261. return nil, fmt.Errorf("v1 certificate already found in pki.cert")
  262. }
  263. v1 = crt
  264. case cert.Version2:
  265. if v2 != nil {
  266. return nil, fmt.Errorf("v2 certificate already found in pki.cert")
  267. }
  268. v2 = crt
  269. default:
  270. return nil, fmt.Errorf("unknown certificate version %v", crt.Version())
  271. }
  272. if len(rawCert) == 0 || strings.TrimSpace(string(rawCert)) == "" {
  273. break
  274. }
  275. }
  276. if v1 == nil && v2 == nil {
  277. return nil, errors.New("no certificates found in pki.cert")
  278. }
  279. useInitiatingVersion := uint32(1)
  280. if v1 == nil {
  281. // The only condition that requires v2 as the default is if only a v2 certificate is present
  282. // We do this to avoid having to configure it specifically in the config file
  283. useInitiatingVersion = 2
  284. }
  285. rawInitiatingVersion := c.GetUint32("pki.initiating_version", useInitiatingVersion)
  286. var initiatingVersion cert.Version
  287. switch rawInitiatingVersion {
  288. case 1:
  289. if v1 == nil {
  290. return nil, fmt.Errorf("can not use pki.initiating_version 1 without a v1 certificate in pki.cert")
  291. }
  292. initiatingVersion = cert.Version1
  293. case 2:
  294. initiatingVersion = cert.Version2
  295. default:
  296. return nil, fmt.Errorf("unknown pki.initiating_version: %v", rawInitiatingVersion)
  297. }
  298. return newCertState(initiatingVersion, v1, v2, isPkcs11, curve, rawKey)
  299. }
  300. func newCertState(dv cert.Version, v1, v2 cert.Certificate, pkcs11backed bool, privateKeyCurve cert.Curve, privateKey []byte) (*CertState, error) {
  301. cs := CertState{
  302. privateKey: privateKey,
  303. pkcs11Backed: pkcs11backed,
  304. myVpnNetworksTable: new(bart.Lite),
  305. myVpnAddrsTable: new(bart.Lite),
  306. myVpnBroadcastAddrsTable: new(bart.Lite),
  307. }
  308. if v1 != nil && v2 != nil {
  309. if !slices.Equal(v1.PublicKey(), v2.PublicKey()) {
  310. return nil, util.NewContextualError("v1 and v2 public keys are not the same, ignoring", nil, nil)
  311. }
  312. if v1.Curve() != v2.Curve() {
  313. return nil, util.NewContextualError("v1 and v2 curve are not the same, ignoring", nil, nil)
  314. }
  315. if v1.Networks()[0] != v2.Networks()[0] {
  316. return nil, util.NewContextualError("v1 and v2 networks are not the same", nil, nil)
  317. }
  318. cs.initiatingVersion = dv
  319. }
  320. if v1 != nil {
  321. if pkcs11backed {
  322. //NOTE: We do not currently have a method to verify a public private key pair when the private key is in an hsm
  323. } else {
  324. if err := v1.VerifyPrivateKey(privateKeyCurve, privateKey); err != nil {
  325. return nil, fmt.Errorf("private key is not a pair with public key in nebula cert")
  326. }
  327. }
  328. v1hs, err := v1.MarshalForHandshakes()
  329. if err != nil {
  330. return nil, fmt.Errorf("error marshalling certificate for handshake: %w", err)
  331. }
  332. cs.v1Cert = v1
  333. cs.v1HandshakeBytes = v1hs
  334. if cs.initiatingVersion == 0 {
  335. cs.initiatingVersion = cert.Version1
  336. }
  337. }
  338. if v2 != nil {
  339. if pkcs11backed {
  340. //NOTE: We do not currently have a method to verify a public private key pair when the private key is in an hsm
  341. } else {
  342. if err := v2.VerifyPrivateKey(privateKeyCurve, privateKey); err != nil {
  343. return nil, fmt.Errorf("private key is not a pair with public key in nebula cert")
  344. }
  345. }
  346. v2hs, err := v2.MarshalForHandshakes()
  347. if err != nil {
  348. return nil, fmt.Errorf("error marshalling certificate for handshake: %w", err)
  349. }
  350. cs.v2Cert = v2
  351. cs.v2HandshakeBytes = v2hs
  352. if cs.initiatingVersion == 0 {
  353. cs.initiatingVersion = cert.Version2
  354. }
  355. }
  356. var crt cert.Certificate
  357. crt = cs.getCertificate(cert.Version2)
  358. if crt == nil {
  359. // v2 certificates are a superset, only look at v1 if its all we have
  360. crt = cs.getCertificate(cert.Version1)
  361. }
  362. for _, network := range crt.Networks() {
  363. cs.myVpnNetworks = append(cs.myVpnNetworks, network)
  364. cs.myVpnNetworksTable.Insert(network)
  365. cs.myVpnAddrs = append(cs.myVpnAddrs, network.Addr())
  366. cs.myVpnAddrsTable.Insert(netip.PrefixFrom(network.Addr(), network.Addr().BitLen()))
  367. if network.Addr().Is4() {
  368. addr := network.Masked().Addr().As4()
  369. mask := net.CIDRMask(network.Bits(), network.Addr().BitLen())
  370. binary.BigEndian.PutUint32(addr[:], binary.BigEndian.Uint32(addr[:])|^binary.BigEndian.Uint32(mask))
  371. cs.myVpnBroadcastAddrsTable.Insert(netip.PrefixFrom(netip.AddrFrom4(addr), network.Addr().BitLen()))
  372. }
  373. }
  374. return &cs, nil
  375. }
  376. func loadPrivateKey(privPathOrPEM string) (rawKey []byte, curve cert.Curve, isPkcs11 bool, err error) {
  377. var pemPrivateKey []byte
  378. if strings.Contains(privPathOrPEM, "-----BEGIN") {
  379. pemPrivateKey = []byte(privPathOrPEM)
  380. privPathOrPEM = "<inline>"
  381. rawKey, _, curve, err = cert.UnmarshalPrivateKeyFromPEM(pemPrivateKey)
  382. if err != nil {
  383. return nil, curve, false, fmt.Errorf("error while unmarshaling pki.key %s: %s", privPathOrPEM, err)
  384. }
  385. } else if strings.HasPrefix(privPathOrPEM, "pkcs11:") {
  386. rawKey = []byte(privPathOrPEM)
  387. return rawKey, cert.Curve_P256, true, nil
  388. } else {
  389. pemPrivateKey, err = os.ReadFile(privPathOrPEM)
  390. if err != nil {
  391. return nil, curve, false, fmt.Errorf("unable to read pki.key file %s: %s", privPathOrPEM, err)
  392. }
  393. rawKey, _, curve, err = cert.UnmarshalPrivateKeyFromPEM(pemPrivateKey)
  394. if err != nil {
  395. return nil, curve, false, fmt.Errorf("error while unmarshaling pki.key %s: %s", privPathOrPEM, err)
  396. }
  397. }
  398. return
  399. }
  400. func loadCertificate(b []byte) (cert.Certificate, []byte, error) {
  401. c, b, err := cert.UnmarshalCertificateFromPEM(b)
  402. if err != nil {
  403. return nil, b, fmt.Errorf("error while unmarshaling pki.cert: %w", err)
  404. }
  405. if c.Expired(time.Now()) {
  406. return nil, b, fmt.Errorf("nebula certificate for this host is expired")
  407. }
  408. if len(c.Networks()) == 0 {
  409. return nil, b, fmt.Errorf("no networks encoded in certificate")
  410. }
  411. if c.IsCA() {
  412. return nil, b, fmt.Errorf("host certificate is a CA certificate")
  413. }
  414. return c, b, nil
  415. }
  416. func loadCAPoolFromConfig(l *logrus.Logger, c *config.C) (*cert.CAPool, error) {
  417. var rawCA []byte
  418. var err error
  419. caPathOrPEM := c.GetString("pki.ca", "")
  420. if caPathOrPEM == "" {
  421. return nil, errors.New("no pki.ca path or PEM data provided")
  422. }
  423. if strings.Contains(caPathOrPEM, "-----BEGIN") {
  424. rawCA = []byte(caPathOrPEM)
  425. } else {
  426. rawCA, err = os.ReadFile(caPathOrPEM)
  427. if err != nil {
  428. return nil, fmt.Errorf("unable to read pki.ca file %s: %s", caPathOrPEM, err)
  429. }
  430. }
  431. caPool, err := cert.NewCAPoolFromPEM(rawCA)
  432. if errors.Is(err, cert.ErrExpired) {
  433. var expired int
  434. for _, crt := range caPool.CAs {
  435. if crt.Certificate.Expired(time.Now()) {
  436. expired++
  437. l.WithField("cert", crt).Warn("expired certificate present in CA pool")
  438. }
  439. }
  440. if expired >= len(caPool.CAs) {
  441. return nil, errors.New("no valid CA certificates present")
  442. }
  443. } else if err != nil {
  444. return nil, fmt.Errorf("error while adding CA certificate to CA trust store: %s", err)
  445. }
  446. for _, fp := range c.GetStringSlice("pki.blocklist", []string{}) {
  447. l.WithField("fingerprint", fp).Info("Blocklisting cert")
  448. caPool.BlocklistFingerprint(fp)
  449. }
  450. return caPool, nil
  451. }