tun_linux.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929
  1. //go:build !android && !e2e_testing
  2. package overlay
  3. import (
  4. "errors"
  5. "fmt"
  6. "log/slog"
  7. "net"
  8. "net/netip"
  9. "os"
  10. "strings"
  11. "sync"
  12. "sync/atomic"
  13. "time"
  14. "unsafe"
  15. "github.com/DefinedNet/netlink"
  16. "github.com/gaissmai/bart"
  17. "github.com/slackhq/nebula/config"
  18. "github.com/slackhq/nebula/overlay/tio"
  19. "github.com/slackhq/nebula/routing"
  20. "github.com/slackhq/nebula/util"
  21. "golang.org/x/sys/unix"
  22. )
  23. type tun struct {
  24. readers tio.QueueSet
  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. offloadFlags uint
  35. Routes atomic.Pointer[[]Route]
  36. routeTree atomic.Pointer[bart.Table[routing.Gateways]]
  37. routeChan chan struct{}
  38. useSystemRoutes bool
  39. useSystemRoutesBufferSize int
  40. // These are routes learned from `tun.use_system_route_table`
  41. // stored here to make it easier to restore them after a reload
  42. routesFromSystem map[netip.Prefix]routing.Gateways
  43. routesFromSystemLock sync.Mutex
  44. l *slog.Logger
  45. }
  46. func (t *tun) Networks() []netip.Prefix {
  47. return t.vpnNetworks
  48. }
  49. type ifReq struct {
  50. Name [16]byte
  51. Flags uint16
  52. pad [8]byte
  53. }
  54. type ifreqMTU struct {
  55. Name [16]byte
  56. MTU int32
  57. pad [8]byte
  58. }
  59. type ifreqQLEN struct {
  60. Name [16]byte
  61. Value int32
  62. pad [8]byte
  63. }
  64. func newTunFromFd(c *config.C, l *slog.Logger, deviceFd int, vpnNetworks []netip.Prefix) (*tun, error) {
  65. // We don't know what flags the caller opened this fd with and can't turn
  66. // on IFF_VNET_HDR after TUNSETIFF, so skip offload on inherited fds.
  67. return newTunGeneric(c, l, deviceFd, false, 0, vpnNetworks, "tun0")
  68. }
  69. // openTunDev opens /dev/net/tun, creating the device node first if it's
  70. // missing (docker containers occasionally omit it).
  71. func openTunDev() (int, error) {
  72. fd, err := unix.Open("/dev/net/tun", os.O_RDWR, 0)
  73. if err == nil {
  74. return fd, nil
  75. }
  76. if !os.IsNotExist(err) {
  77. return -1, err
  78. }
  79. if err = os.MkdirAll("/dev/net", 0755); err != nil {
  80. return -1, fmt.Errorf("/dev/net/tun doesn't exist, failed to mkdir -p /dev/net: %w", err)
  81. }
  82. if err = unix.Mknod("/dev/net/tun", unix.S_IFCHR|0600, int(unix.Mkdev(10, 200))); err != nil {
  83. return -1, fmt.Errorf("failed to create /dev/net/tun: %w", err)
  84. }
  85. fd, err = unix.Open("/dev/net/tun", os.O_RDWR, 0)
  86. if err != nil {
  87. return -1, fmt.Errorf("created /dev/net/tun, but still failed: %w", err)
  88. }
  89. return fd, nil
  90. }
  91. // tunSetIff runs TUNSETIFF with the given flags and returns the kernel-chosen device name on success.
  92. func tunSetIff(fd int, name string, flags uint16) (string, error) {
  93. var req ifReq
  94. req.Flags = flags
  95. copy(req.Name[:], name)
  96. if err := ioctl(uintptr(fd), uintptr(unix.TUNSETIFF), uintptr(unsafe.Pointer(&req))); err != nil {
  97. return "", err
  98. }
  99. return strings.Trim(string(req.Name[:]), "\x00"), nil
  100. }
  101. // tsoOffloadFlags are the TUN_F_* bits we ask the kernel to enable when a TSO-capable TUN is available.
  102. const tsoOffloadFlags = unix.TUN_F_CSUM | unix.TUN_F_TSO4 | unix.TUN_F_TSO6 | unix.TUN_F_TSO_ECN
  103. // usoAndTSOOffloadFlags adds UDP Segmentation Offload to tsoOffloadFlags.
  104. // Requires Linux >= 6.2; older kernels reject it and we fall back to TCP-only TSO
  105. const usoAndTSOOffloadFlags = tsoOffloadFlags | unix.TUN_F_USO4 | unix.TUN_F_USO6
  106. func offloadUSOEnabled(offloadFlags uint) bool {
  107. return offloadFlags&(unix.TUN_F_USO4|unix.TUN_F_USO6) != 0
  108. }
  109. func newTun(c *config.C, l *slog.Logger, vpnNetworks []netip.Prefix, multiqueue bool) (*tun, error) {
  110. var err error
  111. // IFF_TUN_EXCL prevents us from attaching to an already-running tun
  112. baseFlags := uint16(unix.IFF_TUN | unix.IFF_NO_PI | unix.IFF_TUN_EXCL)
  113. if multiqueue {
  114. baseFlags |= unix.IFF_MULTI_QUEUE
  115. }
  116. nameStr := c.GetString("tun.dev", "")
  117. useOffloads := c.GetBool("tun.use_offloads", false)
  118. var fd int
  119. var name string
  120. var offloadFlags uint
  121. if useOffloads {
  122. fd, err = openTunDev()
  123. if err != nil {
  124. return nil, err
  125. }
  126. // First try to enable IFF_VNET_HDR via TUNSETIFF and negotiate TUN_F_* offloads
  127. // We try TSO+USO first, fall back to TSO-only on kernels without USO (Linux < 6.2),
  128. // and finally give up on virtio headers entirely and reopen as a plain TUN if neither offload mask is accepted.
  129. // offloadFlags is the exact TUN_F_* mask the kernel accepted.
  130. // We save it so addQueue can replay the identical device-wide mask on added queues
  131. name, err = tunSetIff(fd, nameStr, baseFlags|unix.IFF_VNET_HDR)
  132. if err != nil {
  133. _ = unix.Close(fd)
  134. useOffloads = false
  135. } else {
  136. if err = ioctl(uintptr(fd), unix.TUNSETOFFLOAD, uintptr(usoAndTSOOffloadFlags)); err == nil {
  137. offloadFlags = usoAndTSOOffloadFlags
  138. } else if err = ioctl(uintptr(fd), unix.TUNSETOFFLOAD, uintptr(tsoOffloadFlags)); err == nil {
  139. offloadFlags = tsoOffloadFlags
  140. } else {
  141. l.Warn("Failed to enable TUN offload (TSO); proceeding without virtio headers", "error", err)
  142. _ = unix.Close(fd)
  143. useOffloads = false
  144. }
  145. }
  146. }
  147. if !useOffloads {
  148. fd, err = openTunDev()
  149. if err != nil {
  150. return nil, err
  151. }
  152. name, err = tunSetIff(fd, nameStr, baseFlags)
  153. if err != nil {
  154. _ = unix.Close(fd)
  155. return nil, &NameError{Name: nameStr, Underlying: err}
  156. }
  157. }
  158. l.Info("TUN offload status", "tso", useOffloads, "uso", offloadUSOEnabled(offloadFlags))
  159. t, err := newTunGeneric(c, l, fd, useOffloads, offloadFlags, vpnNetworks, name)
  160. if err != nil {
  161. return nil, err
  162. }
  163. t.Device = name
  164. return t, nil
  165. }
  166. // newTunGeneric does all the stuff common to different tun initialization paths.
  167. // It will close your files on error.
  168. // offloadFlags is the TUN_F_* mask newTun negotiated (ignored when vnetHdr is false)
  169. func newTunGeneric(c *config.C, l *slog.Logger, fd int, vnetHdr bool, offloadFlags uint, vpnNetworks []netip.Prefix, name string) (*tun, error) {
  170. var qs tio.QueueSet
  171. var err error
  172. if vnetHdr {
  173. qs, err = tio.NewOffloadQueueSet(offloadUSOEnabled(offloadFlags), l)
  174. } else {
  175. qs, err = tio.NewPollQueueSet()
  176. }
  177. if err != nil {
  178. _ = unix.Close(fd)
  179. return nil, err
  180. }
  181. err = qs.Add(fd)
  182. if err != nil {
  183. // Add only appends on success, so closing the set here can't
  184. // double-close fd; it releases the set's shutdown eventfd.
  185. _ = unix.Close(fd)
  186. _ = qs.Close()
  187. return nil, err
  188. }
  189. t := &tun{
  190. Device: name,
  191. readers: qs,
  192. closeLock: sync.Mutex{},
  193. vnetHdr: vnetHdr,
  194. offloadFlags: offloadFlags,
  195. vpnNetworks: vpnNetworks,
  196. TXQueueLen: c.GetInt("tun.tx_queue", 5000),
  197. useSystemRoutes: c.GetBool("tun.use_system_route_table", false),
  198. useSystemRoutesBufferSize: c.GetInt("tun.use_system_route_table_buffer_size", 0),
  199. routesFromSystem: map[netip.Prefix]routing.Gateways{},
  200. l: l,
  201. }
  202. if err = t.reload(c, true); err != nil {
  203. _ = t.Close()
  204. return nil, err
  205. }
  206. c.RegisterReloadCallback(func(c *config.C) {
  207. err := t.reload(c, false)
  208. if err != nil {
  209. util.LogWithContextIfNeeded("failed to reload tun device", err, t.l)
  210. }
  211. })
  212. return t, nil
  213. }
  214. func (t *tun) reload(c *config.C, initial bool) error {
  215. routeChange, routes, err := getAllRoutesFromConfig(t.l, c, t.vpnNetworks, initial)
  216. if err != nil {
  217. return err
  218. }
  219. if !initial && !routeChange && !c.HasChanged("tun.mtu") {
  220. return nil
  221. }
  222. // Only the mtu changed. The routes are the same, parse them again so the ones without their own mtu pick up the
  223. // new default. Without this an mtu change would remove them all
  224. if !routeChange {
  225. _, routes, err = getAllRoutesFromConfig(t.l, c, t.vpnNetworks, true)
  226. if err != nil {
  227. return err
  228. }
  229. }
  230. routeTree, err := makeRouteTree(t.l, routes, true)
  231. if err != nil {
  232. return err
  233. }
  234. // Bring along any routes learned from the system route table on reload
  235. t.routesFromSystemLock.Lock()
  236. for dst, gw := range t.routesFromSystem {
  237. routeTree.Insert(dst, gw)
  238. }
  239. t.routesFromSystemLock.Unlock()
  240. oldDefaultMTU := t.DefaultMTU
  241. oldMaxMTU := t.MaxMTU
  242. newDefaultMTU := getMTU(t.l, c)
  243. newMaxMTU := newDefaultMTU
  244. for i, r := range routes {
  245. if r.MTU == 0 {
  246. routes[i].MTU = newDefaultMTU
  247. }
  248. if r.MTU > newMaxMTU {
  249. newMaxMTU = r.MTU
  250. }
  251. }
  252. t.MaxMTU = newMaxMTU
  253. t.DefaultMTU = newDefaultMTU
  254. // Teach nebula how to handle the routes before establishing them in the system table
  255. oldRoutes := t.Routes.Swap(&routes)
  256. t.routeTree.Store(routeTree)
  257. if !initial {
  258. if oldMaxMTU != newMaxMTU {
  259. t.setMTU()
  260. t.l.Info("Set max MTU", "mtu", t.MaxMTU, "oldMTU", oldMaxMTU)
  261. }
  262. if oldDefaultMTU != newDefaultMTU {
  263. for i := range t.vpnNetworks {
  264. err := t.setDefaultRoute(t.vpnNetworks[i])
  265. if err != nil {
  266. t.l.Warn(err.Error())
  267. } else {
  268. t.l.Info("Set default MTU", "mtu", t.DefaultMTU, "oldMTU", oldDefaultMTU)
  269. }
  270. }
  271. }
  272. // Remove first, if the system removes a wanted route hopefully it will be re-added next
  273. t.removeRoutes(findRemovedRoutes(routes, *oldRoutes))
  274. // Ensure any routes we actually want are installed
  275. err = t.addRoutes(true)
  276. if err != nil {
  277. // This should never be called since addRoutes should log its own errors in a reload condition
  278. util.LogWithContextIfNeeded("Failed to refresh routes", err, t.l)
  279. }
  280. }
  281. return nil
  282. }
  283. // Queues opens additional kernel multiqueue fds until the device has n queues, then returns them all.
  284. func (t *tun) Queues(n int) ([]tio.Queue, error) {
  285. for len(t.readers.Queues()) < n {
  286. if err := t.addQueue(); err != nil {
  287. return nil, err
  288. }
  289. }
  290. return t.readers.Queues(), nil
  291. }
  292. // addQueue opens one more IFF_MULTI_QUEUE fd on the device and adds it to the queue set.
  293. func (t *tun) addQueue() error {
  294. t.closeLock.Lock()
  295. defer t.closeLock.Unlock()
  296. fd, err := unix.Open("/dev/net/tun", os.O_RDWR, 0)
  297. if err != nil {
  298. return err
  299. }
  300. flags := uint16(unix.IFF_TUN | unix.IFF_NO_PI | unix.IFF_MULTI_QUEUE)
  301. if t.vnetHdr {
  302. flags |= unix.IFF_VNET_HDR
  303. }
  304. if _, err = tunSetIff(fd, t.Device, flags); err != nil {
  305. _ = unix.Close(fd)
  306. return err
  307. }
  308. if t.vnetHdr {
  309. if err = ioctl(uintptr(fd), unix.TUNSETOFFLOAD, uintptr(t.offloadFlags)); err != nil {
  310. _ = unix.Close(fd)
  311. return fmt.Errorf("failed to enable offload on multiqueue tun fd: %w", err)
  312. }
  313. }
  314. err = t.readers.Add(fd)
  315. if err != nil {
  316. _ = unix.Close(fd)
  317. return err
  318. }
  319. return nil
  320. }
  321. func (t *tun) RoutesFor(ip netip.Addr) routing.Gateways {
  322. r, _ := t.routeTree.Load().Lookup(ip)
  323. return r
  324. }
  325. func (t *tun) deviceBytes() (o [16]byte) {
  326. for i, c := range t.Device {
  327. o[i] = byte(c)
  328. }
  329. return
  330. }
  331. func hasNetlinkAddr(al []*netlink.Addr, x netlink.Addr) bool {
  332. for i := range al {
  333. if al[i].Equal(x) {
  334. return true
  335. }
  336. }
  337. return false
  338. }
  339. // addIPs uses netlink to add all addresses that don't exist, then it removes ones that should not be there
  340. func (t *tun) addIPs(link netlink.Link) error {
  341. newAddrs := make([]*netlink.Addr, len(t.vpnNetworks))
  342. for i := range t.vpnNetworks {
  343. newAddrs[i] = &netlink.Addr{
  344. IPNet: &net.IPNet{
  345. IP: t.vpnNetworks[i].Addr().AsSlice(),
  346. Mask: net.CIDRMask(t.vpnNetworks[i].Bits(), t.vpnNetworks[i].Addr().BitLen()),
  347. },
  348. Label: t.vpnNetworks[i].Addr().Zone(),
  349. }
  350. }
  351. //add all new addresses
  352. for i := range newAddrs {
  353. //AddrReplace still adds new IPs, but if their properties change it will change them as well
  354. if err := netlink.AddrReplace(link, newAddrs[i]); err != nil {
  355. return err
  356. }
  357. }
  358. //iterate over remainder, remove whoever shouldn't be there
  359. al, err := netlink.AddrList(link, netlink.FAMILY_ALL)
  360. if err != nil {
  361. //RTM_GETADDR dumps the whole system, so any concurrent address change
  362. //interrupts it - including the kernel's async tentative->preferred
  363. //flip of an IPv6 address the AddrReplace calls above just added,
  364. //which makes this a race against our own setup. Partial results are
  365. //still returned; the worst case is a stale address surviving until
  366. //the next config reload, which beats failing startup over it.
  367. if !errors.Is(err, netlink.ErrDumpInterrupted) {
  368. return fmt.Errorf("failed to get tun address list: %s", err)
  369. }
  370. t.l.Warn("tun address list dump was interrupted, stale addresses may remain")
  371. }
  372. for i := range al {
  373. if hasNetlinkAddr(newAddrs, al[i]) {
  374. continue
  375. }
  376. err = netlink.AddrDel(link, &al[i])
  377. if err != nil {
  378. t.l.Error("failed to remove address from tun address list", "error", err)
  379. } else {
  380. t.l.Info("removed address not listed in cert(s)", "removed", al[i].String())
  381. }
  382. }
  383. return nil
  384. }
  385. func (t *tun) Activate() error {
  386. devName := t.deviceBytes()
  387. if t.useSystemRoutes {
  388. t.watchRoutes()
  389. }
  390. s, err := unix.Socket(
  391. unix.AF_INET, //because everything we use t.ioctlFd for is address family independent, this is fine
  392. unix.SOCK_DGRAM,
  393. unix.IPPROTO_IP,
  394. )
  395. if err != nil {
  396. return err
  397. }
  398. t.ioctlFd = uintptr(s)
  399. // Set the device name
  400. ifrf := ifReq{Name: devName}
  401. if err = ioctl(t.ioctlFd, unix.SIOCGIFFLAGS, uintptr(unsafe.Pointer(&ifrf))); err != nil {
  402. return fmt.Errorf("failed to set tun device name: %s", err)
  403. }
  404. link, err := netlink.LinkByName(t.Device)
  405. if err != nil {
  406. return fmt.Errorf("failed to get tun device link: %s", err)
  407. }
  408. t.deviceIndex = link.Attrs().Index
  409. // Setup our default MTU
  410. t.setMTU()
  411. // Set the transmit queue length
  412. ifrq := ifreqQLEN{Name: devName, Value: int32(t.TXQueueLen)}
  413. if err = ioctl(t.ioctlFd, unix.SIOCSIFTXQLEN, uintptr(unsafe.Pointer(&ifrq))); err != nil {
  414. // If we can't set the queue length nebula will still work but it may lead to packet loss
  415. t.l.Error("Failed to set tun tx queue length", "error", err)
  416. }
  417. const modeNone = 1
  418. if err = netlink.LinkSetIP6AddrGenMode(link, modeNone); err != nil {
  419. t.l.Warn("Failed to disable link local address generation", "error", err)
  420. }
  421. if err = t.addIPs(link); err != nil {
  422. return err
  423. }
  424. // Bring up the interface
  425. ifrf.Flags = ifrf.Flags | unix.IFF_UP
  426. if err = ioctl(t.ioctlFd, unix.SIOCSIFFLAGS, uintptr(unsafe.Pointer(&ifrf))); err != nil {
  427. return fmt.Errorf("failed to bring the tun device up: %s", err)
  428. }
  429. //set route MTU
  430. for i := range t.vpnNetworks {
  431. if err = t.setDefaultRoute(t.vpnNetworks[i]); err != nil {
  432. return fmt.Errorf("failed to set default route MTU: %w", err)
  433. }
  434. }
  435. // Set the routes
  436. if err = t.addRoutes(false); err != nil {
  437. return err
  438. }
  439. // Run the interface
  440. ifrf.Flags = ifrf.Flags | unix.IFF_UP | unix.IFF_RUNNING
  441. if err = ioctl(t.ioctlFd, unix.SIOCSIFFLAGS, uintptr(unsafe.Pointer(&ifrf))); err != nil {
  442. return fmt.Errorf("failed to run tun device: %s", err)
  443. }
  444. return nil
  445. }
  446. func (t *tun) setMTU() {
  447. // Set the MTU on the device
  448. ifm := ifreqMTU{Name: t.deviceBytes(), MTU: int32(t.MaxMTU)}
  449. if err := ioctl(t.ioctlFd, unix.SIOCSIFMTU, uintptr(unsafe.Pointer(&ifm))); err != nil {
  450. // This is currently a non fatal condition because the route table must have the MTU set appropriately as well
  451. t.l.Error("Failed to set tun mtu", "error", err)
  452. }
  453. }
  454. func (t *tun) setDefaultRoute(cidr netip.Prefix) error {
  455. dr := &net.IPNet{
  456. IP: cidr.Masked().Addr().AsSlice(),
  457. Mask: net.CIDRMask(cidr.Bits(), cidr.Addr().BitLen()),
  458. }
  459. nr := netlink.Route{
  460. LinkIndex: t.deviceIndex,
  461. Dst: dr,
  462. MTU: t.DefaultMTU,
  463. AdvMSS: t.advMSS(Route{}),
  464. Scope: unix.RT_SCOPE_LINK,
  465. Src: net.IP(cidr.Addr().AsSlice()),
  466. Protocol: unix.RTPROT_KERNEL,
  467. Table: unix.RT_TABLE_MAIN,
  468. Type: unix.RTN_UNICAST,
  469. }
  470. // Match the metric the kernel uses for its auto-installed connected route,
  471. // so RouteReplace overwrites it in place instead of adding a second route at a worse metric.
  472. // IPv6 connected routes are installed at metric 256 (IP6_RT_PRIO_KERN); IPv4 uses 0.
  473. // Without this, the kernel route wins lookups and our MTU / AdvMSS / Features never apply on v6.
  474. if cidr.Addr().Is6() {
  475. nr.Priority = 256
  476. }
  477. held, err := t.otherLinkRoutes()
  478. if err != nil {
  479. return err
  480. }
  481. err = t.replaceRoute(&nr, held)
  482. if err != nil {
  483. t.l.Warn("Failed to set default route MTU, retrying", "error", err, "cidr", cidr)
  484. //retry twice more -- on some systems there appears to be a race condition where if we set routes too soon, netlink says `invalid argument`
  485. for range 2 {
  486. time.Sleep(100 * time.Millisecond)
  487. err = t.replaceRoute(&nr, held)
  488. if err == nil {
  489. break
  490. } else {
  491. t.l.Warn("Failed to set default route MTU, retrying",
  492. "error", err,
  493. "cidr", cidr,
  494. "mtu", t.DefaultMTU,
  495. )
  496. }
  497. }
  498. if err != nil {
  499. return fmt.Errorf("failed to set mtu %v on the default route %v; %v", t.DefaultMTU, dr, err)
  500. }
  501. }
  502. return nil
  503. }
  504. func (t *tun) addRoutes(logErrors bool) error {
  505. held, err := t.otherLinkRoutes()
  506. if err != nil {
  507. if logErrors {
  508. t.l.Error("Failed to add routes", "error", err)
  509. return nil
  510. }
  511. return err
  512. }
  513. // Path routes
  514. routes := *t.Routes.Load()
  515. for _, r := range routes {
  516. if !r.Install {
  517. continue
  518. }
  519. dr := &net.IPNet{
  520. IP: r.Cidr.Masked().Addr().AsSlice(),
  521. Mask: net.CIDRMask(r.Cidr.Bits(), r.Cidr.Addr().BitLen()),
  522. }
  523. nr := netlink.Route{
  524. LinkIndex: t.deviceIndex,
  525. Dst: dr,
  526. MTU: r.MTU,
  527. AdvMSS: t.advMSS(r),
  528. Scope: unix.RT_SCOPE_LINK,
  529. }
  530. if r.Metric > 0 {
  531. nr.Priority = r.Metric
  532. }
  533. err := t.replaceRoute(&nr, held)
  534. if err != nil {
  535. retErr := util.NewContextualError("Failed to add route", map[string]any{"route": r}, err)
  536. if logErrors {
  537. retErr.Log(t.l)
  538. } else {
  539. return retErr
  540. }
  541. } else {
  542. t.l.Info("Added route", "route", r)
  543. }
  544. }
  545. return nil
  546. }
  547. // ip6RoutePrioUser is the metric the kernel gives an IPv6 route added without one
  548. const ip6RoutePrioUser = 1024
  549. // routeKey is where the main table files a route. Replacing a route replaces the first one with the same key, whatever
  550. // device it is on
  551. type routeKey struct {
  552. dst netip.Prefix
  553. priority int
  554. }
  555. func routeKeyOf(dst *net.IPNet, family, priority int) (routeKey, bool) {
  556. var p netip.Prefix
  557. if dst == nil {
  558. // A default route
  559. if family == unix.AF_INET6 {
  560. p = netip.PrefixFrom(netip.IPv6Unspecified(), 0)
  561. } else {
  562. p = netip.PrefixFrom(netip.IPv4Unspecified(), 0)
  563. }
  564. } else {
  565. addr, ok := netip.AddrFromSlice(dst.IP)
  566. if !ok {
  567. return routeKey{}, false
  568. }
  569. ones, _ := dst.Mask.Size()
  570. p = netip.PrefixFrom(addr.Unmap(), ones).Masked()
  571. }
  572. if priority == 0 && p.Addr().Is6() {
  573. priority = ip6RoutePrioUser
  574. }
  575. return routeKey{dst: p, priority: priority}, true
  576. }
  577. // otherLinkRoutes returns the keys of the main table routes that are not on our device
  578. func (t *tun) otherLinkRoutes() (map[routeKey]struct{}, error) {
  579. routes, err := netlink.RouteListFiltered(netlink.FAMILY_ALL, &netlink.Route{Table: unix.RT_TABLE_MAIN}, netlink.RT_FILTER_TABLE)
  580. // An interrupted dump may miss a route, which then gets replaced like it always used to be
  581. if err != nil && !errors.Is(err, netlink.ErrDumpInterrupted) {
  582. return nil, fmt.Errorf("failed to list the system routes: %w", err)
  583. }
  584. held := make(map[routeKey]struct{}, len(routes))
  585. for _, r := range routes {
  586. if r.LinkIndex == t.deviceIndex {
  587. continue
  588. }
  589. if k, ok := routeKeyOf(r.Dst, r.Family, r.Priority); ok {
  590. held[k] = struct{}{}
  591. }
  592. }
  593. return held, nil
  594. }
  595. // replaceRoute puts nr in the main table in place of our own route with its key. Replacing would take the route of
  596. // another device holding that key, so ours goes in behind it instead. Theirs keeps routing and the kernel falls back
  597. // to ours once theirs is removed, like when leaving the lan that had it. A different metric decides which one wins.
  598. func (t *tun) replaceRoute(nr *netlink.Route, held map[routeKey]struct{}) error {
  599. family := unix.AF_INET6
  600. if nr.Dst.IP.To4() != nil {
  601. family = unix.AF_INET
  602. }
  603. k, ok := routeKeyOf(nr.Dst, family, nr.Priority)
  604. if _, taken := held[k]; !ok || !taken {
  605. return netlink.RouteReplace(nr)
  606. }
  607. // Appending doesn't update a route that is already ours, it adds a second one
  608. ours := netlink.Route{
  609. LinkIndex: nr.LinkIndex,
  610. Dst: nr.Dst,
  611. Scope: nr.Scope,
  612. Table: nr.Table,
  613. Priority: k.priority,
  614. }
  615. if err := netlink.RouteDel(&ours); err != nil && !errors.Is(err, unix.ESRCH) {
  616. return err
  617. }
  618. t.l.Warn("Another interface already routes this destination at the same metric, our route is used once theirs is removed", "destination", k.dst, "metric", k.priority)
  619. return netlink.RouteAppend(nr)
  620. }
  621. func (t *tun) removeRoutes(routes []Route) {
  622. for _, r := range routes {
  623. if !r.Install {
  624. continue
  625. }
  626. dr := &net.IPNet{
  627. IP: r.Cidr.Masked().Addr().AsSlice(),
  628. Mask: net.CIDRMask(r.Cidr.Bits(), r.Cidr.Addr().BitLen()),
  629. }
  630. nr := netlink.Route{
  631. LinkIndex: t.deviceIndex,
  632. Dst: dr,
  633. MTU: r.MTU,
  634. AdvMSS: t.advMSS(r),
  635. Scope: unix.RT_SCOPE_LINK,
  636. }
  637. if r.Metric > 0 {
  638. nr.Priority = r.Metric
  639. }
  640. err := netlink.RouteDel(&nr)
  641. if err != nil {
  642. t.l.Error("Failed to remove route", "error", err, "route", r)
  643. } else {
  644. t.l.Info("Removed route", "route", r)
  645. }
  646. }
  647. }
  648. func (t *tun) Name() string {
  649. return t.Device
  650. }
  651. func (t *tun) advMSS(r Route) int {
  652. mtu := r.MTU
  653. if r.MTU == 0 {
  654. mtu = t.DefaultMTU
  655. }
  656. // We only need to set advmss if the route MTU does not match the device MTU
  657. if mtu != t.MaxMTU {
  658. return mtu - 40
  659. }
  660. return 0
  661. }
  662. func (t *tun) watchRoutes() {
  663. rch := make(chan netlink.RouteUpdate)
  664. doneChan := make(chan struct{})
  665. netlinkOptions := netlink.RouteSubscribeOptions{
  666. ReceiveBufferSize: t.useSystemRoutesBufferSize,
  667. ReceiveBufferForceSize: t.useSystemRoutesBufferSize != 0,
  668. ErrorCallback: func(e error) { t.l.Error("netlink error", "error", e) },
  669. }
  670. if err := netlink.RouteSubscribeWithOptions(rch, doneChan, netlinkOptions); err != nil {
  671. t.l.Error("failed to subscribe to system route changes", "error", err)
  672. return
  673. }
  674. t.routeChan = doneChan
  675. go func() {
  676. for {
  677. select {
  678. case r, ok := <-rch:
  679. if ok {
  680. t.updateRoutes(r)
  681. } else {
  682. // may be should do something here as
  683. // netlink stops sending updates
  684. return
  685. }
  686. case <-doneChan:
  687. // netlink.RouteSubscriber will close the rch for us
  688. return
  689. }
  690. }
  691. }()
  692. }
  693. func (t *tun) isGatewayInVpnNetworks(gwAddr netip.Addr) bool {
  694. withinNetworks := false
  695. for i := range t.vpnNetworks {
  696. if t.vpnNetworks[i].Contains(gwAddr) {
  697. withinNetworks = true
  698. break
  699. }
  700. }
  701. return withinNetworks
  702. }
  703. func (t *tun) getGatewaysFromRoute(r *netlink.Route) routing.Gateways {
  704. var gateways routing.Gateways
  705. link, err := netlink.LinkByName(t.Device)
  706. if err != nil {
  707. t.l.Error("Ignoring route update: failed to get link by name", "deviceName", t.Device)
  708. return gateways
  709. }
  710. // If this route is relevant to our interface and there is a gateway then add it
  711. if r.LinkIndex == link.Attrs().Index {
  712. gwAddr, ok := getGatewayAddr(r.Gw, r.Via)
  713. if ok {
  714. if t.isGatewayInVpnNetworks(gwAddr) {
  715. gateways = append(gateways, routing.NewGateway(gwAddr, 1))
  716. } else {
  717. // Gateway isn't in our overlay network, ignore
  718. t.l.Debug("Ignoring route update, gateway is not in our network", "route", r)
  719. }
  720. } else {
  721. t.l.Debug("Ignoring route update, invalid gateway or via address", "route", r)
  722. }
  723. }
  724. for _, p := range r.MultiPath {
  725. // If this route is relevant to our interface and there is a gateway then add it
  726. if p.LinkIndex == link.Attrs().Index {
  727. gwAddr, ok := getGatewayAddr(p.Gw, p.Via)
  728. if ok {
  729. if t.isGatewayInVpnNetworks(gwAddr) {
  730. gateways = append(gateways, routing.NewGateway(gwAddr, p.Hops+1))
  731. } else {
  732. // Gateway isn't in our overlay network, ignore
  733. t.l.Debug("Ignoring route update, gateway is not in our network", "route", r)
  734. }
  735. } else {
  736. t.l.Debug("Ignoring route update, invalid gateway or via address", "route", r)
  737. }
  738. }
  739. }
  740. routing.CalculateBucketsForGateways(gateways)
  741. return gateways
  742. }
  743. func getGatewayAddr(gw net.IP, via netlink.Destination) (netip.Addr, bool) {
  744. // Try to use the old RTA_GATEWAY first
  745. gwAddr, ok := netip.AddrFromSlice(gw)
  746. if !ok {
  747. // Fallback to the new RTA_VIA
  748. rVia, ok := via.(*netlink.Via)
  749. if ok {
  750. gwAddr, ok = netip.AddrFromSlice(rVia.Addr)
  751. }
  752. }
  753. if gwAddr.IsValid() {
  754. gwAddr = gwAddr.Unmap()
  755. return gwAddr, true
  756. }
  757. return netip.Addr{}, false
  758. }
  759. func (t *tun) updateRoutes(r netlink.RouteUpdate) {
  760. gateways := t.getGatewaysFromRoute(&r.Route)
  761. if len(gateways) == 0 {
  762. // No gateways relevant to our network, no routing changes required.
  763. t.l.Debug("Ignoring route update, no gateways", "route", r)
  764. return
  765. }
  766. if r.Dst == nil {
  767. t.l.Debug("Ignoring route update, no destination address", "route", r)
  768. return
  769. }
  770. dstAddr, ok := netip.AddrFromSlice(r.Dst.IP)
  771. if !ok {
  772. t.l.Debug("Ignoring route update, invalid destination address", "route", r)
  773. return
  774. }
  775. ones, _ := r.Dst.Mask.Size()
  776. dst := netip.PrefixFrom(dstAddr, ones)
  777. newTree := t.routeTree.Load().Clone()
  778. t.routesFromSystemLock.Lock()
  779. if r.Type == unix.RTM_NEWROUTE {
  780. t.l.Info("Adding route", "destination", dst, "via", gateways)
  781. t.routesFromSystem[dst] = gateways
  782. newTree.Insert(dst, gateways)
  783. } else {
  784. t.l.Info("Removing route", "destination", dst, "via", gateways)
  785. delete(t.routesFromSystem, dst)
  786. newTree.Delete(dst)
  787. }
  788. t.routesFromSystemLock.Unlock()
  789. t.routeTree.Store(newTree)
  790. }
  791. func (t *tun) Close() error {
  792. t.closeLock.Lock()
  793. defer t.closeLock.Unlock()
  794. if t.routeChan != nil {
  795. close(t.routeChan)
  796. t.routeChan = nil
  797. }
  798. if t.ioctlFd > 0 {
  799. _ = unix.Close(int(t.ioctlFd))
  800. t.ioctlFd = 0
  801. }
  802. return t.readers.Close()
  803. }