tun_water_windows.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. package overlay
  2. import (
  3. "fmt"
  4. "io"
  5. "net"
  6. "net/netip"
  7. "os/exec"
  8. "strconv"
  9. "sync/atomic"
  10. "github.com/gaissmai/bart"
  11. "github.com/sirupsen/logrus"
  12. "github.com/slackhq/nebula/config"
  13. "github.com/slackhq/nebula/util"
  14. "github.com/songgao/water"
  15. )
  16. type waterTun struct {
  17. Device string
  18. cidr netip.Prefix
  19. MTU int
  20. Routes atomic.Pointer[[]Route]
  21. routeTree atomic.Pointer[bart.Table[netip.Addr]]
  22. l *logrus.Logger
  23. f *net.Interface
  24. *water.Interface
  25. }
  26. func newWaterTun(c *config.C, l *logrus.Logger, cidr netip.Prefix, _ bool) (*waterTun, error) {
  27. // NOTE: You cannot set the deviceName under Windows, so you must check tun.Device after calling .Activate()
  28. t := &waterTun{
  29. cidr: cidr,
  30. MTU: c.GetInt("tun.mtu", DefaultMTU),
  31. l: l,
  32. }
  33. err := t.reload(c, true)
  34. if err != nil {
  35. return nil, err
  36. }
  37. c.RegisterReloadCallback(func(c *config.C) {
  38. err := t.reload(c, false)
  39. if err != nil {
  40. util.LogWithContextIfNeeded("failed to reload tun device", err, t.l)
  41. }
  42. })
  43. return t, nil
  44. }
  45. func (t *waterTun) Activate() error {
  46. var err error
  47. t.Interface, err = water.New(water.Config{
  48. DeviceType: water.TUN,
  49. PlatformSpecificParams: water.PlatformSpecificParams{
  50. ComponentID: "tap0901",
  51. Network: t.cidr.String(),
  52. },
  53. })
  54. if err != nil {
  55. return fmt.Errorf("activate failed: %v", err)
  56. }
  57. t.Device = t.Interface.Name()
  58. // TODO use syscalls instead of exec.Command
  59. err = exec.Command(
  60. `C:\Windows\System32\netsh.exe`, "interface", "ipv4", "set", "address",
  61. fmt.Sprintf("name=%s", t.Device),
  62. "source=static",
  63. fmt.Sprintf("addr=%s", t.cidr.Addr()),
  64. fmt.Sprintf("mask=%s", net.CIDRMask(t.cidr.Bits(), t.cidr.Addr().BitLen())),
  65. "gateway=none",
  66. ).Run()
  67. if err != nil {
  68. return fmt.Errorf("failed to run 'netsh' to set address: %s", err)
  69. }
  70. err = exec.Command(
  71. `C:\Windows\System32\netsh.exe`, "interface", "ipv4", "set", "interface",
  72. t.Device,
  73. fmt.Sprintf("mtu=%d", t.MTU),
  74. ).Run()
  75. if err != nil {
  76. return fmt.Errorf("failed to run 'netsh' to set MTU: %s", err)
  77. }
  78. t.f, err = net.InterfaceByName(t.Device)
  79. if err != nil {
  80. return fmt.Errorf("failed to find interface named %s: %v", t.Device, err)
  81. }
  82. err = t.addRoutes(false)
  83. if err != nil {
  84. return err
  85. }
  86. return nil
  87. }
  88. func (t *waterTun) reload(c *config.C, initial bool) error {
  89. change, routes, err := getAllRoutesFromConfig(c, t.cidr, initial)
  90. if err != nil {
  91. return err
  92. }
  93. if !initial && !change {
  94. return nil
  95. }
  96. routeTree, err := makeRouteTree(t.l, routes, false)
  97. if err != nil {
  98. return err
  99. }
  100. // Teach nebula how to handle the routes before establishing them in the system table
  101. oldRoutes := t.Routes.Swap(&routes)
  102. t.routeTree.Store(routeTree)
  103. if !initial {
  104. // Remove first, if the system removes a wanted route hopefully it will be re-added next
  105. t.removeRoutes(findRemovedRoutes(routes, *oldRoutes))
  106. // Ensure any routes we actually want are installed
  107. err = t.addRoutes(true)
  108. if err != nil {
  109. // Catch any stray logs
  110. util.LogWithContextIfNeeded("Failed to set routes", err, t.l)
  111. } else {
  112. for _, r := range findRemovedRoutes(routes, *oldRoutes) {
  113. t.l.WithField("route", r).Info("Removed route")
  114. }
  115. }
  116. }
  117. return nil
  118. }
  119. func (t *waterTun) addRoutes(logErrors bool) error {
  120. // Path routes
  121. routes := *t.Routes.Load()
  122. for _, r := range routes {
  123. if !r.Via.IsValid() || !r.Install {
  124. // We don't allow route MTUs so only install routes with a via
  125. continue
  126. }
  127. err := exec.Command(
  128. "C:\\Windows\\System32\\route.exe", "add", r.Cidr.String(), r.Via.String(), "IF", strconv.Itoa(t.f.Index), "METRIC", strconv.Itoa(r.Metric),
  129. ).Run()
  130. if err != nil {
  131. retErr := util.NewContextualError("Failed to add route", map[string]interface{}{"route": r}, err)
  132. if logErrors {
  133. retErr.Log(t.l)
  134. } else {
  135. return retErr
  136. }
  137. } else {
  138. t.l.WithField("route", r).Info("Added route")
  139. }
  140. }
  141. return nil
  142. }
  143. func (t *waterTun) removeRoutes(routes []Route) {
  144. for _, r := range routes {
  145. if !r.Install {
  146. continue
  147. }
  148. err := exec.Command(
  149. "C:\\Windows\\System32\\route.exe", "delete", r.Cidr.String(), r.Via.String(), "IF", strconv.Itoa(t.f.Index), "METRIC", strconv.Itoa(r.Metric),
  150. ).Run()
  151. if err != nil {
  152. t.l.WithError(err).WithField("route", r).Error("Failed to remove route")
  153. } else {
  154. t.l.WithField("route", r).Info("Removed route")
  155. }
  156. }
  157. }
  158. func (t *waterTun) RouteFor(ip netip.Addr) netip.Addr {
  159. r, _ := t.routeTree.Load().Lookup(ip)
  160. return r
  161. }
  162. func (t *waterTun) Cidr() netip.Prefix {
  163. return t.cidr
  164. }
  165. func (t *waterTun) Name() string {
  166. return t.Device
  167. }
  168. func (t *waterTun) Close() error {
  169. if t.Interface == nil {
  170. return nil
  171. }
  172. return t.Interface.Close()
  173. }
  174. func (t *waterTun) NewMultiQueueReader() (io.ReadWriteCloser, error) {
  175. return nil, fmt.Errorf("TODO: multiqueue not implemented for windows")
  176. }