interface.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805
  1. package nebula
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "net/netip"
  8. "runtime"
  9. "sync"
  10. "sync/atomic"
  11. "time"
  12. "github.com/gaissmai/bart"
  13. "github.com/rcrowley/go-metrics"
  14. "github.com/sirupsen/logrus"
  15. "github.com/slackhq/nebula/config"
  16. "github.com/slackhq/nebula/firewall"
  17. "github.com/slackhq/nebula/header"
  18. "github.com/slackhq/nebula/overlay"
  19. "github.com/slackhq/nebula/packet"
  20. "github.com/slackhq/nebula/udp"
  21. )
  22. const (
  23. mtu = 9001
  24. inboundBatchSizeDefault = 32
  25. outboundBatchSizeDefault = 32
  26. batchFlushIntervalDefault = 50 * time.Microsecond
  27. maxOutstandingBatchesDefault = 1028
  28. sendBatchSizeDefault = 32
  29. )
  30. type InterfaceConfig struct {
  31. HostMap *HostMap
  32. Outside udp.Conn
  33. Inside overlay.Device
  34. pki *PKI
  35. Cipher string
  36. Firewall *Firewall
  37. ServeDns bool
  38. HandshakeManager *HandshakeManager
  39. lightHouse *LightHouse
  40. connectionManager *connectionManager
  41. DropLocalBroadcast bool
  42. DropMulticast bool
  43. routines int
  44. MessageMetrics *MessageMetrics
  45. version string
  46. relayManager *relayManager
  47. punchy *Punchy
  48. tryPromoteEvery uint32
  49. reQueryEvery uint32
  50. reQueryWait time.Duration
  51. ConntrackCacheTimeout time.Duration
  52. BatchConfig BatchConfig
  53. l *logrus.Logger
  54. }
  55. type BatchConfig struct {
  56. InboundBatchSize int
  57. OutboundBatchSize int
  58. FlushInterval time.Duration
  59. MaxOutstandingPerChan int
  60. }
  61. type Interface struct {
  62. hostMap *HostMap
  63. outside udp.Conn
  64. inside overlay.Device
  65. pki *PKI
  66. firewall *Firewall
  67. connectionManager *connectionManager
  68. handshakeManager *HandshakeManager
  69. serveDns bool
  70. createTime time.Time
  71. lightHouse *LightHouse
  72. myBroadcastAddrsTable *bart.Lite
  73. myVpnAddrs []netip.Addr // A list of addresses assigned to us via our certificate
  74. myVpnAddrsTable *bart.Lite
  75. myVpnNetworks []netip.Prefix // A list of networks assigned to us via our certificate
  76. myVpnNetworksTable *bart.Lite
  77. dropLocalBroadcast bool
  78. dropMulticast bool
  79. routines int
  80. disconnectInvalid atomic.Bool
  81. closed atomic.Bool
  82. relayManager *relayManager
  83. tryPromoteEvery atomic.Uint32
  84. reQueryEvery atomic.Uint32
  85. reQueryWait atomic.Int64
  86. sendRecvErrorConfig sendRecvErrorConfig
  87. // rebindCount is used to decide if an active tunnel should trigger a punch notification through a lighthouse
  88. rebindCount int8
  89. version string
  90. conntrackCacheTimeout time.Duration
  91. writers []udp.Conn
  92. readers []io.ReadWriteCloser
  93. wg sync.WaitGroup
  94. metricHandshakes metrics.Histogram
  95. messageMetrics *MessageMetrics
  96. cachedPacketMetrics *cachedPacketMetrics
  97. l *logrus.Logger
  98. inPool sync.Pool
  99. inbound []chan *packetBatch
  100. outPool sync.Pool
  101. outbound []chan *outboundBatch
  102. packetBatchPool sync.Pool
  103. outboundBatchPool sync.Pool
  104. sendPool sync.Pool
  105. sendBatchSize int
  106. inboundBatchSize int
  107. outboundBatchSize int
  108. batchFlushInterval time.Duration
  109. maxOutstandingPerChan int
  110. }
  111. type outboundSend struct {
  112. buf *[]byte
  113. length int
  114. addr netip.AddrPort
  115. }
  116. type packetBatch struct {
  117. packets []*packet.Packet
  118. }
  119. func newPacketBatch(capacity int) *packetBatch {
  120. return &packetBatch{
  121. packets: make([]*packet.Packet, 0, capacity),
  122. }
  123. }
  124. func (b *packetBatch) add(p *packet.Packet) {
  125. b.packets = append(b.packets, p)
  126. }
  127. func (b *packetBatch) reset() {
  128. for i := range b.packets {
  129. b.packets[i] = nil
  130. }
  131. b.packets = b.packets[:0]
  132. }
  133. func (f *Interface) getPacketBatch() *packetBatch {
  134. if v := f.packetBatchPool.Get(); v != nil {
  135. b := v.(*packetBatch)
  136. b.reset()
  137. return b
  138. }
  139. return newPacketBatch(f.inboundBatchSize)
  140. }
  141. func (f *Interface) releasePacketBatch(b *packetBatch) {
  142. b.reset()
  143. f.packetBatchPool.Put(b)
  144. }
  145. type outboundBatch struct {
  146. payloads []*[]byte
  147. }
  148. func newOutboundBatch(capacity int) *outboundBatch {
  149. return &outboundBatch{payloads: make([]*[]byte, 0, capacity)}
  150. }
  151. func (b *outboundBatch) add(buf *[]byte) {
  152. b.payloads = append(b.payloads, buf)
  153. }
  154. func (b *outboundBatch) reset() {
  155. for i := range b.payloads {
  156. b.payloads[i] = nil
  157. }
  158. b.payloads = b.payloads[:0]
  159. }
  160. func (f *Interface) getOutboundBatch() *outboundBatch {
  161. if v := f.outboundBatchPool.Get(); v != nil {
  162. b := v.(*outboundBatch)
  163. b.reset()
  164. return b
  165. }
  166. return newOutboundBatch(f.outboundBatchSize)
  167. }
  168. func (f *Interface) releaseOutboundBatch(b *outboundBatch) {
  169. b.reset()
  170. f.outboundBatchPool.Put(b)
  171. }
  172. func (f *Interface) getSendBuffer() *[]byte {
  173. if v := f.sendPool.Get(); v != nil {
  174. buf := v.(*[]byte)
  175. *buf = (*buf)[:0]
  176. return buf
  177. }
  178. b := make([]byte, mtu)
  179. return &b
  180. }
  181. func (f *Interface) releaseSendBuffer(buf *[]byte) {
  182. if buf == nil {
  183. return
  184. }
  185. *buf = (*buf)[:0]
  186. f.sendPool.Put(buf)
  187. }
  188. func (f *Interface) flushSendQueue(q int, pending *[]outboundSend) {
  189. if len(*pending) == 0 {
  190. return
  191. }
  192. batch := make([]udp.BatchPacket, len(*pending))
  193. for i, entry := range *pending {
  194. batch[i] = udp.BatchPacket{
  195. Payload: (*entry.buf)[:entry.length],
  196. Addr: entry.addr,
  197. }
  198. }
  199. sent, err := f.writers[q].WriteBatch(batch)
  200. if err != nil {
  201. f.l.WithError(err).WithField("sent", sent).Error("Failed to batch send packets")
  202. }
  203. for _, entry := range *pending {
  204. f.releaseSendBuffer(entry.buf)
  205. }
  206. *pending = (*pending)[:0]
  207. }
  208. type EncWriter interface {
  209. SendVia(via *HostInfo,
  210. relay *Relay,
  211. ad,
  212. nb,
  213. out []byte,
  214. nocopy bool,
  215. )
  216. SendMessageToVpnAddr(t header.MessageType, st header.MessageSubType, vpnAddr netip.Addr, p, nb, out []byte)
  217. SendMessageToHostInfo(t header.MessageType, st header.MessageSubType, hostinfo *HostInfo, p, nb, out []byte)
  218. Handshake(vpnAddr netip.Addr)
  219. GetHostInfo(vpnAddr netip.Addr) *HostInfo
  220. GetCertState() *CertState
  221. }
  222. type sendRecvErrorConfig uint8
  223. const (
  224. sendRecvErrorAlways sendRecvErrorConfig = iota
  225. sendRecvErrorNever
  226. sendRecvErrorPrivate
  227. )
  228. func (s sendRecvErrorConfig) ShouldSendRecvError(endpoint netip.AddrPort) bool {
  229. switch s {
  230. case sendRecvErrorPrivate:
  231. return endpoint.Addr().IsPrivate()
  232. case sendRecvErrorAlways:
  233. return true
  234. case sendRecvErrorNever:
  235. return false
  236. default:
  237. panic(fmt.Errorf("invalid sendRecvErrorConfig value: %d", s))
  238. }
  239. }
  240. func (s sendRecvErrorConfig) String() string {
  241. switch s {
  242. case sendRecvErrorAlways:
  243. return "always"
  244. case sendRecvErrorNever:
  245. return "never"
  246. case sendRecvErrorPrivate:
  247. return "private"
  248. default:
  249. return fmt.Sprintf("invalid(%d)", s)
  250. }
  251. }
  252. func NewInterface(ctx context.Context, c *InterfaceConfig) (*Interface, error) {
  253. if c.Outside == nil {
  254. return nil, errors.New("no outside connection")
  255. }
  256. if c.Inside == nil {
  257. return nil, errors.New("no inside interface (tun)")
  258. }
  259. if c.pki == nil {
  260. return nil, errors.New("no certificate state")
  261. }
  262. if c.Firewall == nil {
  263. return nil, errors.New("no firewall rules")
  264. }
  265. if c.connectionManager == nil {
  266. return nil, errors.New("no connection manager")
  267. }
  268. cs := c.pki.getCertState()
  269. bc := c.BatchConfig
  270. if bc.InboundBatchSize <= 0 {
  271. bc.InboundBatchSize = inboundBatchSizeDefault
  272. }
  273. if bc.OutboundBatchSize <= 0 {
  274. bc.OutboundBatchSize = outboundBatchSizeDefault
  275. }
  276. if bc.FlushInterval <= 0 {
  277. bc.FlushInterval = batchFlushIntervalDefault
  278. }
  279. if bc.MaxOutstandingPerChan <= 0 {
  280. bc.MaxOutstandingPerChan = maxOutstandingBatchesDefault
  281. }
  282. ifce := &Interface{
  283. pki: c.pki,
  284. hostMap: c.HostMap,
  285. outside: c.Outside,
  286. inside: c.Inside,
  287. firewall: c.Firewall,
  288. serveDns: c.ServeDns,
  289. handshakeManager: c.HandshakeManager,
  290. createTime: time.Now(),
  291. lightHouse: c.lightHouse,
  292. dropLocalBroadcast: c.DropLocalBroadcast,
  293. dropMulticast: c.DropMulticast,
  294. routines: c.routines,
  295. version: c.version,
  296. writers: make([]udp.Conn, c.routines),
  297. readers: make([]io.ReadWriteCloser, c.routines),
  298. myVpnNetworks: cs.myVpnNetworks,
  299. myVpnNetworksTable: cs.myVpnNetworksTable,
  300. myVpnAddrs: cs.myVpnAddrs,
  301. myVpnAddrsTable: cs.myVpnAddrsTable,
  302. myBroadcastAddrsTable: cs.myVpnBroadcastAddrsTable,
  303. relayManager: c.relayManager,
  304. connectionManager: c.connectionManager,
  305. conntrackCacheTimeout: c.ConntrackCacheTimeout,
  306. metricHandshakes: metrics.GetOrRegisterHistogram("handshakes", nil, metrics.NewExpDecaySample(1028, 0.015)),
  307. messageMetrics: c.MessageMetrics,
  308. cachedPacketMetrics: &cachedPacketMetrics{
  309. sent: metrics.GetOrRegisterCounter("hostinfo.cached_packets.sent", nil),
  310. dropped: metrics.GetOrRegisterCounter("hostinfo.cached_packets.dropped", nil),
  311. },
  312. inbound: make([]chan *packetBatch, c.routines),
  313. outbound: make([]chan *outboundBatch, c.routines),
  314. l: c.l,
  315. inboundBatchSize: bc.InboundBatchSize,
  316. outboundBatchSize: bc.OutboundBatchSize,
  317. batchFlushInterval: bc.FlushInterval,
  318. maxOutstandingPerChan: bc.MaxOutstandingPerChan,
  319. sendBatchSize: bc.OutboundBatchSize,
  320. }
  321. for i := 0; i < c.routines; i++ {
  322. ifce.inbound[i] = make(chan *packetBatch, ifce.maxOutstandingPerChan)
  323. ifce.outbound[i] = make(chan *outboundBatch, ifce.maxOutstandingPerChan)
  324. }
  325. ifce.inPool = sync.Pool{New: func() any {
  326. return packet.New()
  327. }}
  328. ifce.outPool = sync.Pool{New: func() any {
  329. t := make([]byte, mtu)
  330. return &t
  331. }}
  332. ifce.packetBatchPool = sync.Pool{New: func() any {
  333. return newPacketBatch(ifce.inboundBatchSize)
  334. }}
  335. ifce.outboundBatchPool = sync.Pool{New: func() any {
  336. return newOutboundBatch(ifce.outboundBatchSize)
  337. }}
  338. ifce.sendPool = sync.Pool{New: func() any {
  339. buf := make([]byte, mtu)
  340. return &buf
  341. }}
  342. ifce.tryPromoteEvery.Store(c.tryPromoteEvery)
  343. ifce.reQueryEvery.Store(c.reQueryEvery)
  344. ifce.reQueryWait.Store(int64(c.reQueryWait))
  345. ifce.connectionManager.intf = ifce
  346. return ifce, nil
  347. }
  348. // activate creates the interface on the host. After the interface is created, any
  349. // other services that want to bind listeners to its IP may do so successfully. However,
  350. // the interface isn't going to process anything until run() is called.
  351. func (f *Interface) activate() error {
  352. // actually turn on tun dev
  353. addr, err := f.outside.LocalAddr()
  354. if err != nil {
  355. f.l.WithError(err).Error("Failed to get udp listen address")
  356. }
  357. f.l.WithField("interface", f.inside.Name()).WithField("networks", f.myVpnNetworks).
  358. WithField("build", f.version).WithField("udpAddr", addr).
  359. WithField("boringcrypto", boringEnabled()).
  360. Info("Nebula interface is active")
  361. metrics.GetOrRegisterGauge("routines", nil).Update(int64(f.routines))
  362. // Prepare n tun queues
  363. var reader io.ReadWriteCloser = f.inside
  364. for i := 0; i < f.routines; i++ {
  365. if i > 0 {
  366. reader, err = f.inside.NewMultiQueueReader()
  367. if err != nil {
  368. return err
  369. }
  370. }
  371. f.readers[i] = reader
  372. }
  373. if err = f.inside.Activate(); err != nil {
  374. f.inside.Close()
  375. return err
  376. }
  377. return nil
  378. }
  379. func (f *Interface) run(c context.Context) (func(), error) {
  380. for i := 0; i < f.routines; i++ {
  381. // Launch n queues to read packets from udp
  382. f.wg.Add(1)
  383. go f.listenOut(i)
  384. // Launch n queues to read packets from tun dev
  385. f.wg.Add(1)
  386. go f.listenIn(f.readers[i], i)
  387. // Launch n queues to read packets from tun dev
  388. f.wg.Add(1)
  389. go f.workerIn(i, c)
  390. // Launch n queues to read packets from tun dev
  391. f.wg.Add(1)
  392. go f.workerOut(i, c)
  393. }
  394. return f.wg.Wait, nil
  395. }
  396. func (f *Interface) listenOut(i int) {
  397. runtime.LockOSThread()
  398. var li udp.Conn
  399. if i > 0 {
  400. li = f.writers[i]
  401. } else {
  402. li = f.outside
  403. }
  404. batch := f.getPacketBatch()
  405. lastFlush := time.Now()
  406. flush := func(force bool) {
  407. if len(batch.packets) == 0 {
  408. if force {
  409. f.releasePacketBatch(batch)
  410. }
  411. return
  412. }
  413. f.inbound[i] <- batch
  414. batch = f.getPacketBatch()
  415. lastFlush = time.Now()
  416. }
  417. err := li.ListenOut(func(fromUdpAddr netip.AddrPort, payload []byte) {
  418. p := f.inPool.Get().(*packet.Packet)
  419. p.Payload = p.Payload[:mtu]
  420. copy(p.Payload, payload)
  421. p.Payload = p.Payload[:len(payload)]
  422. p.Addr = fromUdpAddr
  423. batch.add(p)
  424. if len(batch.packets) >= f.inboundBatchSize || time.Since(lastFlush) >= f.batchFlushInterval {
  425. flush(false)
  426. }
  427. })
  428. if len(batch.packets) > 0 {
  429. f.inbound[i] <- batch
  430. } else {
  431. f.releasePacketBatch(batch)
  432. }
  433. if err != nil && !f.closed.Load() {
  434. f.l.WithError(err).Error("Error while reading packet inbound packet, closing")
  435. //TODO: Trigger Control to close
  436. }
  437. f.l.Debugf("underlay reader %v is done", i)
  438. f.wg.Done()
  439. }
  440. func (f *Interface) listenIn(reader io.ReadWriteCloser, i int) {
  441. runtime.LockOSThread()
  442. batch := f.getOutboundBatch()
  443. lastFlush := time.Now()
  444. flush := func(force bool) {
  445. if len(batch.payloads) == 0 {
  446. if force {
  447. f.releaseOutboundBatch(batch)
  448. }
  449. return
  450. }
  451. f.outbound[i] <- batch
  452. batch = f.getOutboundBatch()
  453. lastFlush = time.Now()
  454. }
  455. for {
  456. p := f.outPool.Get().(*[]byte)
  457. *p = (*p)[:mtu]
  458. n, err := reader.Read(*p)
  459. if err != nil {
  460. if !f.closed.Load() {
  461. f.l.WithError(err).Error("Error while reading outbound packet, closing")
  462. //TODO: Trigger Control to close
  463. }
  464. break
  465. }
  466. *p = (*p)[:n]
  467. batch.add(p)
  468. if len(batch.payloads) >= f.outboundBatchSize || time.Since(lastFlush) >= f.batchFlushInterval {
  469. flush(false)
  470. }
  471. }
  472. if len(batch.payloads) > 0 {
  473. f.outbound[i] <- batch
  474. } else {
  475. f.releaseOutboundBatch(batch)
  476. }
  477. f.l.Debugf("overlay reader %v is done", i)
  478. f.wg.Done()
  479. }
  480. func (f *Interface) workerIn(i int, ctx context.Context) {
  481. lhh := f.lightHouse.NewRequestHandler()
  482. conntrackCache := firewall.NewConntrackCacheTicker(f.conntrackCacheTimeout)
  483. fwPacket2 := &firewall.Packet{}
  484. nb2 := make([]byte, 12, 12)
  485. result2 := make([]byte, mtu)
  486. h := &header.H{}
  487. for {
  488. select {
  489. case batch := <-f.inbound[i]:
  490. for _, p := range batch.packets {
  491. f.readOutsidePackets(p.Addr, nil, result2[:0], p.Payload, h, fwPacket2, lhh, nb2, i, conntrackCache.Get(f.l))
  492. p.Payload = p.Payload[:mtu]
  493. f.inPool.Put(p)
  494. }
  495. f.releasePacketBatch(batch)
  496. case <-ctx.Done():
  497. f.wg.Done()
  498. return
  499. }
  500. }
  501. }
  502. func (f *Interface) workerOut(i int, ctx context.Context) {
  503. conntrackCache := firewall.NewConntrackCacheTicker(f.conntrackCacheTimeout)
  504. fwPacket1 := &firewall.Packet{}
  505. nb1 := make([]byte, 12, 12)
  506. pending := make([]outboundSend, 0, f.sendBatchSize)
  507. for {
  508. select {
  509. case batch := <-f.outbound[i]:
  510. for _, data := range batch.payloads {
  511. sendBuf := f.getSendBuffer()
  512. buf := (*sendBuf)[:0]
  513. queue := func(addr netip.AddrPort, length int) {
  514. pending = append(pending, outboundSend{
  515. buf: sendBuf,
  516. length: length,
  517. addr: addr,
  518. })
  519. if len(pending) >= f.sendBatchSize {
  520. f.flushSendQueue(i, &pending)
  521. }
  522. }
  523. sent := f.consumeInsidePacket(*data, fwPacket1, nb1, buf, queue, i, conntrackCache.Get(f.l))
  524. if !sent {
  525. f.releaseSendBuffer(sendBuf)
  526. }
  527. *data = (*data)[:mtu]
  528. f.outPool.Put(data)
  529. }
  530. f.releaseOutboundBatch(batch)
  531. if len(pending) > 0 {
  532. f.flushSendQueue(i, &pending)
  533. }
  534. case <-ctx.Done():
  535. if len(pending) > 0 {
  536. f.flushSendQueue(i, &pending)
  537. }
  538. f.wg.Done()
  539. return
  540. }
  541. }
  542. }
  543. func (f *Interface) RegisterConfigChangeCallbacks(c *config.C) {
  544. c.RegisterReloadCallback(f.reloadFirewall)
  545. c.RegisterReloadCallback(f.reloadSendRecvError)
  546. c.RegisterReloadCallback(f.reloadDisconnectInvalid)
  547. c.RegisterReloadCallback(f.reloadMisc)
  548. for _, udpConn := range f.writers {
  549. c.RegisterReloadCallback(udpConn.ReloadConfig)
  550. }
  551. }
  552. func (f *Interface) reloadDisconnectInvalid(c *config.C) {
  553. initial := c.InitialLoad()
  554. if initial || c.HasChanged("pki.disconnect_invalid") {
  555. f.disconnectInvalid.Store(c.GetBool("pki.disconnect_invalid", true))
  556. if !initial {
  557. f.l.Infof("pki.disconnect_invalid changed to %v", f.disconnectInvalid.Load())
  558. }
  559. }
  560. }
  561. func (f *Interface) reloadFirewall(c *config.C) {
  562. //TODO: need to trigger/detect if the certificate changed too
  563. if c.HasChanged("firewall") == false {
  564. f.l.Debug("No firewall config change detected")
  565. return
  566. }
  567. fw, err := NewFirewallFromConfig(f.l, f.pki.getCertState(), c)
  568. if err != nil {
  569. f.l.WithError(err).Error("Error while creating firewall during reload")
  570. return
  571. }
  572. oldFw := f.firewall
  573. conntrack := oldFw.Conntrack
  574. conntrack.Lock()
  575. defer conntrack.Unlock()
  576. fw.rulesVersion = oldFw.rulesVersion + 1
  577. // If rulesVersion is back to zero, we have wrapped all the way around. Be
  578. // safe and just reset conntrack in this case.
  579. if fw.rulesVersion == 0 {
  580. f.l.WithField("firewallHashes", fw.GetRuleHashes()).
  581. WithField("oldFirewallHashes", oldFw.GetRuleHashes()).
  582. WithField("rulesVersion", fw.rulesVersion).
  583. Warn("firewall rulesVersion has overflowed, resetting conntrack")
  584. } else {
  585. fw.Conntrack = conntrack
  586. }
  587. f.firewall = fw
  588. oldFw.Destroy()
  589. f.l.WithField("firewallHashes", fw.GetRuleHashes()).
  590. WithField("oldFirewallHashes", oldFw.GetRuleHashes()).
  591. WithField("rulesVersion", fw.rulesVersion).
  592. Info("New firewall has been installed")
  593. }
  594. func (f *Interface) reloadSendRecvError(c *config.C) {
  595. if c.InitialLoad() || c.HasChanged("listen.send_recv_error") {
  596. stringValue := c.GetString("listen.send_recv_error", "always")
  597. switch stringValue {
  598. case "always":
  599. f.sendRecvErrorConfig = sendRecvErrorAlways
  600. case "never":
  601. f.sendRecvErrorConfig = sendRecvErrorNever
  602. case "private":
  603. f.sendRecvErrorConfig = sendRecvErrorPrivate
  604. default:
  605. if c.GetBool("listen.send_recv_error", true) {
  606. f.sendRecvErrorConfig = sendRecvErrorAlways
  607. } else {
  608. f.sendRecvErrorConfig = sendRecvErrorNever
  609. }
  610. }
  611. f.l.WithField("sendRecvError", f.sendRecvErrorConfig.String()).
  612. Info("Loaded send_recv_error config")
  613. }
  614. }
  615. func (f *Interface) reloadMisc(c *config.C) {
  616. if c.HasChanged("counters.try_promote") {
  617. n := c.GetUint32("counters.try_promote", defaultPromoteEvery)
  618. f.tryPromoteEvery.Store(n)
  619. f.l.Info("counters.try_promote has changed")
  620. }
  621. if c.HasChanged("counters.requery_every_packets") {
  622. n := c.GetUint32("counters.requery_every_packets", defaultReQueryEvery)
  623. f.reQueryEvery.Store(n)
  624. f.l.Info("counters.requery_every_packets has changed")
  625. }
  626. if c.HasChanged("timers.requery_wait_duration") {
  627. n := c.GetDuration("timers.requery_wait_duration", defaultReQueryWait)
  628. f.reQueryWait.Store(int64(n))
  629. f.l.Info("timers.requery_wait_duration has changed")
  630. }
  631. }
  632. func (f *Interface) emitStats(ctx context.Context, i time.Duration) {
  633. ticker := time.NewTicker(i)
  634. defer ticker.Stop()
  635. udpStats := udp.NewUDPStatsEmitter(f.writers)
  636. certExpirationGauge := metrics.GetOrRegisterGauge("certificate.ttl_seconds", nil)
  637. certInitiatingVersion := metrics.GetOrRegisterGauge("certificate.initiating_version", nil)
  638. certMaxVersion := metrics.GetOrRegisterGauge("certificate.max_version", nil)
  639. for {
  640. select {
  641. case <-ctx.Done():
  642. return
  643. case <-ticker.C:
  644. f.firewall.EmitStats()
  645. f.handshakeManager.EmitStats()
  646. udpStats()
  647. certState := f.pki.getCertState()
  648. defaultCrt := certState.GetDefaultCertificate()
  649. certExpirationGauge.Update(int64(defaultCrt.NotAfter().Sub(time.Now()) / time.Second))
  650. certInitiatingVersion.Update(int64(defaultCrt.Version()))
  651. // Report the max certificate version we are capable of using
  652. if certState.v2Cert != nil {
  653. certMaxVersion.Update(int64(certState.v2Cert.Version()))
  654. } else {
  655. certMaxVersion.Update(int64(certState.v1Cert.Version()))
  656. }
  657. }
  658. }
  659. }
  660. func (f *Interface) GetHostInfo(vpnIp netip.Addr) *HostInfo {
  661. return f.hostMap.QueryVpnAddr(vpnIp)
  662. }
  663. func (f *Interface) GetCertState() *CertState {
  664. return f.pki.getCertState()
  665. }
  666. func (f *Interface) Close() error {
  667. f.closed.Store(true)
  668. // Release the udp readers
  669. for _, u := range f.writers {
  670. err := u.Close()
  671. if err != nil {
  672. f.l.WithError(err).Error("Error while closing udp socket")
  673. }
  674. }
  675. // Release the tun readers
  676. for _, u := range f.readers {
  677. err := u.Close()
  678. if err != nil {
  679. f.l.WithError(err).Error("Error while closing tun device")
  680. }
  681. }
  682. return nil
  683. }