tun_linux.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. package nebula
  2. import (
  3. "fmt"
  4. "io"
  5. "net"
  6. "os"
  7. "strings"
  8. "unsafe"
  9. "github.com/vishvananda/netlink"
  10. "golang.org/x/sys/unix"
  11. )
  12. type Tun struct {
  13. io.ReadWriteCloser
  14. fd int
  15. Device string
  16. Cidr *net.IPNet
  17. MaxMTU int
  18. DefaultMTU int
  19. TXQueueLen int
  20. Routes []route
  21. UnsafeRoutes []route
  22. }
  23. type ifReq struct {
  24. Name [16]byte
  25. Flags uint16
  26. pad [8]byte
  27. }
  28. func ioctl(a1, a2, a3 uintptr) error {
  29. _, _, errno := unix.Syscall(unix.SYS_IOCTL, a1, a2, a3)
  30. if errno != 0 {
  31. return errno
  32. }
  33. return nil
  34. }
  35. /*
  36. func ipv4(addr string) (o [4]byte, err error) {
  37. ip := net.ParseIP(addr).To4()
  38. if ip == nil {
  39. err = fmt.Errorf("failed to parse addr %s", addr)
  40. return
  41. }
  42. for i, b := range ip {
  43. o[i] = b
  44. }
  45. return
  46. }
  47. */
  48. const (
  49. cIFF_TUN = 0x0001
  50. cIFF_NO_PI = 0x1000
  51. )
  52. type ifreqAddr struct {
  53. Name [16]byte
  54. Addr unix.RawSockaddrInet4
  55. pad [8]byte
  56. }
  57. type ifreqMTU struct {
  58. Name [16]byte
  59. MTU int32
  60. pad [8]byte
  61. }
  62. type ifreqQLEN struct {
  63. Name [16]byte
  64. Value int32
  65. pad [8]byte
  66. }
  67. func newTunFromFd(deviceFd int, cidr *net.IPNet, defaultMTU int, routes []route, unsafeRoutes []route, txQueueLen int) (ifce *Tun, err error) {
  68. file := os.NewFile(uintptr(deviceFd), "/dev/net/tun")
  69. ifce = &Tun{
  70. ReadWriteCloser: file,
  71. fd: int(file.Fd()),
  72. Device: "tun0",
  73. Cidr: cidr,
  74. DefaultMTU: defaultMTU,
  75. TXQueueLen: txQueueLen,
  76. Routes: routes,
  77. UnsafeRoutes: unsafeRoutes,
  78. }
  79. return
  80. }
  81. func newTun(deviceName string, cidr *net.IPNet, defaultMTU int, routes []route, unsafeRoutes []route, txQueueLen int) (ifce *Tun, err error) {
  82. fd, err := unix.Open("/dev/net/tun", os.O_RDWR, 0)
  83. if err != nil {
  84. return nil, err
  85. }
  86. var req ifReq
  87. req.Flags = uint16(cIFF_TUN | cIFF_NO_PI)
  88. copy(req.Name[:], deviceName)
  89. if err = ioctl(uintptr(fd), uintptr(unix.TUNSETIFF), uintptr(unsafe.Pointer(&req))); err != nil {
  90. return
  91. }
  92. name := strings.Trim(string(req.Name[:]), "\x00")
  93. file := os.NewFile(uintptr(fd), "/dev/net/tun")
  94. maxMTU := defaultMTU
  95. for _, r := range routes {
  96. if r.mtu > maxMTU {
  97. maxMTU = r.mtu
  98. }
  99. }
  100. ifce = &Tun{
  101. ReadWriteCloser: file,
  102. fd: int(file.Fd()),
  103. Device: name,
  104. Cidr: cidr,
  105. MaxMTU: maxMTU,
  106. DefaultMTU: defaultMTU,
  107. TXQueueLen: txQueueLen,
  108. Routes: routes,
  109. UnsafeRoutes: unsafeRoutes,
  110. }
  111. return
  112. }
  113. func (c *Tun) WriteRaw(b []byte) error {
  114. var nn int
  115. for {
  116. max := len(b)
  117. n, err := unix.Write(c.fd, b[nn:max])
  118. if n > 0 {
  119. nn += n
  120. }
  121. if nn == len(b) {
  122. return err
  123. }
  124. if err != nil {
  125. return err
  126. }
  127. if n == 0 {
  128. return io.ErrUnexpectedEOF
  129. }
  130. }
  131. }
  132. func (c Tun) deviceBytes() (o [16]byte) {
  133. for i, c := range c.Device {
  134. o[i] = byte(c)
  135. }
  136. return
  137. }
  138. func (c Tun) Activate() error {
  139. devName := c.deviceBytes()
  140. var addr, mask [4]byte
  141. copy(addr[:], c.Cidr.IP.To4())
  142. copy(mask[:], c.Cidr.Mask)
  143. s, err := unix.Socket(
  144. unix.AF_INET,
  145. unix.SOCK_DGRAM,
  146. unix.IPPROTO_IP,
  147. )
  148. if err != nil {
  149. return err
  150. }
  151. fd := uintptr(s)
  152. ifra := ifreqAddr{
  153. Name: devName,
  154. Addr: unix.RawSockaddrInet4{
  155. Family: unix.AF_INET,
  156. Addr: addr,
  157. },
  158. }
  159. // Set the device ip address
  160. if err = ioctl(fd, unix.SIOCSIFADDR, uintptr(unsafe.Pointer(&ifra))); err != nil {
  161. return fmt.Errorf("failed to set tun address: %s", err)
  162. }
  163. // Set the device network
  164. ifra.Addr.Addr = mask
  165. if err = ioctl(fd, unix.SIOCSIFNETMASK, uintptr(unsafe.Pointer(&ifra))); err != nil {
  166. return fmt.Errorf("failed to set tun netmask: %s", err)
  167. }
  168. // Set the device name
  169. ifrf := ifReq{Name: devName}
  170. if err = ioctl(fd, unix.SIOCGIFFLAGS, uintptr(unsafe.Pointer(&ifrf))); err != nil {
  171. return fmt.Errorf("failed to set tun device name: %s", err)
  172. }
  173. // Set the MTU on the device
  174. ifm := ifreqMTU{Name: devName, MTU: int32(c.MaxMTU)}
  175. if err = ioctl(fd, unix.SIOCSIFMTU, uintptr(unsafe.Pointer(&ifm))); err != nil {
  176. // This is currently a non fatal condition because the route table must have the MTU set appropriately as well
  177. l.WithError(err).Error("Failed to set tun mtu")
  178. }
  179. // Set the transmit queue length
  180. ifrq := ifreqQLEN{Name: devName, Value: int32(c.TXQueueLen)}
  181. if err = ioctl(fd, unix.SIOCSIFTXQLEN, uintptr(unsafe.Pointer(&ifrq))); err != nil {
  182. // If we can't set the queue length nebula will still work but it may lead to packet loss
  183. l.WithError(err).Error("Failed to set tun tx queue length")
  184. }
  185. // Bring up the interface
  186. ifrf.Flags = ifrf.Flags | unix.IFF_UP
  187. if err = ioctl(fd, unix.SIOCSIFFLAGS, uintptr(unsafe.Pointer(&ifrf))); err != nil {
  188. return fmt.Errorf("failed to bring the tun device up: %s", err)
  189. }
  190. // Set the routes
  191. link, err := netlink.LinkByName(c.Device)
  192. if err != nil {
  193. return fmt.Errorf("failed to get tun device link: %s", err)
  194. }
  195. // Default route
  196. dr := &net.IPNet{IP: c.Cidr.IP.Mask(c.Cidr.Mask), Mask: c.Cidr.Mask}
  197. nr := netlink.Route{
  198. LinkIndex: link.Attrs().Index,
  199. Dst: dr,
  200. MTU: c.DefaultMTU,
  201. AdvMSS: c.advMSS(route{}),
  202. Scope: unix.RT_SCOPE_LINK,
  203. Src: c.Cidr.IP,
  204. Protocol: unix.RTPROT_KERNEL,
  205. Table: unix.RT_TABLE_MAIN,
  206. Type: unix.RTN_UNICAST,
  207. }
  208. err = netlink.RouteReplace(&nr)
  209. if err != nil {
  210. return fmt.Errorf("failed to set mtu %v on the default route %v; %v", c.DefaultMTU, dr, err)
  211. }
  212. // Path routes
  213. for _, r := range c.Routes {
  214. nr := netlink.Route{
  215. LinkIndex: link.Attrs().Index,
  216. Dst: r.route,
  217. MTU: r.mtu,
  218. AdvMSS: c.advMSS(r),
  219. Scope: unix.RT_SCOPE_LINK,
  220. }
  221. err = netlink.RouteAdd(&nr)
  222. if err != nil {
  223. return fmt.Errorf("failed to set mtu %v on route %v; %v", r.mtu, r.route, err)
  224. }
  225. }
  226. // Unsafe path routes
  227. for _, r := range c.UnsafeRoutes {
  228. nr := netlink.Route{
  229. LinkIndex: link.Attrs().Index,
  230. Dst: r.route,
  231. MTU: r.mtu,
  232. AdvMSS: c.advMSS(r),
  233. Scope: unix.RT_SCOPE_LINK,
  234. }
  235. err = netlink.RouteAdd(&nr)
  236. if err != nil {
  237. return fmt.Errorf("failed to set mtu %v on route %v; %v", r.mtu, r.route, err)
  238. }
  239. }
  240. // Run the interface
  241. ifrf.Flags = ifrf.Flags | unix.IFF_UP | unix.IFF_RUNNING
  242. if err = ioctl(fd, unix.SIOCSIFFLAGS, uintptr(unsafe.Pointer(&ifrf))); err != nil {
  243. return fmt.Errorf("failed to run tun device: %s", err)
  244. }
  245. return nil
  246. }
  247. func (c Tun) advMSS(r route) int {
  248. mtu := r.mtu
  249. if r.mtu == 0 {
  250. mtu = c.DefaultMTU
  251. }
  252. // We only need to set advmss if the route MTU does not match the device MTU
  253. if mtu != c.MaxMTU {
  254. return mtu - 40
  255. }
  256. return 0
  257. }