userspace.go 48 KB

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