tun_linux.go 26 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117
  1. //go:build !android && !e2e_testing
  2. // +build !android,!e2e_testing
  3. package overlay
  4. import (
  5. "fmt"
  6. "io"
  7. "net"
  8. "net/netip"
  9. "os"
  10. "strings"
  11. "sync"
  12. "sync/atomic"
  13. "time"
  14. "unsafe"
  15. "github.com/gaissmai/bart"
  16. "github.com/sirupsen/logrus"
  17. "github.com/slackhq/nebula/config"
  18. "github.com/slackhq/nebula/routing"
  19. "github.com/slackhq/nebula/util"
  20. "github.com/vishvananda/netlink"
  21. "golang.org/x/sys/unix"
  22. )
  23. const (
  24. // virtioNetHdrLen is the length of virtio_net_hdr (without mergeable buffers)
  25. virtioNetHdrLen = 10
  26. )
  27. type tun struct {
  28. io.ReadWriteCloser
  29. fd int
  30. Device string
  31. vpnNetworks []netip.Prefix
  32. MaxMTU int
  33. DefaultMTU int
  34. TXQueueLen int
  35. deviceIndex int
  36. ioctlFd uintptr
  37. nonBlocking bool // true if fd is in non-blocking mode
  38. vnetHdr bool // true if IFF_VNET_HDR is enabled on the TUN device
  39. // readBuf is used when vnetHdr is enabled to read the full packet+header
  40. // before stripping the header. This is needed because caller-provided
  41. // buffers are sized for MTU but kernel writes MTU+10 with virtio header.
  42. readBuf []byte
  43. Routes atomic.Pointer[[]Route]
  44. routeTree atomic.Pointer[bart.Table[routing.Gateways]]
  45. routeChan chan struct{}
  46. useSystemRoutes bool
  47. useSystemRoutesBufferSize int
  48. // These are routes learned from `tun.use_system_route_table`
  49. // stored here to make it easier to restore them after a reload
  50. routesFromSystem map[netip.Prefix]routing.Gateways
  51. routesFromSystemLock sync.Mutex
  52. l *logrus.Logger
  53. }
  54. func (t *tun) Networks() []netip.Prefix {
  55. return t.vpnNetworks
  56. }
  57. // tunVnetHdrSupported checks if the kernel supports IFF_VNET_HDR on TUN devices
  58. func tunVnetHdrSupported() bool {
  59. fd, err := unix.Open("/dev/net/tun", unix.O_RDONLY, 0)
  60. if err != nil {
  61. return false
  62. }
  63. defer unix.Close(fd)
  64. var features uint32
  65. err = ioctl(uintptr(fd), uintptr(unix.TUNGETFEATURES), uintptr(unsafe.Pointer(&features)))
  66. if err != nil {
  67. return false
  68. }
  69. return features&unix.IFF_VNET_HDR != 0
  70. }
  71. type ifReq struct {
  72. Name [16]byte
  73. Flags uint16
  74. pad [8]byte
  75. }
  76. type ifreqMTU struct {
  77. Name [16]byte
  78. MTU int32
  79. pad [8]byte
  80. }
  81. type ifreqQLEN struct {
  82. Name [16]byte
  83. Value int32
  84. pad [8]byte
  85. }
  86. func newTunFromFd(c *config.C, l *logrus.Logger, deviceFd int, vpnNetworks []netip.Prefix) (*tun, error) {
  87. file := os.NewFile(uintptr(deviceFd), "/dev/net/tun")
  88. t, err := newTunGeneric(c, l, file, vpnNetworks)
  89. if err != nil {
  90. return nil, err
  91. }
  92. t.Device = "tun0"
  93. return t, nil
  94. }
  95. func newTun(c *config.C, l *logrus.Logger, vpnNetworks []netip.Prefix, multiqueue bool) (*tun, error) {
  96. fd, err := unix.Open("/dev/net/tun", os.O_RDWR, 0)
  97. if err != nil {
  98. // If /dev/net/tun doesn't exist, try to create it (will happen in docker)
  99. if os.IsNotExist(err) {
  100. err = os.MkdirAll("/dev/net", 0755)
  101. if err != nil {
  102. return nil, fmt.Errorf("/dev/net/tun doesn't exist, failed to mkdir -p /dev/net: %w", err)
  103. }
  104. err = unix.Mknod("/dev/net/tun", unix.S_IFCHR|0600, int(unix.Mkdev(10, 200)))
  105. if err != nil {
  106. return nil, fmt.Errorf("failed to create /dev/net/tun: %w", err)
  107. }
  108. fd, err = unix.Open("/dev/net/tun", os.O_RDWR, 0)
  109. if err != nil {
  110. return nil, fmt.Errorf("created /dev/net/tun, but still failed: %w", err)
  111. }
  112. } else {
  113. return nil, err
  114. }
  115. }
  116. // Check if VNET_HDR is supported before trying to use it
  117. useVnetHdr := tunVnetHdrSupported()
  118. var req ifReq
  119. req.Flags = uint16(unix.IFF_TUN | unix.IFF_NO_PI)
  120. if multiqueue {
  121. req.Flags |= unix.IFF_MULTI_QUEUE
  122. }
  123. if useVnetHdr {
  124. req.Flags |= unix.IFF_VNET_HDR
  125. }
  126. nameStr := c.GetString("tun.dev", "")
  127. copy(req.Name[:], nameStr)
  128. if err = ioctl(uintptr(fd), uintptr(unix.TUNSETIFF), uintptr(unsafe.Pointer(&req))); err != nil {
  129. return nil, &NameError{
  130. Name: nameStr,
  131. Underlying: err,
  132. }
  133. }
  134. name := strings.Trim(string(req.Name[:]), "\x00")
  135. // Track if VNET_HDR is in use
  136. // Note: We don't call TUNSETOFFLOAD - just handle the headers manually
  137. vnetHdrEnabled := useVnetHdr
  138. if vnetHdrEnabled {
  139. l.Info("TUN VNET_HDR enabled")
  140. }
  141. file := os.NewFile(uintptr(fd), "/dev/net/tun")
  142. t, err := newTunGeneric(c, l, file, vpnNetworks)
  143. if err != nil {
  144. return nil, err
  145. }
  146. t.Device = name
  147. t.vnetHdr = vnetHdrEnabled
  148. // Allocate read buffer for virtio header handling
  149. // Buffer needs to be large enough for virtio header + max packet
  150. if t.vnetHdr {
  151. t.readBuf = make([]byte, t.MaxMTU+virtioNetHdrLen)
  152. }
  153. return t, nil
  154. }
  155. func newTunGeneric(c *config.C, l *logrus.Logger, file *os.File, vpnNetworks []netip.Prefix) (*tun, error) {
  156. t := &tun{
  157. ReadWriteCloser: file,
  158. fd: int(file.Fd()),
  159. vpnNetworks: vpnNetworks,
  160. TXQueueLen: c.GetInt("tun.tx_queue", 500),
  161. useSystemRoutes: c.GetBool("tun.use_system_route_table", false),
  162. useSystemRoutesBufferSize: c.GetInt("tun.use_system_route_table_buffer_size", 0),
  163. routesFromSystem: map[netip.Prefix]routing.Gateways{},
  164. l: l,
  165. }
  166. err := t.reload(c, true)
  167. if err != nil {
  168. return nil, err
  169. }
  170. c.RegisterReloadCallback(func(c *config.C) {
  171. err := t.reload(c, false)
  172. if err != nil {
  173. util.LogWithContextIfNeeded("failed to reload tun device", err, t.l)
  174. }
  175. })
  176. return t, nil
  177. }
  178. func (t *tun) reload(c *config.C, initial bool) error {
  179. routeChange, routes, err := getAllRoutesFromConfig(c, t.vpnNetworks, initial)
  180. if err != nil {
  181. return err
  182. }
  183. if !initial && !routeChange && !c.HasChanged("tun.mtu") {
  184. return nil
  185. }
  186. routeTree, err := makeRouteTree(t.l, routes, true)
  187. if err != nil {
  188. return err
  189. }
  190. // Bring along any routes learned from the system route table on reload
  191. t.routesFromSystemLock.Lock()
  192. for dst, gw := range t.routesFromSystem {
  193. routeTree.Insert(dst, gw)
  194. }
  195. t.routesFromSystemLock.Unlock()
  196. oldDefaultMTU := t.DefaultMTU
  197. oldMaxMTU := t.MaxMTU
  198. newDefaultMTU := c.GetInt("tun.mtu", DefaultMTU)
  199. newMaxMTU := newDefaultMTU
  200. for i, r := range routes {
  201. if r.MTU == 0 {
  202. routes[i].MTU = newDefaultMTU
  203. }
  204. if r.MTU > t.MaxMTU {
  205. newMaxMTU = r.MTU
  206. }
  207. }
  208. t.MaxMTU = newMaxMTU
  209. t.DefaultMTU = newDefaultMTU
  210. // Teach nebula how to handle the routes before establishing them in the system table
  211. oldRoutes := t.Routes.Swap(&routes)
  212. t.routeTree.Store(routeTree)
  213. if !initial {
  214. if oldMaxMTU != newMaxMTU {
  215. t.setMTU()
  216. t.l.Infof("Set max MTU to %v was %v", t.MaxMTU, oldMaxMTU)
  217. }
  218. if oldDefaultMTU != newDefaultMTU {
  219. for i := range t.vpnNetworks {
  220. err := t.setDefaultRoute(t.vpnNetworks[i])
  221. if err != nil {
  222. t.l.Warn(err)
  223. } else {
  224. t.l.Infof("Set default MTU to %v was %v", t.DefaultMTU, oldDefaultMTU)
  225. }
  226. }
  227. }
  228. // Remove first, if the system removes a wanted route hopefully it will be re-added next
  229. t.removeRoutes(findRemovedRoutes(routes, *oldRoutes))
  230. // Ensure any routes we actually want are installed
  231. err = t.addRoutes(true)
  232. if err != nil {
  233. // This should never be called since addRoutes should log its own errors in a reload condition
  234. util.LogWithContextIfNeeded("Failed to refresh routes", err, t.l)
  235. }
  236. }
  237. return nil
  238. }
  239. func (t *tun) SupportsMultiqueue() bool {
  240. return true
  241. }
  242. func (t *tun) NewMultiQueueReader() (io.ReadWriteCloser, error) {
  243. fd, err := unix.Open("/dev/net/tun", os.O_RDWR|unix.O_NONBLOCK, 0)
  244. if err != nil {
  245. return nil, err
  246. }
  247. var req ifReq
  248. req.Flags = uint16(unix.IFF_TUN | unix.IFF_NO_PI | unix.IFF_MULTI_QUEUE)
  249. if t.vnetHdr {
  250. req.Flags |= unix.IFF_VNET_HDR
  251. }
  252. copy(req.Name[:], t.Device)
  253. if err = ioctl(uintptr(fd), uintptr(unix.TUNSETIFF), uintptr(unsafe.Pointer(&req))); err != nil {
  254. return nil, err
  255. }
  256. reader := &tunBatchReader{fd: fd, device: t.Device, vnetHdr: t.vnetHdr}
  257. if t.vnetHdr {
  258. reader.readBuf = make([]byte, t.MaxMTU+virtioNetHdrLen)
  259. }
  260. return reader, nil
  261. }
  262. // tunBatchReader implements BatchReader for efficient batch packet reading
  263. type tunBatchReader struct {
  264. fd int
  265. device string
  266. vnetHdr bool
  267. readBuf []byte // internal buffer for virtio header handling
  268. }
  269. func (r *tunBatchReader) Read(b []byte) (int, error) {
  270. // Choose buffer: use internal buffer for vnetHdr, caller's buffer otherwise
  271. readBuf := b
  272. if r.vnetHdr {
  273. readBuf = r.readBuf
  274. }
  275. // Use poll to wait for data, then read
  276. for {
  277. n, err := unix.Read(r.fd, readBuf)
  278. if err == nil {
  279. if r.vnetHdr && n > virtioNetHdrLen {
  280. packetLen := n - virtioNetHdrLen
  281. copy(b, readBuf[virtioNetHdrLen:n])
  282. return packetLen, nil
  283. }
  284. if r.vnetHdr {
  285. return 0, nil // No packet data
  286. }
  287. return n, nil
  288. }
  289. if err == unix.EAGAIN || err == unix.EWOULDBLOCK {
  290. // Wait for data
  291. pfds := []unix.PollFd{{Fd: int32(r.fd), Events: unix.POLLIN}}
  292. _, err = unix.Poll(pfds, -1)
  293. if err != nil {
  294. if err == unix.EINTR {
  295. continue
  296. }
  297. return 0, err
  298. }
  299. continue
  300. }
  301. return n, err
  302. }
  303. }
  304. func (r *tunBatchReader) Write(b []byte) (int, error) {
  305. if !r.vnetHdr {
  306. return unix.Write(r.fd, b)
  307. }
  308. // Use writev to prepend virtio header without copying the packet data
  309. // Header is all zeros = no GSO, no checksum offload
  310. var hdr [virtioNetHdrLen]byte
  311. bufs := [][]byte{hdr[:], b}
  312. n, err := unix.Writev(r.fd, bufs)
  313. if err != nil {
  314. return 0, err
  315. }
  316. // Return only the packet bytes written (exclude header)
  317. if n > virtioNetHdrLen {
  318. return n - virtioNetHdrLen, nil
  319. }
  320. return 0, nil
  321. }
  322. func (r *tunBatchReader) Close() error {
  323. return unix.Close(r.fd)
  324. }
  325. // ReadBatch reads up to len(packets) packets from the TUN device.
  326. // It drains all available packets without blocking, using poll() only
  327. // when no packets have been read yet.
  328. func (r *tunBatchReader) ReadBatch(packets [][]byte, sizes []int) (int, error) {
  329. count := 0
  330. maxPackets := len(packets)
  331. if len(sizes) < maxPackets {
  332. maxPackets = len(sizes)
  333. }
  334. // Choose read buffer based on vnetHdr
  335. readBuf := packets[0] // Will be updated in loop for non-vnetHdr
  336. if r.vnetHdr {
  337. readBuf = r.readBuf
  338. }
  339. for count < maxPackets {
  340. if !r.vnetHdr {
  341. readBuf = packets[count]
  342. }
  343. n, err := unix.Read(r.fd, readBuf)
  344. if err == nil && n > 0 {
  345. if r.vnetHdr {
  346. if n > virtioNetHdrLen {
  347. packetLen := n - virtioNetHdrLen
  348. copy(packets[count], readBuf[virtioNetHdrLen:n])
  349. sizes[count] = packetLen
  350. } else {
  351. // Malformed packet (no data after header), skip
  352. continue
  353. }
  354. } else {
  355. sizes[count] = n
  356. }
  357. count++
  358. continue
  359. }
  360. if err == unix.EAGAIN || err == unix.EWOULDBLOCK {
  361. // No more packets available
  362. if count > 0 {
  363. // We have some packets, return them
  364. return count, nil
  365. }
  366. // No packets yet, wait for at least one
  367. pfds := []unix.PollFd{{Fd: int32(r.fd), Events: unix.POLLIN}}
  368. _, err = unix.Poll(pfds, -1)
  369. if err != nil {
  370. if err == unix.EINTR {
  371. continue
  372. }
  373. return 0, err
  374. }
  375. continue
  376. }
  377. if err != nil {
  378. if count > 0 {
  379. // Return what we have
  380. return count, nil
  381. }
  382. return 0, err
  383. }
  384. if n == 0 {
  385. if count > 0 {
  386. return count, nil
  387. }
  388. return 0, io.EOF
  389. }
  390. }
  391. return count, nil
  392. }
  393. func (t *tun) RoutesFor(ip netip.Addr) routing.Gateways {
  394. r, _ := t.routeTree.Load().Lookup(ip)
  395. return r
  396. }
  397. func (t *tun) Write(b []byte) (int, error) {
  398. if !t.vnetHdr {
  399. return t.writeSimple(b)
  400. }
  401. // Use writev to prepend virtio header without copying the packet data
  402. // Header is all zeros = no GSO, no checksum offload
  403. var hdr [virtioNetHdrLen]byte
  404. bufs := [][]byte{hdr[:], b}
  405. n, err := unix.Writev(t.fd, bufs)
  406. if err != nil {
  407. return 0, err
  408. }
  409. // Return only the packet bytes written (exclude header)
  410. if n > virtioNetHdrLen {
  411. return n - virtioNetHdrLen, nil
  412. }
  413. return 0, nil
  414. }
  415. func (t *tun) writeSimple(b []byte) (int, error) {
  416. var nn int
  417. maximum := len(b)
  418. for {
  419. n, err := unix.Write(t.fd, b[nn:maximum])
  420. if n > 0 {
  421. nn += n
  422. }
  423. if nn == len(b) {
  424. return nn, err
  425. }
  426. if err != nil {
  427. return nn, err
  428. }
  429. if n == 0 {
  430. return nn, io.ErrUnexpectedEOF
  431. }
  432. }
  433. }
  434. // EnableBatchReading sets the TUN fd to non-blocking mode to enable batch reading.
  435. // This should be called before using ReadBatch.
  436. func (t *tun) EnableBatchReading() error {
  437. if t.nonBlocking {
  438. return nil
  439. }
  440. err := unix.SetNonblock(t.fd, true)
  441. if err != nil {
  442. return err
  443. }
  444. t.nonBlocking = true
  445. return nil
  446. }
  447. // Read overrides the default Read to handle non-blocking mode and virtio headers
  448. func (t *tun) Read(b []byte) (int, error) {
  449. if !t.vnetHdr {
  450. return t.readSimple(b)
  451. }
  452. // With VNET_HDR, read into internal buffer (which has space for header)
  453. // then copy packet data to caller's buffer
  454. if !t.nonBlocking {
  455. n, err := t.ReadWriteCloser.Read(t.readBuf)
  456. if err != nil {
  457. return 0, err
  458. }
  459. if n <= virtioNetHdrLen {
  460. return 0, nil // No packet data
  461. }
  462. packetLen := n - virtioNetHdrLen
  463. copy(b, t.readBuf[virtioNetHdrLen:n])
  464. return packetLen, nil
  465. }
  466. // Non-blocking read with poll
  467. for {
  468. n, err := unix.Read(t.fd, t.readBuf)
  469. if err == nil {
  470. if n <= virtioNetHdrLen {
  471. return 0, nil // No packet data
  472. }
  473. packetLen := n - virtioNetHdrLen
  474. copy(b, t.readBuf[virtioNetHdrLen:n])
  475. return packetLen, nil
  476. }
  477. if err == unix.EAGAIN || err == unix.EWOULDBLOCK {
  478. pfds := []unix.PollFd{{Fd: int32(t.fd), Events: unix.POLLIN}}
  479. _, err = unix.Poll(pfds, -1)
  480. if err != nil {
  481. if err == unix.EINTR {
  482. continue
  483. }
  484. return 0, err
  485. }
  486. continue
  487. }
  488. return n, err
  489. }
  490. }
  491. func (t *tun) readSimple(b []byte) (int, error) {
  492. if !t.nonBlocking {
  493. return t.ReadWriteCloser.Read(b)
  494. }
  495. for {
  496. n, err := unix.Read(t.fd, b)
  497. if err == nil {
  498. return n, nil
  499. }
  500. if err == unix.EAGAIN || err == unix.EWOULDBLOCK {
  501. pfds := []unix.PollFd{{Fd: int32(t.fd), Events: unix.POLLIN}}
  502. _, err = unix.Poll(pfds, -1)
  503. if err != nil {
  504. if err == unix.EINTR {
  505. continue
  506. }
  507. return 0, err
  508. }
  509. continue
  510. }
  511. return n, err
  512. }
  513. }
  514. // ReadBatch reads up to len(packets) packets from the TUN device.
  515. // EnableBatchReading must be called first.
  516. func (t *tun) ReadBatch(packets [][]byte, sizes []int) (int, error) {
  517. if !t.nonBlocking {
  518. // Fallback to single read if non-blocking not enabled
  519. n, err := t.Read(packets[0])
  520. if err != nil {
  521. return 0, err
  522. }
  523. sizes[0] = n
  524. return 1, nil
  525. }
  526. count := 0
  527. maxPackets := len(packets)
  528. if len(sizes) < maxPackets {
  529. maxPackets = len(sizes)
  530. }
  531. // Choose read buffer based on vnetHdr
  532. // With vnetHdr, we need to read into internal buffer (has space for header)
  533. // then copy packet data to caller's buffer
  534. readBuf := packets[0] // Will be updated in the loop
  535. if t.vnetHdr {
  536. readBuf = t.readBuf
  537. }
  538. for count < maxPackets {
  539. if !t.vnetHdr {
  540. readBuf = packets[count]
  541. }
  542. n, err := unix.Read(t.fd, readBuf)
  543. if err == nil && n > 0 {
  544. if t.vnetHdr {
  545. if n > virtioNetHdrLen {
  546. packetLen := n - virtioNetHdrLen
  547. copy(packets[count], readBuf[virtioNetHdrLen:n])
  548. sizes[count] = packetLen
  549. } else {
  550. // Malformed packet (no data after header), skip
  551. continue
  552. }
  553. } else {
  554. sizes[count] = n
  555. }
  556. count++
  557. continue
  558. }
  559. if err == unix.EAGAIN || err == unix.EWOULDBLOCK {
  560. // No more packets available
  561. if count > 0 {
  562. return count, nil
  563. }
  564. // No packets yet, wait for at least one
  565. pfds := []unix.PollFd{{Fd: int32(t.fd), Events: unix.POLLIN}}
  566. _, err = unix.Poll(pfds, -1)
  567. if err != nil {
  568. if err == unix.EINTR {
  569. continue
  570. }
  571. return 0, err
  572. }
  573. continue
  574. }
  575. if err != nil {
  576. if count > 0 {
  577. return count, nil
  578. }
  579. return 0, err
  580. }
  581. if n == 0 {
  582. if count > 0 {
  583. return count, nil
  584. }
  585. return 0, io.EOF
  586. }
  587. }
  588. return count, nil
  589. }
  590. func (t *tun) deviceBytes() (o [16]byte) {
  591. for i, c := range t.Device {
  592. o[i] = byte(c)
  593. }
  594. return
  595. }
  596. func hasNetlinkAddr(al []*netlink.Addr, x netlink.Addr) bool {
  597. for i := range al {
  598. if al[i].Equal(x) {
  599. return true
  600. }
  601. }
  602. return false
  603. }
  604. // addIPs uses netlink to add all addresses that don't exist, then it removes ones that should not be there
  605. func (t *tun) addIPs(link netlink.Link) error {
  606. newAddrs := make([]*netlink.Addr, len(t.vpnNetworks))
  607. for i := range t.vpnNetworks {
  608. newAddrs[i] = &netlink.Addr{
  609. IPNet: &net.IPNet{
  610. IP: t.vpnNetworks[i].Addr().AsSlice(),
  611. Mask: net.CIDRMask(t.vpnNetworks[i].Bits(), t.vpnNetworks[i].Addr().BitLen()),
  612. },
  613. Label: t.vpnNetworks[i].Addr().Zone(),
  614. }
  615. }
  616. //add all new addresses
  617. for i := range newAddrs {
  618. //AddrReplace still adds new IPs, but if their properties change it will change them as well
  619. if err := netlink.AddrReplace(link, newAddrs[i]); err != nil {
  620. return err
  621. }
  622. }
  623. //iterate over remainder, remove whoever shouldn't be there
  624. al, err := netlink.AddrList(link, netlink.FAMILY_ALL)
  625. if err != nil {
  626. return fmt.Errorf("failed to get tun address list: %s", err)
  627. }
  628. for i := range al {
  629. if hasNetlinkAddr(newAddrs, al[i]) {
  630. continue
  631. }
  632. err = netlink.AddrDel(link, &al[i])
  633. if err != nil {
  634. t.l.WithError(err).Error("failed to remove address from tun address list")
  635. } else {
  636. t.l.WithField("removed", al[i].String()).Info("removed address not listed in cert(s)")
  637. }
  638. }
  639. return nil
  640. }
  641. func (t *tun) Activate() error {
  642. devName := t.deviceBytes()
  643. if t.useSystemRoutes {
  644. t.watchRoutes()
  645. }
  646. s, err := unix.Socket(
  647. unix.AF_INET, //because everything we use t.ioctlFd for is address family independent, this is fine
  648. unix.SOCK_DGRAM,
  649. unix.IPPROTO_IP,
  650. )
  651. if err != nil {
  652. return err
  653. }
  654. t.ioctlFd = uintptr(s)
  655. // Set the device name
  656. ifrf := ifReq{Name: devName}
  657. if err = ioctl(t.ioctlFd, unix.SIOCGIFFLAGS, uintptr(unsafe.Pointer(&ifrf))); err != nil {
  658. return fmt.Errorf("failed to set tun device name: %s", err)
  659. }
  660. link, err := netlink.LinkByName(t.Device)
  661. if err != nil {
  662. return fmt.Errorf("failed to get tun device link: %s", err)
  663. }
  664. t.deviceIndex = link.Attrs().Index
  665. // Setup our default MTU
  666. t.setMTU()
  667. // Set the transmit queue length
  668. ifrq := ifreqQLEN{Name: devName, Value: int32(t.TXQueueLen)}
  669. if err = ioctl(t.ioctlFd, unix.SIOCSIFTXQLEN, uintptr(unsafe.Pointer(&ifrq))); err != nil {
  670. // If we can't set the queue length nebula will still work but it may lead to packet loss
  671. t.l.WithError(err).Error("Failed to set tun tx queue length")
  672. }
  673. const modeNone = 1
  674. if err = netlink.LinkSetIP6AddrGenMode(link, modeNone); err != nil {
  675. t.l.WithError(err).Warn("Failed to disable link local address generation")
  676. }
  677. if err = t.addIPs(link); err != nil {
  678. return err
  679. }
  680. // Bring up the interface
  681. ifrf.Flags = ifrf.Flags | unix.IFF_UP
  682. if err = ioctl(t.ioctlFd, unix.SIOCSIFFLAGS, uintptr(unsafe.Pointer(&ifrf))); err != nil {
  683. return fmt.Errorf("failed to bring the tun device up: %s", err)
  684. }
  685. //set route MTU
  686. for i := range t.vpnNetworks {
  687. if err = t.setDefaultRoute(t.vpnNetworks[i]); err != nil {
  688. return fmt.Errorf("failed to set default route MTU: %w", err)
  689. }
  690. }
  691. // Set the routes
  692. if err = t.addRoutes(false); err != nil {
  693. return err
  694. }
  695. // Run the interface
  696. ifrf.Flags = ifrf.Flags | unix.IFF_UP | unix.IFF_RUNNING
  697. if err = ioctl(t.ioctlFd, unix.SIOCSIFFLAGS, uintptr(unsafe.Pointer(&ifrf))); err != nil {
  698. return fmt.Errorf("failed to run tun device: %s", err)
  699. }
  700. return nil
  701. }
  702. func (t *tun) setMTU() {
  703. // Set the MTU on the device
  704. ifm := ifreqMTU{Name: t.deviceBytes(), MTU: int32(t.MaxMTU)}
  705. if err := ioctl(t.ioctlFd, unix.SIOCSIFMTU, uintptr(unsafe.Pointer(&ifm))); err != nil {
  706. // This is currently a non fatal condition because the route table must have the MTU set appropriately as well
  707. t.l.WithError(err).Error("Failed to set tun mtu")
  708. }
  709. }
  710. func (t *tun) setDefaultRoute(cidr netip.Prefix) error {
  711. dr := &net.IPNet{
  712. IP: cidr.Masked().Addr().AsSlice(),
  713. Mask: net.CIDRMask(cidr.Bits(), cidr.Addr().BitLen()),
  714. }
  715. nr := netlink.Route{
  716. LinkIndex: t.deviceIndex,
  717. Dst: dr,
  718. MTU: t.DefaultMTU,
  719. AdvMSS: t.advMSS(Route{}),
  720. Scope: unix.RT_SCOPE_LINK,
  721. Src: net.IP(cidr.Addr().AsSlice()),
  722. Protocol: unix.RTPROT_KERNEL,
  723. Table: unix.RT_TABLE_MAIN,
  724. Type: unix.RTN_UNICAST,
  725. }
  726. err := netlink.RouteReplace(&nr)
  727. if err != nil {
  728. t.l.WithError(err).WithField("cidr", cidr).Warn("Failed to set default route MTU, retrying")
  729. //retry twice more -- on some systems there appears to be a race condition where if we set routes too soon, netlink says `invalid argument`
  730. for i := 0; i < 2; i++ {
  731. time.Sleep(100 * time.Millisecond)
  732. err = netlink.RouteReplace(&nr)
  733. if err == nil {
  734. break
  735. } else {
  736. t.l.WithError(err).WithField("cidr", cidr).WithField("mtu", t.DefaultMTU).Warn("Failed to set default route MTU, retrying")
  737. }
  738. }
  739. if err != nil {
  740. return fmt.Errorf("failed to set mtu %v on the default route %v; %v", t.DefaultMTU, dr, err)
  741. }
  742. }
  743. return nil
  744. }
  745. func (t *tun) addRoutes(logErrors bool) error {
  746. // Path routes
  747. routes := *t.Routes.Load()
  748. for _, r := range routes {
  749. if !r.Install {
  750. continue
  751. }
  752. dr := &net.IPNet{
  753. IP: r.Cidr.Masked().Addr().AsSlice(),
  754. Mask: net.CIDRMask(r.Cidr.Bits(), r.Cidr.Addr().BitLen()),
  755. }
  756. nr := netlink.Route{
  757. LinkIndex: t.deviceIndex,
  758. Dst: dr,
  759. MTU: r.MTU,
  760. AdvMSS: t.advMSS(r),
  761. Scope: unix.RT_SCOPE_LINK,
  762. }
  763. if r.Metric > 0 {
  764. nr.Priority = r.Metric
  765. }
  766. err := netlink.RouteReplace(&nr)
  767. if err != nil {
  768. retErr := util.NewContextualError("Failed to add route", map[string]any{"route": r}, err)
  769. if logErrors {
  770. retErr.Log(t.l)
  771. } else {
  772. return retErr
  773. }
  774. } else {
  775. t.l.WithField("route", r).Info("Added route")
  776. }
  777. }
  778. return nil
  779. }
  780. func (t *tun) removeRoutes(routes []Route) {
  781. for _, r := range routes {
  782. if !r.Install {
  783. continue
  784. }
  785. dr := &net.IPNet{
  786. IP: r.Cidr.Masked().Addr().AsSlice(),
  787. Mask: net.CIDRMask(r.Cidr.Bits(), r.Cidr.Addr().BitLen()),
  788. }
  789. nr := netlink.Route{
  790. LinkIndex: t.deviceIndex,
  791. Dst: dr,
  792. MTU: r.MTU,
  793. AdvMSS: t.advMSS(r),
  794. Scope: unix.RT_SCOPE_LINK,
  795. }
  796. if r.Metric > 0 {
  797. nr.Priority = r.Metric
  798. }
  799. err := netlink.RouteDel(&nr)
  800. if err != nil {
  801. t.l.WithError(err).WithField("route", r).Error("Failed to remove route")
  802. } else {
  803. t.l.WithField("route", r).Info("Removed route")
  804. }
  805. }
  806. }
  807. func (t *tun) Name() string {
  808. return t.Device
  809. }
  810. func (t *tun) advMSS(r Route) int {
  811. mtu := r.MTU
  812. if r.MTU == 0 {
  813. mtu = t.DefaultMTU
  814. }
  815. // We only need to set advmss if the route MTU does not match the device MTU
  816. if mtu != t.MaxMTU {
  817. return mtu - 40
  818. }
  819. return 0
  820. }
  821. func (t *tun) watchRoutes() {
  822. rch := make(chan netlink.RouteUpdate)
  823. doneChan := make(chan struct{})
  824. netlinkOptions := netlink.RouteSubscribeOptions{
  825. ReceiveBufferSize: t.useSystemRoutesBufferSize,
  826. ReceiveBufferForceSize: t.useSystemRoutesBufferSize != 0,
  827. ErrorCallback: func(e error) { t.l.WithError(e).Errorf("netlink error") },
  828. }
  829. if err := netlink.RouteSubscribeWithOptions(rch, doneChan, netlinkOptions); err != nil {
  830. t.l.WithError(err).Errorf("failed to subscribe to system route changes")
  831. return
  832. }
  833. t.routeChan = doneChan
  834. go func() {
  835. for {
  836. select {
  837. case r, ok := <-rch:
  838. if ok {
  839. t.updateRoutes(r)
  840. } else {
  841. // may be should do something here as
  842. // netlink stops sending updates
  843. return
  844. }
  845. case <-doneChan:
  846. // netlink.RouteSubscriber will close the rch for us
  847. return
  848. }
  849. }
  850. }()
  851. }
  852. func (t *tun) isGatewayInVpnNetworks(gwAddr netip.Addr) bool {
  853. withinNetworks := false
  854. for i := range t.vpnNetworks {
  855. if t.vpnNetworks[i].Contains(gwAddr) {
  856. withinNetworks = true
  857. break
  858. }
  859. }
  860. return withinNetworks
  861. }
  862. func (t *tun) getGatewaysFromRoute(r *netlink.Route) routing.Gateways {
  863. var gateways routing.Gateways
  864. link, err := netlink.LinkByName(t.Device)
  865. if err != nil {
  866. t.l.WithField("deviceName", t.Device).Error("Ignoring route update: failed to get link by name")
  867. return gateways
  868. }
  869. // If this route is relevant to our interface and there is a gateway then add it
  870. if r.LinkIndex == link.Attrs().Index {
  871. gwAddr, ok := getGatewayAddr(r.Gw, r.Via)
  872. if ok {
  873. if t.isGatewayInVpnNetworks(gwAddr) {
  874. gateways = append(gateways, routing.NewGateway(gwAddr, 1))
  875. } else {
  876. // Gateway isn't in our overlay network, ignore
  877. t.l.WithField("route", r).Debug("Ignoring route update, gateway is not in our network")
  878. }
  879. } else {
  880. t.l.WithField("route", r).Debug("Ignoring route update, invalid gateway or via address")
  881. }
  882. }
  883. for _, p := range r.MultiPath {
  884. // If this route is relevant to our interface and there is a gateway then add it
  885. if p.LinkIndex == link.Attrs().Index {
  886. gwAddr, ok := getGatewayAddr(p.Gw, p.Via)
  887. if ok {
  888. if t.isGatewayInVpnNetworks(gwAddr) {
  889. gateways = append(gateways, routing.NewGateway(gwAddr, p.Hops+1))
  890. } else {
  891. // Gateway isn't in our overlay network, ignore
  892. t.l.WithField("route", r).Debug("Ignoring route update, gateway is not in our network")
  893. }
  894. } else {
  895. t.l.WithField("route", r).Debug("Ignoring route update, invalid gateway or via address")
  896. }
  897. }
  898. }
  899. routing.CalculateBucketsForGateways(gateways)
  900. return gateways
  901. }
  902. func getGatewayAddr(gw net.IP, via netlink.Destination) (netip.Addr, bool) {
  903. // Try to use the old RTA_GATEWAY first
  904. gwAddr, ok := netip.AddrFromSlice(gw)
  905. if !ok {
  906. // Fallback to the new RTA_VIA
  907. rVia, ok := via.(*netlink.Via)
  908. if ok {
  909. gwAddr, ok = netip.AddrFromSlice(rVia.Addr)
  910. }
  911. }
  912. if gwAddr.IsValid() {
  913. gwAddr = gwAddr.Unmap()
  914. return gwAddr, true
  915. }
  916. return netip.Addr{}, false
  917. }
  918. func (t *tun) updateRoutes(r netlink.RouteUpdate) {
  919. gateways := t.getGatewaysFromRoute(&r.Route)
  920. if len(gateways) == 0 {
  921. // No gateways relevant to our network, no routing changes required.
  922. t.l.WithField("route", r).Debug("Ignoring route update, no gateways")
  923. return
  924. }
  925. if r.Dst == nil {
  926. t.l.WithField("route", r).Debug("Ignoring route update, no destination address")
  927. return
  928. }
  929. dstAddr, ok := netip.AddrFromSlice(r.Dst.IP)
  930. if !ok {
  931. t.l.WithField("route", r).Debug("Ignoring route update, invalid destination address")
  932. return
  933. }
  934. ones, _ := r.Dst.Mask.Size()
  935. dst := netip.PrefixFrom(dstAddr, ones)
  936. newTree := t.routeTree.Load().Clone()
  937. t.routesFromSystemLock.Lock()
  938. if r.Type == unix.RTM_NEWROUTE {
  939. t.l.WithField("destination", dst).WithField("via", gateways).Info("Adding route")
  940. t.routesFromSystem[dst] = gateways
  941. newTree.Insert(dst, gateways)
  942. } else {
  943. t.l.WithField("destination", dst).WithField("via", gateways).Info("Removing route")
  944. delete(t.routesFromSystem, dst)
  945. newTree.Delete(dst)
  946. }
  947. t.routesFromSystemLock.Unlock()
  948. t.routeTree.Store(newTree)
  949. }
  950. func (t *tun) Close() error {
  951. if t.routeChan != nil {
  952. close(t.routeChan)
  953. }
  954. if t.ReadWriteCloser != nil {
  955. _ = t.ReadWriteCloser.Close()
  956. }
  957. if t.ioctlFd > 0 {
  958. _ = os.NewFile(t.ioctlFd, "ioctlFd").Close()
  959. t.ioctlFd = 0
  960. }
  961. return nil
  962. }