interface.go 23 KB

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