interface.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774
  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 lane-tunnel data; base is bound to
  399. // socket 0 and carries base-tunnel and relay data, which must keep the base
  400. // source port (a vanilla peer would otherwise see per-routine source ports
  401. // and roam-thrash). The two alias when multiport is off or laneSlot is 0.
  402. // Concurrent sendmmsg on a shared fd (socket 0, or a lane socket shared by
  403. // overflow routines) is safe: a flow is pinned to one routine by tun
  404. // steering, so per-flow wire order still holds.
  405. type txQueue struct {
  406. laneSlot int
  407. lane *batch.SendBatch
  408. base *batch.SendBatch
  409. }
  410. func (tx *txQueue) full() bool {
  411. if tx.lane.Len() >= batch.SendBatchCap {
  412. return true
  413. }
  414. return tx.base != tx.lane && tx.base.Len() >= batch.SendBatchCap
  415. }
  416. // flush drains base before lane so that when a flow moves from the base
  417. // tunnel onto a freshly established lane mid-window, its packets still leave
  418. // this host in encryption order.
  419. func (tx *txQueue) flush(f *Interface) {
  420. if tx.base != tx.lane {
  421. f.flushSendBatch(tx.base, 0)
  422. }
  423. f.flushSendBatch(tx.lane, tx.laneSlot)
  424. }
  425. // laneSlotFor maps a routine index to the lane its traffic rides. When
  426. // multiport.lanes is below routines, overflow routines share the configured
  427. // lanes round-robin instead of all falling back onto the base tunnel's
  428. // single underlay flow. Sharers use the lane's own socket and 4-tuple, so
  429. // this is vanilla-style same-flow sharing: no cross-path replay skew, and
  430. // per-flow ordering still holds (a flow stays pinned to one routine).
  431. func (f *Interface) laneSlotFor(i int) int {
  432. if f.multiport && f.laneCount > 0 {
  433. return i % f.laneCount
  434. }
  435. return i
  436. }
  437. func (f *Interface) listenIn(queue tio.Queue, i int) {
  438. // Pinning this thread (and goroutine) to a single CPU keeps every sendmmsg from this goroutine going through the
  439. // same TX ring on the nic, so the wire sees per-flow order. Skip entirely when tun.pin_threads is false.
  440. if f.pinThreads {
  441. f.pinThisThread(i)
  442. }
  443. rejectBuf := make([]byte, mtu)
  444. arenaSize := batch.SendBatchCap * (udp.MTU + 32)
  445. laneSlot := f.laneSlotFor(i)
  446. sb := batch.NewSendBatch(f.writers[laneSlot], batch.SendBatchCap, arenaSize)
  447. tx := &txQueue{laneSlot: laneSlot, lane: sb, base: sb}
  448. if f.multiport && laneSlot != 0 {
  449. tx.base = batch.NewSendBatch(f.writers[0], batch.SendBatchCap, arenaSize)
  450. }
  451. fwPacket := &firewall.ParsedPacket{}
  452. nb := make([]byte, 12, 12)
  453. conntrackCache := firewall.NewConntrackCacheTicker(f.ctx, f.l, f.conntrackCacheTimeout)
  454. for {
  455. pkts, err := queue.Read()
  456. if err != nil {
  457. // Same shutdown noise handling as listenOut
  458. if !f.closed.Load() && f.ctx.Err() == nil {
  459. f.l.Error("Error while reading outbound packet, closing", "error", err, "reader", i)
  460. f.onFatal(err)
  461. }
  462. break
  463. }
  464. for _, pkt := range pkts {
  465. f.consumeInsidePacket(pkt, fwPacket, nb, tx, rejectBuf, i, conntrackCache.Get())
  466. // Flush incrementally once a full sendmmsg batch has
  467. // accumulated so the first packets of a deep read drain
  468. // hit the wire while the rest are still being encrypted.
  469. if tx.full() {
  470. tx.flush(f)
  471. }
  472. }
  473. tx.flush(f)
  474. }
  475. f.l.Debug("overlay reader is done", "reader", i)
  476. }
  477. // flushSendBatch drains sb to the underlay and accounts for anything it could not deliver. A shortfall means
  478. // specific destinations were undeliverable (a stale remote, a reject rule), which the backend logs per peer at
  479. // debug; here it is only a counter, so one unreachable peer cannot spam a log line per batch.
  480. func (f *Interface) flushSendBatch(sb *batch.SendBatch, q int) {
  481. queued := sb.Len()
  482. written, err := sb.Flush()
  483. if err != nil {
  484. f.l.Error("Failed to write outgoing batch", "error", err, "writer", q)
  485. }
  486. if dropped := queued - written; dropped > 0 {
  487. f.metricTxDropped.Inc(int64(dropped))
  488. }
  489. }
  490. func (f *Interface) RegisterConfigChangeCallbacks(c *config.C) {
  491. c.RegisterReloadCallback(f.reloadFirewall)
  492. c.RegisterReloadCallback(f.reloadSendRecvError)
  493. c.RegisterReloadCallback(f.reloadAcceptRecvError)
  494. c.RegisterReloadCallback(f.reloadDisconnectInvalid)
  495. c.RegisterReloadCallback(f.reloadMisc)
  496. for _, udpConn := range f.writers {
  497. c.RegisterReloadCallback(udpConn.ReloadConfig)
  498. }
  499. }
  500. func (f *Interface) reloadDisconnectInvalid(c *config.C) {
  501. initial := c.InitialLoad()
  502. if initial || c.HasChanged("pki.disconnect_invalid") {
  503. f.disconnectInvalid.Store(c.GetBool("pki.disconnect_invalid", true))
  504. if !initial {
  505. f.l.Info("pki.disconnect_invalid changed", "value", f.disconnectInvalid.Load())
  506. }
  507. }
  508. }
  509. func (f *Interface) reloadFirewall(c *config.C) {
  510. cs := f.pki.getCertState()
  511. curCert := cs.getCertificate(cert.Version2)
  512. if curCert == nil {
  513. curCert = cs.getCertificate(cert.Version1)
  514. }
  515. // The firewall builds its routableNetworks set from the certificate's UnsafeNetworks at construction.
  516. // Check to see if that set has changed, and if so, rebuild the firewall.
  517. certUnsafeChanged := curCert != nil && !slices.Equal(curCert.UnsafeNetworks(), f.firewall.unsafeNetworks)
  518. if !c.HasChanged("firewall") && !certUnsafeChanged {
  519. f.l.Debug("No firewall config change detected")
  520. return
  521. }
  522. fw, err := NewFirewallFromConfig(f.l, cs, c)
  523. if err != nil {
  524. f.l.Error("Error while creating firewall during reload", "error", err)
  525. return
  526. }
  527. oldFw := f.firewall
  528. conntrack := oldFw.Conntrack
  529. conntrack.Lock()
  530. defer conntrack.Unlock()
  531. fw.rulesVersion = oldFw.rulesVersion + 1
  532. // If rulesVersion is back to zero, we have wrapped all the way around. Be
  533. // safe and just reset conntrack in this case.
  534. if fw.rulesVersion == 0 {
  535. f.l.Warn("firewall rulesVersion has overflowed, resetting conntrack",
  536. "firewallHashes", fw.GetRuleHashes(),
  537. "oldFirewallHashes", oldFw.GetRuleHashes(),
  538. "rulesVersion", fw.rulesVersion,
  539. )
  540. } else {
  541. fw.Conntrack = conntrack
  542. }
  543. f.firewall = fw
  544. oldFw.Destroy()
  545. f.l.Info("New firewall has been installed",
  546. "firewallHashes", fw.GetRuleHashes(),
  547. "oldFirewallHashes", oldFw.GetRuleHashes(),
  548. "rulesVersion", fw.rulesVersion,
  549. )
  550. }
  551. func (f *Interface) reloadSendRecvError(c *config.C) {
  552. if c.InitialLoad() || c.HasChanged("listen.send_recv_error") {
  553. stringValue := c.GetString("listen.send_recv_error", "always")
  554. switch stringValue {
  555. case "always":
  556. f.sendRecvErrorConfig = recvErrorAlways
  557. case "never":
  558. f.sendRecvErrorConfig = recvErrorNever
  559. case "private":
  560. f.sendRecvErrorConfig = recvErrorPrivate
  561. default:
  562. if c.GetBool("listen.send_recv_error", true) {
  563. f.sendRecvErrorConfig = recvErrorAlways
  564. } else {
  565. f.sendRecvErrorConfig = recvErrorNever
  566. }
  567. }
  568. f.l.Info("Loaded send_recv_error config", "sendRecvError", f.sendRecvErrorConfig.String())
  569. }
  570. }
  571. func (f *Interface) reloadAcceptRecvError(c *config.C) {
  572. if c.InitialLoad() || c.HasChanged("listen.accept_recv_error") {
  573. stringValue := c.GetString("listen.accept_recv_error", "always")
  574. switch stringValue {
  575. case "always":
  576. f.acceptRecvErrorConfig = recvErrorAlways
  577. case "never":
  578. f.acceptRecvErrorConfig = recvErrorNever
  579. case "private":
  580. f.acceptRecvErrorConfig = recvErrorPrivate
  581. default:
  582. if c.GetBool("listen.accept_recv_error", true) {
  583. f.acceptRecvErrorConfig = recvErrorAlways
  584. } else {
  585. f.acceptRecvErrorConfig = recvErrorNever
  586. }
  587. }
  588. f.l.Info("Loaded accept_recv_error config", "acceptRecvError", f.acceptRecvErrorConfig.String())
  589. }
  590. }
  591. func (f *Interface) reloadMisc(c *config.C) {
  592. if c.HasChanged("counters.try_promote") {
  593. n := c.GetUint32("counters.try_promote", defaultPromoteEvery)
  594. f.tryPromoteEvery.Store(n)
  595. f.l.Info("counters.try_promote has changed")
  596. }
  597. if c.HasChanged("counters.requery_every_packets") {
  598. n := c.GetUint32("counters.requery_every_packets", defaultReQueryEvery)
  599. f.reQueryEvery.Store(n)
  600. f.l.Info("counters.requery_every_packets has changed")
  601. }
  602. if c.HasChanged("timers.requery_wait_duration") {
  603. n := c.GetDuration("timers.requery_wait_duration", defaultReQueryWait)
  604. f.reQueryWait.Store(int64(n))
  605. f.l.Info("timers.requery_wait_duration has changed")
  606. }
  607. }
  608. func (f *Interface) emitStats(ctx context.Context, i time.Duration) {
  609. ticker := time.NewTicker(i)
  610. defer ticker.Stop()
  611. udpStats := udp.NewUDPStatsEmitter(f.writers)
  612. certExpirationGauge := metrics.GetOrRegisterGauge("certificate.ttl_seconds", nil)
  613. certInitiatingVersion := metrics.GetOrRegisterGauge("certificate.initiating_version", nil)
  614. certMaxVersion := metrics.GetOrRegisterGauge("certificate.max_version", nil)
  615. emit := func() {
  616. f.firewall.EmitStats()
  617. f.handshakeManager.EmitStats()
  618. udpStats()
  619. certState := f.pki.getCertState()
  620. defaultCrt := certState.GetDefaultCertificate()
  621. certExpirationGauge.Update(int64(defaultCrt.NotAfter().Sub(time.Now()) / time.Second))
  622. certInitiatingVersion.Update(int64(defaultCrt.Version()))
  623. // Report the max certificate version we are capable of using
  624. if certState.v2Cert != nil {
  625. certMaxVersion.Update(int64(certState.v2Cert.Version()))
  626. } else {
  627. certMaxVersion.Update(int64(certState.v1Cert.Version()))
  628. }
  629. }
  630. // Prime gauges so a Prometheus scrape that lands before the first tick
  631. // sees real values instead of the zero defaults (issue #907).
  632. emit()
  633. for {
  634. select {
  635. case <-ctx.Done():
  636. return
  637. case <-ticker.C:
  638. emit()
  639. }
  640. }
  641. }
  642. func (f *Interface) GetHostInfo(vpnIp netip.Addr) *HostInfo {
  643. return f.hostMap.QueryVpnAddr(vpnIp)
  644. }
  645. func (f *Interface) GetCertState() *CertState {
  646. return f.pki.getCertState()
  647. }
  648. // Close releases the interface's resources: the udp sockets and the tun device.
  649. // It is idempotent and safe to call at any point in the lifecycle, including on an interface that never activated,
  650. // calls after the first return nil without doing anything.
  651. func (f *Interface) Close() error {
  652. if !f.closed.CompareAndSwap(false, true) {
  653. return nil
  654. }
  655. var errs []error
  656. // Release the udp readers
  657. for i, u := range f.writers {
  658. err := u.Close()
  659. if err != nil {
  660. f.l.Error("Error while closing udp socket", "error", err, "writer", i)
  661. errs = append(errs, err)
  662. }
  663. }
  664. // Release the tun device (closing the tun also closes all readers)
  665. closeErr := f.inside.Close()
  666. if closeErr != nil {
  667. errs = append(errs, closeErr)
  668. }
  669. // Release the construction token so waiters know the resources are gone
  670. f.wg.Done()
  671. return errors.Join(errs...)
  672. }