tun_linux.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  1. //go:build !android && !e2e_testing
  2. // +build !android,!e2e_testing
  3. package overlay
  4. import (
  5. "fmt"
  6. "net"
  7. "net/netip"
  8. "os"
  9. "strings"
  10. "sync"
  11. "sync/atomic"
  12. "time"
  13. "unsafe"
  14. "github.com/gaissmai/bart"
  15. "github.com/sirupsen/logrus"
  16. "github.com/slackhq/nebula/config"
  17. "github.com/slackhq/nebula/overlay/tio"
  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. type tun struct {
  24. readers tio.Container
  25. closeLock sync.Mutex
  26. Device string
  27. vpnNetworks []netip.Prefix
  28. MaxMTU int
  29. DefaultMTU int
  30. TXQueueLen int
  31. deviceIndex int
  32. ioctlFd uintptr
  33. vnetHdr bool
  34. Routes atomic.Pointer[[]Route]
  35. routeTree atomic.Pointer[bart.Table[routing.Gateways]]
  36. routeChan chan struct{}
  37. useSystemRoutes bool
  38. useSystemRoutesBufferSize int
  39. // These are routes learned from `tun.use_system_route_table`
  40. // stored here to make it easier to restore them after a reload
  41. routesFromSystem map[netip.Prefix]routing.Gateways
  42. routesFromSystemLock sync.Mutex
  43. l *logrus.Logger
  44. }
  45. func (t *tun) Networks() []netip.Prefix {
  46. return t.vpnNetworks
  47. }
  48. type ifReq struct {
  49. Name [16]byte
  50. Flags uint16
  51. pad [8]byte
  52. }
  53. type ifreqMTU struct {
  54. Name [16]byte
  55. MTU int32
  56. pad [8]byte
  57. }
  58. type ifreqQLEN struct {
  59. Name [16]byte
  60. Value int32
  61. pad [8]byte
  62. }
  63. func newTunFromFd(c *config.C, l *logrus.Logger, deviceFd int, vpnNetworks []netip.Prefix) (*tun, error) {
  64. // We don't know what flags the caller opened this fd with and can't turn
  65. // on IFF_VNET_HDR after TUNSETIFF, so skip offload on inherited fds.
  66. t, err := newTunGeneric(c, l, deviceFd, false, vpnNetworks)
  67. if err != nil {
  68. return nil, err
  69. }
  70. t.Device = "tun0"
  71. return t, nil
  72. }
  73. // openTunDev opens /dev/net/tun, creating the device node first if it's
  74. // missing (docker containers occasionally omit it).
  75. func openTunDev() (int, error) {
  76. fd, err := unix.Open("/dev/net/tun", os.O_RDWR, 0)
  77. if err == nil {
  78. return fd, nil
  79. }
  80. if !os.IsNotExist(err) {
  81. return -1, err
  82. }
  83. if err = os.MkdirAll("/dev/net", 0755); err != nil {
  84. return -1, fmt.Errorf("/dev/net/tun doesn't exist, failed to mkdir -p /dev/net: %w", err)
  85. }
  86. if err = unix.Mknod("/dev/net/tun", unix.S_IFCHR|0600, int(unix.Mkdev(10, 200))); err != nil {
  87. return -1, fmt.Errorf("failed to create /dev/net/tun: %w", err)
  88. }
  89. fd, err = unix.Open("/dev/net/tun", os.O_RDWR, 0)
  90. if err != nil {
  91. return -1, fmt.Errorf("created /dev/net/tun, but still failed: %w", err)
  92. }
  93. return fd, nil
  94. }
  95. // tunSetIff runs TUNSETIFF with the given flags and returns the kernel-chosen
  96. // device name on success.
  97. func tunSetIff(fd int, name string, flags uint16) (string, error) {
  98. var req ifReq
  99. req.Flags = flags
  100. copy(req.Name[:], name)
  101. if err := ioctl(uintptr(fd), uintptr(unix.TUNSETIFF), uintptr(unsafe.Pointer(&req))); err != nil {
  102. return "", err
  103. }
  104. return strings.Trim(string(req.Name[:]), "\x00"), nil
  105. }
  106. // tsoOffloadFlags are the TUN_F_* bits we ask the kernel to enable when a
  107. // TSO-capable TUN is available. CSUM is required as a prerequisite for TSO.
  108. const tsoOffloadFlags = unix.TUN_F_CSUM | unix.TUN_F_TSO4 | unix.TUN_F_TSO6
  109. func newTun(c *config.C, l *logrus.Logger, vpnNetworks []netip.Prefix, multiqueue bool) (*tun, error) {
  110. baseFlags := uint16(unix.IFF_TUN | unix.IFF_NO_PI)
  111. if multiqueue {
  112. baseFlags |= unix.IFF_MULTI_QUEUE
  113. }
  114. nameStr := c.GetString("tun.dev", "")
  115. // First try to open with IFF_VNET_HDR + TUNSETOFFLOAD so we can receive
  116. // TSO superpackets. If either step fails (older kernel, unprivileged
  117. // container, etc.) we close and fall back to a plain TUN.
  118. fd, err := openTunDev()
  119. if err != nil {
  120. return nil, err
  121. }
  122. vnetHdr := true
  123. name, err := tunSetIff(fd, nameStr, baseFlags|unix.IFF_VNET_HDR|unix.IFF_NAPI)
  124. if err != nil {
  125. _ = unix.Close(fd)
  126. vnetHdr = false
  127. } else if err = ioctl(uintptr(fd), unix.TUNSETOFFLOAD, uintptr(tsoOffloadFlags)); err != nil {
  128. l.WithError(err).Warn("Failed to enable TUN offload (TSO); proceeding without virtio headers")
  129. _ = unix.Close(fd)
  130. vnetHdr = false
  131. }
  132. if !vnetHdr {
  133. fd, err = openTunDev()
  134. if err != nil {
  135. return nil, err
  136. }
  137. name, err = tunSetIff(fd, nameStr, baseFlags)
  138. if err != nil {
  139. _ = unix.Close(fd)
  140. return nil, &NameError{Name: nameStr, Underlying: err}
  141. }
  142. }
  143. t, err := newTunGeneric(c, l, fd, vnetHdr, vpnNetworks)
  144. if err != nil {
  145. return nil, err
  146. }
  147. t.Device = name
  148. return t, nil
  149. }
  150. // newTunGeneric does all the stuff common to different tun initialization paths. It will close your files on error.
  151. func newTunGeneric(c *config.C, l *logrus.Logger, fd int, vnetHdr bool, vpnNetworks []netip.Prefix) (*tun, error) {
  152. var container tio.Container
  153. var err error
  154. if vnetHdr {
  155. container, err = tio.NewOffloadContainer()
  156. } else {
  157. container, err = tio.NewPollContainer()
  158. }
  159. if err != nil {
  160. _ = unix.Close(fd)
  161. return nil, err
  162. }
  163. err = container.Add(fd)
  164. if err != nil {
  165. _ = unix.Close(fd)
  166. return nil, err
  167. }
  168. t := &tun{
  169. readers: container,
  170. closeLock: sync.Mutex{},
  171. vnetHdr: vnetHdr,
  172. vpnNetworks: vpnNetworks,
  173. TXQueueLen: c.GetInt("tun.tx_queue", 500),
  174. useSystemRoutes: c.GetBool("tun.use_system_route_table", false),
  175. useSystemRoutesBufferSize: c.GetInt("tun.use_system_route_table_buffer_size", 0),
  176. routesFromSystem: map[netip.Prefix]routing.Gateways{},
  177. l: l,
  178. }
  179. if err = t.reload(c, true); err != nil {
  180. _ = t.Close()
  181. return nil, err
  182. }
  183. c.RegisterReloadCallback(func(c *config.C) {
  184. err := t.reload(c, false)
  185. if err != nil {
  186. util.LogWithContextIfNeeded("failed to reload tun device", err, t.l)
  187. }
  188. })
  189. return t, nil
  190. }
  191. func (t *tun) reload(c *config.C, initial bool) error {
  192. routeChange, routes, err := getAllRoutesFromConfig(c, t.vpnNetworks, initial)
  193. if err != nil {
  194. return err
  195. }
  196. if !initial && !routeChange && !c.HasChanged("tun.mtu") {
  197. return nil
  198. }
  199. routeTree, err := makeRouteTree(t.l, routes, true)
  200. if err != nil {
  201. return err
  202. }
  203. // Bring along any routes learned from the system route table on reload
  204. t.routesFromSystemLock.Lock()
  205. for dst, gw := range t.routesFromSystem {
  206. routeTree.Insert(dst, gw)
  207. }
  208. t.routesFromSystemLock.Unlock()
  209. oldDefaultMTU := t.DefaultMTU
  210. oldMaxMTU := t.MaxMTU
  211. newDefaultMTU := c.GetInt("tun.mtu", DefaultMTU)
  212. newMaxMTU := newDefaultMTU
  213. for i, r := range routes {
  214. if r.MTU == 0 {
  215. routes[i].MTU = newDefaultMTU
  216. }
  217. if r.MTU > t.MaxMTU {
  218. newMaxMTU = r.MTU
  219. }
  220. }
  221. t.MaxMTU = newMaxMTU
  222. t.DefaultMTU = newDefaultMTU
  223. // Teach nebula how to handle the routes before establishing them in the system table
  224. oldRoutes := t.Routes.Swap(&routes)
  225. t.routeTree.Store(routeTree)
  226. if !initial {
  227. if oldMaxMTU != newMaxMTU {
  228. t.setMTU()
  229. t.l.Infof("Set max MTU to %v was %v", t.MaxMTU, oldMaxMTU)
  230. }
  231. if oldDefaultMTU != newDefaultMTU {
  232. for i := range t.vpnNetworks {
  233. err := t.setDefaultRoute(t.vpnNetworks[i])
  234. if err != nil {
  235. t.l.Warn(err)
  236. } else {
  237. t.l.Infof("Set default MTU to %v was %v", t.DefaultMTU, oldDefaultMTU)
  238. }
  239. }
  240. }
  241. // Remove first, if the system removes a wanted route hopefully it will be re-added next
  242. t.removeRoutes(findRemovedRoutes(routes, *oldRoutes))
  243. // Ensure any routes we actually want are installed
  244. err = t.addRoutes(true)
  245. if err != nil {
  246. // This should never be called since addRoutes should log its own errors in a reload condition
  247. util.LogWithContextIfNeeded("Failed to refresh routes", err, t.l)
  248. }
  249. }
  250. return nil
  251. }
  252. func (t *tun) SupportsMultiqueue() bool {
  253. return true
  254. }
  255. func (t *tun) NewMultiQueueReader() error {
  256. t.closeLock.Lock()
  257. defer t.closeLock.Unlock()
  258. fd, err := unix.Open("/dev/net/tun", os.O_RDWR, 0)
  259. if err != nil {
  260. return err
  261. }
  262. flags := uint16(unix.IFF_TUN | unix.IFF_NO_PI | unix.IFF_MULTI_QUEUE)
  263. if t.vnetHdr {
  264. flags |= unix.IFF_VNET_HDR | unix.IFF_NAPI
  265. }
  266. if _, err = tunSetIff(fd, t.Device, flags); err != nil {
  267. _ = unix.Close(fd)
  268. return err
  269. }
  270. if t.vnetHdr {
  271. if err = ioctl(uintptr(fd), unix.TUNSETOFFLOAD, uintptr(tsoOffloadFlags)); err != nil {
  272. _ = unix.Close(fd)
  273. return fmt.Errorf("failed to enable offload on multiqueue tun fd: %w", err)
  274. }
  275. }
  276. err = t.readers.Add(fd)
  277. if err != nil {
  278. _ = unix.Close(fd)
  279. return err
  280. }
  281. return nil
  282. }
  283. func (t *tun) RoutesFor(ip netip.Addr) routing.Gateways {
  284. r, _ := t.routeTree.Load().Lookup(ip)
  285. return r
  286. }
  287. func (t *tun) deviceBytes() (o [16]byte) {
  288. for i, c := range t.Device {
  289. o[i] = byte(c)
  290. }
  291. return
  292. }
  293. func hasNetlinkAddr(al []*netlink.Addr, x netlink.Addr) bool {
  294. for i := range al {
  295. if al[i].Equal(x) {
  296. return true
  297. }
  298. }
  299. return false
  300. }
  301. // addIPs uses netlink to add all addresses that don't exist, then it removes ones that should not be there
  302. func (t *tun) addIPs(link netlink.Link) error {
  303. newAddrs := make([]*netlink.Addr, len(t.vpnNetworks))
  304. for i := range t.vpnNetworks {
  305. newAddrs[i] = &netlink.Addr{
  306. IPNet: &net.IPNet{
  307. IP: t.vpnNetworks[i].Addr().AsSlice(),
  308. Mask: net.CIDRMask(t.vpnNetworks[i].Bits(), t.vpnNetworks[i].Addr().BitLen()),
  309. },
  310. Label: t.vpnNetworks[i].Addr().Zone(),
  311. }
  312. }
  313. //add all new addresses
  314. for i := range newAddrs {
  315. //AddrReplace still adds new IPs, but if their properties change it will change them as well
  316. if err := netlink.AddrReplace(link, newAddrs[i]); err != nil {
  317. return err
  318. }
  319. }
  320. //iterate over remainder, remove whoever shouldn't be there
  321. al, err := netlink.AddrList(link, netlink.FAMILY_ALL)
  322. if err != nil {
  323. return fmt.Errorf("failed to get tun address list: %s", err)
  324. }
  325. for i := range al {
  326. if hasNetlinkAddr(newAddrs, al[i]) {
  327. continue
  328. }
  329. err = netlink.AddrDel(link, &al[i])
  330. if err != nil {
  331. t.l.WithError(err).Error("failed to remove address from tun address list")
  332. } else {
  333. t.l.WithField("removed", al[i].String()).Info("removed address not listed in cert(s)")
  334. }
  335. }
  336. return nil
  337. }
  338. func (t *tun) Activate() error {
  339. devName := t.deviceBytes()
  340. if t.useSystemRoutes {
  341. t.watchRoutes()
  342. }
  343. s, err := unix.Socket(
  344. unix.AF_INET, //because everything we use t.ioctlFd for is address family independent, this is fine
  345. unix.SOCK_DGRAM,
  346. unix.IPPROTO_IP,
  347. )
  348. if err != nil {
  349. return err
  350. }
  351. t.ioctlFd = uintptr(s)
  352. // Set the device name
  353. ifrf := ifReq{Name: devName}
  354. if err = ioctl(t.ioctlFd, unix.SIOCGIFFLAGS, uintptr(unsafe.Pointer(&ifrf))); err != nil {
  355. return fmt.Errorf("failed to set tun device name: %s", err)
  356. }
  357. link, err := netlink.LinkByName(t.Device)
  358. if err != nil {
  359. return fmt.Errorf("failed to get tun device link: %s", err)
  360. }
  361. t.deviceIndex = link.Attrs().Index
  362. // Setup our default MTU
  363. t.setMTU()
  364. // Set the transmit queue length
  365. ifrq := ifreqQLEN{Name: devName, Value: int32(t.TXQueueLen)}
  366. if err = ioctl(t.ioctlFd, unix.SIOCSIFTXQLEN, uintptr(unsafe.Pointer(&ifrq))); err != nil {
  367. // If we can't set the queue length nebula will still work but it may lead to packet loss
  368. t.l.WithError(err).Error("Failed to set tun tx queue length")
  369. }
  370. const modeNone = 1
  371. if err = netlink.LinkSetIP6AddrGenMode(link, modeNone); err != nil {
  372. t.l.WithError(err).Warn("Failed to disable link local address generation")
  373. }
  374. if err = t.addIPs(link); err != nil {
  375. return err
  376. }
  377. // Bring up the interface
  378. ifrf.Flags = ifrf.Flags | unix.IFF_UP
  379. if err = ioctl(t.ioctlFd, unix.SIOCSIFFLAGS, uintptr(unsafe.Pointer(&ifrf))); err != nil {
  380. return fmt.Errorf("failed to bring the tun device up: %s", err)
  381. }
  382. //set route MTU
  383. for i := range t.vpnNetworks {
  384. if err = t.setDefaultRoute(t.vpnNetworks[i]); err != nil {
  385. return fmt.Errorf("failed to set default route MTU: %w", err)
  386. }
  387. }
  388. // Set the routes
  389. if err = t.addRoutes(false); err != nil {
  390. return err
  391. }
  392. // Run the interface
  393. ifrf.Flags = ifrf.Flags | unix.IFF_UP | unix.IFF_RUNNING
  394. if err = ioctl(t.ioctlFd, unix.SIOCSIFFLAGS, uintptr(unsafe.Pointer(&ifrf))); err != nil {
  395. return fmt.Errorf("failed to run tun device: %s", err)
  396. }
  397. return nil
  398. }
  399. func (t *tun) setMTU() {
  400. // Set the MTU on the device
  401. ifm := ifreqMTU{Name: t.deviceBytes(), MTU: int32(t.MaxMTU)}
  402. if err := ioctl(t.ioctlFd, unix.SIOCSIFMTU, uintptr(unsafe.Pointer(&ifm))); err != nil {
  403. // This is currently a non fatal condition because the route table must have the MTU set appropriately as well
  404. t.l.WithError(err).Error("Failed to set tun mtu")
  405. }
  406. }
  407. func (t *tun) setDefaultRoute(cidr netip.Prefix) error {
  408. dr := &net.IPNet{
  409. IP: cidr.Masked().Addr().AsSlice(),
  410. Mask: net.CIDRMask(cidr.Bits(), cidr.Addr().BitLen()),
  411. }
  412. nr := netlink.Route{
  413. LinkIndex: t.deviceIndex,
  414. Dst: dr,
  415. MTU: t.DefaultMTU,
  416. AdvMSS: t.advMSS(Route{}),
  417. Scope: unix.RT_SCOPE_LINK,
  418. Src: net.IP(cidr.Addr().AsSlice()),
  419. Protocol: unix.RTPROT_KERNEL,
  420. Table: unix.RT_TABLE_MAIN,
  421. Type: unix.RTN_UNICAST,
  422. }
  423. err := netlink.RouteReplace(&nr)
  424. if err != nil {
  425. t.l.WithError(err).WithField("cidr", cidr).Warn("Failed to set default route MTU, retrying")
  426. //retry twice more -- on some systems there appears to be a race condition where if we set routes too soon, netlink says `invalid argument`
  427. for i := 0; i < 2; i++ {
  428. time.Sleep(100 * time.Millisecond)
  429. err = netlink.RouteReplace(&nr)
  430. if err == nil {
  431. break
  432. } else {
  433. t.l.WithError(err).WithField("cidr", cidr).WithField("mtu", t.DefaultMTU).Warn("Failed to set default route MTU, retrying")
  434. }
  435. }
  436. if err != nil {
  437. return fmt.Errorf("failed to set mtu %v on the default route %v; %v", t.DefaultMTU, dr, err)
  438. }
  439. }
  440. return nil
  441. }
  442. func (t *tun) addRoutes(logErrors bool) error {
  443. // Path routes
  444. routes := *t.Routes.Load()
  445. for _, r := range routes {
  446. if !r.Install {
  447. continue
  448. }
  449. dr := &net.IPNet{
  450. IP: r.Cidr.Masked().Addr().AsSlice(),
  451. Mask: net.CIDRMask(r.Cidr.Bits(), r.Cidr.Addr().BitLen()),
  452. }
  453. nr := netlink.Route{
  454. LinkIndex: t.deviceIndex,
  455. Dst: dr,
  456. MTU: r.MTU,
  457. AdvMSS: t.advMSS(r),
  458. Scope: unix.RT_SCOPE_LINK,
  459. }
  460. if r.Metric > 0 {
  461. nr.Priority = r.Metric
  462. }
  463. err := netlink.RouteReplace(&nr)
  464. if err != nil {
  465. retErr := util.NewContextualError("Failed to add route", map[string]any{"route": r}, err)
  466. if logErrors {
  467. retErr.Log(t.l)
  468. } else {
  469. return retErr
  470. }
  471. } else {
  472. t.l.WithField("route", r).Info("Added route")
  473. }
  474. }
  475. return nil
  476. }
  477. func (t *tun) removeRoutes(routes []Route) {
  478. for _, r := range routes {
  479. if !r.Install {
  480. continue
  481. }
  482. dr := &net.IPNet{
  483. IP: r.Cidr.Masked().Addr().AsSlice(),
  484. Mask: net.CIDRMask(r.Cidr.Bits(), r.Cidr.Addr().BitLen()),
  485. }
  486. nr := netlink.Route{
  487. LinkIndex: t.deviceIndex,
  488. Dst: dr,
  489. MTU: r.MTU,
  490. AdvMSS: t.advMSS(r),
  491. Scope: unix.RT_SCOPE_LINK,
  492. }
  493. if r.Metric > 0 {
  494. nr.Priority = r.Metric
  495. }
  496. err := netlink.RouteDel(&nr)
  497. if err != nil {
  498. t.l.WithError(err).WithField("route", r).Error("Failed to remove route")
  499. } else {
  500. t.l.WithField("route", r).Info("Removed route")
  501. }
  502. }
  503. }
  504. func (t *tun) Name() string {
  505. return t.Device
  506. }
  507. func (t *tun) advMSS(r Route) int {
  508. mtu := r.MTU
  509. if r.MTU == 0 {
  510. mtu = t.DefaultMTU
  511. }
  512. // We only need to set advmss if the route MTU does not match the device MTU
  513. if mtu != t.MaxMTU {
  514. return mtu - 40
  515. }
  516. return 0
  517. }
  518. func (t *tun) watchRoutes() {
  519. rch := make(chan netlink.RouteUpdate)
  520. doneChan := make(chan struct{})
  521. netlinkOptions := netlink.RouteSubscribeOptions{
  522. ReceiveBufferSize: t.useSystemRoutesBufferSize,
  523. ReceiveBufferForceSize: t.useSystemRoutesBufferSize != 0,
  524. ErrorCallback: func(e error) { t.l.WithError(e).Errorf("netlink error") },
  525. }
  526. if err := netlink.RouteSubscribeWithOptions(rch, doneChan, netlinkOptions); err != nil {
  527. t.l.WithError(err).Errorf("failed to subscribe to system route changes")
  528. return
  529. }
  530. t.routeChan = doneChan
  531. go func() {
  532. for {
  533. select {
  534. case r, ok := <-rch:
  535. if ok {
  536. t.updateRoutes(r)
  537. } else {
  538. // may be should do something here as
  539. // netlink stops sending updates
  540. return
  541. }
  542. case <-doneChan:
  543. // netlink.RouteSubscriber will close the rch for us
  544. return
  545. }
  546. }
  547. }()
  548. }
  549. func (t *tun) isGatewayInVpnNetworks(gwAddr netip.Addr) bool {
  550. withinNetworks := false
  551. for i := range t.vpnNetworks {
  552. if t.vpnNetworks[i].Contains(gwAddr) {
  553. withinNetworks = true
  554. break
  555. }
  556. }
  557. return withinNetworks
  558. }
  559. func (t *tun) getGatewaysFromRoute(r *netlink.Route) routing.Gateways {
  560. var gateways routing.Gateways
  561. link, err := netlink.LinkByName(t.Device)
  562. if err != nil {
  563. t.l.WithField("deviceName", t.Device).Error("Ignoring route update: failed to get link by name")
  564. return gateways
  565. }
  566. // If this route is relevant to our interface and there is a gateway then add it
  567. if r.LinkIndex == link.Attrs().Index {
  568. gwAddr, ok := getGatewayAddr(r.Gw, r.Via)
  569. if ok {
  570. if t.isGatewayInVpnNetworks(gwAddr) {
  571. gateways = append(gateways, routing.NewGateway(gwAddr, 1))
  572. } else {
  573. // Gateway isn't in our overlay network, ignore
  574. t.l.WithField("route", r).Debug("Ignoring route update, gateway is not in our network")
  575. }
  576. } else {
  577. t.l.WithField("route", r).Debug("Ignoring route update, invalid gateway or via address")
  578. }
  579. }
  580. for _, p := range r.MultiPath {
  581. // If this route is relevant to our interface and there is a gateway then add it
  582. if p.LinkIndex == link.Attrs().Index {
  583. gwAddr, ok := getGatewayAddr(p.Gw, p.Via)
  584. if ok {
  585. if t.isGatewayInVpnNetworks(gwAddr) {
  586. gateways = append(gateways, routing.NewGateway(gwAddr, p.Hops+1))
  587. } else {
  588. // Gateway isn't in our overlay network, ignore
  589. t.l.WithField("route", r).Debug("Ignoring route update, gateway is not in our network")
  590. }
  591. } else {
  592. t.l.WithField("route", r).Debug("Ignoring route update, invalid gateway or via address")
  593. }
  594. }
  595. }
  596. routing.CalculateBucketsForGateways(gateways)
  597. return gateways
  598. }
  599. func getGatewayAddr(gw net.IP, via netlink.Destination) (netip.Addr, bool) {
  600. // Try to use the old RTA_GATEWAY first
  601. gwAddr, ok := netip.AddrFromSlice(gw)
  602. if !ok {
  603. // Fallback to the new RTA_VIA
  604. rVia, ok := via.(*netlink.Via)
  605. if ok {
  606. gwAddr, ok = netip.AddrFromSlice(rVia.Addr)
  607. }
  608. }
  609. if gwAddr.IsValid() {
  610. gwAddr = gwAddr.Unmap()
  611. return gwAddr, true
  612. }
  613. return netip.Addr{}, false
  614. }
  615. func (t *tun) updateRoutes(r netlink.RouteUpdate) {
  616. gateways := t.getGatewaysFromRoute(&r.Route)
  617. if len(gateways) == 0 {
  618. // No gateways relevant to our network, no routing changes required.
  619. t.l.WithField("route", r).Debug("Ignoring route update, no gateways")
  620. return
  621. }
  622. if r.Dst == nil {
  623. t.l.WithField("route", r).Debug("Ignoring route update, no destination address")
  624. return
  625. }
  626. dstAddr, ok := netip.AddrFromSlice(r.Dst.IP)
  627. if !ok {
  628. t.l.WithField("route", r).Debug("Ignoring route update, invalid destination address")
  629. return
  630. }
  631. ones, _ := r.Dst.Mask.Size()
  632. dst := netip.PrefixFrom(dstAddr, ones)
  633. newTree := t.routeTree.Load().Clone()
  634. t.routesFromSystemLock.Lock()
  635. if r.Type == unix.RTM_NEWROUTE {
  636. t.l.WithField("destination", dst).WithField("via", gateways).Info("Adding route")
  637. t.routesFromSystem[dst] = gateways
  638. newTree.Insert(dst, gateways)
  639. } else {
  640. t.l.WithField("destination", dst).WithField("via", gateways).Info("Removing route")
  641. delete(t.routesFromSystem, dst)
  642. newTree.Delete(dst)
  643. }
  644. t.routesFromSystemLock.Unlock()
  645. t.routeTree.Store(newTree)
  646. }
  647. func (t *tun) Readers() []tio.Queue {
  648. return t.readers.Queues()
  649. }
  650. func (t *tun) Close() error {
  651. t.closeLock.Lock()
  652. defer t.closeLock.Unlock()
  653. if t.routeChan != nil {
  654. close(t.routeChan)
  655. t.routeChan = nil
  656. }
  657. if t.ioctlFd > 0 {
  658. _ = unix.Close(int(t.ioctlFd))
  659. t.ioctlFd = 0
  660. }
  661. return t.readers.Close()
  662. }