userspace.go 45 KB

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