tun_windows.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. //go:build !e2e_testing
  2. // +build !e2e_testing
  3. package overlay
  4. import (
  5. "crypto"
  6. "fmt"
  7. "log/slog"
  8. "net/netip"
  9. "os"
  10. "path/filepath"
  11. "runtime"
  12. "sync/atomic"
  13. "syscall"
  14. "unsafe"
  15. "github.com/gaissmai/bart"
  16. "github.com/slackhq/nebula/config"
  17. "github.com/slackhq/nebula/overlay/tio"
  18. "github.com/slackhq/nebula/routing"
  19. "github.com/slackhq/nebula/util"
  20. "github.com/slackhq/nebula/wintun"
  21. "golang.org/x/sys/windows"
  22. "golang.zx2c4.com/wireguard/windows/tunnel/winipcfg"
  23. )
  24. type closer interface {
  25. Close()
  26. }
  27. const tunGUIDLabel = "Fixed Nebula Windows GUID v1"
  28. type winTun struct {
  29. Device string
  30. vpnNetworks []netip.Prefix
  31. MTU int
  32. Routes atomic.Pointer[[]Route]
  33. routeTree atomic.Pointer[bart.Table[routing.Gateways]]
  34. guid windows.GUID
  35. networkCategory networkCategory
  36. setCategory bool
  37. bypassWDF bool
  38. wdfBypass closer
  39. l *slog.Logger
  40. tun *wintun.NativeTun
  41. }
  42. func (t *winTun) Read(b []byte) (int, error) {
  43. return t.tun.Read(b, 0)
  44. }
  45. func newTunFromFd(_ *config.C, _ *slog.Logger, _ int, _ []netip.Prefix) (Device, error) {
  46. return nil, fmt.Errorf("newTunFromFd not supported in Windows")
  47. }
  48. func newTun(c *config.C, l *slog.Logger, vpnNetworks []netip.Prefix, _ bool) (*winTun, error) {
  49. err := checkWinTunExists()
  50. if err != nil {
  51. return nil, fmt.Errorf("can not load the wintun driver: %w", err)
  52. }
  53. deviceName := c.GetString("tun.dev", "")
  54. guid, err := generateGUIDByDeviceName(deviceName)
  55. if err != nil {
  56. return nil, fmt.Errorf("generate GUID failed: %w", err)
  57. }
  58. cat, setCat, err := parseNetworkCategory(c.GetString("tun.network_category", "private"))
  59. if err != nil {
  60. return nil, err
  61. }
  62. t := &winTun{
  63. Device: deviceName,
  64. vpnNetworks: vpnNetworks,
  65. MTU: c.GetInt("tun.mtu", DefaultMTU),
  66. guid: *guid,
  67. networkCategory: cat,
  68. setCategory: setCat,
  69. bypassWDF: c.GetBool("tun.windows_bypass_wdf", true),
  70. l: l,
  71. }
  72. err = t.reload(c, true)
  73. if err != nil {
  74. return nil, err
  75. }
  76. var tunDevice wintun.Device
  77. tunDevice, err = wintun.CreateTUNWithRequestedGUID(deviceName, guid, t.MTU)
  78. if err != nil {
  79. // Windows 10 has an issue with unclean shutdowns not fully cleaning up the wintun device.
  80. // Trying a second time resolves the issue.
  81. l.Debug("Failed to create wintun device, retrying", "error", err)
  82. tunDevice, err = wintun.CreateTUNWithRequestedGUID(deviceName, guid, t.MTU)
  83. if err != nil {
  84. return nil, &NameError{
  85. Name: deviceName,
  86. Underlying: fmt.Errorf("create TUN device failed: %w", err),
  87. }
  88. }
  89. }
  90. t.tun = tunDevice.(*wintun.NativeTun)
  91. c.RegisterReloadCallback(func(c *config.C) {
  92. err := t.reload(c, false)
  93. if err != nil {
  94. util.LogWithContextIfNeeded("failed to reload tun device", err, t.l)
  95. }
  96. })
  97. return t, nil
  98. }
  99. func (t *winTun) reload(c *config.C, initial bool) error {
  100. change, routes, err := getAllRoutesFromConfig(c, t.vpnNetworks, initial)
  101. if err != nil {
  102. return err
  103. }
  104. if !initial && !change {
  105. return nil
  106. }
  107. routeTree, err := makeRouteTree(t.l, routes, false)
  108. if err != nil {
  109. return err
  110. }
  111. // Teach nebula how to handle the routes before establishing them in the system table
  112. oldRoutes := t.Routes.Swap(&routes)
  113. t.routeTree.Store(routeTree)
  114. if !initial {
  115. // Remove first, if the system removes a wanted route hopefully it will be re-added next
  116. err := t.removeRoutes(findRemovedRoutes(routes, *oldRoutes))
  117. if err != nil {
  118. util.LogWithContextIfNeeded("Failed to remove routes", err, t.l)
  119. }
  120. // Ensure any routes we actually want are installed
  121. err = t.addRoutes(true)
  122. if err != nil {
  123. // Catch any stray logs
  124. util.LogWithContextIfNeeded("Failed to add routes", err, t.l)
  125. }
  126. }
  127. return nil
  128. }
  129. func (t *winTun) Activate() error {
  130. luid := winipcfg.LUID(t.tun.LUID())
  131. err := luid.SetIPAddresses(t.vpnNetworks)
  132. if err != nil {
  133. return fmt.Errorf("failed to set address: %w", err)
  134. }
  135. err = t.addRoutes(false)
  136. if err != nil {
  137. return err
  138. }
  139. if t.setCategory {
  140. // The wintun adapter takes a moment to register with the Network List
  141. // Manager, so we apply the category in the background and retry until
  142. // it shows up.
  143. go applyNetworkCategory(t.l, t.guid, t.networkCategory)
  144. }
  145. if t.bypassWDF {
  146. t.wdfBypass = installInterfaceBypass(t.l, uint64(t.tun.LUID()))
  147. }
  148. return nil
  149. }
  150. func (t *winTun) addRoutes(logErrors bool) error {
  151. luid := winipcfg.LUID(t.tun.LUID())
  152. routes := *t.Routes.Load()
  153. foundDefault4 := false
  154. for _, r := range routes {
  155. if len(r.Via) == 0 || !r.Install {
  156. // We don't allow route MTUs so only install routes with a via
  157. continue
  158. }
  159. // Add our unsafe route as an on-link route to the nebula tun device.
  160. err := luid.AddRoute(r.Cidr, unspecifiedNextHop(r.Cidr), uint32(r.Metric))
  161. if err != nil {
  162. retErr := util.NewContextualError("Failed to add route", map[string]any{"route": r}, err)
  163. if logErrors {
  164. retErr.Log(t.l)
  165. continue
  166. } else {
  167. return retErr
  168. }
  169. } else {
  170. t.l.Info("Added route", "route", r)
  171. }
  172. if !foundDefault4 {
  173. if r.Cidr.Bits() == 0 && r.Cidr.Addr().BitLen() == 32 {
  174. foundDefault4 = true
  175. }
  176. }
  177. }
  178. ipif, err := luid.IPInterface(windows.AF_INET)
  179. if err != nil {
  180. return fmt.Errorf("failed to get ip interface: %w", err)
  181. }
  182. ipif.NLMTU = uint32(t.MTU)
  183. if foundDefault4 {
  184. ipif.UseAutomaticMetric = false
  185. ipif.Metric = 0
  186. }
  187. if err := ipif.Set(); err != nil {
  188. return fmt.Errorf("failed to set ip interface: %w", err)
  189. }
  190. return nil
  191. }
  192. func (t *winTun) removeRoutes(routes []Route) error {
  193. luid := winipcfg.LUID(t.tun.LUID())
  194. for _, r := range routes {
  195. if !r.Install {
  196. continue
  197. }
  198. // See comment on luid.AddRoute
  199. err := luid.DeleteRoute(r.Cidr, unspecifiedNextHop(r.Cidr))
  200. if err != nil {
  201. t.l.Error("Failed to remove route", "error", err, "route", r)
  202. } else {
  203. t.l.Info("Removed route", "route", r)
  204. }
  205. }
  206. return nil
  207. }
  208. func (t *winTun) RoutesFor(ip netip.Addr) routing.Gateways {
  209. r, _ := t.routeTree.Load().Lookup(ip)
  210. return r
  211. }
  212. func (t *winTun) Networks() []netip.Prefix {
  213. return t.vpnNetworks
  214. }
  215. func (t *winTun) Name() string {
  216. return t.Device
  217. }
  218. func (t *winTun) Write(b []byte) (int, error) {
  219. return t.tun.Write(b, 0)
  220. }
  221. func (t *winTun) Queues(int) ([]tio.Queue, error) {
  222. return []tio.Queue{tio.NewSingleQueue(t, defaultBatchBufSize)}, nil
  223. }
  224. func (t *winTun) Close() error {
  225. // It seems that the Windows networking stack doesn't like it when we destroy interfaces that have active routes,
  226. // so to be certain, just remove everything before destroying.
  227. luid := winipcfg.LUID(t.tun.LUID())
  228. _ = luid.FlushRoutes(windows.AF_INET)
  229. _ = luid.FlushIPAddresses(windows.AF_INET)
  230. _ = luid.FlushRoutes(windows.AF_INET6)
  231. _ = luid.FlushIPAddresses(windows.AF_INET6)
  232. _ = luid.FlushDNS(windows.AF_INET)
  233. _ = luid.FlushDNS(windows.AF_INET6)
  234. if t.wdfBypass != nil {
  235. t.wdfBypass.Close()
  236. t.wdfBypass = nil
  237. }
  238. return t.tun.Close()
  239. }
  240. func unspecifiedNextHop(p netip.Prefix) netip.Addr {
  241. if p.Addr().Is4() {
  242. return netip.IPv4Unspecified()
  243. }
  244. return netip.IPv6Unspecified()
  245. }
  246. func generateGUIDByDeviceName(name string) (*windows.GUID, error) {
  247. // GUID is 128 bit
  248. hash := crypto.MD5.New()
  249. _, err := hash.Write([]byte(tunGUIDLabel))
  250. if err != nil {
  251. return nil, err
  252. }
  253. _, err = hash.Write([]byte(name))
  254. if err != nil {
  255. return nil, err
  256. }
  257. sum := hash.Sum(nil)
  258. return (*windows.GUID)(unsafe.Pointer(&sum[0])), nil
  259. }
  260. func checkWinTunExists() error {
  261. myPath, err := os.Executable()
  262. if err != nil {
  263. return err
  264. }
  265. arch := runtime.GOARCH
  266. switch arch {
  267. case "386":
  268. //NOTE: wintun bundles 386 as x86
  269. arch = "x86"
  270. }
  271. _, err = syscall.LoadDLL(filepath.Join(filepath.Dir(myPath), "dist", "windows", "wintun", "bin", arch, "wintun.dll"))
  272. return err
  273. }