pki.go 14 KB

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