interface.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  1. package nebula
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "log/slog"
  7. "net/netip"
  8. "runtime"
  9. "slices"
  10. "sync"
  11. "sync/atomic"
  12. "time"
  13. "github.com/gaissmai/bart"
  14. "github.com/rcrowley/go-metrics"
  15. "github.com/slackhq/nebula/util"
  16. "github.com/slackhq/nebula/cert"
  17. "github.com/slackhq/nebula/config"
  18. "github.com/slackhq/nebula/firewall"
  19. "github.com/slackhq/nebula/header"
  20. "github.com/slackhq/nebula/overlay"
  21. "github.com/slackhq/nebula/overlay/batch"
  22. "github.com/slackhq/nebula/overlay/tio"
  23. "github.com/slackhq/nebula/udp"
  24. )
  25. const mtu = 9001
  26. type InterfaceConfig struct {
  27. HostMap *HostMap
  28. Outside udp.Conn
  29. Inside overlay.Device
  30. pki *PKI
  31. Cipher string
  32. Firewall *Firewall
  33. DnsServer *dnsServer
  34. HandshakeManager *HandshakeManager
  35. lightHouse *LightHouse
  36. connectionManager *connectionManager
  37. DropLocalBroadcast bool
  38. DropMulticast bool
  39. routines int
  40. // Multiport means writers[i] is bound to listen.port+i (not a shared
  41. // SO_REUSEPORT port) and lane tunnels are negotiated with capable peers.
  42. Multiport bool
  43. // LaneCount is the number of lanes counting the base tunnel as lane 0
  44. // (multiport.lanes, clamped to routines). Routines at or beyond it share
  45. // the configured lanes round-robin.
  46. LaneCount int
  47. MessageMetrics *MessageMetrics
  48. version string
  49. relayManager *relayManager
  50. punchy *Punchy
  51. tryPromoteEvery uint32
  52. reQueryEvery uint32
  53. reQueryWait time.Duration
  54. ConntrackCacheTimeout time.Duration
  55. // CpuAffinity, when non-empty, names the CPUs each TUN reader goroutine
  56. // should pin to. Queue i pins to CpuAffinity[i % len(CpuAffinity)] —
  57. // shorter lists than `routines` cycle. Empty list keeps the default
  58. // pin-to-(i % NumCPU) behavior. Only consulted when PinThreads is true.
  59. CpuAffinity []int
  60. // PinThreads controls whether each TUN reader OS thread is pinned to a
  61. // single CPU (via tun.pin_threads, default true). Pinning keeps each
  62. // goroutine's sendmmsg on one XPS-selected NIC TX ring so per-flow
  63. // packets stay ordered on the wire.
  64. PinThreads bool
  65. l *slog.Logger
  66. }
  67. type Interface struct {
  68. hostMap *HostMap
  69. outside udp.Conn
  70. inside overlay.Device
  71. pki *PKI
  72. firewall *Firewall
  73. connectionManager *connectionManager
  74. handshakeManager *HandshakeManager
  75. dnsServer *dnsServer
  76. createTime time.Time
  77. lightHouse *LightHouse
  78. myBroadcastAddrsTable *bart.Lite
  79. myVpnAddrs []netip.Addr // A list of addresses assigned to us via our certificate
  80. myVpnAddrsTable *bart.Lite
  81. myVpnNetworks []netip.Prefix // A list of networks assigned to us via our certificate
  82. myVpnNetworksTable *bart.Lite
  83. dropLocalBroadcast bool
  84. dropMulticast bool
  85. routines int
  86. multiport bool
  87. laneCount int
  88. disconnectInvalid atomic.Bool
  89. closed atomic.Bool
  90. // cpuAffinity, when non-empty, names the CPUs each TUN reader goroutine
  91. // should pin to. Queue i pins to cpuAffinity[i % len(cpuAffinity)].
  92. // Empty falls back to the default pin-to-(allowed CPU) behavior.
  93. // Only consulted when pinThreads is true.
  94. cpuAffinity []int
  95. // pinThreads controls whether listenIn pins each TUN reader OS thread to
  96. // a CPU at all (tun.pin_threads, default true). When false, threads are
  97. // left free to migrate as on stock nebula.
  98. pinThreads bool
  99. // ecnEnabled gates RFC 6040 underlay ECN propagation. When true,
  100. // inside.go copies the inner ECN onto the outer carrier on encap and
  101. // decryptToTun folds outer CE into the inner header on decap. Toggle
  102. // via tunnels.ecn (default true).
  103. ecnEnabled atomic.Bool
  104. relayManager *relayManager
  105. tryPromoteEvery atomic.Uint32
  106. reQueryEvery atomic.Uint32
  107. reQueryWait atomic.Int64
  108. sendRecvErrorConfig recvErrorConfig
  109. acceptRecvErrorConfig recvErrorConfig
  110. // rebindCount is used to decide if an active tunnel should trigger a punch notification through a lighthouse
  111. rebindCount int8
  112. version string
  113. conntrackCacheTimeout time.Duration
  114. ctx context.Context
  115. writers []udp.Conn
  116. queues []tio.Queue
  117. // batchers is one per tun queue, wrapping queues[i]. readOutsidePackets
  118. // commits plaintext into the batch.RxBatcher; the plaintext is decrypted
  119. // in place inside the UDP receive buffers, so listenOut must call Flush
  120. // at the end of each UDP recvmmsg batch, before those buffers are
  121. // reused (every udp.Conn ListenOut guarantees that ordering).
  122. batchers []batch.RxBatcher
  123. wg sync.WaitGroup
  124. // fatalErr holds the first unexpected reader error that caused shutdown.
  125. // nil means "no fatal error" (yet)
  126. fatalErr atomic.Pointer[error]
  127. // triggerShutdown is a function that will be run exactly once, when onFatal swaps something non-nil into fatalErr
  128. triggerShutdown func()
  129. metricHandshakes metrics.Histogram
  130. messageMetrics *MessageMetrics
  131. cachedPacketMetrics *cachedPacketMetrics
  132. l *slog.Logger
  133. }
  134. type EncWriter interface {
  135. SendVia(via *HostInfo,
  136. relay *Relay,
  137. ad,
  138. nb,
  139. out []byte,
  140. nocopy bool,
  141. )
  142. SendMessageToVpnAddr(t header.MessageType, st header.MessageSubType, vpnAddr netip.Addr, p, nb, out []byte)
  143. SendMessageToHostInfo(t header.MessageType, st header.MessageSubType, hostinfo *HostInfo, p, nb, out []byte)
  144. Handshake(vpnAddr netip.Addr)
  145. GetHostInfo(vpnAddr netip.Addr) *HostInfo
  146. GetCertState() *CertState
  147. }
  148. type recvErrorConfig uint8
  149. const (
  150. recvErrorAlways recvErrorConfig = iota
  151. recvErrorNever
  152. recvErrorPrivate
  153. )
  154. func (s recvErrorConfig) ShouldRecvError(endpoint netip.AddrPort) bool {
  155. switch s {
  156. case recvErrorPrivate:
  157. return endpoint.Addr().IsPrivate()
  158. case recvErrorAlways:
  159. return true
  160. case recvErrorNever:
  161. return false
  162. default:
  163. panic(fmt.Errorf("invalid recvErrorConfig value: %d", s))
  164. }
  165. }
  166. func (s recvErrorConfig) String() string {
  167. switch s {
  168. case recvErrorAlways:
  169. return "always"
  170. case recvErrorNever:
  171. return "never"
  172. case recvErrorPrivate:
  173. return "private"
  174. default:
  175. return fmt.Sprintf("invalid(%d)", s)
  176. }
  177. }
  178. func NewInterface(ctx context.Context, c *InterfaceConfig) (*Interface, error) {
  179. if c.Outside == nil {
  180. return nil, errors.New("no outside connection")
  181. }
  182. if c.Inside == nil {
  183. return nil, errors.New("no inside interface (tun)")
  184. }
  185. if c.pki == nil {
  186. return nil, errors.New("no certificate state")
  187. }
  188. if c.Firewall == nil {
  189. return nil, errors.New("no firewall rules")
  190. }
  191. if c.connectionManager == nil {
  192. return nil, errors.New("no connection manager")
  193. }
  194. cs := c.pki.getCertState()
  195. ifce := &Interface{
  196. ctx: ctx,
  197. pki: c.pki,
  198. hostMap: c.HostMap,
  199. outside: c.Outside,
  200. inside: c.Inside,
  201. firewall: c.Firewall,
  202. dnsServer: c.DnsServer,
  203. handshakeManager: c.HandshakeManager,
  204. createTime: time.Now(),
  205. lightHouse: c.lightHouse,
  206. dropLocalBroadcast: c.DropLocalBroadcast,
  207. dropMulticast: c.DropMulticast,
  208. routines: c.routines,
  209. multiport: c.Multiport,
  210. laneCount: c.LaneCount,
  211. version: c.version,
  212. writers: make([]udp.Conn, c.routines),
  213. batchers: make([]batch.RxBatcher, c.routines),
  214. myVpnNetworks: cs.myVpnNetworks,
  215. myVpnNetworksTable: cs.myVpnNetworksTable,
  216. myVpnAddrs: cs.myVpnAddrs,
  217. myVpnAddrsTable: cs.myVpnAddrsTable,
  218. myBroadcastAddrsTable: cs.myVpnBroadcastAddrsTable,
  219. relayManager: c.relayManager,
  220. connectionManager: c.connectionManager,
  221. conntrackCacheTimeout: c.ConntrackCacheTimeout,
  222. cpuAffinity: c.CpuAffinity,
  223. pinThreads: c.PinThreads,
  224. metricHandshakes: metrics.GetOrRegisterHistogram("handshakes", nil, metrics.NewExpDecaySample(1028, 0.015)),
  225. messageMetrics: c.MessageMetrics,
  226. cachedPacketMetrics: &cachedPacketMetrics{
  227. sent: metrics.GetOrRegisterCounter("hostinfo.cached_packets.sent", nil),
  228. dropped: metrics.GetOrRegisterCounter("hostinfo.cached_packets.dropped", nil),
  229. },
  230. l: c.l,
  231. }
  232. ifce.tryPromoteEvery.Store(c.tryPromoteEvery)
  233. ifce.reQueryEvery.Store(c.reQueryEvery)
  234. ifce.reQueryWait.Store(int64(c.reQueryWait))
  235. ifce.connectionManager.intf = ifce
  236. // Held until Close so waiting on the interface blocks until the resources are actually released
  237. ifce.wg.Add(1)
  238. return ifce, nil
  239. }
  240. // activate creates the interface on the host. After the interface is created, any
  241. // other services that want to bind listeners to its IP may do so successfully. However,
  242. // the interface isn't going to process anything until run() is called.
  243. func (f *Interface) activate() error {
  244. // actually turn on tun dev
  245. addr, err := f.outside.LocalAddr()
  246. if err != nil {
  247. f.l.Error("Failed to get udp listen address", "error", err)
  248. }
  249. f.l.Info("Nebula interface is active",
  250. "interface", f.inside.Name(),
  251. "networks", f.myVpnNetworks,
  252. "build", f.version,
  253. "udpAddr", addr,
  254. "boringcrypto", boringEnabled(),
  255. )
  256. // Under multiport each socket has exactly one reader on its own port, so
  257. // the shared-port multi-reader capability is irrelevant (and main.go
  258. // already hard-errored on unsupported platforms).
  259. if f.routines > 1 && !f.multiport && !f.outside.SupportsMultipleReaders() {
  260. f.routines = 1
  261. f.l.Warn("multiple udp readers are not supported on this platform, falling back to a single routine")
  262. }
  263. // Prepare the tun queues. A device that can't open that many hands back
  264. // fewer (a single queue on platforms without multiqueue support) and we
  265. // size the reader routines to what we actually got.
  266. queues, err := f.inside.Queues(f.routines)
  267. if err != nil {
  268. return err
  269. }
  270. if len(queues) < f.routines {
  271. if f.multiport {
  272. // The lane sockets are already bound one-per-routine; shrinking
  273. // the routine count would leave bound ports with no reader.
  274. return fmt.Errorf("multiport requires %d tun queues, device provided %d", f.routines, len(queues))
  275. }
  276. f.l.Warn("tun multiqueue is not supported on this platform, falling back to fewer routines",
  277. "requested", f.routines, "opened", len(queues))
  278. f.routines = len(queues)
  279. }
  280. f.queues = queues
  281. metrics.GetOrRegisterGauge("routines", nil).Update(int64(f.routines))
  282. for i := range f.queues {
  283. caps := tio.QueueCapabilities(f.queues[i])
  284. if caps.TSO || caps.USO {
  285. // Multi-lane: TCP gets coalesced when TSO is on, UDP when USO
  286. // is on, everything else (and either lane disabled) falls
  287. // through to passthrough so non-IP / non-TCP-UDP traffic still
  288. // reaches the TUN.
  289. f.batchers[i] = batch.NewMultiCoalescer(f.queues[i], f.l, caps.TSO, caps.USO)
  290. } else {
  291. f.batchers[i] = batch.NewPassthrough(f.queues[i])
  292. }
  293. }
  294. // On error the caller owns the cleanup, Control.Start cancels the service context
  295. // before releasing our resources so a waiter never observes a live context
  296. if err = f.inside.Activate(); err != nil {
  297. return err
  298. }
  299. return nil
  300. }
  301. func (f *Interface) run() {
  302. // Launch n queues to read packets from udp
  303. for i := 0; i < f.routines; i++ {
  304. f.wg.Go(func() {
  305. f.listenOut(i)
  306. })
  307. }
  308. // Launch n queues to read packets from tun dev
  309. for i := 0; i < f.routines; i++ {
  310. f.wg.Go(func() {
  311. f.listenIn(f.queues[i], i)
  312. })
  313. }
  314. }
  315. func (f *Interface) wait() error {
  316. f.wg.Wait()
  317. if e := f.fatalErr.Load(); e != nil {
  318. return *e
  319. }
  320. return nil
  321. }
  322. // onFatal stores the first fatal reader error, and calls triggerShutdown if it was the first one
  323. func (f *Interface) onFatal(err error) {
  324. swapped := f.fatalErr.CompareAndSwap(nil, &err)
  325. if !swapped {
  326. return
  327. }
  328. if f.triggerShutdown != nil {
  329. f.triggerShutdown()
  330. }
  331. }
  332. func (f *Interface) listenOut(i int) {
  333. var li udp.Conn
  334. if i > 0 {
  335. li = f.writers[i]
  336. } else {
  337. li = f.outside
  338. }
  339. ctCache := firewall.NewConntrackCacheTicker(f.ctx, f.l, f.conntrackCacheTimeout)
  340. lhh := f.lightHouse.NewRequestHandler()
  341. h := &header.H{}
  342. fwPacket := &firewall.Packet{}
  343. nb := make([]byte, 12, 12)
  344. scratch := make([]byte, mtu)
  345. listener := func(fromUdpAddr netip.AddrPort, payload []byte, meta udp.RxMeta) {
  346. f.readOutsidePackets(ViaSender{UdpAddr: fromUdpAddr, SockIdx: i}, scratch, payload, h, fwPacket, lhh, nb, i, ctCache.Get(), meta)
  347. }
  348. flusher := func() {
  349. if err := f.batchers[i].Flush(); err != nil {
  350. f.l.Error("Failed to flush tun coalescer", "error", err)
  351. }
  352. }
  353. err := li.ListenOut(listener, flusher)
  354. // An error after teardown began is shutdown noise, the closed flag covers resources
  355. // Close releases itself and the cancelled ctx covers ones torn down by their owners
  356. // reacting to it, like the user device pipes
  357. if err != nil && !f.closed.Load() && f.ctx.Err() == nil {
  358. f.l.Error("Error while reading inbound packet, closing", "error", err)
  359. f.onFatal(err)
  360. }
  361. f.l.Debug("underlay reader is done", "reader", i)
  362. }
  363. // txQueue is the per-routine TX state owned by one listenIn goroutine.
  364. // laneSlot is the lane this routine's traffic rides (laneSlotFor); lane is
  365. // bound to that slot's socket and carries lane-tunnel data; base is bound to
  366. // socket 0 and carries base-tunnel and relay data, which must keep the base
  367. // source port (a vanilla peer would otherwise see per-routine source ports
  368. // and roam-thrash). The two alias when multiport is off or laneSlot is 0.
  369. // Concurrent sendmmsg on a shared fd (socket 0, or a lane socket shared by
  370. // overflow routines) is safe: a flow is pinned to one routine by tun
  371. // steering, so per-flow wire order still holds.
  372. type txQueue struct {
  373. laneSlot int
  374. lane *batch.SendBatch
  375. base *batch.SendBatch
  376. }
  377. func (tx *txQueue) full() bool {
  378. if tx.lane.Len() >= batch.SendBatchCap {
  379. return true
  380. }
  381. return tx.base != tx.lane && tx.base.Len() >= batch.SendBatchCap
  382. }
  383. // flush drains base before lane so that when a flow moves from the base
  384. // tunnel onto a freshly established lane mid-window, its packets still leave
  385. // this host in encryption order.
  386. func (tx *txQueue) flush(l *slog.Logger) {
  387. if tx.base != tx.lane {
  388. if err := tx.base.Flush(); err != nil {
  389. l.Error("Failed to write outgoing batch", "error", err, "writer", 0)
  390. }
  391. }
  392. if err := tx.lane.Flush(); err != nil {
  393. l.Error("Failed to write outgoing batch", "error", err, "writer", tx.laneSlot)
  394. }
  395. }
  396. // laneSlotFor maps a routine index to the lane its traffic rides. When
  397. // multiport.lanes is below routines, overflow routines share the configured
  398. // lanes round-robin instead of all falling back onto the base tunnel's
  399. // single underlay flow. Sharers use the lane's own socket and 4-tuple, so
  400. // this is vanilla-style same-flow sharing: no cross-path replay skew, and
  401. // per-flow ordering still holds (a flow stays pinned to one routine).
  402. func (f *Interface) laneSlotFor(i int) int {
  403. if f.multiport && f.laneCount > 0 {
  404. return i % f.laneCount
  405. }
  406. return i
  407. }
  408. func (f *Interface) listenIn(queue tio.Queue, i int) {
  409. // Pinning this thread (and goroutine) to a single CPU keeps every sendmmsg from this goroutine going through the
  410. // same TX ring on the nic, so the wire sees per-flow order. Skip entirely when tun.pin_threads is false.
  411. if f.pinThreads {
  412. var cpu int
  413. if n := len(f.cpuAffinity); n > 0 {
  414. // Explicit tun.cpu_affinity list wins; parseCpuAffinity already
  415. // validated the entries against the allowed CPU set.
  416. cpu = f.cpuAffinity[i%n]
  417. } else if allowed, err := util.AllowedCPUs(); err == nil && len(allowed) > 0 {
  418. // Default: spread queues across the CPUs we're actually allowed to
  419. // run on. Under a cpuset/taskset mask these aren't 0..NumCPU-1, so
  420. // i % NumCPU would pick unrunnable IDs and every pin would fail.
  421. cpu = allowed[i%len(allowed)]
  422. } else {
  423. cpu = i % runtime.NumCPU()
  424. }
  425. if err := util.PinThreadToCPU(cpu); err != nil {
  426. f.l.Warn("failed to pin tun reader to CPU", "queue", i, "cpu", cpu, "err", err)
  427. }
  428. }
  429. rejectBuf := make([]byte, mtu)
  430. arenaSize := batch.SendBatchCap * (udp.MTU + 32)
  431. laneSlot := f.laneSlotFor(i)
  432. sb := batch.NewSendBatch(f.writers[laneSlot], batch.SendBatchCap, arenaSize)
  433. tx := &txQueue{laneSlot: laneSlot, lane: sb, base: sb}
  434. if f.multiport && laneSlot != 0 {
  435. tx.base = batch.NewSendBatch(f.writers[0], batch.SendBatchCap, arenaSize)
  436. }
  437. fwPacket := &firewall.Packet{}
  438. nb := make([]byte, 12, 12)
  439. conntrackCache := firewall.NewConntrackCacheTicker(f.ctx, f.l, f.conntrackCacheTimeout)
  440. for {
  441. pkts, err := queue.Read()
  442. if err != nil {
  443. // Same shutdown noise handling as listenOut
  444. if !f.closed.Load() && f.ctx.Err() == nil {
  445. f.l.Error("Error while reading outbound packet, closing", "error", err, "reader", i)
  446. f.onFatal(err)
  447. }
  448. break
  449. }
  450. for _, pkt := range pkts {
  451. f.consumeInsidePacket(pkt, fwPacket, nb, tx, rejectBuf, i, conntrackCache.Get())
  452. // Flush incrementally once a full sendmmsg batch has
  453. // accumulated so the first packets of a deep read drain
  454. // hit the wire while the rest are still being encrypted.
  455. if tx.full() {
  456. tx.flush(f.l)
  457. }
  458. }
  459. tx.flush(f.l)
  460. }
  461. f.l.Debug("overlay reader is done", "reader", i)
  462. }
  463. func (f *Interface) RegisterConfigChangeCallbacks(c *config.C) {
  464. c.RegisterReloadCallback(f.reloadFirewall)
  465. c.RegisterReloadCallback(f.reloadSendRecvError)
  466. c.RegisterReloadCallback(f.reloadAcceptRecvError)
  467. c.RegisterReloadCallback(f.reloadDisconnectInvalid)
  468. c.RegisterReloadCallback(f.reloadMisc)
  469. c.RegisterReloadCallback(f.reloadEcn)
  470. for _, udpConn := range f.writers {
  471. c.RegisterReloadCallback(udpConn.ReloadConfig)
  472. }
  473. }
  474. func (f *Interface) reloadDisconnectInvalid(c *config.C) {
  475. initial := c.InitialLoad()
  476. if initial || c.HasChanged("pki.disconnect_invalid") {
  477. f.disconnectInvalid.Store(c.GetBool("pki.disconnect_invalid", true))
  478. if !initial {
  479. f.l.Info("pki.disconnect_invalid changed", "value", f.disconnectInvalid.Load())
  480. }
  481. }
  482. }
  483. func (f *Interface) reloadFirewall(c *config.C) {
  484. cs := f.pki.getCertState()
  485. curCert := cs.getCertificate(cert.Version2)
  486. if curCert == nil {
  487. curCert = cs.getCertificate(cert.Version1)
  488. }
  489. // The firewall builds its routableNetworks set from the certificate's UnsafeNetworks at construction.
  490. // Check to see if that set has changed, and if so, rebuild the firewall.
  491. certUnsafeChanged := curCert != nil && !slices.Equal(curCert.UnsafeNetworks(), f.firewall.unsafeNetworks)
  492. if !c.HasChanged("firewall") && !certUnsafeChanged {
  493. f.l.Debug("No firewall config change detected")
  494. return
  495. }
  496. fw, err := NewFirewallFromConfig(f.l, cs, c)
  497. if err != nil {
  498. f.l.Error("Error while creating firewall during reload", "error", err)
  499. return
  500. }
  501. oldFw := f.firewall
  502. conntrack := oldFw.Conntrack
  503. conntrack.Lock()
  504. defer conntrack.Unlock()
  505. fw.rulesVersion = oldFw.rulesVersion + 1
  506. // If rulesVersion is back to zero, we have wrapped all the way around. Be
  507. // safe and just reset conntrack in this case.
  508. if fw.rulesVersion == 0 {
  509. f.l.Warn("firewall rulesVersion has overflowed, resetting conntrack",
  510. "firewallHashes", fw.GetRuleHashes(),
  511. "oldFirewallHashes", oldFw.GetRuleHashes(),
  512. "rulesVersion", fw.rulesVersion,
  513. )
  514. } else {
  515. fw.Conntrack = conntrack
  516. }
  517. f.firewall = fw
  518. oldFw.Destroy()
  519. f.l.Info("New firewall has been installed",
  520. "firewallHashes", fw.GetRuleHashes(),
  521. "oldFirewallHashes", oldFw.GetRuleHashes(),
  522. "rulesVersion", fw.rulesVersion,
  523. )
  524. }
  525. func (f *Interface) reloadSendRecvError(c *config.C) {
  526. if c.InitialLoad() || c.HasChanged("listen.send_recv_error") {
  527. stringValue := c.GetString("listen.send_recv_error", "always")
  528. switch stringValue {
  529. case "always":
  530. f.sendRecvErrorConfig = recvErrorAlways
  531. case "never":
  532. f.sendRecvErrorConfig = recvErrorNever
  533. case "private":
  534. f.sendRecvErrorConfig = recvErrorPrivate
  535. default:
  536. if c.GetBool("listen.send_recv_error", true) {
  537. f.sendRecvErrorConfig = recvErrorAlways
  538. } else {
  539. f.sendRecvErrorConfig = recvErrorNever
  540. }
  541. }
  542. f.l.Info("Loaded send_recv_error config", "sendRecvError", f.sendRecvErrorConfig.String())
  543. }
  544. }
  545. func (f *Interface) reloadAcceptRecvError(c *config.C) {
  546. if c.InitialLoad() || c.HasChanged("listen.accept_recv_error") {
  547. stringValue := c.GetString("listen.accept_recv_error", "always")
  548. switch stringValue {
  549. case "always":
  550. f.acceptRecvErrorConfig = recvErrorAlways
  551. case "never":
  552. f.acceptRecvErrorConfig = recvErrorNever
  553. case "private":
  554. f.acceptRecvErrorConfig = recvErrorPrivate
  555. default:
  556. if c.GetBool("listen.accept_recv_error", true) {
  557. f.acceptRecvErrorConfig = recvErrorAlways
  558. } else {
  559. f.acceptRecvErrorConfig = recvErrorNever
  560. }
  561. }
  562. f.l.Info("Loaded accept_recv_error config", "acceptRecvError", f.acceptRecvErrorConfig.String())
  563. }
  564. }
  565. func (f *Interface) reloadMisc(c *config.C) {
  566. if c.HasChanged("counters.try_promote") {
  567. n := c.GetUint32("counters.try_promote", defaultPromoteEvery)
  568. f.tryPromoteEvery.Store(n)
  569. f.l.Info("counters.try_promote has changed")
  570. }
  571. if c.HasChanged("counters.requery_every_packets") {
  572. n := c.GetUint32("counters.requery_every_packets", defaultReQueryEvery)
  573. f.reQueryEvery.Store(n)
  574. f.l.Info("counters.requery_every_packets has changed")
  575. }
  576. if c.HasChanged("timers.requery_wait_duration") {
  577. n := c.GetDuration("timers.requery_wait_duration", defaultReQueryWait)
  578. f.reQueryWait.Store(int64(n))
  579. f.l.Info("timers.requery_wait_duration has changed")
  580. }
  581. }
  582. // reloadEcn syncs Interface.ecnEnabled with the tunnels.ecn config knob.
  583. // Default is enabled (RFC 6040 normal mode); set false on the rare path
  584. // where an underlay middlebox rewrites or drops ECN bits unpredictably.
  585. func (f *Interface) reloadEcn(c *config.C) {
  586. initial := c.InitialLoad()
  587. if initial || c.HasChanged("tunnels.ecn") {
  588. v := c.GetBool("tunnels.ecn", true)
  589. changed := f.ecnEnabled.Swap(v) != v
  590. if !initial {
  591. f.l.Info("tunnels.ecn changed", "enabled", v)
  592. if changed {
  593. f.l.Warn("tunnels.ecn datapath toggled, but route-level ECN negotiation (RTAX_FEATURE_ECN) retains its previous state until nebula is restarted", "enabled", v)
  594. }
  595. }
  596. }
  597. }
  598. func (f *Interface) emitStats(ctx context.Context, i time.Duration) {
  599. ticker := time.NewTicker(i)
  600. defer ticker.Stop()
  601. udpStats := udp.NewUDPStatsEmitter(f.writers)
  602. certExpirationGauge := metrics.GetOrRegisterGauge("certificate.ttl_seconds", nil)
  603. certInitiatingVersion := metrics.GetOrRegisterGauge("certificate.initiating_version", nil)
  604. certMaxVersion := metrics.GetOrRegisterGauge("certificate.max_version", nil)
  605. emit := func() {
  606. f.firewall.EmitStats()
  607. f.handshakeManager.EmitStats()
  608. udpStats()
  609. certState := f.pki.getCertState()
  610. defaultCrt := certState.GetDefaultCertificate()
  611. certExpirationGauge.Update(int64(defaultCrt.NotAfter().Sub(time.Now()) / time.Second))
  612. certInitiatingVersion.Update(int64(defaultCrt.Version()))
  613. // Report the max certificate version we are capable of using
  614. if certState.v2Cert != nil {
  615. certMaxVersion.Update(int64(certState.v2Cert.Version()))
  616. } else {
  617. certMaxVersion.Update(int64(certState.v1Cert.Version()))
  618. }
  619. }
  620. // Prime gauges so a Prometheus scrape that lands before the first tick
  621. // sees real values instead of the zero defaults (issue #907).
  622. emit()
  623. for {
  624. select {
  625. case <-ctx.Done():
  626. return
  627. case <-ticker.C:
  628. emit()
  629. }
  630. }
  631. }
  632. func (f *Interface) GetHostInfo(vpnIp netip.Addr) *HostInfo {
  633. return f.hostMap.QueryVpnAddr(vpnIp)
  634. }
  635. func (f *Interface) GetCertState() *CertState {
  636. return f.pki.getCertState()
  637. }
  638. // Close releases the interface's resources: the udp sockets and the tun device.
  639. // It is idempotent and safe to call at any point in the lifecycle, including on an interface that never activated,
  640. // calls after the first return nil without doing anything.
  641. func (f *Interface) Close() error {
  642. if !f.closed.CompareAndSwap(false, true) {
  643. return nil
  644. }
  645. var errs []error
  646. // Release the udp readers
  647. for i, u := range f.writers {
  648. err := u.Close()
  649. if err != nil {
  650. f.l.Error("Error while closing udp socket", "error", err, "writer", i)
  651. errs = append(errs, err)
  652. }
  653. }
  654. // Release the tun device (closing the tun also closes all readers)
  655. closeErr := f.inside.Close()
  656. if closeErr != nil {
  657. errs = append(errs, closeErr)
  658. }
  659. // Release the construction token so waiters know the resources are gone
  660. f.wg.Done()
  661. return errors.Join(errs...)
  662. }