interface.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  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. // PinThreads controls whether each TUN reader OS thread is pinned to a
  56. // single CPU (via tun.pin_threads, default true). Pinning keeps each
  57. // goroutine's sendmmsg on one XPS-selected NIC TX ring so per-flow
  58. // packets stay ordered on the wire.
  59. PinThreads bool
  60. l *slog.Logger
  61. }
  62. type Interface struct {
  63. hostMap *HostMap
  64. outside udp.Conn
  65. inside overlay.Device
  66. pki *PKI
  67. firewall *Firewall
  68. connectionManager *connectionManager
  69. handshakeManager *HandshakeManager
  70. dnsServer *dnsServer
  71. createTime time.Time
  72. lightHouse *LightHouse
  73. myBroadcastAddrsTable *bart.Lite
  74. myVpnAddrs []netip.Addr // A list of addresses assigned to us via our certificate
  75. myVpnAddrsTable *bart.Lite
  76. myVpnNetworks []netip.Prefix // A list of networks assigned to us via our certificate
  77. myVpnNetworksTable *bart.Lite
  78. dropLocalBroadcast bool
  79. dropMulticast bool
  80. routines int
  81. disconnectInvalid atomic.Bool
  82. closed atomic.Bool
  83. // cpuAffinity, when non-empty, names the CPUs each TUN reader goroutine
  84. // should pin to. Queue i pins to cpuAffinity[i % len(cpuAffinity)].
  85. // Empty falls back to the default pin-to-(allowed CPU) behavior.
  86. // Only consulted when pinThreads is true.
  87. cpuAffinity []int
  88. // pinThreads controls whether listenIn pins each TUN reader OS thread to
  89. // a CPU at all (tun.pin_threads, default true). When false, threads are
  90. // left free to migrate as on stock nebula.
  91. pinThreads bool
  92. relayManager *relayManager
  93. tryPromoteEvery atomic.Uint32
  94. reQueryEvery atomic.Uint32
  95. reQueryWait atomic.Int64
  96. sendRecvErrorConfig recvErrorConfig
  97. acceptRecvErrorConfig recvErrorConfig
  98. // Bumped on every udp rebind, tunnels compare it to decide they need a punch from the far side
  99. rebindEpoch atomic.Uint32
  100. version string
  101. conntrackCacheTimeout time.Duration
  102. ctx context.Context
  103. writers []udp.Conn
  104. queues []tio.Queue
  105. // batchers is one per tun queue, wrapping queues[i]. readOutsidePackets
  106. // commits plaintext into the batcher; the plaintext is decrypted
  107. // in place inside the UDP receive buffers, so listenOut must call Flush
  108. // at the end of each UDP recvmmsg batch, before those buffers are
  109. // reused (every udp.Conn ListenOut guarantees that ordering).
  110. batchers []*batch.MultiCoalescer
  111. wg sync.WaitGroup
  112. // readers covers just the listenIn and listenOut goroutines, wg also holds the construction token Close releases
  113. readers sync.WaitGroup
  114. udpTxErrLimiter *ratelimit.Limiter // udp direct transmit error log limiter
  115. udpRelayTxErrLimiter *ratelimit.Limiter // udp relay transmit error log limiter
  116. txOversizeLimiter *ratelimit.Limiter // oversized outbound packet drop log limiter
  117. // fatalErr holds the first unexpected reader error that caused shutdown.
  118. // nil means "no fatal error" (yet)
  119. fatalErr atomic.Pointer[error]
  120. // triggerShutdown is a function that will be run exactly once, when onFatal swaps something non-nil into fatalErr
  121. triggerShutdown func()
  122. metricHandshakes metrics.Histogram
  123. messageMetrics *MessageMetrics
  124. cachedPacketMetrics *cachedPacketMetrics
  125. metricTxDropped metrics.Counter
  126. l *slog.Logger
  127. }
  128. type EncWriter interface {
  129. SendVia(via *HostInfo, relay *Relay, ad, nb, out []byte, nocopy bool, q int)
  130. SendMessageToVpnAddr(t header.MessageType, st header.MessageSubType, vpnAddr netip.Addr, p, nb, out []byte)
  131. SendMessageToHostInfo(t header.MessageType, st header.MessageSubType, hostinfo *HostInfo, p, nb, out []byte)
  132. Handshake(vpnAddr netip.Addr)
  133. GetHostInfo(vpnAddr netip.Addr) *HostInfo
  134. GetCertState() *CertState
  135. }
  136. type recvErrorConfig uint8
  137. const (
  138. recvErrorAlways recvErrorConfig = iota
  139. recvErrorNever
  140. recvErrorPrivate
  141. )
  142. func (s recvErrorConfig) ShouldRecvError(endpoint netip.AddrPort) bool {
  143. switch s {
  144. case recvErrorPrivate:
  145. return endpoint.Addr().IsPrivate()
  146. case recvErrorAlways:
  147. return true
  148. case recvErrorNever:
  149. return false
  150. default:
  151. panic(fmt.Errorf("invalid recvErrorConfig value: %d", s))
  152. }
  153. }
  154. func (s recvErrorConfig) String() string {
  155. switch s {
  156. case recvErrorAlways:
  157. return "always"
  158. case recvErrorNever:
  159. return "never"
  160. case recvErrorPrivate:
  161. return "private"
  162. default:
  163. return fmt.Sprintf("invalid(%d)", s)
  164. }
  165. }
  166. func NewInterface(ctx context.Context, c *InterfaceConfig) (*Interface, error) {
  167. if c.Outside == nil {
  168. return nil, errors.New("no outside connection")
  169. }
  170. if c.Inside == nil {
  171. return nil, errors.New("no inside interface (tun)")
  172. }
  173. if c.pki == nil {
  174. return nil, errors.New("no certificate state")
  175. }
  176. if c.Firewall == nil {
  177. return nil, errors.New("no firewall rules")
  178. }
  179. if c.connectionManager == nil {
  180. return nil, errors.New("no connection manager")
  181. }
  182. udpTxErrLimiter, err := ratelimit.New(1, time.Second)
  183. if err != nil {
  184. return nil, err
  185. }
  186. udpRelayTxErrLimiter, err := ratelimit.New(1, time.Second)
  187. if err != nil {
  188. return nil, err
  189. }
  190. txOversizeLimiter, err := ratelimit.New(1, time.Second)
  191. if err != nil {
  192. return nil, err
  193. }
  194. if c.routines <= 1 {
  195. c.PinThreads = false //pinning is not useful unless there's more than one tun reader
  196. }
  197. cs := c.pki.getCertState()
  198. ifce := &Interface{
  199. ctx: ctx,
  200. pki: c.pki,
  201. hostMap: c.HostMap,
  202. outside: c.Outside,
  203. inside: c.Inside,
  204. firewall: c.Firewall,
  205. dnsServer: c.DnsServer,
  206. handshakeManager: c.HandshakeManager,
  207. createTime: time.Now(),
  208. lightHouse: c.lightHouse,
  209. dropLocalBroadcast: c.DropLocalBroadcast,
  210. dropMulticast: c.DropMulticast,
  211. routines: c.routines,
  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. udpTxErrLimiter: udpTxErrLimiter,
  226. udpRelayTxErrLimiter: udpRelayTxErrLimiter,
  227. txOversizeLimiter: txOversizeLimiter,
  228. metricHandshakes: metrics.GetOrRegisterHistogram("handshakes", nil, metrics.NewExpDecaySample(1028, 0.015)),
  229. metricTxDropped: metrics.GetOrRegisterCounter("udp.tx.dropped", nil),
  230. messageMetrics: c.MessageMetrics,
  231. cachedPacketMetrics: &cachedPacketMetrics{
  232. sent: metrics.GetOrRegisterCounter("hostinfo.cached_packets.sent", nil),
  233. dropped: metrics.GetOrRegisterCounter("hostinfo.cached_packets.dropped", nil),
  234. },
  235. l: c.l,
  236. }
  237. ifce.tryPromoteEvery.Store(c.tryPromoteEvery)
  238. ifce.reQueryEvery.Store(c.reQueryEvery)
  239. ifce.reQueryWait.Store(int64(c.reQueryWait))
  240. ifce.connectionManager.intf = ifce
  241. // Held until Close so waiting on the interface blocks until the resources are actually released
  242. ifce.wg.Add(1)
  243. return ifce, nil
  244. }
  245. // activate creates the interface on the host. After the interface is created, any
  246. // other services that want to bind listeners to its IP may do so successfully. However,
  247. // the interface isn't going to process anything until run() is called.
  248. func (f *Interface) activate() error {
  249. // actually turn on tun dev
  250. addr, err := f.outside.LocalAddr()
  251. if err != nil {
  252. f.l.Error("Failed to get udp listen address", "error", err)
  253. }
  254. f.l.Info("Nebula interface is active",
  255. "interface", f.inside.Name(),
  256. "networks", f.myVpnNetworks,
  257. "build", f.version,
  258. "udpAddr", addr,
  259. "boringcrypto", boringEnabled(),
  260. "fips140Version", fips140.Version(),
  261. "fips140Enabled", fips140.Enabled(),
  262. "fips140Enforced", fips140.Enforced(),
  263. )
  264. if f.routines > 1 && !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. // TODO: this clamp is only safe because it is unreachable when the
  277. // udp side has multiple readers (linux Queues opens exactly n or
  278. // errors; every other platform already clamped routines to 1 above).
  279. // If a platform ever returns fewer queues than routines with
  280. // SO_REUSEPORT sockets already bound, the surplus sockets get no
  281. // listenOut and the kernel blackholes every flow it hashes to them —
  282. // fail loudly or close the extra sockets instead.
  283. f.l.Warn("tun multiqueue is not supported on this platform, falling back to fewer routines",
  284. "requested", f.routines, "opened", len(queues))
  285. f.routines = len(queues)
  286. }
  287. f.queues = queues
  288. metrics.GetOrRegisterGauge("routines", nil).Update(int64(f.routines))
  289. for i := range f.queues {
  290. f.batchers[i] = batch.NewMultiCoalescer(f.queues[i], f.l)
  291. }
  292. // On error the caller owns the cleanup, Control.Start cancels the service context
  293. // before releasing our resources so a waiter never observes a live context
  294. if err = f.inside.Activate(); err != nil {
  295. return err
  296. }
  297. return nil
  298. }
  299. func (f *Interface) run() {
  300. // Launch n queues to read packets from udp
  301. for i := 0; i < f.routines; i++ {
  302. f.readers.Add(1)
  303. f.wg.Go(func() {
  304. defer f.readers.Done()
  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.readers.Add(1)
  311. f.wg.Go(func() {
  312. defer f.readers.Done()
  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.
  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. func (f *Interface) listenIn(queue tio.Queue, i int) {
  403. // Pinning this thread (and goroutine) to a single CPU keeps every sendmmsg from this goroutine going through the
  404. // same TX ring on the nic, so the wire sees per-flow order. Skip entirely when tun.pin_threads is false.
  405. if f.pinThreads {
  406. f.pinThisThread(i)
  407. }
  408. rejectBuf := make([]byte, mtu)
  409. arenaSize := batch.SendBatchCap * (udp.MTU + 32)
  410. sb := batch.NewSendBatch(f.writers[i], batch.SendBatchCap, arenaSize)
  411. fwPacket := &firewall.ParsedPacket{}
  412. nb := make([]byte, 12, 12)
  413. conntrackCache := firewall.NewConntrackCacheTicker(f.ctx, f.l, f.conntrackCacheTimeout)
  414. for {
  415. pkts, err := queue.Read()
  416. if err != nil {
  417. // Same shutdown noise handling as listenOut
  418. if !f.closed.Load() && f.ctx.Err() == nil {
  419. f.l.Error("Error while reading outbound packet, closing", "error", err, "reader", i)
  420. f.onFatal(err)
  421. }
  422. break
  423. }
  424. for _, pkt := range pkts {
  425. f.consumeInsidePacket(pkt, fwPacket, nb, sb, rejectBuf, i, conntrackCache.Get())
  426. // Flush incrementally once a full sendmmsg batch has
  427. // accumulated so the first packets of a deep read drain
  428. // hit the wire while the rest are still being encrypted.
  429. if sb.Len() >= batch.SendBatchCap {
  430. f.flushSendBatch(sb, i)
  431. }
  432. }
  433. f.flushSendBatch(sb, i)
  434. }
  435. f.l.Debug("overlay reader is done", "reader", i)
  436. }
  437. // flushSendBatch drains sb to the underlay and accounts for anything it could not deliver. A shortfall means
  438. // specific destinations were undeliverable (a stale remote, a reject rule), which the backend logs per peer at
  439. // debug; here it is only a counter, so one unreachable peer cannot spam a log line per batch.
  440. func (f *Interface) flushSendBatch(sb *batch.SendBatch, q int) {
  441. queued := sb.Len()
  442. written, err := sb.Flush()
  443. if err != nil {
  444. f.l.Error("Failed to write outgoing batch", "error", err, "writer", q)
  445. }
  446. if dropped := queued - written; dropped > 0 {
  447. f.metricTxDropped.Inc(int64(dropped))
  448. }
  449. }
  450. func (f *Interface) RegisterConfigChangeCallbacks(c *config.C) {
  451. c.RegisterReloadCallback(f.reloadFirewall)
  452. for _, reload := range []func(*config.C){
  453. f.reloadSendRecvError, f.reloadAcceptRecvError, f.reloadDisconnectInvalid, f.reloadMisc,
  454. } {
  455. c.RegisterReloadCallback(func(c *config.C, _ *config.Reload) { reload(c) })
  456. }
  457. for _, udpConn := range f.writers {
  458. c.RegisterReloadCallback(udpConn.ReloadConfig)
  459. }
  460. }
  461. func (f *Interface) reloadDisconnectInvalid(c *config.C) {
  462. initial := c.InitialLoad()
  463. if initial || c.HasChanged("pki.disconnect_invalid") {
  464. f.disconnectInvalid.Store(c.GetBool("pki.disconnect_invalid", true))
  465. if !initial {
  466. f.l.Info("pki.disconnect_invalid changed", "value", f.disconnectInvalid.Load())
  467. }
  468. }
  469. }
  470. func (f *Interface) reloadFirewall(c *config.C, r *config.Reload) {
  471. cs := f.pki.getCertState()
  472. curCert := cs.getCertificate(cert.Version2)
  473. if curCert == nil {
  474. curCert = cs.getCertificate(cert.Version1)
  475. }
  476. // Compare with what the running firewall was built from, not the last config, so a firewall that failed to build
  477. // is tried again. The cert is the one this reload brought, PKI registers its reload callback before this one
  478. src := c.Render("firewall")
  479. if src != "" && src == f.firewall.source && curCert != nil &&
  480. slices.Equal(curCert.Networks(), f.firewall.assignedNetworks) &&
  481. slices.Equal(curCert.UnsafeNetworks(), f.firewall.unsafeNetworks) {
  482. f.l.Debug("No firewall config change detected")
  483. return
  484. }
  485. fw, err := NewFirewallFromConfig(f.l, cs, c)
  486. if err != nil {
  487. f.l.Error("Error while creating firewall during reload", "error", err)
  488. r.Failed()
  489. return
  490. }
  491. oldFw := f.firewall
  492. conntrack := oldFw.Conntrack
  493. conntrack.Lock()
  494. defer conntrack.Unlock()
  495. fw.rulesVersion = oldFw.rulesVersion + 1
  496. // If rulesVersion is back to zero, we have wrapped all the way around. Be
  497. // safe and just reset conntrack in this case.
  498. if fw.rulesVersion == 0 {
  499. f.l.Warn("firewall rulesVersion has overflowed, resetting conntrack",
  500. "firewallHashes", fw.GetRuleHashes(),
  501. "oldFirewallHashes", oldFw.GetRuleHashes(),
  502. "rulesVersion", fw.rulesVersion,
  503. )
  504. } else {
  505. fw.Conntrack = conntrack
  506. }
  507. f.firewall = fw
  508. oldFw.Destroy()
  509. f.l.Info("New firewall has been installed",
  510. "firewallHashes", fw.GetRuleHashes(),
  511. "oldFirewallHashes", oldFw.GetRuleHashes(),
  512. "rulesVersion", fw.rulesVersion,
  513. )
  514. }
  515. func (f *Interface) reloadSendRecvError(c *config.C) {
  516. if c.InitialLoad() || c.HasChanged("listen.send_recv_error") {
  517. stringValue := c.GetString("listen.send_recv_error", "always")
  518. switch stringValue {
  519. case "always":
  520. f.sendRecvErrorConfig = recvErrorAlways
  521. case "never":
  522. f.sendRecvErrorConfig = recvErrorNever
  523. case "private":
  524. f.sendRecvErrorConfig = recvErrorPrivate
  525. default:
  526. if c.GetBool("listen.send_recv_error", true) {
  527. f.sendRecvErrorConfig = recvErrorAlways
  528. } else {
  529. f.sendRecvErrorConfig = recvErrorNever
  530. }
  531. }
  532. f.l.Info("Loaded send_recv_error config", "sendRecvError", f.sendRecvErrorConfig.String())
  533. }
  534. }
  535. func (f *Interface) reloadAcceptRecvError(c *config.C) {
  536. if c.InitialLoad() || c.HasChanged("listen.accept_recv_error") {
  537. stringValue := c.GetString("listen.accept_recv_error", "always")
  538. switch stringValue {
  539. case "always":
  540. f.acceptRecvErrorConfig = recvErrorAlways
  541. case "never":
  542. f.acceptRecvErrorConfig = recvErrorNever
  543. case "private":
  544. f.acceptRecvErrorConfig = recvErrorPrivate
  545. default:
  546. if c.GetBool("listen.accept_recv_error", true) {
  547. f.acceptRecvErrorConfig = recvErrorAlways
  548. } else {
  549. f.acceptRecvErrorConfig = recvErrorNever
  550. }
  551. }
  552. f.l.Info("Loaded accept_recv_error config", "acceptRecvError", f.acceptRecvErrorConfig.String())
  553. }
  554. }
  555. func (f *Interface) reloadMisc(c *config.C) {
  556. if c.HasChanged("counters.try_promote") {
  557. n := c.GetUint32("counters.try_promote", defaultPromoteEvery)
  558. f.tryPromoteEvery.Store(n)
  559. f.l.Info("counters.try_promote has changed")
  560. }
  561. if c.HasChanged("counters.requery_every_packets") {
  562. n := c.GetUint32("counters.requery_every_packets", defaultReQueryEvery)
  563. f.reQueryEvery.Store(n)
  564. f.l.Info("counters.requery_every_packets has changed")
  565. }
  566. if c.HasChanged("timers.requery_wait_duration") {
  567. n := c.GetDuration("timers.requery_wait_duration", defaultReQueryWait)
  568. f.reQueryWait.Store(int64(n))
  569. f.l.Info("timers.requery_wait_duration has changed")
  570. }
  571. }
  572. // statsEmitter updates the interface's gauges, the stats server runs it on its capture loop.
  573. func (f *Interface) statsEmitter() func() {
  574. udpStats := udp.NewUDPStatsEmitter(f.writers)
  575. certExpirationGauge := metrics.GetOrRegisterGauge("certificate.ttl_seconds", nil)
  576. certInitiatingVersion := metrics.GetOrRegisterGauge("certificate.initiating_version", nil)
  577. certMaxVersion := metrics.GetOrRegisterGauge("certificate.max_version", nil)
  578. return func() {
  579. f.firewall.EmitStats()
  580. f.handshakeManager.EmitStats()
  581. udpStats()
  582. certState := f.pki.getCertState()
  583. defaultCrt := certState.GetDefaultCertificate()
  584. certExpirationGauge.Update(int64(defaultCrt.NotAfter().Sub(time.Now()) / time.Second))
  585. certInitiatingVersion.Update(int64(defaultCrt.Version()))
  586. // Report the max certificate version we are capable of using
  587. if certState.v2Cert != nil {
  588. certMaxVersion.Update(int64(certState.v2Cert.Version()))
  589. } else {
  590. certMaxVersion.Update(int64(certState.v1Cert.Version()))
  591. }
  592. }
  593. }
  594. func (f *Interface) GetHostInfo(vpnIp netip.Addr) *HostInfo {
  595. return f.hostMap.QueryVpnAddr(vpnIp)
  596. }
  597. func (f *Interface) GetCertState() *CertState {
  598. return f.pki.getCertState()
  599. }
  600. // shutdowner is a udp.Conn or overlay.Device whose readers can be woken without releasing their fds
  601. type shutdowner interface {
  602. Shutdown() error
  603. }
  604. // readerShutdownTimeout bounds how long Close waits on woken readers before releasing their fds anyway
  605. const readerShutdownTimeout = 5 * time.Second
  606. // Close releases the interface's resources: the udp sockets and the tun device.
  607. // It is idempotent and safe to call at any point in the lifecycle, including on an interface that never activated,
  608. // calls after the first return nil without doing anything.
  609. func (f *Interface) Close() error {
  610. if !f.closed.CompareAndSwap(false, true) {
  611. return nil
  612. }
  613. var errs []error
  614. closeUdp := func(i int, u udp.Conn) {
  615. if err := u.Close(); err != nil {
  616. f.l.Error("Error while closing udp socket", "error", err, "writer", i)
  617. errs = append(errs, err)
  618. }
  619. }
  620. closeTun := func() {
  621. if err := f.inside.Close(); err != nil {
  622. errs = append(errs, err)
  623. }
  624. }
  625. // Wake every reader before releasing any fd, one that loops back into a syscall on a reused fd number never wakes.
  626. // Anything without Shutdown is closed right away, as before.
  627. var deferred []func()
  628. for i, u := range f.writers {
  629. if s, ok := u.(shutdowner); ok {
  630. if err := s.Shutdown(); err != nil {
  631. f.l.Error("Error while shutting down udp socket", "error", err, "writer", i)
  632. errs = append(errs, err)
  633. }
  634. deferred = append(deferred, func() { closeUdp(i, u) })
  635. } else {
  636. closeUdp(i, u)
  637. }
  638. }
  639. if s, ok := f.inside.(shutdowner); ok {
  640. if err := s.Shutdown(); err != nil {
  641. errs = append(errs, err)
  642. }
  643. deferred = append(deferred, closeTun)
  644. } else {
  645. closeTun()
  646. }
  647. if len(deferred) > 0 {
  648. readersDone := make(chan struct{})
  649. go func() {
  650. f.readers.Wait()
  651. close(readersDone)
  652. }()
  653. select {
  654. case <-readersDone:
  655. case <-time.After(readerShutdownTimeout):
  656. f.l.Warn("Readers did not stop, closing their fds anyway", "timeout", readerShutdownTimeout)
  657. }
  658. for _, closeFn := range deferred {
  659. closeFn()
  660. }
  661. }
  662. // Release the construction token so waiters know the resources are gone
  663. f.wg.Done()
  664. return errors.Join(errs...)
  665. }