userspace.go 45 KB

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