tun_windows.go 11 KB

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