interface.go 25 KB

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