tun_windows.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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, nil)
  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, r *config.Reload) {
  95. r.RestartRequiredIfChanged("tun.dev", "tun.mtu")
  96. // Compare with the running category, not the last config. A restart with one we can't parse would fail, so say
  97. // that now rather than ask for one, and going back to the running one after a bad reload needs no restart
  98. if cat, setCat, err := parseNetworkCategory(c.GetString("tun.network_category", "private")); err != nil {
  99. t.l.Error("Invalid tun.network_category, a restart with it would fail", "error", err)
  100. r.Failed()
  101. } else if cat != t.networkCategory || setCat != t.setCategory {
  102. r.RestartRequiredIfChanged("tun.network_category")
  103. }
  104. r.RestartRequiredIfChanged(interfaceBypassKeys...)
  105. err := t.reload(c, false, r)
  106. if err != nil {
  107. util.LogWithContextIfNeeded("failed to reload tun device", err, t.l)
  108. r.Failed()
  109. }
  110. })
  111. return t, nil
  112. }
  113. func (t *winTun) reload(c *config.C, initial bool, r *config.Reload) error {
  114. change, routes, err := getAllRoutesFromConfig(t.l, c, t.vpnNetworks, initial)
  115. if err != nil {
  116. return err
  117. }
  118. if !initial && !change {
  119. return nil
  120. }
  121. routeTree, err := makeRouteTree(t.l, routes, false)
  122. if err != nil {
  123. return err
  124. }
  125. // Teach nebula how to handle the routes before establishing them in the system table
  126. oldRoutes := t.Routes.Swap(&routes)
  127. t.routeTree.Store(routeTree)
  128. if !initial {
  129. // Remove first, if the system removes a wanted route hopefully it will be re-added next
  130. err := t.removeRoutes(findRemovedSystemRoutes(routes, *oldRoutes), r)
  131. if err != nil {
  132. util.LogWithContextIfNeeded("Failed to remove routes", err, t.l)
  133. r.Failed()
  134. }
  135. // Ensure any routes we actually want are installed
  136. err = t.addRoutes(true, r)
  137. if err != nil {
  138. // Catch any stray logs
  139. util.LogWithContextIfNeeded("Failed to add routes", err, t.l)
  140. r.Failed()
  141. }
  142. }
  143. return nil
  144. }
  145. func (t *winTun) Activate() error {
  146. luid := winipcfg.LUID(t.tun.LUID())
  147. err := luid.SetIPAddresses(t.vpnNetworks)
  148. if err != nil {
  149. return fmt.Errorf("failed to set address: %w", err)
  150. }
  151. err = t.addRoutes(false, nil)
  152. if err != nil {
  153. return err
  154. }
  155. if t.setCategory {
  156. // The wintun adapter takes a moment to register with the Network List
  157. // Manager, so we apply the category in the background and retry until
  158. // it shows up.
  159. go applyNetworkCategory(t.l, t.guid, t.networkCategory)
  160. }
  161. if t.bypassWDF {
  162. t.wdfBypass = installInterfaceBypass(t.l, uint64(t.tun.LUID()))
  163. }
  164. return nil
  165. }
  166. func (t *winTun) addRoutes(logErrors bool, rl *config.Reload) error {
  167. luid := winipcfg.LUID(t.tun.LUID())
  168. routes := *t.Routes.Load()
  169. foundDefault4 := false
  170. carriesV6 := slices.ContainsFunc(t.vpnNetworks, func(p netip.Prefix) bool { return p.Addr().Is6() })
  171. // A CIDR listed twice routes by its last entry, install only that one or each reload would flip between them. The
  172. // same rule as systemRoutes
  173. last := make(map[netip.Prefix]int, len(routes))
  174. for i, r := range routes {
  175. last[r.Cidr] = i
  176. }
  177. for i, r := range routes {
  178. if len(r.Via) == 0 || !r.Install {
  179. // We don't allow route MTUs so only install routes with a via
  180. continue
  181. }
  182. if last[r.Cidr] != i {
  183. continue
  184. }
  185. // A v6 unsafe_route is legal under a v4-only cert; uninstalled ones put nothing on the adapter.
  186. carriesV6 = carriesV6 || r.Cidr.Addr().Is6()
  187. // Add our unsafe route as an on-link route to the nebula tun device.
  188. result, err := addRoute(luid, r)
  189. if err != nil {
  190. retErr := util.NewContextualError("Failed to add route", map[string]any{"route": r}, err)
  191. if logErrors {
  192. retErr.Log(t.l)
  193. rl.Failed()
  194. continue
  195. } else {
  196. return retErr
  197. }
  198. } else {
  199. switch result {
  200. case routeAdded:
  201. t.l.Info("Added route", "route", r)
  202. case routeMetricUpdated:
  203. t.l.Info("Updated route metric", "route", r)
  204. }
  205. }
  206. if !foundDefault4 {
  207. if r.Cidr.Bits() == 0 && r.Cidr.Addr().BitLen() == 32 {
  208. foundDefault4 = true
  209. }
  210. }
  211. }
  212. return t.setMTU(luid, foundDefault4, carriesV6)
  213. }
  214. // setMTU applies tun.mtu per address family. The default route metric rides along on the v4 handle.
  215. func (t *winTun) setMTU(luid winipcfg.LUID, foundDefault4, carriesV6 bool) error {
  216. ipif, err := luid.IPInterface(windows.AF_INET)
  217. if err != nil {
  218. return fmt.Errorf("failed to get ip interface: %w", err)
  219. }
  220. ipif.NLMTU = uint32(t.MTU)
  221. if foundDefault4 {
  222. ipif.UseAutomaticMetric = false
  223. ipif.Metric = 0
  224. }
  225. if err := ipif.Set(); err != nil {
  226. return fmt.Errorf("failed to set ip interface: %w", err)
  227. }
  228. // Windows tracks NLMTU per family and wintun sets neither, so v6 keeps the adapter default of 65535.
  229. // Gated so a v4-only overlay under 1280 boots; a v6 one deliberately does not, as linux also refuses.
  230. if !carriesV6 {
  231. return nil
  232. }
  233. ipif6, err := luid.IPInterface(windows.AF_INET6)
  234. if err != nil {
  235. // No v6 on the adapter means there is no NLMTU to get wrong. A failed Set below is not the same thing.
  236. t.l.Info("Skipping ipv6 MTU, no ipv6 interface on this adapter", "error", err)
  237. return nil
  238. }
  239. ipif6.NLMTU = uint32(t.MTU)
  240. if err := ipif6.Set(); err != nil {
  241. return fmt.Errorf("failed to set ipv6 interface: %w", err)
  242. }
  243. return nil
  244. }
  245. func (t *winTun) removeRoutes(routes []Route, rl *config.Reload) error {
  246. luid := winipcfg.LUID(t.tun.LUID())
  247. for _, r := range routes {
  248. if !r.Install {
  249. continue
  250. }
  251. // See comment on luid.AddRoute
  252. err := luid.DeleteRoute(r.Cidr, unspecifiedNextHop(r.Cidr))
  253. if errors.Is(err, windows.ERROR_NOT_FOUND) {
  254. // Already gone, which is what we wanted
  255. t.l.Info("Route was already removed", "route", r)
  256. } else if err != nil {
  257. t.l.Error("Failed to remove route", "error", err, "route", r)
  258. rl.Failed()
  259. } else {
  260. t.l.Info("Removed route", "route", r)
  261. }
  262. }
  263. return nil
  264. }
  265. func (t *winTun) RoutesFor(ip netip.Addr) routing.Gateways {
  266. r, _ := t.routeTree.Load().Lookup(ip)
  267. return r
  268. }
  269. func (t *winTun) Networks() []netip.Prefix {
  270. return t.vpnNetworks
  271. }
  272. func (t *winTun) Name() string {
  273. return t.Device
  274. }
  275. func (t *winTun) Write(b []byte) (int, error) {
  276. return t.tun.Write(b, 0)
  277. }
  278. func (t *winTun) Queues(int) ([]tio.Queue, error) {
  279. return []tio.Queue{tio.NewSingleQueue(t, defaultBatchBufSize)}, nil
  280. }
  281. func (t *winTun) Close() error {
  282. // It seems that the Windows networking stack doesn't like it when we destroy interfaces that have active routes,
  283. // so to be certain, just remove everything before destroying.
  284. luid := winipcfg.LUID(t.tun.LUID())
  285. _ = luid.FlushRoutes(windows.AF_INET)
  286. _ = luid.FlushIPAddresses(windows.AF_INET)
  287. _ = luid.FlushRoutes(windows.AF_INET6)
  288. _ = luid.FlushIPAddresses(windows.AF_INET6)
  289. _ = luid.FlushDNS(windows.AF_INET)
  290. _ = luid.FlushDNS(windows.AF_INET6)
  291. if t.wdfBypass != nil {
  292. t.wdfBypass.Close()
  293. t.wdfBypass = nil
  294. }
  295. return t.tun.Close()
  296. }
  297. // systemRoutes maps each CIDR to the route that puts it in the system table. A CIDR's last entry decides, including
  298. // one that says not to install it
  299. func systemRoutes(routes []Route) map[netip.Prefix]Route {
  300. out := make(map[netip.Prefix]Route, len(routes))
  301. for _, r := range routes {
  302. if len(r.Via) > 0 && r.Install {
  303. out[r.Cidr] = r
  304. } else {
  305. delete(out, r.Cidr)
  306. }
  307. }
  308. return out
  309. }
  310. // findRemovedSystemRoutes is the routes to delete from the system table. Windows deletes by destination and next hop,
  311. // so only a CIDR nothing installs anymore goes, a changed metric is set on the route in place by addRoute
  312. func findRemovedSystemRoutes(newRoutes, oldRoutes []Route) []Route {
  313. keep := systemRoutes(newRoutes)
  314. var removed []Route
  315. for _, r := range systemRoutes(oldRoutes) {
  316. if _, ok := keep[r.Cidr]; !ok {
  317. removed = append(removed, r)
  318. }
  319. }
  320. return removed
  321. }
  322. type routeResult int
  323. const (
  324. routeAdded routeResult = iota
  325. routeMetricUpdated
  326. routeAlreadyInstalled
  327. )
  328. // addRoute installs r on the interface. A reload re-adds every route to catch any the system dropped, and Windows
  329. // refuses one it has with the same destination and next hop whatever its metric. One that is there with another
  330. // metric, ours from before a metric change or someone else's, is brought to ours in place
  331. func addRoute(luid winipcfg.LUID, r Route) (routeResult, error) {
  332. nextHop := unspecifiedNextHop(r.Cidr)
  333. err := luid.AddRoute(r.Cidr, nextHop, uint32(r.Metric))
  334. if !errors.Is(err, windows.ERROR_OBJECT_ALREADY_EXISTS) {
  335. return routeAdded, err
  336. }
  337. row, err := luid.Route(r.Cidr, nextHop)
  338. if err != nil {
  339. return routeAlreadyInstalled, err
  340. }
  341. if row.Metric != uint32(r.Metric) {
  342. row.Metric = uint32(r.Metric)
  343. return routeMetricUpdated, row.Set()
  344. }
  345. return routeAlreadyInstalled, nil
  346. }
  347. func unspecifiedNextHop(p netip.Prefix) netip.Addr {
  348. if p.Addr().Is4() {
  349. return netip.IPv4Unspecified()
  350. }
  351. return netip.IPv6Unspecified()
  352. }
  353. func generateGUIDByDeviceName(name string) (*windows.GUID, error) {
  354. // GUID is 128 bit
  355. hash := crypto.MD5.New()
  356. _, err := hash.Write([]byte(tunGUIDLabel))
  357. if err != nil {
  358. return nil, err
  359. }
  360. _, err = hash.Write([]byte(name))
  361. if err != nil {
  362. return nil, err
  363. }
  364. sum := hash.Sum(nil)
  365. return (*windows.GUID)(unsafe.Pointer(&sum[0])), nil
  366. }
  367. func checkWinTunExists() error {
  368. myPath, err := os.Executable()
  369. if err != nil {
  370. return err
  371. }
  372. arch := runtime.GOARCH
  373. switch arch {
  374. case "386":
  375. //NOTE: wintun bundles 386 as x86
  376. arch = "x86"
  377. }
  378. _, err = syscall.LoadDLL(filepath.Join(filepath.Dir(myPath), "dist", "windows", "wintun", "bin", arch, "wintun.dll"))
  379. return err
  380. }