1
0

tun_linux.go 26 KB

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