interface.go 23 KB

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