interface.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850
  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. // tunnels 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 each socket has exactly one reader on its own port, so
  262. // the shared-port multi-reader capability is irrelevant (and main.go
  263. // already hard-errored on unsupported platforms).
  264. if f.routines > 1 && !f.multiport && !f.outside.SupportsMultipleReaders() {
  265. f.routines = 1
  266. f.l.Warn("multiple udp readers are not supported on this platform, falling back to a single routine")
  267. }
  268. // Prepare the tun queues. A device that can't open that many hands back
  269. // fewer (a single queue on platforms without multiqueue support) and we
  270. // size the reader routines to what we actually got.
  271. queues, err := f.inside.Queues(f.routines)
  272. if err != nil {
  273. return err
  274. }
  275. if len(queues) < f.routines {
  276. if f.multiport {
  277. // The lane sockets are already bound one-per-routine; shrinking
  278. // the routine count would leave bound ports with no reader.
  279. return fmt.Errorf("multiport requires %d tun queues, device provided %d", f.routines, len(queues))
  280. }
  281. // TODO: this clamp is only safe because it is unreachable when the
  282. // udp side has multiple readers (linux Queues opens exactly n or
  283. // errors; every other platform already clamped routines to 1 above).
  284. // If a platform ever returns fewer queues than routines with
  285. // SO_REUSEPORT sockets already bound, the surplus sockets get no
  286. // listenOut and the kernel blackholes every flow it hashes to them —
  287. // fail loudly or close the extra sockets instead.
  288. f.l.Warn("tun multiqueue is not supported on this platform, falling back to fewer routines",
  289. "requested", f.routines, "opened", len(queues))
  290. f.routines = len(queues)
  291. }
  292. f.queues = queues
  293. metrics.GetOrRegisterGauge("routines", nil).Update(int64(f.routines))
  294. for i := range f.queues {
  295. f.batchers[i] = batch.NewMultiCoalescer(f.queues[i], f.l)
  296. }
  297. // On error the caller owns the cleanup, Control.Start cancels the service context
  298. // before releasing our resources so a waiter never observes a live context
  299. if err = f.inside.Activate(); err != nil {
  300. return err
  301. }
  302. return nil
  303. }
  304. func (f *Interface) run() {
  305. // Launch n queues to read packets from udp
  306. for i := 0; i < f.routines; i++ {
  307. f.wg.Go(func() {
  308. f.listenOut(i)
  309. })
  310. }
  311. // Launch n queues to read packets from tun dev
  312. for i := 0; i < f.routines; i++ {
  313. f.wg.Go(func() {
  314. f.listenIn(f.queues[i], i)
  315. })
  316. }
  317. }
  318. func (f *Interface) wait() error {
  319. f.wg.Wait()
  320. if e := f.fatalErr.Load(); e != nil {
  321. return *e
  322. }
  323. return nil
  324. }
  325. // onFatal stores the first fatal reader error, and calls triggerShutdown if it was the first one
  326. func (f *Interface) onFatal(err error) {
  327. swapped := f.fatalErr.CompareAndSwap(nil, &err)
  328. if !swapped {
  329. return
  330. }
  331. if f.triggerShutdown != nil {
  332. f.triggerShutdown()
  333. }
  334. }
  335. type rxContext struct {
  336. q int
  337. scratch []byte
  338. // nb is a re-usable nonce buffer for decrypt calls to use
  339. nb []byte
  340. h *header.H
  341. fwPacket *firewall.ParsedPacket
  342. hostmapCache map[uint32]*HostInfo
  343. lhh *LightHouseHandler
  344. ctCache *firewall.ConntrackCacheTicker
  345. }
  346. func newRxContext(f *Interface, q int) *rxContext {
  347. return &rxContext{
  348. q: q,
  349. scratch: make([]byte, mtu),
  350. nb: make([]byte, 12, 12),
  351. h: &header.H{},
  352. fwPacket: &firewall.ParsedPacket{},
  353. hostmapCache: map[uint32]*HostInfo{},
  354. lhh: f.lightHouse.NewRequestHandler(),
  355. ctCache: firewall.NewConntrackCacheTicker(f.ctx, f.l, f.conntrackCacheTimeout),
  356. }
  357. }
  358. func (f *Interface) listenOut(i int) {
  359. var li udp.Conn
  360. if i > 0 {
  361. li = f.writers[i]
  362. } else {
  363. li = f.outside
  364. }
  365. rxc := newRxContext(f, i)
  366. listener := func(fromUdpAddr netip.AddrPort, payload []byte) {
  367. f.readOutsidePackets(ViaSender{UdpAddr: fromUdpAddr, SockIdx: i}, payload, rxc)
  368. }
  369. flusher := func() {
  370. if err := f.batchers[i].Flush(); err != nil {
  371. f.l.Error("Failed to flush tun coalescer", "error", err)
  372. }
  373. clear(rxc.hostmapCache)
  374. }
  375. err := li.ListenOut(listener, flusher)
  376. // An error after teardown began is shutdown noise, the closed flag covers resources
  377. // Close releases itself and the cancelled ctx covers ones torn down by their owners
  378. // reacting to it, like the user device pipes
  379. if err != nil && !f.closed.Load() && f.ctx.Err() == nil {
  380. f.l.Error("Error while reading inbound packet, closing", "error", err)
  381. f.onFatal(err)
  382. }
  383. f.l.Debug("underlay reader is done", "reader", i)
  384. }
  385. func (f *Interface) pinThisThread(i int) {
  386. var cpu int
  387. if n := len(f.cpuAffinity); n > 0 {
  388. // Explicit tun.cpu_affinity list wins; parseCpuAffinity already
  389. // validated the entries against the allowed CPU set.
  390. cpu = f.cpuAffinity[i%n]
  391. } else if allowed, err := util.AllowedCPUs(); err == nil && len(allowed) > 0 {
  392. // Default: spread queues across the CPUs we're actually allowed to
  393. // run on. Under a cpuset/taskset mask these aren't 0..NumCPU-1, so
  394. // i % NumCPU would pick unrunnable IDs and every pin would fail.
  395. cpu = allowed[i%len(allowed)]
  396. } else {
  397. cpu = i % runtime.NumCPU()
  398. }
  399. if err := util.PinThreadToCPU(cpu); err != nil {
  400. f.l.Warn("failed to pin tun reader to CPU", "queue", i, "cpu", cpu, "err", err)
  401. }
  402. }
  403. // txQueue is the per-routine TX state owned by one listenIn goroutine.
  404. //
  405. // base carries base-session data, relay carriers, and everything on a tunnel
  406. // without lanes. It goes out a socket on the base port — egressSock's pick — since
  407. // base traffic must keep the base source port or a vanilla peer would see it move
  408. // and roam-thrash. lane[s] goes out a socket on listen.port+s and carries traffic
  409. // encrypted with lane s's session; lane[0] is base, and the rest are built on the
  410. // first packet that picks them, since a routine that never sends on a lane should
  411. // not hold a batch for it. Both come from laneSock, so a routine writes to its own
  412. // share of each port's socket group.
  413. //
  414. // Which lane a packet rides comes from its own flow hash, not from this
  415. // routine's index. That is deliberate. Which routine reads a flow is the
  416. // kernel's decision: it hashes the flow to a tun queue, but it also *learns*
  417. // the queue we write that flow's inbound packets to, and prefers what it
  418. // learned. So if the lane followed the routine, a peer whose lanes were still
  419. // down — every peer, for the first moments of a tunnel — would write all of its
  420. // inbound traffic to queue 0, teaching both kernels to steer every flow to
  421. // queue 0, and every tunnel would collapse onto lane 0 and stay there for as
  422. // long as its flows kept busy. Hashing here makes lane spread independent of
  423. // tun steering entirely.
  424. //
  425. // Every batch borrows arena, so a routine holding a batch per lane still costs
  426. // one slab. The arena is reset by flush once every batch over it is drained.
  427. //
  428. // Several routines can still write to one socket — the sockets on a port are
  429. // shared by the routines whose lane arithmetic lands on them — which the underlay
  430. // serializes (see batchWriter). Per-flow wire order still holds: a flow is hashed
  431. // onto one lane and read by one routine, so nothing else is writing it.
  432. type txQueue struct {
  433. // q is the queue this state belongs to, which laneSock needs to resolve a lane
  434. // to one of its port's sockets.
  435. q int
  436. base *batch.SendBatch
  437. lane []*batch.SendBatch
  438. arena *batch.Arena
  439. // live is every batch built so far, in build order, so base is first: see
  440. // flush. Kept as its own slice because lane is mostly nil holes and both
  441. // full and flush walk this per read batch.
  442. live []txBatch
  443. }
  444. // txBatch is a live batch and the index in writers of the socket it flushes to.
  445. type txBatch struct {
  446. sb *batch.SendBatch
  447. sock int
  448. }
  449. func (f *Interface) newTxQueue(q int) *txQueue {
  450. baseSock := f.egressSock(q)
  451. arena := batch.NewArena(batch.SendBatchCap * (udp.MTU + 32))
  452. base := batch.NewSendBatchSharedArena(f.writers[baseSock], batch.SendBatchCap, arena)
  453. tx := &txQueue{
  454. q: q,
  455. base: base,
  456. arena: arena,
  457. live: []txBatch{{sb: base, sock: baseSock}},
  458. }
  459. if f.multiport && f.laneCount > 1 {
  460. tx.lane = make([]*batch.SendBatch, f.laneCount)
  461. tx.lane[0] = base
  462. }
  463. return tx
  464. }
  465. // laneBatch returns the batch for lane s, building it the first time this
  466. // routine sends on that lane. Lanes this queue doesn't cover fall back to base,
  467. // which is also lane 0's batch.
  468. func (tx *txQueue) laneBatch(f *Interface, s int) *batch.SendBatch {
  469. if s <= 0 || s >= len(tx.lane) {
  470. return tx.base
  471. }
  472. sb := tx.lane[s]
  473. if sb == nil {
  474. sock := f.laneSock(tx.q, s)
  475. sb = batch.NewSendBatchSharedArena(f.writers[sock], batch.SendBatchCap, tx.arena)
  476. tx.lane[s] = sb
  477. tx.live = append(tx.live, txBatch{sb: sb, sock: sock})
  478. }
  479. return sb
  480. }
  481. // full reports a full sendmmsg worth of work queued across every lane, rather
  482. // than on any one of them: the arena is shared, so it is the total that bounds
  483. // how much is outstanding.
  484. func (tx *txQueue) full() bool {
  485. n := 0
  486. for _, b := range tx.live {
  487. n += b.sb.Len()
  488. }
  489. return n >= batch.SendBatchCap
  490. }
  491. // flush drains base before the lanes so that when a flow moves from the base
  492. // session onto a freshly promoted lane mid-window, its packets still leave this
  493. // host in encryption order. Resetting the shared arena is this queue's job,
  494. // since no single batch's Flush can know the others are done with it.
  495. func (tx *txQueue) flush(f *Interface) {
  496. for _, b := range tx.live {
  497. if b.sb.Len() > 0 {
  498. f.flushSendBatch(b.sb, b.sock)
  499. }
  500. }
  501. tx.arena.Reset()
  502. }
  503. func (f *Interface) listenIn(queue tio.Queue, i int) {
  504. // Pinning this thread (and goroutine) to a single CPU keeps every sendmmsg from this goroutine going through the
  505. // same TX ring on the nic, so the wire sees per-flow order. Skip entirely when tun.pin_threads is false.
  506. if f.pinThreads {
  507. f.pinThisThread(i)
  508. }
  509. rejectBuf := make([]byte, mtu)
  510. tx := f.newTxQueue(i)
  511. fwPacket := &firewall.ParsedPacket{}
  512. nb := make([]byte, 12, 12)
  513. conntrackCache := firewall.NewConntrackCacheTicker(f.ctx, f.l, f.conntrackCacheTimeout)
  514. for {
  515. pkts, err := queue.Read()
  516. if err != nil {
  517. // Same shutdown noise handling as listenOut
  518. if !f.closed.Load() && f.ctx.Err() == nil {
  519. f.l.Error("Error while reading outbound packet, closing", "error", err, "reader", i)
  520. f.onFatal(err)
  521. }
  522. break
  523. }
  524. for _, pkt := range pkts {
  525. f.consumeInsidePacket(pkt, fwPacket, nb, tx, rejectBuf, i, conntrackCache.Get())
  526. // Flush incrementally once a full sendmmsg batch has
  527. // accumulated so the first packets of a deep read drain
  528. // hit the wire while the rest are still being encrypted.
  529. if tx.full() {
  530. tx.flush(f)
  531. }
  532. }
  533. tx.flush(f)
  534. }
  535. f.l.Debug("overlay reader is done", "reader", i)
  536. }
  537. // flushSendBatch drains sb to the underlay and accounts for anything it could not deliver. A shortfall means
  538. // specific destinations were undeliverable (a stale remote, a reject rule), which the backend logs per peer at
  539. // debug; here it is only a counter, so one unreachable peer cannot spam a log line per batch.
  540. func (f *Interface) flushSendBatch(sb *batch.SendBatch, q int) {
  541. queued := sb.Len()
  542. written, err := sb.Flush()
  543. if err != nil {
  544. f.l.Error("Failed to write outgoing batch", "error", err, "writer", q)
  545. }
  546. if dropped := queued - written; dropped > 0 {
  547. f.metricTxDropped.Inc(int64(dropped))
  548. }
  549. }
  550. func (f *Interface) RegisterConfigChangeCallbacks(c *config.C) {
  551. c.RegisterReloadCallback(f.reloadFirewall)
  552. c.RegisterReloadCallback(f.reloadSendRecvError)
  553. c.RegisterReloadCallback(f.reloadAcceptRecvError)
  554. c.RegisterReloadCallback(f.reloadDisconnectInvalid)
  555. c.RegisterReloadCallback(f.reloadMisc)
  556. for _, udpConn := range f.writers {
  557. c.RegisterReloadCallback(udpConn.ReloadConfig)
  558. }
  559. }
  560. func (f *Interface) reloadDisconnectInvalid(c *config.C) {
  561. initial := c.InitialLoad()
  562. if initial || c.HasChanged("pki.disconnect_invalid") {
  563. f.disconnectInvalid.Store(c.GetBool("pki.disconnect_invalid", true))
  564. if !initial {
  565. f.l.Info("pki.disconnect_invalid changed", "value", f.disconnectInvalid.Load())
  566. }
  567. }
  568. }
  569. func (f *Interface) reloadFirewall(c *config.C) {
  570. cs := f.pki.getCertState()
  571. curCert := cs.getCertificate(cert.Version2)
  572. if curCert == nil {
  573. curCert = cs.getCertificate(cert.Version1)
  574. }
  575. // The firewall builds its routableNetworks set from the certificate's UnsafeNetworks at construction.
  576. // Check to see if that set has changed, and if so, rebuild the firewall.
  577. certUnsafeChanged := curCert != nil && !slices.Equal(curCert.UnsafeNetworks(), f.firewall.unsafeNetworks)
  578. if !c.HasChanged("firewall") && !certUnsafeChanged {
  579. f.l.Debug("No firewall config change detected")
  580. return
  581. }
  582. fw, err := NewFirewallFromConfig(f.l, cs, c)
  583. if err != nil {
  584. f.l.Error("Error while creating firewall during reload", "error", err)
  585. return
  586. }
  587. oldFw := f.firewall
  588. conntrack := oldFw.Conntrack
  589. conntrack.Lock()
  590. defer conntrack.Unlock()
  591. fw.rulesVersion = oldFw.rulesVersion + 1
  592. // If rulesVersion is back to zero, we have wrapped all the way around. Be
  593. // safe and just reset conntrack in this case.
  594. if fw.rulesVersion == 0 {
  595. f.l.Warn("firewall rulesVersion has overflowed, resetting conntrack",
  596. "firewallHashes", fw.GetRuleHashes(),
  597. "oldFirewallHashes", oldFw.GetRuleHashes(),
  598. "rulesVersion", fw.rulesVersion,
  599. )
  600. } else {
  601. fw.Conntrack = conntrack
  602. }
  603. f.firewall = fw
  604. oldFw.Destroy()
  605. f.l.Info("New firewall has been installed",
  606. "firewallHashes", fw.GetRuleHashes(),
  607. "oldFirewallHashes", oldFw.GetRuleHashes(),
  608. "rulesVersion", fw.rulesVersion,
  609. )
  610. }
  611. func (f *Interface) reloadSendRecvError(c *config.C) {
  612. if c.InitialLoad() || c.HasChanged("listen.send_recv_error") {
  613. stringValue := c.GetString("listen.send_recv_error", "always")
  614. switch stringValue {
  615. case "always":
  616. f.sendRecvErrorConfig = recvErrorAlways
  617. case "never":
  618. f.sendRecvErrorConfig = recvErrorNever
  619. case "private":
  620. f.sendRecvErrorConfig = recvErrorPrivate
  621. default:
  622. if c.GetBool("listen.send_recv_error", true) {
  623. f.sendRecvErrorConfig = recvErrorAlways
  624. } else {
  625. f.sendRecvErrorConfig = recvErrorNever
  626. }
  627. }
  628. f.l.Info("Loaded send_recv_error config", "sendRecvError", f.sendRecvErrorConfig.String())
  629. }
  630. }
  631. func (f *Interface) reloadAcceptRecvError(c *config.C) {
  632. if c.InitialLoad() || c.HasChanged("listen.accept_recv_error") {
  633. stringValue := c.GetString("listen.accept_recv_error", "always")
  634. switch stringValue {
  635. case "always":
  636. f.acceptRecvErrorConfig = recvErrorAlways
  637. case "never":
  638. f.acceptRecvErrorConfig = recvErrorNever
  639. case "private":
  640. f.acceptRecvErrorConfig = recvErrorPrivate
  641. default:
  642. if c.GetBool("listen.accept_recv_error", true) {
  643. f.acceptRecvErrorConfig = recvErrorAlways
  644. } else {
  645. f.acceptRecvErrorConfig = recvErrorNever
  646. }
  647. }
  648. f.l.Info("Loaded accept_recv_error config", "acceptRecvError", f.acceptRecvErrorConfig.String())
  649. }
  650. }
  651. func (f *Interface) reloadMisc(c *config.C) {
  652. if c.HasChanged("counters.try_promote") {
  653. n := c.GetUint32("counters.try_promote", defaultPromoteEvery)
  654. f.tryPromoteEvery.Store(n)
  655. f.l.Info("counters.try_promote has changed")
  656. }
  657. if c.HasChanged("counters.requery_every_packets") {
  658. n := c.GetUint32("counters.requery_every_packets", defaultReQueryEvery)
  659. f.reQueryEvery.Store(n)
  660. f.l.Info("counters.requery_every_packets has changed")
  661. }
  662. if c.HasChanged("timers.requery_wait_duration") {
  663. n := c.GetDuration("timers.requery_wait_duration", defaultReQueryWait)
  664. f.reQueryWait.Store(int64(n))
  665. f.l.Info("timers.requery_wait_duration has changed")
  666. }
  667. }
  668. func (f *Interface) emitStats(ctx context.Context, i time.Duration) {
  669. ticker := time.NewTicker(i)
  670. defer ticker.Stop()
  671. udpStats := udp.NewUDPStatsEmitter(f.writers)
  672. certExpirationGauge := metrics.GetOrRegisterGauge("certificate.ttl_seconds", nil)
  673. certInitiatingVersion := metrics.GetOrRegisterGauge("certificate.initiating_version", nil)
  674. certMaxVersion := metrics.GetOrRegisterGauge("certificate.max_version", nil)
  675. // Registered only when we run multiport, so these don't sit at zero on a node
  676. // that was never going to have a lane and read as a broken feature.
  677. var lanesUpGauge, laneTunnelsGauge metrics.Gauge
  678. if f.multiport && f.laneCount > 1 {
  679. lanesUpGauge = metrics.GetOrRegisterGauge("multiport.lanes.up", nil)
  680. laneTunnelsGauge = metrics.GetOrRegisterGauge("multiport.lanes.tunnels", nil)
  681. }
  682. emit := func() {
  683. f.firewall.EmitStats()
  684. f.handshakeManager.EmitStats()
  685. udpStats()
  686. if lanesUpGauge != nil {
  687. f.emitLaneStats(lanesUpGauge, laneTunnelsGauge)
  688. }
  689. certState := f.pki.getCertState()
  690. defaultCrt := certState.GetDefaultCertificate()
  691. certExpirationGauge.Update(int64(defaultCrt.NotAfter().Sub(time.Now()) / time.Second))
  692. certInitiatingVersion.Update(int64(defaultCrt.Version()))
  693. // Report the max certificate version we are capable of using
  694. if certState.v2Cert != nil {
  695. certMaxVersion.Update(int64(certState.v2Cert.Version()))
  696. } else {
  697. certMaxVersion.Update(int64(certState.v1Cert.Version()))
  698. }
  699. }
  700. // Prime gauges so a Prometheus scrape that lands before the first tick
  701. // sees real values instead of the zero defaults (issue #907).
  702. emit()
  703. for {
  704. select {
  705. case <-ctx.Done():
  706. return
  707. case <-ticker.C:
  708. emit()
  709. }
  710. }
  711. }
  712. func (f *Interface) GetHostInfo(vpnIp netip.Addr) *HostInfo {
  713. return f.hostMap.QueryVpnAddr(vpnIp)
  714. }
  715. func (f *Interface) GetCertState() *CertState {
  716. return f.pki.getCertState()
  717. }
  718. // Close releases the interface's resources: the udp sockets and the tun device.
  719. // It is idempotent and safe to call at any point in the lifecycle, including on an interface that never activated,
  720. // calls after the first return nil without doing anything.
  721. func (f *Interface) Close() error {
  722. if !f.closed.CompareAndSwap(false, true) {
  723. return nil
  724. }
  725. var errs []error
  726. // Release the udp readers
  727. for i, u := range f.writers {
  728. err := u.Close()
  729. if err != nil {
  730. f.l.Error("Error while closing udp socket", "error", err, "writer", i)
  731. errs = append(errs, err)
  732. }
  733. }
  734. // Release the tun device (closing the tun also closes all readers)
  735. closeErr := f.inside.Close()
  736. if closeErr != nil {
  737. errs = append(errs, closeErr)
  738. }
  739. // Release the construction token so waiters know the resources are gone
  740. f.wg.Done()
  741. return errors.Join(errs...)
  742. }