tun_windows.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. //go:build !e2e_testing
  2. package overlay
  3. import (
  4. "crypto"
  5. "errors"
  6. "fmt"
  7. "log/slog"
  8. "net/netip"
  9. "os"
  10. "path/filepath"
  11. "runtime"
  12. "slices"
  13. "sync/atomic"
  14. "syscall"
  15. "unsafe"
  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. "github.com/slackhq/nebula/wintun"
  22. "golang.org/x/sys/windows"
  23. "golang.zx2c4.com/wireguard/windows/tunnel/winipcfg"
  24. )
  25. type closer interface {
  26. Close()
  27. }
  28. const tunGUIDLabel = "Fixed Nebula Windows GUID v1"
  29. type winTun struct {
  30. Device string
  31. vpnNetworks []netip.Prefix
  32. MTU int
  33. Routes atomic.Pointer[[]Route]
  34. routeTree atomic.Pointer[bart.Table[routing.Gateways]]
  35. guid windows.GUID
  36. networkCategory networkCategory
  37. setCategory bool
  38. bypassWDF bool
  39. wdfBypass closer
  40. l *slog.Logger
  41. tun *wintun.NativeTun
  42. }
  43. func (t *winTun) Read(b []byte) (int, error) {
  44. return t.tun.Read(b, 0)
  45. }
  46. func newTunFromFd(_ *config.C, _ *slog.Logger, _ int, _ []netip.Prefix) (Device, error) {
  47. return nil, fmt.Errorf("newTunFromFd not supported in Windows")
  48. }
  49. func newTun(c *config.C, l *slog.Logger, vpnNetworks []netip.Prefix, _ bool) (*winTun, error) {
  50. err := checkWinTunExists()
  51. if err != nil {
  52. return nil, fmt.Errorf("can not load the wintun driver: %w", err)
  53. }
  54. deviceName := c.GetString("tun.dev", "")
  55. guid, err := generateGUIDByDeviceName(deviceName)
  56. if err != nil {
  57. return nil, fmt.Errorf("generate GUID failed: %w", err)
  58. }
  59. cat, setCat, err := parseNetworkCategory(c.GetString("tun.network_category", "private"))
  60. if err != nil {
  61. return nil, err
  62. }
  63. t := &winTun{
  64. Device: deviceName,
  65. vpnNetworks: vpnNetworks,
  66. MTU: getMTU(l, c),
  67. guid: *guid,
  68. networkCategory: cat,
  69. setCategory: setCat,
  70. bypassWDF: c.GetBool("tun.windows_bypass_wdf", true),
  71. l: l,
  72. }
  73. err = t.reload(c, true)
  74. if err != nil {
  75. return nil, err
  76. }
  77. var tunDevice wintun.Device
  78. tunDevice, err = wintun.CreateTUNWithRequestedGUID(deviceName, guid, t.MTU)
  79. if err != nil {
  80. // Windows 10 has an issue with unclean shutdowns not fully cleaning up the wintun device.
  81. // Trying a second time resolves the issue.
  82. l.Debug("Failed to create wintun device, retrying", "error", err)
  83. tunDevice, err = wintun.CreateTUNWithRequestedGUID(deviceName, guid, t.MTU)
  84. if err != nil {
  85. return nil, &NameError{
  86. Name: deviceName,
  87. Underlying: fmt.Errorf("create TUN device failed: %w", err),
  88. }
  89. }
  90. }
  91. t.tun = tunDevice.(*wintun.NativeTun)
  92. // Disable registration before Activate assigns addresses and triggers it.
  93. disableDNSRegistration(l, *guid)
  94. c.RegisterReloadCallback(func(c *config.C) {
  95. err := t.reload(c, false)
  96. if err != nil {
  97. util.LogWithContextIfNeeded("failed to reload tun device", err, t.l)
  98. }
  99. })
  100. return t, nil
  101. }
  102. func (t *winTun) reload(c *config.C, initial bool) error {
  103. change, routes, err := getAllRoutesFromConfig(t.l, c, t.vpnNetworks, initial)
  104. if err != nil {
  105. return err
  106. }
  107. if !initial && !change {
  108. return nil
  109. }
  110. routeTree, err := makeRouteTree(t.l, routes, false)
  111. if err != nil {
  112. return err
  113. }
  114. // Teach nebula how to handle the routes before establishing them in the system table
  115. oldRoutes := t.Routes.Swap(&routes)
  116. t.routeTree.Store(routeTree)
  117. if !initial {
  118. // Remove first, if the system removes a wanted route hopefully it will be re-added next
  119. err := t.removeRoutes(findRemovedSystemRoutes(routes, *oldRoutes))
  120. if err != nil {
  121. util.LogWithContextIfNeeded("Failed to remove routes", err, t.l)
  122. }
  123. // Ensure any routes we actually want are installed
  124. err = t.addRoutes(true)
  125. if err != nil {
  126. // Catch any stray logs
  127. util.LogWithContextIfNeeded("Failed to add routes", err, t.l)
  128. }
  129. }
  130. return nil
  131. }
  132. func (t *winTun) Activate() error {
  133. luid := winipcfg.LUID(t.tun.LUID())
  134. err := luid.SetIPAddresses(t.vpnNetworks)
  135. if err != nil {
  136. return fmt.Errorf("failed to set address: %w", err)
  137. }
  138. err = t.addRoutes(false)
  139. if err != nil {
  140. return err
  141. }
  142. if t.setCategory {
  143. // The wintun adapter takes a moment to register with the Network List
  144. // Manager, so we apply the category in the background and retry until
  145. // it shows up.
  146. go applyNetworkCategory(t.l, t.guid, t.networkCategory)
  147. }
  148. if t.bypassWDF {
  149. t.wdfBypass = installInterfaceBypass(t.l, uint64(t.tun.LUID()))
  150. }
  151. return nil
  152. }
  153. func (t *winTun) addRoutes(logErrors bool) error {
  154. luid := winipcfg.LUID(t.tun.LUID())
  155. routes := *t.Routes.Load()
  156. foundDefault4 := false
  157. carriesV6 := slices.ContainsFunc(t.vpnNetworks, func(p netip.Prefix) bool { return p.Addr().Is6() })
  158. // A CIDR listed twice routes by its last entry, install only that one or each reload would flip between them. The
  159. // same rule as systemRoutes
  160. last := make(map[netip.Prefix]int, len(routes))
  161. for i, r := range routes {
  162. last[r.Cidr] = i
  163. }
  164. for i, r := range routes {
  165. if len(r.Via) == 0 || !r.Install {
  166. // We don't allow route MTUs so only install routes with a via
  167. continue
  168. }
  169. if last[r.Cidr] != i {
  170. continue
  171. }
  172. // A v6 unsafe_route is legal under a v4-only cert; uninstalled ones put nothing on the adapter.
  173. carriesV6 = carriesV6 || r.Cidr.Addr().Is6()
  174. // Add our unsafe route as an on-link route to the nebula tun device.
  175. result, err := addRoute(luid, r)
  176. if err != nil {
  177. retErr := util.NewContextualError("Failed to add route", map[string]any{"route": r}, err)
  178. if logErrors {
  179. retErr.Log(t.l)
  180. continue
  181. } else {
  182. return retErr
  183. }
  184. } else {
  185. switch result {
  186. case routeAdded:
  187. t.l.Info("Added route", "route", r)
  188. case routeMetricUpdated:
  189. t.l.Info("Updated route metric", "route", r)
  190. }
  191. }
  192. if !foundDefault4 {
  193. if r.Cidr.Bits() == 0 && r.Cidr.Addr().BitLen() == 32 {
  194. foundDefault4 = true
  195. }
  196. }
  197. }
  198. return t.setMTU(luid, foundDefault4, carriesV6)
  199. }
  200. // setMTU applies tun.mtu per address family. The default route metric rides along on the v4 handle.
  201. func (t *winTun) setMTU(luid winipcfg.LUID, foundDefault4, carriesV6 bool) error {
  202. ipif, err := luid.IPInterface(windows.AF_INET)
  203. if err != nil {
  204. return fmt.Errorf("failed to get ip interface: %w", err)
  205. }
  206. ipif.NLMTU = uint32(t.MTU)
  207. if foundDefault4 {
  208. ipif.UseAutomaticMetric = false
  209. ipif.Metric = 0
  210. }
  211. if err := ipif.Set(); err != nil {
  212. return fmt.Errorf("failed to set ip interface: %w", err)
  213. }
  214. // Windows tracks NLMTU per family and wintun sets neither, so v6 keeps the adapter default of 65535.
  215. // Gated so a v4-only overlay under 1280 boots; a v6 one deliberately does not, as linux also refuses.
  216. if !carriesV6 {
  217. return nil
  218. }
  219. ipif6, err := luid.IPInterface(windows.AF_INET6)
  220. if err != nil {
  221. // No v6 on the adapter means there is no NLMTU to get wrong. A failed Set below is not the same thing.
  222. t.l.Info("Skipping ipv6 MTU, no ipv6 interface on this adapter", "error", err)
  223. return nil
  224. }
  225. ipif6.NLMTU = uint32(t.MTU)
  226. if err := ipif6.Set(); err != nil {
  227. return fmt.Errorf("failed to set ipv6 interface: %w", err)
  228. }
  229. return nil
  230. }
  231. func (t *winTun) removeRoutes(routes []Route) error {
  232. luid := winipcfg.LUID(t.tun.LUID())
  233. for _, r := range routes {
  234. if !r.Install {
  235. continue
  236. }
  237. // See comment on luid.AddRoute
  238. err := luid.DeleteRoute(r.Cidr, unspecifiedNextHop(r.Cidr))
  239. if err != nil {
  240. t.l.Error("Failed to remove route", "error", err, "route", r)
  241. } else {
  242. t.l.Info("Removed route", "route", r)
  243. }
  244. }
  245. return nil
  246. }
  247. func (t *winTun) RoutesFor(ip netip.Addr) routing.Gateways {
  248. r, _ := t.routeTree.Load().Lookup(ip)
  249. return r
  250. }
  251. func (t *winTun) Networks() []netip.Prefix {
  252. return t.vpnNetworks
  253. }
  254. func (t *winTun) Name() string {
  255. return t.Device
  256. }
  257. func (t *winTun) Write(b []byte) (int, error) {
  258. return t.tun.Write(b, 0)
  259. }
  260. func (t *winTun) Queues(int) ([]tio.Queue, error) {
  261. return []tio.Queue{tio.NewSingleQueue(t, defaultBatchBufSize)}, nil
  262. }
  263. func (t *winTun) Close() error {
  264. // It seems that the Windows networking stack doesn't like it when we destroy interfaces that have active routes,
  265. // so to be certain, just remove everything before destroying.
  266. luid := winipcfg.LUID(t.tun.LUID())
  267. _ = luid.FlushRoutes(windows.AF_INET)
  268. _ = luid.FlushIPAddresses(windows.AF_INET)
  269. _ = luid.FlushRoutes(windows.AF_INET6)
  270. _ = luid.FlushIPAddresses(windows.AF_INET6)
  271. _ = luid.FlushDNS(windows.AF_INET)
  272. _ = luid.FlushDNS(windows.AF_INET6)
  273. if t.wdfBypass != nil {
  274. t.wdfBypass.Close()
  275. t.wdfBypass = nil
  276. }
  277. return t.tun.Close()
  278. }
  279. // systemRoutes maps each CIDR to the route that puts it in the system table. A CIDR's last entry decides, including
  280. // one that says not to install it
  281. func systemRoutes(routes []Route) map[netip.Prefix]Route {
  282. out := make(map[netip.Prefix]Route, len(routes))
  283. for _, r := range routes {
  284. if len(r.Via) > 0 && r.Install {
  285. out[r.Cidr] = r
  286. } else {
  287. delete(out, r.Cidr)
  288. }
  289. }
  290. return out
  291. }
  292. // findRemovedSystemRoutes is the routes to delete from the system table. Windows deletes by destination and next hop,
  293. // so only a CIDR nothing installs anymore goes, a changed metric is set on the route in place by addRoute
  294. func findRemovedSystemRoutes(newRoutes, oldRoutes []Route) []Route {
  295. keep := systemRoutes(newRoutes)
  296. var removed []Route
  297. for _, r := range systemRoutes(oldRoutes) {
  298. if _, ok := keep[r.Cidr]; !ok {
  299. removed = append(removed, r)
  300. }
  301. }
  302. return removed
  303. }
  304. type routeResult int
  305. const (
  306. routeAdded routeResult = iota
  307. routeMetricUpdated
  308. routeAlreadyInstalled
  309. )
  310. // addRoute installs r on the interface. A reload re-adds every route to catch any the system dropped, and Windows
  311. // refuses one it has with the same destination and next hop whatever its metric. One that is there with another
  312. // metric, ours from before a metric change or someone else's, is brought to ours in place
  313. func addRoute(luid winipcfg.LUID, r Route) (routeResult, error) {
  314. nextHop := unspecifiedNextHop(r.Cidr)
  315. err := luid.AddRoute(r.Cidr, nextHop, uint32(r.Metric))
  316. if !errors.Is(err, windows.ERROR_OBJECT_ALREADY_EXISTS) {
  317. return routeAdded, err
  318. }
  319. row, err := luid.Route(r.Cidr, nextHop)
  320. if err != nil {
  321. return routeAlreadyInstalled, err
  322. }
  323. if row.Metric != uint32(r.Metric) {
  324. row.Metric = uint32(r.Metric)
  325. return routeMetricUpdated, row.Set()
  326. }
  327. return routeAlreadyInstalled, nil
  328. }
  329. func unspecifiedNextHop(p netip.Prefix) netip.Addr {
  330. if p.Addr().Is4() {
  331. return netip.IPv4Unspecified()
  332. }
  333. return netip.IPv6Unspecified()
  334. }
  335. func generateGUIDByDeviceName(name string) (*windows.GUID, error) {
  336. // GUID is 128 bit
  337. hash := crypto.MD5.New()
  338. _, err := hash.Write([]byte(tunGUIDLabel))
  339. if err != nil {
  340. return nil, err
  341. }
  342. _, err = hash.Write([]byte(name))
  343. if err != nil {
  344. return nil, err
  345. }
  346. sum := hash.Sum(nil)
  347. return (*windows.GUID)(unsafe.Pointer(&sum[0])), nil
  348. }
  349. func checkWinTunExists() error {
  350. myPath, err := os.Executable()
  351. if err != nil {
  352. return err
  353. }
  354. arch := runtime.GOARCH
  355. switch arch {
  356. case "386":
  357. //NOTE: wintun bundles 386 as x86
  358. arch = "x86"
  359. }
  360. _, err = syscall.LoadDLL(filepath.Join(filepath.Dir(myPath), "dist", "windows", "wintun", "bin", arch, "wintun.dll"))
  361. return err
  362. }