tun_linux.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916
  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. // Only read when we create the device, an fd handed to us already has its name and offloads
  165. c.RegisterReloadCallback(func(c *config.C, r *config.Reload) {
  166. r.RestartRequiredIfChanged("tun.dev", "tun.use_offloads")
  167. })
  168. return t, nil
  169. }
  170. // newTunGeneric does all the stuff common to different tun initialization paths.
  171. // It will close your files on error.
  172. // offloadFlags is the TUN_F_* mask newTun negotiated (ignored when vnetHdr is false)
  173. func newTunGeneric(c *config.C, l *slog.Logger, fd int, vnetHdr bool, offloadFlags uint, vpnNetworks []netip.Prefix, name string) (*tun, error) {
  174. var qs tio.QueueSet
  175. var err error
  176. if vnetHdr {
  177. qs, err = tio.NewOffloadQueueSet(offloadUSOEnabled(offloadFlags), l)
  178. } else {
  179. qs, err = tio.NewPollQueueSet()
  180. }
  181. if err != nil {
  182. _ = unix.Close(fd)
  183. return nil, err
  184. }
  185. err = qs.Add(fd)
  186. if err != nil {
  187. // Add only appends on success, so closing the set here can't
  188. // double-close fd; it releases the set's shutdown eventfd.
  189. _ = unix.Close(fd)
  190. _ = qs.Close()
  191. return nil, err
  192. }
  193. t := &tun{
  194. Device: name,
  195. readers: qs,
  196. closeLock: sync.Mutex{},
  197. vnetHdr: vnetHdr,
  198. offloadFlags: offloadFlags,
  199. vpnNetworks: vpnNetworks,
  200. TXQueueLen: c.GetInt("tun.tx_queue", 5000),
  201. useSystemRoutes: c.GetBool("tun.use_system_route_table", false),
  202. useSystemRoutesBufferSize: c.GetInt("tun.use_system_route_table_buffer_size", 0),
  203. routesFromSystem: map[netip.Prefix]routing.Gateways{},
  204. l: l,
  205. }
  206. if err = t.reload(c, true, nil); err != nil {
  207. _ = t.Close()
  208. return nil, err
  209. }
  210. c.RegisterReloadCallback(func(c *config.C, r *config.Reload) {
  211. r.RestartRequiredIfChanged("tun.tx_queue", "tun.use_system_route_table", "tun.use_system_route_table_buffer_size")
  212. err := t.reload(c, false, r)
  213. if err != nil {
  214. util.LogWithContextIfNeeded("failed to reload tun device", err, t.l)
  215. r.Failed()
  216. }
  217. })
  218. return t, nil
  219. }
  220. func (t *tun) reload(c *config.C, initial bool, r *config.Reload) error {
  221. routeChange, routes, err := getAllRoutesFromConfig(t.l, c, t.vpnNetworks, initial)
  222. if err != nil {
  223. return err
  224. }
  225. if !initial && !routeChange && !c.HasChanged("tun.mtu") && t.deviceHasConfiguredMTU() {
  226. return nil
  227. }
  228. // Only the mtu changed. The routes are the same, parse them again so the ones without their own mtu pick up the
  229. // new default. Without this an mtu change would remove them all
  230. if !routeChange {
  231. _, routes, err = getAllRoutesFromConfig(t.l, c, t.vpnNetworks, true)
  232. if err != nil {
  233. return err
  234. }
  235. }
  236. routeTree, err := makeRouteTree(t.l, routes, true)
  237. if err != nil {
  238. return err
  239. }
  240. // Bring along any routes learned from the system route table on reload
  241. t.routesFromSystemLock.Lock()
  242. for dst, gw := range t.routesFromSystem {
  243. routeTree.Insert(dst, gw)
  244. }
  245. t.routesFromSystemLock.Unlock()
  246. newDefaultMTU := getMTU(t.l, c)
  247. newMaxMTU := newDefaultMTU
  248. for i, r := range routes {
  249. if r.MTU == 0 {
  250. routes[i].MTU = newDefaultMTU
  251. }
  252. if r.MTU > newMaxMTU {
  253. newMaxMTU = r.MTU
  254. }
  255. }
  256. t.MaxMTU = newMaxMTU
  257. t.DefaultMTU = newDefaultMTU
  258. // Teach nebula how to handle the routes before establishing them in the system table
  259. oldRoutes := t.Routes.Swap(&routes)
  260. t.routeTree.Store(routeTree)
  261. if !initial {
  262. // Compare with the device rather than the last config, the mtu may have been refused or changed under us
  263. if !t.deviceHasMaxMTU() {
  264. oldMTU, _ := t.deviceMTU()
  265. if err := t.setMTU(t.MaxMTU); err != nil {
  266. t.l.Error("Failed to set tun mtu", "mtu", t.MaxMTU, "error", err)
  267. r.Failed()
  268. } else {
  269. t.l.Info("Set max MTU", "mtu", t.MaxMTU, "oldMTU", oldMTU)
  270. }
  271. }
  272. for _, network := range t.vpnNetworks {
  273. if t.defaultRouteHasMTU(network) {
  274. continue
  275. }
  276. err := t.setDefaultRoute(network)
  277. if err != nil {
  278. t.l.Error(err.Error())
  279. r.Failed()
  280. } else {
  281. t.l.Info("Set default MTU", "mtu", t.DefaultMTU, "network", network)
  282. }
  283. }
  284. // Remove first, if the system removes a wanted route hopefully it will be re-added next
  285. t.removeRoutes(findRemovedRoutes(routes, *oldRoutes), r)
  286. // Ensure any routes we actually want are installed
  287. err = t.addRoutes(true, r)
  288. if err != nil {
  289. // This should never be called since addRoutes should log its own errors in a reload condition
  290. util.LogWithContextIfNeeded("Failed to refresh routes", err, t.l)
  291. r.Failed()
  292. }
  293. }
  294. return nil
  295. }
  296. // Queues opens additional kernel multiqueue fds until the device has n queues, then returns them all.
  297. func (t *tun) Queues(n int) ([]tio.Queue, error) {
  298. for len(t.readers.Queues()) < n {
  299. if err := t.addQueue(); err != nil {
  300. return nil, err
  301. }
  302. }
  303. return t.readers.Queues(), nil
  304. }
  305. // addQueue opens one more IFF_MULTI_QUEUE fd on the device and adds it to the queue set.
  306. func (t *tun) addQueue() error {
  307. t.closeLock.Lock()
  308. defer t.closeLock.Unlock()
  309. fd, err := unix.Open("/dev/net/tun", os.O_RDWR, 0)
  310. if err != nil {
  311. return err
  312. }
  313. flags := uint16(unix.IFF_TUN | unix.IFF_NO_PI | unix.IFF_MULTI_QUEUE)
  314. if t.vnetHdr {
  315. flags |= unix.IFF_VNET_HDR
  316. }
  317. if _, err = tunSetIff(fd, t.Device, flags); err != nil {
  318. _ = unix.Close(fd)
  319. return err
  320. }
  321. if t.vnetHdr {
  322. if err = ioctl(uintptr(fd), unix.TUNSETOFFLOAD, uintptr(t.offloadFlags)); err != nil {
  323. _ = unix.Close(fd)
  324. return fmt.Errorf("failed to enable offload on multiqueue tun fd: %w", err)
  325. }
  326. }
  327. err = t.readers.Add(fd)
  328. if err != nil {
  329. _ = unix.Close(fd)
  330. return err
  331. }
  332. return nil
  333. }
  334. func (t *tun) RoutesFor(ip netip.Addr) routing.Gateways {
  335. r, _ := t.routeTree.Load().Lookup(ip)
  336. return r
  337. }
  338. func (t *tun) deviceBytes() (o [16]byte) {
  339. for i, c := range t.Device {
  340. o[i] = byte(c)
  341. }
  342. return
  343. }
  344. func hasNetlinkAddr(al []*netlink.Addr, x netlink.Addr) bool {
  345. for i := range al {
  346. if al[i].Equal(x) {
  347. return true
  348. }
  349. }
  350. return false
  351. }
  352. // addIPs uses netlink to add all addresses that don't exist, then it removes ones that should not be there
  353. func (t *tun) addIPs(link netlink.Link) error {
  354. newAddrs := make([]*netlink.Addr, len(t.vpnNetworks))
  355. for i := range t.vpnNetworks {
  356. newAddrs[i] = &netlink.Addr{
  357. IPNet: &net.IPNet{
  358. IP: t.vpnNetworks[i].Addr().AsSlice(),
  359. Mask: net.CIDRMask(t.vpnNetworks[i].Bits(), t.vpnNetworks[i].Addr().BitLen()),
  360. },
  361. Label: t.vpnNetworks[i].Addr().Zone(),
  362. }
  363. }
  364. //add all new addresses
  365. for i := range newAddrs {
  366. //AddrReplace still adds new IPs, but if their properties change it will change them as well
  367. if err := netlink.AddrReplace(link, newAddrs[i]); err != nil {
  368. return err
  369. }
  370. }
  371. //iterate over remainder, remove whoever shouldn't be there
  372. al, err := netlink.AddrList(link, netlink.FAMILY_ALL)
  373. if err != nil {
  374. //RTM_GETADDR dumps the whole system, so any concurrent address change
  375. //interrupts it - including the kernel's async tentative->preferred
  376. //flip of an IPv6 address the AddrReplace calls above just added,
  377. //which makes this a race against our own setup. Partial results are
  378. //still returned; the worst case is a stale address surviving until
  379. //the next config reload, which beats failing startup over it.
  380. if !errors.Is(err, netlink.ErrDumpInterrupted) {
  381. return fmt.Errorf("failed to get tun address list: %s", err)
  382. }
  383. t.l.Warn("tun address list dump was interrupted, stale addresses may remain")
  384. }
  385. for i := range al {
  386. if hasNetlinkAddr(newAddrs, al[i]) {
  387. continue
  388. }
  389. err = netlink.AddrDel(link, &al[i])
  390. if err != nil {
  391. t.l.Error("failed to remove address from tun address list", "error", err)
  392. } else {
  393. t.l.Info("removed address not listed in cert(s)", "removed", al[i].String())
  394. }
  395. }
  396. return nil
  397. }
  398. func (t *tun) Activate() error {
  399. devName := t.deviceBytes()
  400. if t.useSystemRoutes {
  401. t.watchRoutes()
  402. }
  403. s, err := unix.Socket(
  404. unix.AF_INET, //because everything we use t.ioctlFd for is address family independent, this is fine
  405. unix.SOCK_DGRAM,
  406. unix.IPPROTO_IP,
  407. )
  408. if err != nil {
  409. return err
  410. }
  411. t.ioctlFd = uintptr(s)
  412. // Set the device name
  413. ifrf := ifReq{Name: devName}
  414. if err = ioctl(t.ioctlFd, unix.SIOCGIFFLAGS, uintptr(unsafe.Pointer(&ifrf))); err != nil {
  415. return fmt.Errorf("failed to set tun device name: %s", err)
  416. }
  417. link, err := netlink.LinkByName(t.Device)
  418. if err != nil {
  419. return fmt.Errorf("failed to get tun device link: %s", err)
  420. }
  421. t.deviceIndex = link.Attrs().Index
  422. // Setup our default MTU
  423. if err := t.setMTU(t.MaxMTU); err != nil {
  424. // This is currently a non fatal condition because the route table must have the MTU set appropriately as well
  425. t.l.Error("Failed to set tun mtu", "error", err)
  426. }
  427. // Set the transmit queue length
  428. ifrq := ifreqQLEN{Name: devName, Value: int32(t.TXQueueLen)}
  429. if err = ioctl(t.ioctlFd, unix.SIOCSIFTXQLEN, uintptr(unsafe.Pointer(&ifrq))); err != nil {
  430. // If we can't set the queue length nebula will still work but it may lead to packet loss
  431. t.l.Error("Failed to set tun tx queue length", "error", err)
  432. }
  433. const modeNone = 1
  434. if err = netlink.LinkSetIP6AddrGenMode(link, modeNone); err != nil {
  435. t.l.Warn("Failed to disable link local address generation", "error", err)
  436. }
  437. if err = t.addIPs(link); err != nil {
  438. return err
  439. }
  440. // Bring up the interface
  441. ifrf.Flags = ifrf.Flags | unix.IFF_UP
  442. if err = ioctl(t.ioctlFd, unix.SIOCSIFFLAGS, uintptr(unsafe.Pointer(&ifrf))); err != nil {
  443. return fmt.Errorf("failed to bring the tun device up: %s", err)
  444. }
  445. //set route MTU
  446. for i := range t.vpnNetworks {
  447. if err = t.setDefaultRoute(t.vpnNetworks[i]); err != nil {
  448. return fmt.Errorf("failed to set default route MTU: %w", err)
  449. }
  450. }
  451. // Set the routes
  452. if err = t.addRoutes(false, nil); err != nil {
  453. return err
  454. }
  455. // Run the interface
  456. ifrf.Flags = ifrf.Flags | unix.IFF_UP | unix.IFF_RUNNING
  457. if err = ioctl(t.ioctlFd, unix.SIOCSIFFLAGS, uintptr(unsafe.Pointer(&ifrf))); err != nil {
  458. return fmt.Errorf("failed to run tun device: %s", err)
  459. }
  460. return nil
  461. }
  462. func (t *tun) setMTU(mtu int) error {
  463. ifm := ifreqMTU{Name: t.deviceBytes(), MTU: int32(mtu)}
  464. return ioctl(t.ioctlFd, unix.SIOCSIFMTU, uintptr(unsafe.Pointer(&ifm)))
  465. }
  466. // deviceMTU asks the kernel for the device's mtu.
  467. func (t *tun) deviceMTU() (int, error) {
  468. ifm := ifreqMTU{Name: t.deviceBytes()}
  469. if err := ioctl(t.ioctlFd, unix.SIOCGIFMTU, uintptr(unsafe.Pointer(&ifm))); err != nil {
  470. return 0, err
  471. }
  472. return int(ifm.MTU), nil
  473. }
  474. // deviceHasConfiguredMTU is true when the device and the route for each of our networks carry the mtu the config asks
  475. // for.
  476. func (t *tun) deviceHasConfiguredMTU() bool {
  477. if !t.deviceHasMaxMTU() {
  478. return false
  479. }
  480. for _, network := range t.vpnNetworks {
  481. if !t.defaultRouteHasMTU(network) {
  482. return false
  483. }
  484. }
  485. return true
  486. }
  487. // defaultRouteHasMTU is true when the kernel's route for network on our device has the default mtu and advmss. Before
  488. // Activate there's nothing to check, Activate installs it.
  489. func (t *tun) defaultRouteHasMTU(network netip.Prefix) bool {
  490. if t.deviceIndex == 0 {
  491. return true
  492. }
  493. family := netlink.FAMILY_V4
  494. if network.Addr().Is6() {
  495. family = netlink.FAMILY_V6
  496. }
  497. filter := &netlink.Route{
  498. LinkIndex: t.deviceIndex,
  499. Dst: &net.IPNet{
  500. IP: network.Masked().Addr().AsSlice(),
  501. Mask: net.CIDRMask(network.Bits(), network.Addr().BitLen()),
  502. },
  503. Table: unix.RT_TABLE_MAIN,
  504. }
  505. routes, err := netlink.RouteListFiltered(family, filter, netlink.RT_FILTER_OIF|netlink.RT_FILTER_DST|netlink.RT_FILTER_TABLE)
  506. if err != nil {
  507. return false
  508. }
  509. for _, r := range routes {
  510. if r.MTU == t.DefaultMTU && r.AdvMSS == t.advMSS(Route{}) {
  511. return true
  512. }
  513. }
  514. return false
  515. }
  516. // deviceHasMaxMTU is true when the device's mtu is the one the config asks for. Before Activate there's nothing to
  517. // check, Activate sets it.
  518. func (t *tun) deviceHasMaxMTU() bool {
  519. if t.ioctlFd == 0 {
  520. return true
  521. }
  522. mtu, err := t.deviceMTU()
  523. return err == nil && mtu == t.MaxMTU
  524. }
  525. func (t *tun) setDefaultRoute(cidr netip.Prefix) error {
  526. dr := &net.IPNet{
  527. IP: cidr.Masked().Addr().AsSlice(),
  528. Mask: net.CIDRMask(cidr.Bits(), cidr.Addr().BitLen()),
  529. }
  530. nr := netlink.Route{
  531. LinkIndex: t.deviceIndex,
  532. Dst: dr,
  533. MTU: t.DefaultMTU,
  534. AdvMSS: t.advMSS(Route{}),
  535. Scope: unix.RT_SCOPE_LINK,
  536. Src: net.IP(cidr.Addr().AsSlice()),
  537. Protocol: unix.RTPROT_KERNEL,
  538. Table: unix.RT_TABLE_MAIN,
  539. Type: unix.RTN_UNICAST,
  540. }
  541. // Match the metric the kernel uses for its auto-installed connected route,
  542. // so RouteReplace overwrites it in place instead of adding a second route at a worse metric.
  543. // IPv6 connected routes are installed at metric 256 (IP6_RT_PRIO_KERN); IPv4 uses 0.
  544. // Without this, the kernel route wins lookups and our MTU / AdvMSS / Features never apply on v6.
  545. if cidr.Addr().Is6() {
  546. nr.Priority = 256
  547. }
  548. err := netlink.RouteReplace(&nr)
  549. if err != nil {
  550. t.l.Warn("Failed to set default route MTU, retrying", "error", err, "cidr", cidr)
  551. //retry twice more -- on some systems there appears to be a race condition where if we set routes too soon, netlink says `invalid argument`
  552. for range 2 {
  553. time.Sleep(100 * time.Millisecond)
  554. err = netlink.RouteReplace(&nr)
  555. if err == nil {
  556. break
  557. } else {
  558. t.l.Warn("Failed to set default route MTU, retrying",
  559. "error", err,
  560. "cidr", cidr,
  561. "mtu", t.DefaultMTU,
  562. )
  563. }
  564. }
  565. if err != nil {
  566. return fmt.Errorf("failed to set mtu %v on the default route %v; %v", t.DefaultMTU, dr, err)
  567. }
  568. }
  569. return nil
  570. }
  571. func (t *tun) addRoutes(logErrors bool, rl *config.Reload) error {
  572. // Path routes
  573. routes := *t.Routes.Load()
  574. for _, r := range routes {
  575. if !r.Install {
  576. continue
  577. }
  578. dr := &net.IPNet{
  579. IP: r.Cidr.Masked().Addr().AsSlice(),
  580. Mask: net.CIDRMask(r.Cidr.Bits(), r.Cidr.Addr().BitLen()),
  581. }
  582. nr := netlink.Route{
  583. LinkIndex: t.deviceIndex,
  584. Dst: dr,
  585. MTU: r.MTU,
  586. AdvMSS: t.advMSS(r),
  587. Scope: unix.RT_SCOPE_LINK,
  588. }
  589. if r.Metric > 0 {
  590. nr.Priority = r.Metric
  591. }
  592. err := netlink.RouteReplace(&nr)
  593. if err != nil {
  594. retErr := util.NewContextualError("Failed to add route", map[string]any{"route": r}, err)
  595. if logErrors {
  596. retErr.Log(t.l)
  597. rl.Failed()
  598. } else {
  599. return retErr
  600. }
  601. } else {
  602. t.l.Info("Added route", "route", r)
  603. }
  604. }
  605. return nil
  606. }
  607. func (t *tun) removeRoutes(routes []Route, rl *config.Reload) {
  608. for _, r := range routes {
  609. if !r.Install {
  610. continue
  611. }
  612. dr := &net.IPNet{
  613. IP: r.Cidr.Masked().Addr().AsSlice(),
  614. Mask: net.CIDRMask(r.Cidr.Bits(), r.Cidr.Addr().BitLen()),
  615. }
  616. nr := netlink.Route{
  617. LinkIndex: t.deviceIndex,
  618. Dst: dr,
  619. MTU: r.MTU,
  620. AdvMSS: t.advMSS(r),
  621. Scope: unix.RT_SCOPE_LINK,
  622. }
  623. if r.Metric > 0 {
  624. nr.Priority = r.Metric
  625. }
  626. err := netlink.RouteDel(&nr)
  627. if errors.Is(err, unix.ESRCH) {
  628. // Already gone, which is what we wanted
  629. t.l.Info("Route was already removed", "route", r)
  630. } else if err != nil {
  631. t.l.Error("Failed to remove route", "error", err, "route", r)
  632. rl.Failed()
  633. } else {
  634. t.l.Info("Removed route", "route", r)
  635. }
  636. }
  637. }
  638. func (t *tun) Name() string {
  639. return t.Device
  640. }
  641. func (t *tun) advMSS(r Route) int {
  642. mtu := r.MTU
  643. if r.MTU == 0 {
  644. mtu = t.DefaultMTU
  645. }
  646. // We only need to set advmss if the route MTU does not match the device MTU
  647. if mtu != t.MaxMTU {
  648. return mtu - 40
  649. }
  650. return 0
  651. }
  652. func (t *tun) watchRoutes() {
  653. rch := make(chan netlink.RouteUpdate)
  654. doneChan := make(chan struct{})
  655. netlinkOptions := netlink.RouteSubscribeOptions{
  656. ReceiveBufferSize: t.useSystemRoutesBufferSize,
  657. ReceiveBufferForceSize: t.useSystemRoutesBufferSize != 0,
  658. ErrorCallback: func(e error) { t.l.Error("netlink error", "error", e) },
  659. }
  660. if err := netlink.RouteSubscribeWithOptions(rch, doneChan, netlinkOptions); err != nil {
  661. t.l.Error("failed to subscribe to system route changes", "error", err)
  662. return
  663. }
  664. t.routeChan = doneChan
  665. go func() {
  666. for {
  667. select {
  668. case r, ok := <-rch:
  669. if ok {
  670. t.updateRoutes(r)
  671. } else {
  672. // may be should do something here as
  673. // netlink stops sending updates
  674. return
  675. }
  676. case <-doneChan:
  677. // netlink.RouteSubscriber will close the rch for us
  678. return
  679. }
  680. }
  681. }()
  682. }
  683. func (t *tun) isGatewayInVpnNetworks(gwAddr netip.Addr) bool {
  684. withinNetworks := false
  685. for i := range t.vpnNetworks {
  686. if t.vpnNetworks[i].Contains(gwAddr) {
  687. withinNetworks = true
  688. break
  689. }
  690. }
  691. return withinNetworks
  692. }
  693. func (t *tun) getGatewaysFromRoute(r *netlink.Route) routing.Gateways {
  694. var gateways routing.Gateways
  695. link, err := netlink.LinkByName(t.Device)
  696. if err != nil {
  697. t.l.Error("Ignoring route update: failed to get link by name", "deviceName", t.Device)
  698. return gateways
  699. }
  700. // If this route is relevant to our interface and there is a gateway then add it
  701. if r.LinkIndex == link.Attrs().Index {
  702. gwAddr, ok := getGatewayAddr(r.Gw, r.Via)
  703. if ok {
  704. if t.isGatewayInVpnNetworks(gwAddr) {
  705. gateways = append(gateways, routing.NewGateway(gwAddr, 1))
  706. } else {
  707. // Gateway isn't in our overlay network, ignore
  708. t.l.Debug("Ignoring route update, gateway is not in our network", "route", r)
  709. }
  710. } else {
  711. t.l.Debug("Ignoring route update, invalid gateway or via address", "route", r)
  712. }
  713. }
  714. for _, p := range r.MultiPath {
  715. // If this route is relevant to our interface and there is a gateway then add it
  716. if p.LinkIndex == link.Attrs().Index {
  717. gwAddr, ok := getGatewayAddr(p.Gw, p.Via)
  718. if ok {
  719. if t.isGatewayInVpnNetworks(gwAddr) {
  720. gateways = append(gateways, routing.NewGateway(gwAddr, p.Hops+1))
  721. } else {
  722. // Gateway isn't in our overlay network, ignore
  723. t.l.Debug("Ignoring route update, gateway is not in our network", "route", r)
  724. }
  725. } else {
  726. t.l.Debug("Ignoring route update, invalid gateway or via address", "route", r)
  727. }
  728. }
  729. }
  730. routing.CalculateBucketsForGateways(gateways)
  731. return gateways
  732. }
  733. func getGatewayAddr(gw net.IP, via netlink.Destination) (netip.Addr, bool) {
  734. // Try to use the old RTA_GATEWAY first
  735. gwAddr, ok := netip.AddrFromSlice(gw)
  736. if !ok {
  737. // Fallback to the new RTA_VIA
  738. rVia, ok := via.(*netlink.Via)
  739. if ok {
  740. gwAddr, ok = netip.AddrFromSlice(rVia.Addr)
  741. }
  742. }
  743. if gwAddr.IsValid() {
  744. gwAddr = gwAddr.Unmap()
  745. return gwAddr, true
  746. }
  747. return netip.Addr{}, false
  748. }
  749. func (t *tun) updateRoutes(r netlink.RouteUpdate) {
  750. gateways := t.getGatewaysFromRoute(&r.Route)
  751. if len(gateways) == 0 {
  752. // No gateways relevant to our network, no routing changes required.
  753. t.l.Debug("Ignoring route update, no gateways", "route", r)
  754. return
  755. }
  756. if r.Dst == nil {
  757. t.l.Debug("Ignoring route update, no destination address", "route", r)
  758. return
  759. }
  760. dstAddr, ok := netip.AddrFromSlice(r.Dst.IP)
  761. if !ok {
  762. t.l.Debug("Ignoring route update, invalid destination address", "route", r)
  763. return
  764. }
  765. ones, _ := r.Dst.Mask.Size()
  766. dst := netip.PrefixFrom(dstAddr, ones)
  767. newTree := t.routeTree.Load().Clone()
  768. t.routesFromSystemLock.Lock()
  769. if r.Type == unix.RTM_NEWROUTE {
  770. t.l.Info("Adding route", "destination", dst, "via", gateways)
  771. t.routesFromSystem[dst] = gateways
  772. newTree.Insert(dst, gateways)
  773. } else {
  774. t.l.Info("Removing route", "destination", dst, "via", gateways)
  775. delete(t.routesFromSystem, dst)
  776. newTree.Delete(dst)
  777. }
  778. t.routesFromSystemLock.Unlock()
  779. t.routeTree.Store(newTree)
  780. }
  781. func (t *tun) Close() error {
  782. t.closeLock.Lock()
  783. defer t.closeLock.Unlock()
  784. if t.routeChan != nil {
  785. close(t.routeChan)
  786. t.routeChan = nil
  787. }
  788. if t.ioctlFd > 0 {
  789. _ = unix.Close(int(t.ioctlFd))
  790. t.ioctlFd = 0
  791. }
  792. return t.readers.Close()
  793. }