1
0

interface.go 22 KB

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