userspace.go 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. package wgengine
  4. import (
  5. "bufio"
  6. "context"
  7. crand "crypto/rand"
  8. "errors"
  9. "fmt"
  10. "io"
  11. "maps"
  12. "math"
  13. "net/netip"
  14. "reflect"
  15. "runtime"
  16. "slices"
  17. "strings"
  18. "sync"
  19. "time"
  20. "github.com/tailscale/wireguard-go/device"
  21. "github.com/tailscale/wireguard-go/tun"
  22. "tailscale.com/control/controlknobs"
  23. "tailscale.com/drive"
  24. "tailscale.com/envknob"
  25. "tailscale.com/feature"
  26. "tailscale.com/feature/buildfeatures"
  27. "tailscale.com/health"
  28. "tailscale.com/ipn/ipnstate"
  29. "tailscale.com/net/dns"
  30. "tailscale.com/net/dns/resolver"
  31. "tailscale.com/net/ipset"
  32. "tailscale.com/net/netmon"
  33. "tailscale.com/net/packet"
  34. "tailscale.com/net/sockstats"
  35. "tailscale.com/net/tsaddr"
  36. "tailscale.com/net/tsdial"
  37. "tailscale.com/net/tstun"
  38. "tailscale.com/syncs"
  39. "tailscale.com/tailcfg"
  40. "tailscale.com/tstime/mono"
  41. "tailscale.com/types/dnstype"
  42. "tailscale.com/types/ipproto"
  43. "tailscale.com/types/key"
  44. "tailscale.com/types/logger"
  45. "tailscale.com/types/netmap"
  46. "tailscale.com/types/views"
  47. "tailscale.com/util/checkchange"
  48. "tailscale.com/util/clientmetric"
  49. "tailscale.com/util/eventbus"
  50. "tailscale.com/util/mak"
  51. "tailscale.com/util/set"
  52. "tailscale.com/util/testenv"
  53. "tailscale.com/util/usermetric"
  54. "tailscale.com/version"
  55. "tailscale.com/wgengine/filter"
  56. "tailscale.com/wgengine/magicsock"
  57. "tailscale.com/wgengine/netlog"
  58. "tailscale.com/wgengine/netstack/gro"
  59. "tailscale.com/wgengine/router"
  60. "tailscale.com/wgengine/wgcfg"
  61. "tailscale.com/wgengine/wgint"
  62. "tailscale.com/wgengine/wglog"
  63. )
  64. // Lazy wireguard-go configuration parameters.
  65. const (
  66. // lazyPeerIdleThreshold is the idle duration after
  67. // which we remove a peer from the wireguard configuration.
  68. // (This includes peers that have never been idle, which
  69. // effectively have infinite idleness)
  70. lazyPeerIdleThreshold = 5 * time.Minute
  71. // packetSendTimeUpdateFrequency controls how often we record
  72. // the time that we wrote a packet to an IP address.
  73. packetSendTimeUpdateFrequency = 10 * time.Second
  74. // packetSendRecheckWireguardThreshold controls how long we can go
  75. // between packet sends to an IP before checking to see
  76. // whether this IP address needs to be added back to the
  77. // WireGuard peer oconfig.
  78. packetSendRecheckWireguardThreshold = 1 * time.Minute
  79. )
  80. // statusPollInterval is how often we ask wireguard-go for its engine
  81. // status (as long as there's activity). See docs on its use below.
  82. const statusPollInterval = 1 * time.Minute
  83. // networkLoggerUploadTimeout is the maximum timeout to wait when
  84. // shutting down the network logger as it uploads the last network log messages.
  85. const networkLoggerUploadTimeout = 5 * time.Second
  86. type userspaceEngine struct {
  87. // eventBus will eventually become required, but for now may be nil.
  88. eventBus *eventbus.Bus
  89. eventClient *eventbus.Client
  90. logf logger.Logf
  91. wgLogger *wglog.Logger // a wireguard-go logging wrapper
  92. reqCh chan struct{}
  93. waitCh chan struct{} // chan is closed when first Close call completes; contrast with closing bool
  94. timeNow func() mono.Time
  95. tundev *tstun.Wrapper
  96. wgdev *device.Device
  97. router router.Router
  98. dialer *tsdial.Dialer
  99. confListenPort uint16 // original conf.ListenPort
  100. dns *dns.Manager
  101. magicConn *magicsock.Conn
  102. netMon *netmon.Monitor
  103. health *health.Tracker
  104. netMonOwned bool // whether we created netMon (and thus need to close it)
  105. birdClient BIRDClient // or nil
  106. controlKnobs *controlknobs.Knobs // or nil
  107. testMaybeReconfigHook func() // for tests; if non-nil, fires if maybeReconfigWireguardLocked called
  108. // isLocalAddr reports the whether an IP is assigned to the local
  109. // tunnel interface. It's used to reflect local packets
  110. // incorrectly sent to us.
  111. isLocalAddr syncs.AtomicValue[func(netip.Addr) bool]
  112. // isDNSIPOverTailscale reports the whether a DNS resolver's IP
  113. // is being routed over Tailscale.
  114. isDNSIPOverTailscale syncs.AtomicValue[func(netip.Addr) bool]
  115. wgLock sync.Mutex // serializes all wgdev operations; see lock order comment below
  116. lastCfgFull wgcfg.Config
  117. lastNMinPeers int
  118. lastRouter *router.Config
  119. lastEngineFull *wgcfg.Config // of full wireguard config, not trimmed
  120. lastEngineInputs *maybeReconfigInputs
  121. lastDNSConfig dns.ConfigView // or invalid if none
  122. lastIsSubnetRouter bool // was the node a primary subnet router in the last run.
  123. recvActivityAt map[key.NodePublic]mono.Time
  124. trimmedNodes map[key.NodePublic]bool // set of node keys of peers currently excluded from wireguard config
  125. sentActivityAt map[netip.Addr]*mono.Time // value is accessed atomically
  126. destIPActivityFuncs map[netip.Addr]func()
  127. lastStatusPollTime mono.Time // last time we polled the engine status
  128. reconfigureVPN func() error // or nil
  129. mu sync.Mutex // guards following; see lock order comment below
  130. netMap *netmap.NetworkMap // or nil
  131. closing bool // Close was called (even if we're still closing)
  132. statusCallback StatusCallback
  133. peerSequence []key.NodePublic
  134. endpoints []tailcfg.Endpoint
  135. pendOpen map[flowtrackTuple]*pendingOpenFlow // see pendopen.go
  136. // pongCallback is the map of response handlers waiting for disco or TSMP
  137. // pong callbacks. The map key is a random slice of bytes.
  138. pongCallback map[[8]byte]func(packet.TSMPPongReply)
  139. // icmpEchoResponseCallback is the map of response handlers waiting for ICMP
  140. // echo responses. The map key is a random uint32 that is the little endian
  141. // value of the ICMP identifier and sequence number concatenated.
  142. icmpEchoResponseCallback map[uint32]func()
  143. // networkLogger logs statistics about network connections.
  144. networkLogger netlog.Logger
  145. // Lock ordering: magicsock.Conn.mu, wgLock, then mu.
  146. }
  147. // BIRDClient handles communication with the BIRD Internet Routing Daemon.
  148. type BIRDClient interface {
  149. EnableProtocol(proto string) error
  150. DisableProtocol(proto string) error
  151. Close() error
  152. }
  153. // Config is the engine configuration.
  154. type Config struct {
  155. // Tun is the device used by the Engine to exchange packets with
  156. // the OS.
  157. // If nil, a fake Device that does nothing is used.
  158. Tun tun.Device
  159. // IsTAP is whether Tun is actually a TAP (Layer 2) device that'll
  160. // require ethernet headers.
  161. IsTAP bool
  162. // Router interfaces the Engine to the OS network stack.
  163. // If nil, a fake Router that does nothing is used.
  164. Router router.Router
  165. // DNS interfaces the Engine to the OS DNS resolver configuration.
  166. // If nil, a fake OSConfigurator that does nothing is used.
  167. DNS dns.OSConfigurator
  168. // ReconfigureVPN provides an optional hook for platforms like Android to
  169. // know when it's time to reconfigure their VPN implementation. Such
  170. // platforms can only set their entire VPN configuration (routes, DNS, etc)
  171. // at all once and can't make piecemeal incremental changes, so this
  172. // provides a hook to "flush" a batch of Router and/or DNS changes.
  173. ReconfigureVPN func() error
  174. // NetMon optionally provides an existing network monitor to re-use.
  175. // If nil, a new network monitor is created.
  176. NetMon *netmon.Monitor
  177. // HealthTracker, if non-nil, is the health tracker to use.
  178. HealthTracker *health.Tracker
  179. // Metrics is the usermetrics registry to use.
  180. // Mandatory, if not set, an error is returned.
  181. Metrics *usermetric.Registry
  182. // Dialer is the dialer to use for outbound connections.
  183. // If nil, a new Dialer is created.
  184. Dialer *tsdial.Dialer
  185. // ControlKnobs is the set of control plane-provied knobs
  186. // to use.
  187. // If nil, defaults are used.
  188. ControlKnobs *controlknobs.Knobs
  189. // ListenPort is the port on which the engine will listen.
  190. // If zero, a port is automatically selected.
  191. ListenPort uint16
  192. // RespondToPing determines whether this engine should internally
  193. // reply to ICMP pings, without involving the OS.
  194. // Used in "fake" mode for development.
  195. RespondToPing bool
  196. // BIRDClient, if non-nil, will be used to configure BIRD whenever
  197. // this node is a primary subnet router.
  198. BIRDClient BIRDClient
  199. // SetSubsystem, if non-nil, is called for each new subsystem created, just before a successful return.
  200. SetSubsystem func(any)
  201. // DriveForLocal, if populated, will cause the engine to expose a Taildrive
  202. // listener at 100.100.100.100:8080.
  203. DriveForLocal drive.FileSystemForLocal
  204. // EventBus, if non-nil, is used for event publication and subscription by
  205. // the Engine and its subsystems.
  206. //
  207. // TODO(creachadair): As of 2025-03-19 this is optional, but is intended to
  208. // become required non-nil.
  209. EventBus *eventbus.Bus
  210. }
  211. // NewFakeUserspaceEngine returns a new userspace engine for testing.
  212. //
  213. // The opts may contain the following types:
  214. //
  215. // - int or uint16: to set the ListenPort.
  216. func NewFakeUserspaceEngine(logf logger.Logf, opts ...any) (Engine, error) {
  217. conf := Config{
  218. RespondToPing: true,
  219. }
  220. for _, o := range opts {
  221. switch v := o.(type) {
  222. case uint16:
  223. conf.ListenPort = v
  224. case int:
  225. if v < 0 || v > math.MaxUint16 {
  226. return nil, fmt.Errorf("invalid ListenPort: %d", v)
  227. }
  228. conf.ListenPort = uint16(v)
  229. case func(any):
  230. conf.SetSubsystem = v
  231. case *controlknobs.Knobs:
  232. conf.ControlKnobs = v
  233. case *health.Tracker:
  234. conf.HealthTracker = v
  235. case *usermetric.Registry:
  236. conf.Metrics = v
  237. case *eventbus.Bus:
  238. conf.EventBus = v
  239. default:
  240. return nil, fmt.Errorf("unknown option type %T", v)
  241. }
  242. }
  243. logf("Starting userspace WireGuard engine (with fake TUN device)")
  244. return NewUserspaceEngine(logf, conf)
  245. }
  246. // NewUserspaceEngine creates the named tun device and returns a
  247. // Tailscale Engine running on it.
  248. func NewUserspaceEngine(logf logger.Logf, conf Config) (_ Engine, reterr error) {
  249. var closePool closeOnErrorPool
  250. defer closePool.closeAllIfError(&reterr)
  251. if testenv.InTest() && conf.HealthTracker == nil {
  252. panic("NewUserspaceEngine called without HealthTracker (being strict in tests)")
  253. }
  254. if conf.Metrics == nil {
  255. return nil, errors.New("NewUserspaceEngine: opts.Metrics is required, please pass a *usermetric.Registry")
  256. }
  257. if conf.Tun == nil {
  258. logf("[v1] using fake (no-op) tun device")
  259. conf.Tun = tstun.NewFake()
  260. }
  261. if conf.Router == nil {
  262. logf("[v1] using fake (no-op) OS network configurator")
  263. conf.Router = router.NewFake(logf)
  264. }
  265. if conf.DNS == nil {
  266. logf("[v1] using fake (no-op) DNS configurator")
  267. d, err := dns.NewNoopManager()
  268. if err != nil {
  269. return nil, err
  270. }
  271. conf.DNS = d
  272. }
  273. if conf.Dialer == nil {
  274. conf.Dialer = &tsdial.Dialer{Logf: logf}
  275. if conf.EventBus != nil {
  276. conf.Dialer.SetBus(conf.EventBus)
  277. }
  278. }
  279. var tsTUNDev *tstun.Wrapper
  280. if conf.IsTAP {
  281. tsTUNDev = tstun.WrapTAP(logf, conf.Tun, conf.Metrics)
  282. } else {
  283. tsTUNDev = tstun.Wrap(logf, conf.Tun, conf.Metrics)
  284. }
  285. closePool.add(tsTUNDev)
  286. rtr := conf.Router
  287. if version.IsMobile() {
  288. // Android and iOS don't handle large numbers of routes well, so we
  289. // wrap the Router with one that consolidates routes down to the
  290. // smallest number possible.
  291. //
  292. // On Android, too many routes at VPN configuration time result in an
  293. // android.os.TransactionTooLargeException because Android's VPNBuilder
  294. // tries to send the entire set of routes to the VPNService as a single
  295. // Bundle, which is typically limited to 1 MB. The number of routes
  296. // that's too much seems to be very roughly around 4000.
  297. //
  298. // On iOS, the VPNExtension is limited to only 50 MB of memory, so
  299. // keeping the number of routes down helps with memory consumption.
  300. rtr = router.ConsolidatingRoutes(logf, rtr)
  301. }
  302. e := &userspaceEngine{
  303. eventBus: conf.EventBus,
  304. timeNow: mono.Now,
  305. logf: logf,
  306. reqCh: make(chan struct{}, 1),
  307. waitCh: make(chan struct{}),
  308. tundev: tsTUNDev,
  309. router: rtr,
  310. dialer: conf.Dialer,
  311. confListenPort: conf.ListenPort,
  312. birdClient: conf.BIRDClient,
  313. controlKnobs: conf.ControlKnobs,
  314. reconfigureVPN: conf.ReconfigureVPN,
  315. health: conf.HealthTracker,
  316. }
  317. if e.birdClient != nil {
  318. // Disable the protocol at start time.
  319. if err := e.birdClient.DisableProtocol("tailscale"); err != nil {
  320. return nil, err
  321. }
  322. }
  323. e.isLocalAddr.Store(ipset.FalseContainsIPFunc())
  324. e.isDNSIPOverTailscale.Store(ipset.FalseContainsIPFunc())
  325. if conf.NetMon != nil {
  326. e.netMon = conf.NetMon
  327. } else {
  328. mon, err := netmon.New(conf.EventBus, logf)
  329. if err != nil {
  330. return nil, err
  331. }
  332. closePool.add(mon)
  333. e.netMon = mon
  334. e.netMonOwned = true
  335. }
  336. tunName, _ := conf.Tun.Name()
  337. conf.Dialer.SetTUNName(tunName)
  338. conf.Dialer.SetNetMon(e.netMon)
  339. conf.Dialer.SetBus(e.eventBus)
  340. e.dns = dns.NewManager(logf, conf.DNS, e.health, conf.Dialer, fwdDNSLinkSelector{e, tunName}, conf.ControlKnobs, runtime.GOOS)
  341. // TODO: there's probably a better place for this
  342. sockstats.SetNetMon(e.netMon)
  343. logf("link state: %+v", e.netMon.InterfaceState())
  344. endpointsFn := func(endpoints []tailcfg.Endpoint) {
  345. e.mu.Lock()
  346. e.endpoints = append(e.endpoints[:0], endpoints...)
  347. e.mu.Unlock()
  348. e.RequestStatus()
  349. }
  350. magicsockOpts := magicsock.Options{
  351. EventBus: e.eventBus,
  352. Logf: logf,
  353. Port: conf.ListenPort,
  354. EndpointsFunc: endpointsFn,
  355. DERPActiveFunc: e.RequestStatus,
  356. IdleFunc: e.tundev.IdleDuration,
  357. NetMon: e.netMon,
  358. HealthTracker: e.health,
  359. Metrics: conf.Metrics,
  360. ControlKnobs: conf.ControlKnobs,
  361. PeerByKeyFunc: e.PeerByKey,
  362. }
  363. if buildfeatures.HasLazyWG {
  364. magicsockOpts.NoteRecvActivity = e.noteRecvActivity
  365. }
  366. var err error
  367. e.magicConn, err = magicsock.NewConn(magicsockOpts)
  368. if err != nil {
  369. return nil, fmt.Errorf("wgengine: %v", err)
  370. }
  371. closePool.add(e.magicConn)
  372. e.magicConn.SetNetworkUp(e.netMon.InterfaceState().AnyInterfaceUp())
  373. tsTUNDev.SetDiscoKey(e.magicConn.DiscoPublicKey())
  374. if conf.RespondToPing {
  375. e.tundev.PostFilterPacketInboundFromWireGuard = echoRespondToAll
  376. }
  377. e.tundev.PreFilterPacketOutboundToWireGuardEngineIntercept = e.handleLocalPackets
  378. if buildfeatures.HasDebug && envknob.BoolDefaultTrue("TS_DEBUG_CONNECT_FAILURES") {
  379. if e.tundev.PreFilterPacketInboundFromWireGuard != nil {
  380. return nil, errors.New("unexpected PreFilterIn already set")
  381. }
  382. e.tundev.PreFilterPacketInboundFromWireGuard = e.trackOpenPreFilterIn
  383. if e.tundev.PostFilterPacketOutboundToWireGuard != nil {
  384. return nil, errors.New("unexpected PostFilterOut already set")
  385. }
  386. e.tundev.PostFilterPacketOutboundToWireGuard = e.trackOpenPostFilterOut
  387. }
  388. e.wgLogger = wglog.NewLogger(logf)
  389. e.tundev.OnTSMPPongReceived = func(pong packet.TSMPPongReply) {
  390. e.mu.Lock()
  391. defer e.mu.Unlock()
  392. cb := e.pongCallback[pong.Data]
  393. e.logf("wgengine: got TSMP pong %02x, peerAPIPort=%v; cb=%v", pong.Data, pong.PeerAPIPort, cb != nil)
  394. if cb != nil {
  395. go cb(pong)
  396. }
  397. }
  398. e.tundev.OnICMPEchoResponseReceived = func(p *packet.Parsed) bool {
  399. idSeq := p.EchoIDSeq()
  400. e.mu.Lock()
  401. defer e.mu.Unlock()
  402. cb := e.icmpEchoResponseCallback[idSeq]
  403. if cb == nil {
  404. // We didn't swallow it, so let it flow to the host.
  405. return false
  406. }
  407. e.logf("wgengine: got diagnostic ICMP response %02x", idSeq)
  408. go cb()
  409. return true
  410. }
  411. // wgdev takes ownership of tundev, will close it when closed.
  412. e.logf("Creating WireGuard device...")
  413. e.wgdev = wgcfg.NewDevice(e.tundev, e.magicConn.Bind(), e.wgLogger.DeviceLogger)
  414. closePool.addFunc(e.wgdev.Close)
  415. closePool.addFunc(func() {
  416. if err := e.magicConn.Close(); err != nil {
  417. e.logf("error closing magicconn: %v", err)
  418. }
  419. })
  420. go func() {
  421. up := false
  422. for event := range e.tundev.EventsUpDown() {
  423. if event&tun.EventUp != 0 && !up {
  424. e.logf("external route: up")
  425. e.RequestStatus()
  426. up = true
  427. }
  428. if event&tun.EventDown != 0 && up {
  429. e.logf("external route: down")
  430. e.RequestStatus()
  431. up = false
  432. }
  433. }
  434. }()
  435. go func() {
  436. select {
  437. case <-e.wgdev.Wait():
  438. e.mu.Lock()
  439. closing := e.closing
  440. e.mu.Unlock()
  441. if !closing {
  442. e.logf("Closing the engine because the WireGuard device has been closed...")
  443. e.Close()
  444. }
  445. case <-e.waitCh:
  446. // continue
  447. }
  448. }()
  449. e.logf("Bringing WireGuard device up...")
  450. if err := e.wgdev.Up(); err != nil {
  451. return nil, fmt.Errorf("wgdev.Up: %w", err)
  452. }
  453. e.logf("Bringing router up...")
  454. if err := e.router.Up(); err != nil {
  455. return nil, fmt.Errorf("router.Up: %w", err)
  456. }
  457. tsTUNDev.SetLinkFeaturesPostUp()
  458. // It's a little pointless to apply no-op settings here (they
  459. // should already be empty?), but it at least exercises the
  460. // router implementation early on.
  461. e.logf("Clearing router settings...")
  462. if err := e.router.Set(nil); err != nil {
  463. return nil, fmt.Errorf("router.Set(nil): %w", err)
  464. }
  465. e.logf("Starting network monitor...")
  466. e.netMon.Start()
  467. if conf.SetSubsystem != nil {
  468. conf.SetSubsystem(e.tundev)
  469. conf.SetSubsystem(e.magicConn)
  470. conf.SetSubsystem(e.dns)
  471. conf.SetSubsystem(conf.Router)
  472. conf.SetSubsystem(conf.Dialer)
  473. conf.SetSubsystem(e.netMon)
  474. if conf.DriveForLocal != nil {
  475. conf.SetSubsystem(conf.DriveForLocal)
  476. }
  477. }
  478. ec := e.eventBus.Client("userspaceEngine")
  479. eventbus.SubscribeFunc(ec, func(cd netmon.ChangeDelta) {
  480. if f, ok := feature.HookProxyInvalidateCache.GetOk(); ok {
  481. f()
  482. }
  483. e.linkChange(&cd)
  484. })
  485. e.eventClient = ec
  486. e.logf("Engine created.")
  487. return e, nil
  488. }
  489. // echoRespondToAll is an inbound post-filter responding to all echo requests.
  490. func echoRespondToAll(p *packet.Parsed, t *tstun.Wrapper, gro *gro.GRO) (filter.Response, *gro.GRO) {
  491. if p.IsEchoRequest() {
  492. header := p.ICMP4Header()
  493. header.ToResponse()
  494. outp := packet.Generate(&header, p.Payload())
  495. t.InjectOutbound(outp)
  496. // We already responded to it, but it's not an error.
  497. // Proceed with regular delivery. (Since this code is only
  498. // used in fake mode, regular delivery just means throwing
  499. // it away. If this ever gets run in non-fake mode, you'll
  500. // get double responses to pings, which is an indicator you
  501. // shouldn't be doing that I guess.)
  502. return filter.Accept, gro
  503. }
  504. return filter.Accept, gro
  505. }
  506. // handleLocalPackets inspects packets coming from the local network
  507. // stack, and intercepts any packets that should be handled by
  508. // tailscaled directly. Other packets are allowed to proceed into the
  509. // main ACL filter.
  510. func (e *userspaceEngine) handleLocalPackets(p *packet.Parsed, t *tstun.Wrapper) filter.Response {
  511. if runtime.GOOS == "darwin" || runtime.GOOS == "ios" {
  512. isLocalAddr, ok := e.isLocalAddr.LoadOk()
  513. if !ok {
  514. e.logf("[unexpected] e.isLocalAddr was nil, can't check for loopback packet")
  515. } else if isLocalAddr(p.Dst.Addr()) {
  516. // macOS NetworkExtension directs packets destined to the
  517. // tunnel's local IP address into the tunnel, instead of
  518. // looping back within the kernel network stack. We have to
  519. // notice that an outbound packet is actually destined for
  520. // ourselves, and loop it back into macOS.
  521. t.InjectInboundCopy(p.Buffer())
  522. metricReflectToOS.Add(1)
  523. return filter.Drop
  524. }
  525. }
  526. if runtime.GOOS == "plan9" {
  527. isLocalAddr, ok := e.isLocalAddr.LoadOk()
  528. if ok {
  529. if isLocalAddr(p.Dst.Addr()) {
  530. // On Plan9's "tun" equivalent, everything goes back in and out
  531. // the tun, even when the kernel's replying to itself.
  532. t.InjectInboundCopy(p.Buffer())
  533. return filter.Drop
  534. }
  535. }
  536. }
  537. return filter.Accept
  538. }
  539. var debugTrimWireguard = envknob.RegisterOptBool("TS_DEBUG_TRIM_WIREGUARD")
  540. // forceFullWireguardConfig reports whether we should give wireguard our full
  541. // network map, even for inactive peers.
  542. //
  543. // TODO(bradfitz): remove this at some point. We had a TODO to do it before 1.0
  544. // but it's still there as of 1.30. Really we should not do this wireguard lazy
  545. // peer config at all and just fix wireguard-go to not have so much extra memory
  546. // usage per peer. That would simplify a lot of Tailscale code. OTOH, we have 50
  547. // MB of memory on iOS now instead of 15 MB, so the other option is to just give
  548. // up on lazy wireguard config and blow the memory and hope for the best on iOS.
  549. // That's sad too. Or we get rid of these knobs (lazy wireguard config has been
  550. // stable!) but I'm worried that a future regression would be easier to debug
  551. // with these knobs in place.
  552. func (e *userspaceEngine) forceFullWireguardConfig(numPeers int) bool {
  553. // Did the user explicitly enable trimming via the environment variable knob?
  554. if b, ok := debugTrimWireguard().Get(); ok {
  555. return !b
  556. }
  557. return e.controlKnobs != nil && e.controlKnobs.KeepFullWGConfig.Load()
  558. }
  559. // isTrimmablePeer reports whether p is a peer that we can trim out of the
  560. // network map.
  561. //
  562. // For implementation simplicity, we can only trim peers that have
  563. // only non-subnet AllowedIPs (an IPv4 /32 or IPv6 /128), which is the
  564. // common case for most peers. Subnet router nodes will just always be
  565. // created in the wireguard-go config.
  566. func (e *userspaceEngine) isTrimmablePeer(p *wgcfg.Peer, numPeers int) bool {
  567. if e.forceFullWireguardConfig(numPeers) {
  568. return false
  569. }
  570. // AllowedIPs must all be single IPs, not subnets.
  571. for _, aip := range p.AllowedIPs {
  572. if !aip.IsSingleIP() {
  573. return false
  574. }
  575. }
  576. return true
  577. }
  578. // noteRecvActivity is called by magicsock when a packet has been
  579. // received for the peer with node key nk. Magicsock calls this no
  580. // more than every 10 seconds for a given peer.
  581. func (e *userspaceEngine) noteRecvActivity(nk key.NodePublic) {
  582. e.wgLock.Lock()
  583. defer e.wgLock.Unlock()
  584. if _, ok := e.recvActivityAt[nk]; !ok {
  585. // Not a trimmable peer we care about tracking. (See isTrimmablePeer)
  586. if e.trimmedNodes[nk] {
  587. e.logf("wgengine: [unexpected] noteReceiveActivity called on idle node %v that's not in recvActivityAt", nk.ShortString())
  588. }
  589. return
  590. }
  591. now := e.timeNow()
  592. e.recvActivityAt[nk] = now
  593. // As long as there's activity, periodically poll the engine to get
  594. // stats for the far away side effect of
  595. // ipn/ipnlocal.LocalBackend.parseWgStatusLocked to log activity, for
  596. // use in various admin dashboards.
  597. // This particularly matters on platforms without a connected GUI, as
  598. // the GUIs generally poll this enough to cause that logging. But
  599. // tailscaled alone did not, hence this.
  600. if e.lastStatusPollTime.IsZero() || now.Sub(e.lastStatusPollTime) >= statusPollInterval {
  601. e.lastStatusPollTime = now
  602. go e.RequestStatus()
  603. }
  604. // If the last activity time jumped a bunch (say, at least
  605. // half the idle timeout) then see if we need to reprogram
  606. // WireGuard. This could probably be just
  607. // lazyPeerIdleThreshold without the divide by 2, but
  608. // maybeReconfigWireguardLocked is cheap enough to call every
  609. // couple minutes (just not on every packet).
  610. if e.trimmedNodes[nk] {
  611. e.logf("wgengine: idle peer %v now active, reconfiguring WireGuard", nk.ShortString())
  612. e.maybeReconfigWireguardLocked(nil)
  613. }
  614. }
  615. // isActiveSinceLocked reports whether the peer identified by (nk, ip)
  616. // has had a packet sent to or received from it since t.
  617. //
  618. // e.wgLock must be held.
  619. func (e *userspaceEngine) isActiveSinceLocked(nk key.NodePublic, ip netip.Addr, t mono.Time) bool {
  620. if e.recvActivityAt[nk].After(t) {
  621. return true
  622. }
  623. timePtr, ok := e.sentActivityAt[ip]
  624. if !ok {
  625. return false
  626. }
  627. return timePtr.LoadAtomic().After(t)
  628. }
  629. // maybeReconfigInputs holds the inputs to the maybeReconfigWireguardLocked
  630. // function. If these things don't change between calls, there's nothing to do.
  631. type maybeReconfigInputs struct {
  632. WGConfig *wgcfg.Config
  633. TrimmedNodes map[key.NodePublic]bool
  634. TrackNodes views.Slice[key.NodePublic]
  635. TrackIPs views.Slice[netip.Addr]
  636. }
  637. func (i *maybeReconfigInputs) Equal(o *maybeReconfigInputs) bool {
  638. return reflect.DeepEqual(i, o)
  639. }
  640. func (i *maybeReconfigInputs) Clone() *maybeReconfigInputs {
  641. if i == nil {
  642. return nil
  643. }
  644. v := *i
  645. v.WGConfig = i.WGConfig.Clone()
  646. v.TrimmedNodes = maps.Clone(i.TrimmedNodes)
  647. return &v
  648. }
  649. // discoChanged are the set of peers whose disco keys have changed, implying they've restarted.
  650. // If a peer is in this set and was previously in the live wireguard config,
  651. // it needs to be first removed and then re-added to flush out its wireguard session key.
  652. // If discoChanged is nil or empty, this extra removal step isn't done.
  653. //
  654. // e.wgLock must be held.
  655. func (e *userspaceEngine) maybeReconfigWireguardLocked(discoChanged map[key.NodePublic]bool) error {
  656. if hook := e.testMaybeReconfigHook; hook != nil {
  657. hook()
  658. return nil
  659. }
  660. full := e.lastCfgFull
  661. e.wgLogger.SetPeers(full.Peers)
  662. // Compute a minimal config to pass to wireguard-go
  663. // based on the full config. Prune off all the peers
  664. // and only add the active ones back.
  665. min := full
  666. min.Peers = make([]wgcfg.Peer, 0, e.lastNMinPeers)
  667. // We'll only keep a peer around if it's been active in
  668. // the past 5 minutes. That's more than WireGuard's key
  669. // rotation time anyway so it's no harm if we remove it
  670. // later if it's been inactive.
  671. var activeCutoff mono.Time
  672. if buildfeatures.HasLazyWG {
  673. activeCutoff = e.timeNow().Add(-lazyPeerIdleThreshold)
  674. }
  675. // Not all peers can be trimmed from the network map (see
  676. // isTrimmablePeer). For those that are trimmable, keep track of
  677. // their NodeKey and Tailscale IPs. These are the ones we'll need
  678. // to install tracking hooks for to watch their send/receive
  679. // activity.
  680. var trackNodes []key.NodePublic
  681. var trackIPs []netip.Addr
  682. if buildfeatures.HasLazyWG {
  683. trackNodes = make([]key.NodePublic, 0, len(full.Peers))
  684. trackIPs = make([]netip.Addr, 0, len(full.Peers))
  685. }
  686. // Don't re-alloc the map; the Go compiler optimizes map clears as of
  687. // Go 1.11, so we can re-use the existing + allocated map.
  688. if e.trimmedNodes != nil {
  689. clear(e.trimmedNodes)
  690. } else {
  691. e.trimmedNodes = make(map[key.NodePublic]bool)
  692. }
  693. needRemoveStep := false
  694. for i := range full.Peers {
  695. p := &full.Peers[i]
  696. nk := p.PublicKey
  697. if !buildfeatures.HasLazyWG || !e.isTrimmablePeer(p, len(full.Peers)) {
  698. min.Peers = append(min.Peers, *p)
  699. if discoChanged[nk] {
  700. needRemoveStep = true
  701. }
  702. continue
  703. }
  704. trackNodes = append(trackNodes, nk)
  705. recentlyActive := false
  706. for _, cidr := range p.AllowedIPs {
  707. trackIPs = append(trackIPs, cidr.Addr())
  708. recentlyActive = recentlyActive || e.isActiveSinceLocked(nk, cidr.Addr(), activeCutoff)
  709. }
  710. if recentlyActive {
  711. min.Peers = append(min.Peers, *p)
  712. if discoChanged[nk] {
  713. needRemoveStep = true
  714. }
  715. } else {
  716. e.trimmedNodes[nk] = true
  717. }
  718. }
  719. e.lastNMinPeers = len(min.Peers)
  720. if changed := checkchange.Update(&e.lastEngineInputs, &maybeReconfigInputs{
  721. WGConfig: &min,
  722. TrimmedNodes: e.trimmedNodes,
  723. TrackNodes: views.SliceOf(trackNodes),
  724. TrackIPs: views.SliceOf(trackIPs),
  725. }); !changed {
  726. return nil
  727. }
  728. if buildfeatures.HasLazyWG {
  729. e.updateActivityMapsLocked(trackNodes, trackIPs)
  730. }
  731. if needRemoveStep {
  732. minner := min
  733. minner.Peers = nil
  734. numRemove := 0
  735. for _, p := range min.Peers {
  736. if discoChanged[p.PublicKey] {
  737. numRemove++
  738. continue
  739. }
  740. minner.Peers = append(minner.Peers, p)
  741. }
  742. if numRemove > 0 {
  743. e.logf("wgengine: Reconfig: removing session keys for %d peers", numRemove)
  744. if err := wgcfg.ReconfigDevice(e.wgdev, &minner, e.logf); err != nil {
  745. e.logf("wgdev.Reconfig: %v", err)
  746. return err
  747. }
  748. }
  749. }
  750. e.logf("wgengine: Reconfig: configuring userspace WireGuard config (with %d/%d peers)", len(min.Peers), len(full.Peers))
  751. if err := wgcfg.ReconfigDevice(e.wgdev, &min, e.logf); err != nil {
  752. e.logf("wgdev.Reconfig: %v", err)
  753. return err
  754. }
  755. return nil
  756. }
  757. // updateActivityMapsLocked updates the data structures used for tracking the activity
  758. // of wireguard peers that we might add/remove dynamically from the real config
  759. // as given to wireguard-go.
  760. //
  761. // e.wgLock must be held.
  762. func (e *userspaceEngine) updateActivityMapsLocked(trackNodes []key.NodePublic, trackIPs []netip.Addr) {
  763. if !buildfeatures.HasLazyWG {
  764. return
  765. }
  766. // Generate the new map of which nodekeys we want to track
  767. // receive times for.
  768. mr := map[key.NodePublic]mono.Time{} // TODO: only recreate this if set of keys changed
  769. for _, nk := range trackNodes {
  770. // Preserve old times in the new map, but also
  771. // populate map entries for new trackNodes values with
  772. // time.Time{} zero values. (Only entries in this map
  773. // are tracked, so the Time zero values allow it to be
  774. // tracked later)
  775. mr[nk] = e.recvActivityAt[nk]
  776. }
  777. e.recvActivityAt = mr
  778. oldTime := e.sentActivityAt
  779. e.sentActivityAt = make(map[netip.Addr]*mono.Time, len(oldTime))
  780. oldFunc := e.destIPActivityFuncs
  781. e.destIPActivityFuncs = make(map[netip.Addr]func(), len(oldFunc))
  782. updateFn := func(timePtr *mono.Time) func() {
  783. return func() {
  784. now := e.timeNow()
  785. old := timePtr.LoadAtomic()
  786. // How long's it been since we last sent a packet?
  787. elapsed := now.Sub(old)
  788. if old == 0 {
  789. // For our first packet, old is 0, which has indeterminate meaning.
  790. // Set elapsed to a big number (four score and seven years).
  791. elapsed = 762642 * time.Hour
  792. }
  793. if elapsed >= packetSendTimeUpdateFrequency {
  794. timePtr.StoreAtomic(now)
  795. }
  796. // On a big jump, assume we might no longer be in the wireguard
  797. // config and go check.
  798. if elapsed >= packetSendRecheckWireguardThreshold {
  799. e.wgLock.Lock()
  800. defer e.wgLock.Unlock()
  801. e.maybeReconfigWireguardLocked(nil)
  802. }
  803. }
  804. }
  805. for _, ip := range trackIPs {
  806. timePtr := oldTime[ip]
  807. if timePtr == nil {
  808. timePtr = new(mono.Time)
  809. }
  810. e.sentActivityAt[ip] = timePtr
  811. fn := oldFunc[ip]
  812. if fn == nil {
  813. fn = updateFn(timePtr)
  814. }
  815. e.destIPActivityFuncs[ip] = fn
  816. }
  817. e.tundev.SetDestIPActivityFuncs(e.destIPActivityFuncs)
  818. }
  819. // hasOverlap checks if there is a IPPrefix which is common amongst the two
  820. // provided slices.
  821. func hasOverlap(aips, rips views.Slice[netip.Prefix]) bool {
  822. for _, aip := range aips.All() {
  823. if views.SliceContains(rips, aip) {
  824. return true
  825. }
  826. }
  827. return false
  828. }
  829. func (e *userspaceEngine) Reconfig(cfg *wgcfg.Config, routerCfg *router.Config, dnsCfg *dns.Config) error {
  830. if routerCfg == nil {
  831. panic("routerCfg must not be nil")
  832. }
  833. if dnsCfg == nil {
  834. panic("dnsCfg must not be nil")
  835. }
  836. e.isLocalAddr.Store(ipset.NewContainsIPFunc(views.SliceOf(routerCfg.LocalAddrs)))
  837. e.wgLock.Lock()
  838. defer e.wgLock.Unlock()
  839. e.tundev.SetWGConfig(cfg)
  840. peerSet := make(set.Set[key.NodePublic], len(cfg.Peers))
  841. e.mu.Lock()
  842. e.peerSequence = e.peerSequence[:0]
  843. for _, p := range cfg.Peers {
  844. e.peerSequence = append(e.peerSequence, p.PublicKey)
  845. peerSet.Add(p.PublicKey)
  846. }
  847. nm := e.netMap
  848. e.mu.Unlock()
  849. listenPort := e.confListenPort
  850. if e.controlKnobs != nil && e.controlKnobs.RandomizeClientPort.Load() {
  851. listenPort = 0
  852. }
  853. peerMTUEnable := e.magicConn.ShouldPMTUD()
  854. isSubnetRouter := false
  855. if buildfeatures.HasBird && e.birdClient != nil && nm != nil && nm.SelfNode.Valid() {
  856. isSubnetRouter = hasOverlap(nm.SelfNode.PrimaryRoutes(), nm.SelfNode.Hostinfo().RoutableIPs())
  857. e.logf("[v1] Reconfig: hasOverlap(%v, %v) = %v; isSubnetRouter=%v lastIsSubnetRouter=%v",
  858. nm.SelfNode.PrimaryRoutes(), nm.SelfNode.Hostinfo().RoutableIPs(),
  859. isSubnetRouter, isSubnetRouter, e.lastIsSubnetRouter)
  860. }
  861. isSubnetRouterChanged := buildfeatures.HasAdvertiseRoutes && isSubnetRouter != e.lastIsSubnetRouter
  862. engineChanged := checkchange.Update(&e.lastEngineFull, cfg)
  863. routerChanged := checkchange.Update(&e.lastRouter, routerCfg)
  864. dnsChanged := buildfeatures.HasDNS && !e.lastDNSConfig.Equal(dnsCfg.View())
  865. if dnsChanged {
  866. e.lastDNSConfig = dnsCfg.View()
  867. }
  868. listenPortChanged := listenPort != e.magicConn.LocalPort()
  869. peerMTUChanged := peerMTUEnable != e.magicConn.PeerMTUEnabled()
  870. if !engineChanged && !routerChanged && !dnsChanged && !listenPortChanged && !isSubnetRouterChanged && !peerMTUChanged {
  871. return ErrNoChanges
  872. }
  873. newLogIDs := cfg.NetworkLogging
  874. oldLogIDs := e.lastCfgFull.NetworkLogging
  875. netLogIDsNowValid := !newLogIDs.NodeID.IsZero() && !newLogIDs.DomainID.IsZero()
  876. netLogIDsWasValid := !oldLogIDs.NodeID.IsZero() && !oldLogIDs.DomainID.IsZero()
  877. netLogIDsChanged := netLogIDsNowValid && netLogIDsWasValid && newLogIDs != oldLogIDs
  878. netLogRunning := netLogIDsNowValid && !routerCfg.Equal(&router.Config{})
  879. if !buildfeatures.HasNetLog || envknob.NoLogsNoSupport() {
  880. netLogRunning = false
  881. }
  882. // TODO(bradfitz,danderson): maybe delete this isDNSIPOverTailscale
  883. // field and delete the resolver.ForwardLinkSelector hook and
  884. // instead have ipnlocal populate a map of DNS IP => linkName and
  885. // put that in the *dns.Config instead, and plumb it down to the
  886. // dns.Manager. Maybe also with isLocalAddr above.
  887. if buildfeatures.HasDNS {
  888. e.isDNSIPOverTailscale.Store(ipset.NewContainsIPFunc(views.SliceOf(dnsIPsOverTailscale(dnsCfg, routerCfg))))
  889. }
  890. // See if any peers have changed disco keys, which means they've restarted.
  891. // If so, we need to update the wireguard-go/device.Device in two phases:
  892. // once without the node which has restarted, to clear its wireguard session key,
  893. // and a second time with it.
  894. discoChanged := make(map[key.NodePublic]bool)
  895. {
  896. prevEP := make(map[key.NodePublic]key.DiscoPublic)
  897. for i := range e.lastCfgFull.Peers {
  898. if p := &e.lastCfgFull.Peers[i]; !p.DiscoKey.IsZero() {
  899. prevEP[p.PublicKey] = p.DiscoKey
  900. }
  901. }
  902. for i := range cfg.Peers {
  903. p := &cfg.Peers[i]
  904. if p.DiscoKey.IsZero() {
  905. continue
  906. }
  907. pub := p.PublicKey
  908. if old, ok := prevEP[pub]; ok && old != p.DiscoKey {
  909. discoChanged[pub] = true
  910. e.logf("wgengine: Reconfig: %s changed from %q to %q", pub.ShortString(), old, p.DiscoKey)
  911. }
  912. }
  913. }
  914. e.lastCfgFull = *cfg.Clone()
  915. // Tell magicsock about the new (or initial) private key
  916. // (which is needed by DERP) before wgdev gets it, as wgdev
  917. // will start trying to handshake, which we want to be able to
  918. // go over DERP.
  919. if err := e.magicConn.SetPrivateKey(cfg.PrivateKey); err != nil {
  920. e.logf("wgengine: Reconfig: SetPrivateKey: %v", err)
  921. }
  922. e.magicConn.UpdatePeers(peerSet)
  923. e.magicConn.SetPreferredPort(listenPort)
  924. e.magicConn.UpdatePMTUD()
  925. if err := e.maybeReconfigWireguardLocked(discoChanged); err != nil {
  926. return err
  927. }
  928. // Shutdown the network logger because the IDs changed.
  929. // Let it be started back up by subsequent logic.
  930. if buildfeatures.HasNetLog && netLogIDsChanged && e.networkLogger.Running() {
  931. e.logf("wgengine: Reconfig: shutting down network logger")
  932. ctx, cancel := context.WithTimeout(context.Background(), networkLoggerUploadTimeout)
  933. defer cancel()
  934. if err := e.networkLogger.Shutdown(ctx); err != nil {
  935. e.logf("wgengine: Reconfig: error shutting down network logger: %v", err)
  936. }
  937. }
  938. // Startup the network logger.
  939. // Do this before configuring the router so that we capture initial packets.
  940. if buildfeatures.HasNetLog && netLogRunning && !e.networkLogger.Running() {
  941. nid := cfg.NetworkLogging.NodeID
  942. tid := cfg.NetworkLogging.DomainID
  943. logExitFlowEnabled := cfg.NetworkLogging.LogExitFlowEnabled
  944. e.logf("wgengine: Reconfig: starting up network logger (node:%s tailnet:%s)", nid.Public(), tid.Public())
  945. if err := e.networkLogger.Startup(cfg.NodeID, nid, tid, e.tundev, e.magicConn, e.netMon, e.health, e.eventBus, logExitFlowEnabled); err != nil {
  946. e.logf("wgengine: Reconfig: error starting up network logger: %v", err)
  947. }
  948. e.networkLogger.ReconfigRoutes(routerCfg)
  949. }
  950. if routerChanged {
  951. e.logf("wgengine: Reconfig: configuring router")
  952. e.networkLogger.ReconfigRoutes(routerCfg)
  953. err := e.router.Set(routerCfg)
  954. e.health.SetRouterHealth(err)
  955. if err != nil {
  956. return err
  957. }
  958. }
  959. // We've historically re-set DNS even after just a router change. While
  960. // refactoring in tailscale/tailscale#17448 and and
  961. // tailscale/tailscale#17499, I'm erring on the side of keeping that
  962. // historical quirk for now (2025-10-08), lest it's load bearing in
  963. // unexpected ways
  964. //
  965. // TODO(bradfitz): try to do the "configuring DNS" part below only if
  966. // dnsChanged, not routerChanged. The "resolver.ShouldUseRoutes" part
  967. // probably needs to keep happening for both.
  968. if buildfeatures.HasDNS && (routerChanged || dnsChanged) {
  969. if resolver.ShouldUseRoutes(e.controlKnobs) {
  970. e.logf("wgengine: Reconfig: user dialer")
  971. e.dialer.SetRoutes(routerCfg.Routes, routerCfg.LocalRoutes)
  972. } else {
  973. e.dialer.SetRoutes(nil, nil)
  974. }
  975. // Keep DNS configuration after router configuration, as some
  976. // DNS managers refuse to apply settings if the device has no
  977. // assigned address.
  978. e.logf("wgengine: Reconfig: configuring DNS")
  979. err := e.dns.Set(*dnsCfg)
  980. e.health.SetDNSHealth(err)
  981. if err != nil {
  982. return err
  983. }
  984. if err := e.reconfigureVPNIfNecessary(); err != nil {
  985. return err
  986. }
  987. }
  988. // Shutdown the network logger.
  989. // Do this after configuring the router so that we capture final packets.
  990. // This attempts to flush out any log messages and may block.
  991. if !netLogRunning && e.networkLogger.Running() {
  992. e.logf("wgengine: Reconfig: shutting down network logger")
  993. ctx, cancel := context.WithTimeout(context.Background(), networkLoggerUploadTimeout)
  994. defer cancel()
  995. if err := e.networkLogger.Shutdown(ctx); err != nil {
  996. e.logf("wgengine: Reconfig: error shutting down network logger: %v", err)
  997. }
  998. }
  999. if buildfeatures.HasBird && isSubnetRouterChanged && e.birdClient != nil {
  1000. e.logf("wgengine: Reconfig: configuring BIRD")
  1001. var err error
  1002. if isSubnetRouter {
  1003. err = e.birdClient.EnableProtocol("tailscale")
  1004. } else {
  1005. err = e.birdClient.DisableProtocol("tailscale")
  1006. }
  1007. if err != nil {
  1008. // Log but don't fail here.
  1009. e.logf("wgengine: error configuring BIRD: %v", err)
  1010. } else {
  1011. e.lastIsSubnetRouter = isSubnetRouter
  1012. }
  1013. }
  1014. e.logf("[v1] wgengine: Reconfig done")
  1015. return nil
  1016. }
  1017. func (e *userspaceEngine) GetFilter() *filter.Filter {
  1018. return e.tundev.GetFilter()
  1019. }
  1020. func (e *userspaceEngine) SetFilter(filt *filter.Filter) {
  1021. e.tundev.SetFilter(filt)
  1022. }
  1023. func (e *userspaceEngine) GetJailedFilter() *filter.Filter {
  1024. return e.tundev.GetJailedFilter()
  1025. }
  1026. func (e *userspaceEngine) SetJailedFilter(filt *filter.Filter) {
  1027. e.tundev.SetJailedFilter(filt)
  1028. }
  1029. func (e *userspaceEngine) SetStatusCallback(cb StatusCallback) {
  1030. e.mu.Lock()
  1031. defer e.mu.Unlock()
  1032. e.statusCallback = cb
  1033. }
  1034. func (e *userspaceEngine) getStatusCallback() StatusCallback {
  1035. e.mu.Lock()
  1036. defer e.mu.Unlock()
  1037. return e.statusCallback
  1038. }
  1039. var ErrEngineClosing = errors.New("engine closing; no status")
  1040. func (e *userspaceEngine) PeerByKey(pubKey key.NodePublic) (_ wgint.Peer, ok bool) {
  1041. e.wgLock.Lock()
  1042. dev := e.wgdev
  1043. e.wgLock.Unlock()
  1044. if dev == nil {
  1045. return wgint.Peer{}, false
  1046. }
  1047. peer := dev.LookupPeer(pubKey.Raw32())
  1048. if peer == nil {
  1049. return wgint.Peer{}, false
  1050. }
  1051. return wgint.PeerOf(peer), true
  1052. }
  1053. func (e *userspaceEngine) getPeerStatusLite(pk key.NodePublic) (status ipnstate.PeerStatusLite, ok bool) {
  1054. peer, ok := e.PeerByKey(pk)
  1055. if !ok {
  1056. return status, false
  1057. }
  1058. status.NodeKey = pk
  1059. status.RxBytes = int64(peer.RxBytes())
  1060. status.TxBytes = int64(peer.TxBytes())
  1061. status.LastHandshake = peer.LastHandshake()
  1062. return status, true
  1063. }
  1064. func (e *userspaceEngine) getStatus() (*Status, error) {
  1065. // Grab derpConns before acquiring wgLock to not violate lock ordering;
  1066. // the DERPs method acquires magicsock.Conn.mu.
  1067. // (See comment in userspaceEngine's declaration.)
  1068. derpConns := e.magicConn.DERPs()
  1069. e.mu.Lock()
  1070. closing := e.closing
  1071. peerKeys := slices.Clone(e.peerSequence)
  1072. localAddrs := slices.Clone(e.endpoints)
  1073. e.mu.Unlock()
  1074. if closing {
  1075. return nil, ErrEngineClosing
  1076. }
  1077. peers := make([]ipnstate.PeerStatusLite, 0, len(peerKeys))
  1078. for _, key := range peerKeys {
  1079. if status, ok := e.getPeerStatusLite(key); ok {
  1080. peers = append(peers, status)
  1081. }
  1082. }
  1083. return &Status{
  1084. AsOf: time.Now(),
  1085. LocalAddrs: localAddrs,
  1086. Peers: peers,
  1087. DERPs: derpConns,
  1088. }, nil
  1089. }
  1090. func (e *userspaceEngine) RequestStatus() {
  1091. // This is slightly tricky. e.getStatus() can theoretically get
  1092. // blocked inside wireguard for a while, and RequestStatus() is
  1093. // sometimes called from a goroutine, so we don't want a lot of
  1094. // them hanging around. On the other hand, requesting multiple
  1095. // status updates simultaneously is pointless anyway; they will
  1096. // all say the same thing.
  1097. // Enqueue at most one request. If one is in progress already, this
  1098. // adds one more to the queue. If one has been requested but not
  1099. // started, it is a no-op.
  1100. select {
  1101. case e.reqCh <- struct{}{}:
  1102. default:
  1103. }
  1104. // Dequeue at most one request. Another thread may have already
  1105. // dequeued the request we enqueued above, which is fine, since the
  1106. // information is guaranteed to be at least as recent as the current
  1107. // call to RequestStatus().
  1108. select {
  1109. case <-e.reqCh:
  1110. s, err := e.getStatus()
  1111. if s == nil && err == nil {
  1112. e.logf("[unexpected] RequestStatus: both s and err are nil")
  1113. return
  1114. }
  1115. if cb := e.getStatusCallback(); cb != nil {
  1116. cb(s, err)
  1117. }
  1118. default:
  1119. }
  1120. }
  1121. func (e *userspaceEngine) Close() {
  1122. e.eventClient.Close()
  1123. e.mu.Lock()
  1124. if e.closing {
  1125. e.mu.Unlock()
  1126. return
  1127. }
  1128. e.closing = true
  1129. e.mu.Unlock()
  1130. r := bufio.NewReader(strings.NewReader(""))
  1131. e.wgdev.IpcSetOperation(r)
  1132. e.magicConn.Close()
  1133. if e.netMonOwned {
  1134. e.netMon.Close()
  1135. }
  1136. e.dns.Down()
  1137. e.router.Close()
  1138. e.wgdev.Close()
  1139. e.tundev.Close()
  1140. if e.birdClient != nil {
  1141. e.birdClient.DisableProtocol("tailscale")
  1142. e.birdClient.Close()
  1143. }
  1144. close(e.waitCh)
  1145. ctx, cancel := context.WithTimeout(context.Background(), networkLoggerUploadTimeout)
  1146. defer cancel()
  1147. if err := e.networkLogger.Shutdown(ctx); err != nil {
  1148. e.logf("wgengine: Close: error shutting down network logger: %v", err)
  1149. }
  1150. }
  1151. func (e *userspaceEngine) Done() <-chan struct{} {
  1152. return e.waitCh
  1153. }
  1154. func (e *userspaceEngine) linkChange(delta *netmon.ChangeDelta) {
  1155. changed := delta.Major // TODO(bradfitz): ask more specific questions?
  1156. cur := delta.New
  1157. up := cur.AnyInterfaceUp()
  1158. if !up {
  1159. e.logf("LinkChange: all links down; pausing: %v", cur)
  1160. } else if changed {
  1161. e.logf("LinkChange: major, rebinding. New state: %v", cur)
  1162. } else {
  1163. e.logf("[v1] LinkChange: minor")
  1164. }
  1165. e.health.SetAnyInterfaceUp(up)
  1166. e.magicConn.SetNetworkUp(up)
  1167. if !up || changed {
  1168. if err := e.dns.FlushCaches(); err != nil {
  1169. e.logf("wgengine: dns flush failed after major link change: %v", err)
  1170. }
  1171. }
  1172. // Hacky workaround for Unix DNS issue 2458: on
  1173. // suspend/resume or whenever NetworkManager is started, it
  1174. // nukes all systemd-resolved configs. So reapply our DNS
  1175. // config on major link change.
  1176. // TODO: explain why this is ncessary not just on Linux but also android
  1177. // and Apple platforms.
  1178. if changed {
  1179. switch runtime.GOOS {
  1180. case "linux", "android", "ios", "darwin", "openbsd":
  1181. e.wgLock.Lock()
  1182. dnsCfg := e.lastDNSConfig
  1183. e.wgLock.Unlock()
  1184. if dnsCfg.Valid() {
  1185. if err := e.dns.Set(*dnsCfg.AsStruct()); err != nil {
  1186. e.logf("wgengine: error setting DNS config after major link change: %v", err)
  1187. } else if err := e.reconfigureVPNIfNecessary(); err != nil {
  1188. e.logf("wgengine: error reconfiguring VPN after major link change: %v", err)
  1189. } else {
  1190. e.logf("wgengine: set DNS config again after major link change")
  1191. }
  1192. }
  1193. }
  1194. }
  1195. why := "link-change-minor"
  1196. if changed {
  1197. why = "link-change-major"
  1198. metricNumMajorChanges.Add(1)
  1199. e.magicConn.Rebind()
  1200. } else {
  1201. metricNumMinorChanges.Add(1)
  1202. }
  1203. e.magicConn.ReSTUN(why)
  1204. }
  1205. func (e *userspaceEngine) SetNetworkMap(nm *netmap.NetworkMap) {
  1206. e.mu.Lock()
  1207. e.netMap = nm
  1208. e.mu.Unlock()
  1209. }
  1210. func (e *userspaceEngine) UpdateStatus(sb *ipnstate.StatusBuilder) {
  1211. st, err := e.getStatus()
  1212. if err != nil {
  1213. e.logf("wgengine: getStatus: %v", err)
  1214. return
  1215. }
  1216. if sb.WantPeers {
  1217. for _, ps := range st.Peers {
  1218. sb.AddPeer(ps.NodeKey, &ipnstate.PeerStatus{
  1219. RxBytes: int64(ps.RxBytes),
  1220. TxBytes: int64(ps.TxBytes),
  1221. LastHandshake: ps.LastHandshake,
  1222. InEngine: true,
  1223. })
  1224. }
  1225. }
  1226. e.magicConn.UpdateStatus(sb)
  1227. }
  1228. func (e *userspaceEngine) Ping(ip netip.Addr, pingType tailcfg.PingType, size int, cb func(*ipnstate.PingResult)) {
  1229. res := &ipnstate.PingResult{IP: ip.String()}
  1230. pip, ok := e.PeerForIP(ip)
  1231. if !ok {
  1232. e.logf("ping(%v): no matching peer", ip)
  1233. res.Err = "no matching peer"
  1234. cb(res)
  1235. return
  1236. }
  1237. if pip.IsSelf {
  1238. res.Err = fmt.Sprintf("%v is local Tailscale IP", ip)
  1239. res.IsLocalIP = true
  1240. cb(res)
  1241. return
  1242. }
  1243. peer := pip.Node
  1244. e.logf("ping(%v): sending %v ping to %v %v ...", ip, pingType, peer.Key().ShortString(), peer.ComputedName())
  1245. switch pingType {
  1246. case "disco":
  1247. e.magicConn.Ping(peer, res, size, cb)
  1248. case "TSMP":
  1249. e.sendTSMPPing(ip, peer, res, cb)
  1250. case "ICMP":
  1251. e.sendICMPEchoRequest(ip, peer, res, cb)
  1252. }
  1253. }
  1254. func (e *userspaceEngine) mySelfIPMatchingFamily(dst netip.Addr) (src netip.Addr, err error) {
  1255. var zero netip.Addr
  1256. e.mu.Lock()
  1257. defer e.mu.Unlock()
  1258. if e.netMap == nil {
  1259. return zero, errors.New("no netmap")
  1260. }
  1261. addrs := e.netMap.GetAddresses()
  1262. if addrs.Len() == 0 {
  1263. return zero, errors.New("no self address in netmap")
  1264. }
  1265. for _, p := range addrs.All() {
  1266. if p.IsSingleIP() && p.Addr().BitLen() == dst.BitLen() {
  1267. return p.Addr(), nil
  1268. }
  1269. }
  1270. return zero, errors.New("no self address in netmap matching address family")
  1271. }
  1272. func (e *userspaceEngine) sendICMPEchoRequest(destIP netip.Addr, peer tailcfg.NodeView, res *ipnstate.PingResult, cb func(*ipnstate.PingResult)) {
  1273. srcIP, err := e.mySelfIPMatchingFamily(destIP)
  1274. if err != nil {
  1275. res.Err = err.Error()
  1276. cb(res)
  1277. return
  1278. }
  1279. var icmph packet.Header
  1280. if srcIP.Is4() {
  1281. icmph = packet.ICMP4Header{
  1282. IP4Header: packet.IP4Header{
  1283. IPProto: ipproto.ICMPv4,
  1284. Src: srcIP,
  1285. Dst: destIP,
  1286. },
  1287. Type: packet.ICMP4EchoRequest,
  1288. Code: packet.ICMP4NoCode,
  1289. }
  1290. } else {
  1291. icmph = packet.ICMP6Header{
  1292. IP6Header: packet.IP6Header{
  1293. IPProto: ipproto.ICMPv6,
  1294. Src: srcIP,
  1295. Dst: destIP,
  1296. },
  1297. Type: packet.ICMP6EchoRequest,
  1298. Code: packet.ICMP6NoCode,
  1299. }
  1300. }
  1301. idSeq, payload := packet.ICMPEchoPayload(nil)
  1302. expireTimer := time.AfterFunc(10*time.Second, func() {
  1303. e.setICMPEchoResponseCallback(idSeq, nil)
  1304. })
  1305. t0 := time.Now()
  1306. e.setICMPEchoResponseCallback(idSeq, func() {
  1307. expireTimer.Stop()
  1308. d := time.Since(t0)
  1309. res.LatencySeconds = d.Seconds()
  1310. res.NodeIP = destIP.String()
  1311. res.NodeName = peer.ComputedName()
  1312. cb(res)
  1313. })
  1314. icmpPing := packet.Generate(icmph, payload)
  1315. e.tundev.InjectOutbound(icmpPing)
  1316. }
  1317. func (e *userspaceEngine) sendTSMPPing(ip netip.Addr, peer tailcfg.NodeView, res *ipnstate.PingResult, cb func(*ipnstate.PingResult)) {
  1318. srcIP, err := e.mySelfIPMatchingFamily(ip)
  1319. if err != nil {
  1320. res.Err = err.Error()
  1321. cb(res)
  1322. return
  1323. }
  1324. var iph packet.Header
  1325. if srcIP.Is4() {
  1326. iph = packet.IP4Header{
  1327. IPProto: ipproto.TSMP,
  1328. Src: srcIP,
  1329. Dst: ip,
  1330. }
  1331. } else {
  1332. iph = packet.IP6Header{
  1333. IPProto: ipproto.TSMP,
  1334. Src: srcIP,
  1335. Dst: ip,
  1336. }
  1337. }
  1338. var data [8]byte
  1339. crand.Read(data[:])
  1340. expireTimer := time.AfterFunc(10*time.Second, func() {
  1341. e.setTSMPPongCallback(data, nil)
  1342. })
  1343. t0 := time.Now()
  1344. e.setTSMPPongCallback(data, func(pong packet.TSMPPongReply) {
  1345. expireTimer.Stop()
  1346. d := time.Since(t0)
  1347. res.LatencySeconds = d.Seconds()
  1348. res.NodeIP = ip.String()
  1349. res.NodeName = peer.ComputedName()
  1350. res.PeerAPIPort = pong.PeerAPIPort
  1351. cb(res)
  1352. })
  1353. var tsmpPayload [9]byte
  1354. tsmpPayload[0] = byte(packet.TSMPTypePing)
  1355. copy(tsmpPayload[1:], data[:])
  1356. tsmpPing := packet.Generate(iph, tsmpPayload[:])
  1357. e.tundev.InjectOutbound(tsmpPing)
  1358. }
  1359. func (e *userspaceEngine) setTSMPPongCallback(data [8]byte, cb func(packet.TSMPPongReply)) {
  1360. e.mu.Lock()
  1361. defer e.mu.Unlock()
  1362. if e.pongCallback == nil {
  1363. e.pongCallback = map[[8]byte]func(packet.TSMPPongReply){}
  1364. }
  1365. if cb == nil {
  1366. delete(e.pongCallback, data)
  1367. } else {
  1368. e.pongCallback[data] = cb
  1369. }
  1370. }
  1371. func (e *userspaceEngine) setICMPEchoResponseCallback(idSeq uint32, cb func()) {
  1372. e.mu.Lock()
  1373. defer e.mu.Unlock()
  1374. if cb == nil {
  1375. delete(e.icmpEchoResponseCallback, idSeq)
  1376. } else {
  1377. mak.Set(&e.icmpEchoResponseCallback, idSeq, cb)
  1378. }
  1379. }
  1380. // PeerForIP returns the Node in the wireguard config
  1381. // that's responsible for handling the given IP address.
  1382. //
  1383. // If none is found in the wireguard config but one is found in
  1384. // the netmap, it's described in an error.
  1385. //
  1386. // peerForIP acquires both e.mu and e.wgLock, but neither at the same
  1387. // time.
  1388. func (e *userspaceEngine) PeerForIP(ip netip.Addr) (ret PeerForIP, ok bool) {
  1389. e.mu.Lock()
  1390. nm := e.netMap
  1391. e.mu.Unlock()
  1392. if nm == nil {
  1393. return ret, false
  1394. }
  1395. // Check for exact matches before looking for subnet matches.
  1396. // TODO(bradfitz): add maps for these. on NetworkMap?
  1397. for _, p := range nm.Peers {
  1398. for i := range p.Addresses().Len() {
  1399. a := p.Addresses().At(i)
  1400. if a.Addr() == ip && a.IsSingleIP() && tsaddr.IsTailscaleIP(ip) {
  1401. return PeerForIP{Node: p, Route: a}, true
  1402. }
  1403. }
  1404. }
  1405. addrs := nm.GetAddresses()
  1406. for i := range addrs.Len() {
  1407. if a := addrs.At(i); a.Addr() == ip && a.IsSingleIP() && tsaddr.IsTailscaleIP(ip) {
  1408. return PeerForIP{Node: nm.SelfNode, IsSelf: true, Route: a}, true
  1409. }
  1410. }
  1411. e.wgLock.Lock()
  1412. defer e.wgLock.Unlock()
  1413. // TODO(bradfitz): this is O(n peers). Add ART to netaddr?
  1414. var best netip.Prefix
  1415. var bestKey key.NodePublic
  1416. for _, p := range e.lastCfgFull.Peers {
  1417. for _, cidr := range p.AllowedIPs {
  1418. if !cidr.Contains(ip) {
  1419. continue
  1420. }
  1421. if !best.IsValid() || cidr.Bits() > best.Bits() {
  1422. best = cidr
  1423. bestKey = p.PublicKey
  1424. }
  1425. }
  1426. }
  1427. // And another pass. Probably better than allocating a map per peerForIP
  1428. // call. But TODO(bradfitz): add a lookup map to netmap.NetworkMap.
  1429. if !bestKey.IsZero() {
  1430. for _, p := range nm.Peers {
  1431. if p.Key() == bestKey {
  1432. return PeerForIP{Node: p, Route: best}, true
  1433. }
  1434. }
  1435. }
  1436. return ret, false
  1437. }
  1438. type closeOnErrorPool []func()
  1439. func (p *closeOnErrorPool) add(c io.Closer) { *p = append(*p, func() { c.Close() }) }
  1440. func (p *closeOnErrorPool) addFunc(fn func()) { *p = append(*p, fn) }
  1441. func (p closeOnErrorPool) closeAllIfError(errp *error) {
  1442. if *errp != nil {
  1443. for _, closeFn := range p {
  1444. closeFn()
  1445. }
  1446. }
  1447. }
  1448. // ipInPrefixes reports whether ip is in any of pp.
  1449. func ipInPrefixes(ip netip.Addr, pp []netip.Prefix) bool {
  1450. for _, p := range pp {
  1451. if p.Contains(ip) {
  1452. return true
  1453. }
  1454. }
  1455. return false
  1456. }
  1457. // dnsIPsOverTailscale returns the IPPrefixes of DNS resolver IPs that are
  1458. // routed over Tailscale. The returned value does not contain duplicates is
  1459. // not necessarily sorted.
  1460. func dnsIPsOverTailscale(dnsCfg *dns.Config, routerCfg *router.Config) (ret []netip.Prefix) {
  1461. m := map[netip.Addr]bool{}
  1462. add := func(resolvers []*dnstype.Resolver) {
  1463. for _, r := range resolvers {
  1464. ip, err := netip.ParseAddr(r.Addr)
  1465. if err != nil {
  1466. if ipp, err := netip.ParseAddrPort(r.Addr); err == nil {
  1467. ip = ipp.Addr()
  1468. } else {
  1469. continue
  1470. }
  1471. }
  1472. if ipInPrefixes(ip, routerCfg.Routes) && !ipInPrefixes(ip, routerCfg.LocalRoutes) {
  1473. m[ip] = true
  1474. }
  1475. }
  1476. }
  1477. add(dnsCfg.DefaultResolvers)
  1478. for _, resolvers := range dnsCfg.Routes {
  1479. add(resolvers)
  1480. }
  1481. ret = make([]netip.Prefix, 0, len(m))
  1482. for ip := range m {
  1483. ret = append(ret, netip.PrefixFrom(ip, ip.BitLen()))
  1484. }
  1485. return ret
  1486. }
  1487. // fwdDNSLinkSelector is userspaceEngine's resolver.ForwardLinkSelector, to pick
  1488. // which network interface to send DNS queries out of.
  1489. type fwdDNSLinkSelector struct {
  1490. ue *userspaceEngine
  1491. tunName string
  1492. }
  1493. func (ls fwdDNSLinkSelector) PickLink(ip netip.Addr) (linkName string) {
  1494. // sandboxed macOS does not automatically bind to the loopback interface so
  1495. // we must be explicit about it.
  1496. if runtime.GOOS == "darwin" && ip.IsLoopback() {
  1497. return "lo0"
  1498. }
  1499. if ls.ue.isDNSIPOverTailscale.Load()(ip) {
  1500. return ls.tunName
  1501. }
  1502. return ""
  1503. }
  1504. var (
  1505. metricReflectToOS = clientmetric.NewCounter("packet_reflect_to_os")
  1506. metricNumMajorChanges = clientmetric.NewCounter("wgengine_major_changes")
  1507. metricNumMinorChanges = clientmetric.NewCounter("wgengine_minor_changes")
  1508. )
  1509. func (e *userspaceEngine) InstallCaptureHook(cb packet.CaptureCallback) {
  1510. if !buildfeatures.HasCapture {
  1511. return
  1512. }
  1513. e.tundev.InstallCaptureHook(cb)
  1514. e.magicConn.InstallCaptureHook(cb)
  1515. }
  1516. func (e *userspaceEngine) reconfigureVPNIfNecessary() error {
  1517. if e.reconfigureVPN == nil {
  1518. return nil
  1519. }
  1520. return e.reconfigureVPN()
  1521. }