tun_linux.go 23 KB

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