interface.go 27 KB

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