direct.go 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841
  1. // Copyright (c) Tailscale Inc & contributors
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. package controlclient
  4. import (
  5. "bytes"
  6. "cmp"
  7. "context"
  8. "crypto"
  9. "crypto/sha256"
  10. "encoding/binary"
  11. "encoding/json"
  12. "errors"
  13. "fmt"
  14. "io"
  15. "log"
  16. "net"
  17. "net/http"
  18. "net/netip"
  19. "os"
  20. "reflect"
  21. "runtime"
  22. "slices"
  23. "strings"
  24. "sync/atomic"
  25. "time"
  26. "go4.org/mem"
  27. "tailscale.com/control/controlknobs"
  28. "tailscale.com/control/ts2021"
  29. "tailscale.com/envknob"
  30. "tailscale.com/feature"
  31. "tailscale.com/feature/buildfeatures"
  32. "tailscale.com/health"
  33. "tailscale.com/hostinfo"
  34. "tailscale.com/ipn/ipnstate"
  35. "tailscale.com/logtail"
  36. "tailscale.com/net/dnscache"
  37. "tailscale.com/net/dnsfallback"
  38. "tailscale.com/net/netmon"
  39. "tailscale.com/net/netutil"
  40. "tailscale.com/net/netx"
  41. "tailscale.com/net/tlsdial"
  42. "tailscale.com/net/tsdial"
  43. "tailscale.com/syncs"
  44. "tailscale.com/tailcfg"
  45. "tailscale.com/tka"
  46. "tailscale.com/tstime"
  47. "tailscale.com/types/key"
  48. "tailscale.com/types/logger"
  49. "tailscale.com/types/netmap"
  50. "tailscale.com/types/persist"
  51. "tailscale.com/types/ptr"
  52. "tailscale.com/types/tkatype"
  53. "tailscale.com/util/clientmetric"
  54. "tailscale.com/util/eventbus"
  55. "tailscale.com/util/singleflight"
  56. "tailscale.com/util/syspolicy/pkey"
  57. "tailscale.com/util/syspolicy/policyclient"
  58. "tailscale.com/util/testenv"
  59. "tailscale.com/util/zstdframe"
  60. )
  61. // Direct is the client that connects to a tailcontrol server for a node.
  62. type Direct struct {
  63. httpc *http.Client // HTTP client used to do TLS requests to control (just https://controlplane.tailscale.com/key?v=123)
  64. interceptedDial *atomic.Bool // if non-nil, pointer to bool whether ScreenTime intercepted our dial
  65. dialer *tsdial.Dialer
  66. dnsCache *dnscache.Resolver
  67. controlKnobs *controlknobs.Knobs // always non-nil
  68. serverURL string // URL of the tailcontrol server
  69. clock tstime.Clock
  70. logf logger.Logf
  71. netMon *netmon.Monitor // non-nil
  72. health *health.Tracker
  73. busClient *eventbus.Client
  74. clientVersionPub *eventbus.Publisher[tailcfg.ClientVersion]
  75. autoUpdatePub *eventbus.Publisher[AutoUpdate]
  76. controlTimePub *eventbus.Publisher[ControlTime]
  77. getMachinePrivKey func() (key.MachinePrivate, error)
  78. debugFlags []string
  79. skipIPForwardingCheck bool
  80. pinger Pinger
  81. popBrowser func(url string) // or nil
  82. polc policyclient.Client // always non-nil
  83. c2nHandler http.Handler // or nil
  84. panicOnUse bool // if true, panic if client is used (for testing)
  85. closedCtx context.Context // alive until Direct.Close is called
  86. closeCtx context.CancelFunc // cancels closedCtx
  87. dialPlan ControlDialPlanner // can be nil
  88. mu syncs.Mutex // mutex guards the following fields
  89. serverLegacyKey key.MachinePublic // original ("legacy") nacl crypto_box-based public key; only used for signRegisterRequest on Windows now
  90. serverNoiseKey key.MachinePublic
  91. discoPubKey key.DiscoPublic // protected by mu; can be updated via [SetDiscoPublicKey]
  92. sfGroup singleflight.Group[struct{}, *ts2021.Client] // protects noiseClient creation.
  93. noiseClient *ts2021.Client // also protected by mu
  94. persist persist.PersistView
  95. authKey string
  96. tryingNewKey key.NodePrivate
  97. expiry time.Time // or zero value if none/unknown
  98. hostinfo *tailcfg.Hostinfo // always non-nil
  99. netinfo *tailcfg.NetInfo
  100. endpoints []tailcfg.Endpoint
  101. tkaHead string
  102. lastPingURL string // last PingRequest.URL received, for dup suppression
  103. connectionHandleForTest string // sent in MapRequest.ConnectionHandleForTest
  104. controlClientID int64 // Random ID used to differentiate clients for consumers of messages.
  105. }
  106. // Observer is implemented by users of the control client (such as LocalBackend)
  107. // to get notified of changes in the control client's status.
  108. //
  109. // If an implementation of Observer also implements [NetmapDeltaUpdater], they get
  110. // delta updates as well as full netmap updates.
  111. type Observer interface {
  112. // SetControlClientStatus is called when the client has a new status to
  113. // report. The Client is provided to allow the Observer to track which
  114. // Client is reporting the status, allowing it to ignore stale status
  115. // reports from previous Clients.
  116. SetControlClientStatus(Client, Status)
  117. }
  118. type Options struct {
  119. Persist persist.Persist // initial persistent data
  120. GetMachinePrivateKey func() (key.MachinePrivate, error) // returns the machine key to use
  121. ServerURL string // URL of the tailcontrol server
  122. AuthKey string // optional node auth key for auto registration
  123. Clock tstime.Clock
  124. Hostinfo *tailcfg.Hostinfo // non-nil passes ownership, nil means to use default using os.Hostname, etc
  125. DiscoPublicKey key.DiscoPublic
  126. PolicyClient policyclient.Client // or nil for none
  127. Logf logger.Logf
  128. HTTPTestClient *http.Client // optional HTTP client to use (for tests only)
  129. NoiseTestClient *http.Client // optional HTTP client to use for noise RPCs (tests only)
  130. DebugFlags []string // debug settings to send to control
  131. HealthTracker *health.Tracker
  132. PopBrowserURL func(url string) // optional func to open browser
  133. Dialer *tsdial.Dialer // non-nil
  134. C2NHandler http.Handler // or nil
  135. ControlKnobs *controlknobs.Knobs // or nil to ignore
  136. Bus *eventbus.Bus // non-nil, for setting up publishers
  137. SkipStartForTests bool // if true, don't call [Auto.Start] to avoid any background goroutines (for tests only)
  138. // StartPaused indicates whether the client should start in a paused state
  139. // where it doesn't do network requests. This primarily exists for testing
  140. // but not necessarily "go test" tests, so it isn't restricted to only
  141. // being used in tests.
  142. StartPaused bool
  143. // Observer is called when there's a change in status to report
  144. // from the control client.
  145. // If nil, no status updates are reported.
  146. Observer Observer
  147. // SkipIPForwardingCheck declares that the host's IP
  148. // forwarding works and should not be double-checked by the
  149. // controlclient package.
  150. SkipIPForwardingCheck bool
  151. // Pinger optionally specifies the Pinger to use to satisfy
  152. // MapResponse.PingRequest queries from the control plane.
  153. // If nil, PingRequest queries are not answered.
  154. Pinger Pinger
  155. // DialPlan contains and stores a previous dial plan that we received
  156. // from the control server; if nil, we fall back to using DNS.
  157. //
  158. // If we receive a new DialPlan from the server, this value will be
  159. // updated.
  160. DialPlan ControlDialPlanner
  161. // Shutdown is an optional function that will be called before client shutdown is
  162. // attempted. It is used to allow the client to clean up any resources or complete any
  163. // tasks that are dependent on a live client.
  164. Shutdown func()
  165. }
  166. // ControlDialPlanner is the interface optionally supplied when creating a
  167. // control client to control exactly how TCP connections to the control plane
  168. // are dialed.
  169. //
  170. // It is usually implemented by an atomic.Pointer.
  171. type ControlDialPlanner interface {
  172. // Load returns the current plan for how to connect to control.
  173. //
  174. // The returned plan can be nil. If so, connections should be made by
  175. // resolving the control URL using DNS.
  176. Load() *tailcfg.ControlDialPlan
  177. // Store updates the dial plan with new directions from the control
  178. // server.
  179. //
  180. // The dial plan can span multiple connections to the control server.
  181. // That is, a dial plan received when connected over Wi-Fi is still
  182. // valid for a subsequent connection over LTE after a network switch.
  183. Store(*tailcfg.ControlDialPlan)
  184. }
  185. // Pinger is the LocalBackend.Ping method.
  186. type Pinger interface {
  187. // Ping is a request to do a ping with the peer handling the given IP.
  188. Ping(ctx context.Context, ip netip.Addr, pingType tailcfg.PingType, size int) (*ipnstate.PingResult, error)
  189. }
  190. // NetmapUpdater is the interface needed by the controlclient to enact change in
  191. // the world as a function of updates received from the network.
  192. type NetmapUpdater interface {
  193. UpdateFullNetmap(*netmap.NetworkMap)
  194. // TODO(bradfitz): add methods to do fine-grained updates, mutating just
  195. // parts of peers, without implementations of NetmapUpdater needing to do
  196. // the diff themselves between the previous full & next full network maps.
  197. }
  198. // NetmapDeltaUpdater is an optional interface that can be implemented by
  199. // NetmapUpdater implementations to receive delta updates from the controlclient
  200. // rather than just full updates.
  201. type NetmapDeltaUpdater interface {
  202. // UpdateNetmapDelta is called with discrete changes to the network map.
  203. //
  204. // The ok result is whether the implementation was able to apply the
  205. // mutations. It might return false if its internal state doesn't
  206. // support applying them or a NetmapUpdater it's wrapping doesn't
  207. // implement the NetmapDeltaUpdater optional method.
  208. UpdateNetmapDelta([]netmap.NodeMutation) (ok bool)
  209. }
  210. var nextControlClientID atomic.Int64
  211. // NewDirect returns a new Direct client.
  212. func NewDirect(opts Options) (*Direct, error) {
  213. if opts.ServerURL == "" {
  214. return nil, errors.New("controlclient.New: no server URL specified")
  215. }
  216. if opts.GetMachinePrivateKey == nil {
  217. return nil, errors.New("controlclient.New: no GetMachinePrivateKey specified")
  218. }
  219. if opts.Dialer == nil {
  220. if testenv.InTest() {
  221. panic("no Dialer")
  222. }
  223. return nil, errors.New("controlclient.New: no Dialer specified")
  224. }
  225. netMon := opts.Dialer.NetMon()
  226. if netMon == nil {
  227. if testenv.InTest() {
  228. panic("no NetMon in Dialer")
  229. }
  230. return nil, errors.New("controlclient.New: Dialer has nil NetMon")
  231. }
  232. if opts.ControlKnobs == nil {
  233. opts.ControlKnobs = &controlknobs.Knobs{}
  234. }
  235. opts.ServerURL = strings.TrimRight(opts.ServerURL, "/")
  236. if opts.Clock == nil {
  237. opts.Clock = tstime.StdClock{}
  238. }
  239. if opts.Logf == nil {
  240. // TODO(apenwarr): remove this default and fail instead.
  241. // TODO(bradfitz): ... but then it shouldn't be in Options.
  242. opts.Logf = log.Printf
  243. }
  244. dnsCache := &dnscache.Resolver{
  245. Forward: dnscache.Get().Forward, // use default cache's forwarder
  246. UseLastGood: true,
  247. LookupIPFallback: dnsfallback.MakeLookupFunc(opts.Logf, netMon),
  248. Logf: opts.Logf,
  249. }
  250. httpc := opts.HTTPTestClient
  251. if httpc == nil && runtime.GOOS == "js" {
  252. // In js/wasm, net/http.Transport (as of Go 1.18) will
  253. // only use the browser's Fetch API if you're using
  254. // the DefaultClient (or a client without dial hooks
  255. // etc set).
  256. httpc = http.DefaultClient
  257. }
  258. var interceptedDial *atomic.Bool
  259. if httpc == nil {
  260. tr := http.DefaultTransport.(*http.Transport).Clone()
  261. if buildfeatures.HasUseProxy {
  262. tr.Proxy = feature.HookProxyFromEnvironment.GetOrNil()
  263. if f, ok := feature.HookProxySetTransportGetProxyConnectHeader.GetOk(); ok {
  264. f(tr)
  265. }
  266. }
  267. tr.TLSClientConfig = tlsdial.Config(opts.HealthTracker, tr.TLSClientConfig)
  268. var dialFunc netx.DialFunc
  269. dialFunc, interceptedDial = makeScreenTimeDetectingDialFunc(opts.Dialer.SystemDial)
  270. tr.DialContext = dnscache.Dialer(dialFunc, dnsCache)
  271. tr.DialTLSContext = dnscache.TLSDialer(dialFunc, dnsCache, tr.TLSClientConfig)
  272. tr.ForceAttemptHTTP2 = true
  273. // Disable implicit gzip compression; the various
  274. // handlers (register, map, set-dns, etc) do their own
  275. // zstd compression per naclbox.
  276. tr.DisableCompression = true
  277. httpc = &http.Client{Transport: tr}
  278. }
  279. c := &Direct{
  280. httpc: httpc,
  281. interceptedDial: interceptedDial,
  282. controlKnobs: opts.ControlKnobs,
  283. getMachinePrivKey: opts.GetMachinePrivateKey,
  284. serverURL: opts.ServerURL,
  285. clock: opts.Clock,
  286. logf: opts.Logf,
  287. persist: opts.Persist.View(),
  288. authKey: opts.AuthKey,
  289. debugFlags: opts.DebugFlags,
  290. netMon: netMon,
  291. health: opts.HealthTracker,
  292. skipIPForwardingCheck: opts.SkipIPForwardingCheck,
  293. pinger: opts.Pinger,
  294. polc: cmp.Or(opts.PolicyClient, policyclient.Client(policyclient.NoPolicyClient{})),
  295. popBrowser: opts.PopBrowserURL,
  296. c2nHandler: opts.C2NHandler,
  297. dialer: opts.Dialer,
  298. dnsCache: dnsCache,
  299. dialPlan: opts.DialPlan,
  300. }
  301. c.discoPubKey = opts.DiscoPublicKey
  302. c.closedCtx, c.closeCtx = context.WithCancel(context.Background())
  303. c.controlClientID = nextControlClientID.Add(1)
  304. if opts.Hostinfo == nil {
  305. c.SetHostinfo(hostinfo.New())
  306. } else {
  307. c.SetHostinfo(opts.Hostinfo)
  308. if ni := opts.Hostinfo.NetInfo; ni != nil {
  309. c.SetNetInfo(ni)
  310. }
  311. }
  312. if opts.NoiseTestClient != nil {
  313. c.noiseClient = &ts2021.Client{
  314. Client: opts.NoiseTestClient,
  315. }
  316. c.serverNoiseKey = key.NewMachine().Public() // prevent early error before hitting test client
  317. }
  318. if strings.Contains(opts.ServerURL, "controlplane.tailscale.com") && envknob.Bool("TS_PANIC_IF_HIT_MAIN_CONTROL") {
  319. c.panicOnUse = true
  320. }
  321. c.busClient = opts.Bus.Client("controlClient.direct")
  322. c.clientVersionPub = eventbus.Publish[tailcfg.ClientVersion](c.busClient)
  323. c.autoUpdatePub = eventbus.Publish[AutoUpdate](c.busClient)
  324. c.controlTimePub = eventbus.Publish[ControlTime](c.busClient)
  325. return c, nil
  326. }
  327. // Close closes the underlying Noise connection(s).
  328. func (c *Direct) Close() error {
  329. c.closeCtx()
  330. c.mu.Lock()
  331. defer c.mu.Unlock()
  332. c.busClient.Close()
  333. if c.noiseClient != nil {
  334. if err := c.noiseClient.Close(); err != nil {
  335. return err
  336. }
  337. }
  338. c.noiseClient = nil
  339. c.httpc.CloseIdleConnections()
  340. return nil
  341. }
  342. // SetHostinfo clones the provided Hostinfo and remembers it for the
  343. // next update. It reports whether the Hostinfo has changed.
  344. func (c *Direct) SetHostinfo(hi *tailcfg.Hostinfo) bool {
  345. if hi == nil {
  346. panic("nil Hostinfo")
  347. }
  348. hi = ptr.To(*hi)
  349. hi.NetInfo = nil
  350. c.mu.Lock()
  351. defer c.mu.Unlock()
  352. if hi.Equal(c.hostinfo) {
  353. return false
  354. }
  355. c.hostinfo = hi.Clone()
  356. j, _ := json.Marshal(c.hostinfo)
  357. c.logf("[v1] HostInfo: %s", j)
  358. return true
  359. }
  360. // SetNetInfo clones the provided NetInfo and remembers it for the
  361. // next update. It reports whether the NetInfo has changed.
  362. func (c *Direct) SetNetInfo(ni *tailcfg.NetInfo) bool {
  363. if ni == nil {
  364. panic("nil NetInfo")
  365. }
  366. c.mu.Lock()
  367. defer c.mu.Unlock()
  368. if reflect.DeepEqual(ni, c.netinfo) {
  369. return false
  370. }
  371. c.netinfo = ni.Clone()
  372. c.logf("NetInfo: %v", ni)
  373. return true
  374. }
  375. // SetTKAHead stores a new TKA head value for next update.
  376. // It reports whether the TKA head changed.
  377. func (c *Direct) SetTKAHead(tkaHead string) bool {
  378. c.mu.Lock()
  379. defer c.mu.Unlock()
  380. if tkaHead == c.tkaHead {
  381. return false
  382. }
  383. c.tkaHead = tkaHead
  384. c.logf("tkaHead: %v", tkaHead)
  385. return true
  386. }
  387. // SetConnectionHandleForTest stores a new MapRequest.ConnectionHandleForTest
  388. // value for the next update.
  389. func (c *Direct) SetConnectionHandleForTest(handle string) {
  390. c.mu.Lock()
  391. defer c.mu.Unlock()
  392. c.connectionHandleForTest = handle
  393. }
  394. func (c *Direct) GetPersist() persist.PersistView {
  395. c.mu.Lock()
  396. defer c.mu.Unlock()
  397. return c.persist
  398. }
  399. func (c *Direct) TryLogout(ctx context.Context) error {
  400. c.logf("[v1] direct.TryLogout()")
  401. mustRegen, newURL, _, err := c.doLogin(ctx, loginOpt{Logout: true})
  402. c.logf("[v1] TryLogout control response: mustRegen=%v, newURL=%v, err=%v", mustRegen, newURL, err)
  403. c.mu.Lock()
  404. c.persist = new(persist.Persist).View()
  405. c.mu.Unlock()
  406. return err
  407. }
  408. func (c *Direct) TryLogin(ctx context.Context, flags LoginFlags) (url string, err error) {
  409. if strings.Contains(c.serverURL, "controlplane.tailscale.com") && envknob.Bool("TS_PANIC_IF_HIT_MAIN_CONTROL") {
  410. panic(fmt.Sprintf("[unexpected] controlclient: TryLogin called on %s; tainted=%v", c.serverURL, c.panicOnUse))
  411. }
  412. c.logf("[v1] direct.TryLogin(flags=%v)", flags)
  413. return c.doLoginOrRegen(ctx, loginOpt{Flags: flags})
  414. }
  415. // WaitLoginURL sits in a long poll waiting for the user to authenticate at url.
  416. //
  417. // On success, newURL and err will both be nil.
  418. func (c *Direct) WaitLoginURL(ctx context.Context, url string) (newURL string, err error) {
  419. c.logf("[v1] direct.WaitLoginURL")
  420. return c.doLoginOrRegen(ctx, loginOpt{URL: url})
  421. }
  422. func (c *Direct) doLoginOrRegen(ctx context.Context, opt loginOpt) (newURL string, err error) {
  423. mustRegen, url, oldNodeKeySignature, err := c.doLogin(ctx, opt)
  424. if err != nil {
  425. return url, err
  426. }
  427. if mustRegen {
  428. opt.Regen = true
  429. opt.OldNodeKeySignature = oldNodeKeySignature
  430. _, url, _, err = c.doLogin(ctx, opt)
  431. }
  432. return url, err
  433. }
  434. // SetExpirySooner attempts to shorten the expiry to the specified time.
  435. func (c *Direct) SetExpirySooner(ctx context.Context, expiry time.Time) error {
  436. c.logf("[v1] direct.SetExpirySooner()")
  437. newURL, err := c.doLoginOrRegen(ctx, loginOpt{Expiry: &expiry})
  438. c.logf("[v1] SetExpirySooner control response: newURL=%v, err=%v", newURL, err)
  439. return err
  440. }
  441. type loginOpt struct {
  442. Flags LoginFlags
  443. Regen bool // generate a new nodekey, can be overridden in doLogin
  444. URL string
  445. Logout bool // set the expiry to the far past, expiring the node
  446. // Expiry, if non-nil, attempts to set the node expiry to the
  447. // specified time and cannot be used to extend the expiry.
  448. // It is ignored if Logout is set since Logout works by setting a
  449. // expiry time in the far past.
  450. Expiry *time.Time
  451. // OldNodeKeySignature indicates the former NodeKeySignature
  452. // that must be resigned for the new node-key.
  453. OldNodeKeySignature tkatype.MarshaledSignature
  454. }
  455. // hostInfoLocked returns a Clone of c.hostinfo and c.netinfo.
  456. // It must only be called with c.mu held.
  457. func (c *Direct) hostInfoLocked() *tailcfg.Hostinfo {
  458. hi := c.hostinfo.Clone()
  459. hi.NetInfo = c.netinfo.Clone()
  460. return hi
  461. }
  462. var macOSScreenTime = health.Register(&health.Warnable{
  463. Code: "macos-screen-time-controlclient",
  464. Severity: health.SeverityHigh,
  465. Title: "Tailscale blocked by Screen Time",
  466. Text: func(args health.Args) string {
  467. return "macOS Screen Time seems to be blocking Tailscale. Try disabling Screen Time in System Settings > Screen Time > Content & Privacy > Access to Web Content."
  468. },
  469. ImpactsConnectivity: true,
  470. })
  471. func (c *Direct) doLogin(ctx context.Context, opt loginOpt) (mustRegen bool, newURL string, nks tkatype.MarshaledSignature, err error) {
  472. if c.panicOnUse {
  473. panic("tainted client")
  474. }
  475. c.mu.Lock()
  476. persist := c.persist.AsStruct()
  477. tryingNewKey := c.tryingNewKey
  478. serverKey := c.serverLegacyKey
  479. serverNoiseKey := c.serverNoiseKey
  480. authKey, isWrapped, wrappedSig, wrappedKey := tka.DecodeWrappedAuthkey(c.authKey, c.logf)
  481. hi := c.hostInfoLocked()
  482. backendLogID := hi.BackendLogID
  483. expired := !c.expiry.IsZero() && c.expiry.Before(c.clock.Now())
  484. c.mu.Unlock()
  485. machinePrivKey, err := c.getMachinePrivKey()
  486. if err != nil {
  487. return false, "", nil, fmt.Errorf("getMachinePrivKey: %w", err)
  488. }
  489. if machinePrivKey.IsZero() {
  490. return false, "", nil, errors.New("getMachinePrivKey returned zero key")
  491. }
  492. regen := opt.Regen
  493. if opt.Logout {
  494. c.logf("logging out...")
  495. } else {
  496. if expired {
  497. c.logf("Old key expired -> regen=true")
  498. if f, ok := feature.HookSystemdStatus.GetOk(); ok {
  499. f("key expired; run 'tailscale up' to authenticate")
  500. }
  501. regen = true
  502. }
  503. if (opt.Flags & LoginInteractive) != 0 {
  504. c.logf("LoginInteractive -> regen=true")
  505. regen = true
  506. }
  507. }
  508. c.logf("doLogin(regen=%v, hasUrl=%v)", regen, opt.URL != "")
  509. if serverKey.IsZero() {
  510. keys, err := loadServerPubKeys(ctx, c.httpc, c.serverURL)
  511. if err != nil && c.interceptedDial != nil && c.interceptedDial.Load() {
  512. c.health.SetUnhealthy(macOSScreenTime, nil)
  513. } else {
  514. c.health.SetHealthy(macOSScreenTime)
  515. }
  516. if err != nil {
  517. return regen, opt.URL, nil, err
  518. }
  519. c.logf("control server key from %s: ts2021=%s, legacy=%v", c.serverURL, keys.PublicKey.ShortString(), keys.LegacyPublicKey.ShortString())
  520. c.mu.Lock()
  521. c.serverLegacyKey = keys.LegacyPublicKey
  522. c.serverNoiseKey = keys.PublicKey
  523. c.mu.Unlock()
  524. serverKey = keys.LegacyPublicKey
  525. serverNoiseKey = keys.PublicKey
  526. // Proactively shut down our TLS TCP connection.
  527. // We're not going to need it and it's nicer to the
  528. // server.
  529. c.httpc.CloseIdleConnections()
  530. }
  531. if serverNoiseKey.IsZero() {
  532. return false, "", nil, errors.New("control server is too old; no noise key")
  533. }
  534. var oldNodeKey key.NodePublic
  535. switch {
  536. case opt.Logout:
  537. tryingNewKey = persist.PrivateNodeKey
  538. case opt.URL != "":
  539. // Nothing.
  540. case regen || persist.PrivateNodeKey.IsZero():
  541. c.logf("Generating a new nodekey.")
  542. persist.OldPrivateNodeKey = persist.PrivateNodeKey
  543. tryingNewKey = key.NewNode()
  544. default:
  545. // Try refreshing the current key first
  546. tryingNewKey = persist.PrivateNodeKey
  547. }
  548. if !persist.OldPrivateNodeKey.IsZero() {
  549. oldNodeKey = persist.OldPrivateNodeKey.Public()
  550. }
  551. if persist.NetworkLockKey.IsZero() {
  552. persist.NetworkLockKey = key.NewNLPrivate()
  553. }
  554. nlPub := persist.NetworkLockKey.Public()
  555. if tryingNewKey.IsZero() {
  556. if opt.Logout {
  557. return false, "", nil, errors.New("no nodekey to log out")
  558. }
  559. log.Fatalf("tryingNewKey is empty, give up")
  560. }
  561. var nodeKeySignature tkatype.MarshaledSignature
  562. if !oldNodeKey.IsZero() && opt.OldNodeKeySignature != nil {
  563. if nodeKeySignature, err = tka.ResignNKS(persist.NetworkLockKey, tryingNewKey.Public(), opt.OldNodeKeySignature); err != nil {
  564. c.logf("Failed re-signing node-key signature: %v", err)
  565. }
  566. } else if isWrapped {
  567. // We were given a wrapped pre-auth key, which means that in addition
  568. // to being a regular pre-auth key there was a suffix with information to
  569. // generate a tailnet-lock signature.
  570. nodeKeySignature, err = tka.SignByCredential(wrappedKey, wrappedSig, tryingNewKey.Public())
  571. if err != nil {
  572. return false, "", nil, err
  573. }
  574. }
  575. if backendLogID == "" {
  576. err = errors.New("hostinfo: BackendLogID missing")
  577. return regen, opt.URL, nil, err
  578. }
  579. tailnet, err := c.polc.GetString(pkey.Tailnet, "")
  580. if err != nil {
  581. c.logf("unable to provide Tailnet field in register request. err: %v", err)
  582. }
  583. now := c.clock.Now().Round(time.Second)
  584. request := tailcfg.RegisterRequest{
  585. Version: 1,
  586. OldNodeKey: oldNodeKey,
  587. NodeKey: tryingNewKey.Public(),
  588. NLKey: nlPub,
  589. Hostinfo: hi,
  590. Followup: opt.URL,
  591. Timestamp: &now,
  592. Ephemeral: (opt.Flags & LoginEphemeral) != 0,
  593. NodeKeySignature: nodeKeySignature,
  594. Tailnet: tailnet,
  595. }
  596. if opt.Logout {
  597. request.Expiry = time.Unix(123, 0) // far in the past
  598. } else if opt.Expiry != nil {
  599. request.Expiry = *opt.Expiry
  600. }
  601. c.logf("RegisterReq: onode=%v node=%v fup=%v nks=%v",
  602. request.OldNodeKey.ShortString(),
  603. request.NodeKey.ShortString(), opt.URL != "", len(nodeKeySignature) > 0)
  604. if authKey != "" {
  605. request.Auth = &tailcfg.RegisterResponseAuth{
  606. AuthKey: authKey,
  607. }
  608. }
  609. err = signRegisterRequest(c.polc, &request, c.serverURL, c.serverLegacyKey, machinePrivKey.Public())
  610. if err != nil {
  611. // If signing failed, clear all related fields
  612. request.SignatureType = tailcfg.SignatureNone
  613. request.Timestamp = nil
  614. request.DeviceCert = nil
  615. request.Signature = nil
  616. // Don't log the common error types. Signatures are not usually enabled,
  617. // so these are expected.
  618. if !errors.Is(err, errCertificateNotConfigured) && !errors.Is(err, errNoCertStore) {
  619. c.logf("RegisterReq sign error: %v", err)
  620. }
  621. }
  622. if DevKnob.DumpRegister() {
  623. j, _ := json.MarshalIndent(request, "", "\t")
  624. c.logf("RegisterRequest: %s", j)
  625. }
  626. // URL and httpc are protocol specific.
  627. request.Version = tailcfg.CurrentCapabilityVersion
  628. httpc, err := c.getNoiseClient()
  629. if err != nil {
  630. return regen, opt.URL, nil, fmt.Errorf("getNoiseClient: %w", err)
  631. }
  632. url := fmt.Sprintf("%s/machine/register", c.serverURL)
  633. url = strings.Replace(url, "http:", "https:", 1)
  634. bodyData, err := encode(request)
  635. if err != nil {
  636. return regen, opt.URL, nil, err
  637. }
  638. req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(bodyData))
  639. if err != nil {
  640. return regen, opt.URL, nil, err
  641. }
  642. ts2021.AddLBHeader(req, request.OldNodeKey)
  643. ts2021.AddLBHeader(req, request.NodeKey)
  644. res, err := httpc.Do(req)
  645. if err != nil {
  646. return regen, opt.URL, nil, fmt.Errorf("register request: %w", err)
  647. }
  648. if res.StatusCode != 200 {
  649. msg, _ := io.ReadAll(res.Body)
  650. res.Body.Close()
  651. return regen, opt.URL, nil, fmt.Errorf("register request: http %d: %.200s",
  652. res.StatusCode, strings.TrimSpace(string(msg)))
  653. }
  654. resp := tailcfg.RegisterResponse{}
  655. if err := decode(res, &resp); err != nil {
  656. c.logf("error decoding RegisterResponse with server key %s and machine key %s: %v", serverKey, machinePrivKey.Public(), err)
  657. return regen, opt.URL, nil, fmt.Errorf("register request: %v", err)
  658. }
  659. if DevKnob.DumpRegister() {
  660. j, _ := json.MarshalIndent(resp, "", "\t")
  661. c.logf("RegisterResponse: %s", j)
  662. }
  663. // Log without PII:
  664. c.logf("RegisterReq: got response; nodeKeyExpired=%v, machineAuthorized=%v; authURL=%v",
  665. resp.NodeKeyExpired, resp.MachineAuthorized, resp.AuthURL != "")
  666. if resp.Error != "" {
  667. return false, "", nil, UserVisibleError(resp.Error)
  668. }
  669. if len(resp.NodeKeySignature) > 0 {
  670. return true, "", resp.NodeKeySignature, nil
  671. }
  672. if resp.NodeKeyExpired {
  673. if regen {
  674. return true, "", nil, fmt.Errorf("weird: regen=true but server says NodeKeyExpired: %v", request.NodeKey)
  675. }
  676. c.logf("server reports new node key %v has expired",
  677. request.NodeKey.ShortString())
  678. return true, "", nil, nil
  679. }
  680. persist.UserProfile = tailcfg.UserProfile{
  681. ID: resp.User.ID,
  682. DisplayName: resp.Login.DisplayName,
  683. ProfilePicURL: resp.Login.ProfilePicURL,
  684. LoginName: resp.Login.LoginName,
  685. }
  686. // TODO(crawshaw): RegisterResponse should be able to mechanically
  687. // communicate some extra instructions from the server:
  688. // - new node key required
  689. // - machine key no longer supported
  690. // - user is disabled
  691. if resp.AuthURL != "" {
  692. c.logf("AuthURL is %v", resp.AuthURL)
  693. } else {
  694. c.logf("[v1] No AuthURL")
  695. }
  696. c.mu.Lock()
  697. if resp.AuthURL == "" {
  698. // key rotation is complete
  699. persist.PrivateNodeKey = tryingNewKey
  700. } else {
  701. // save it for the retry-with-URL
  702. c.tryingNewKey = tryingNewKey
  703. }
  704. c.persist = persist.View()
  705. c.mu.Unlock()
  706. if ctx.Err() != nil {
  707. return regen, "", nil, ctx.Err()
  708. }
  709. return false, resp.AuthURL, nil, nil
  710. }
  711. // newEndpoints acquires c.mu and sets the local port and endpoints and reports
  712. // whether they've changed.
  713. //
  714. // It does not retain the provided slice.
  715. func (c *Direct) newEndpoints(endpoints []tailcfg.Endpoint) (changed bool) {
  716. c.mu.Lock()
  717. defer c.mu.Unlock()
  718. // Nothing new?
  719. if slices.Equal(c.endpoints, endpoints) {
  720. return false // unchanged
  721. }
  722. c.logf("[v2] client.newEndpoints(%v)", endpoints)
  723. c.endpoints = slices.Clone(endpoints)
  724. return true // changed
  725. }
  726. // SetEndpoints updates the list of locally advertised endpoints.
  727. // It won't be replicated to the server until a *fresh* call to PollNetMap().
  728. // You don't need to restart PollNetMap if we return changed==false.
  729. func (c *Direct) SetEndpoints(endpoints []tailcfg.Endpoint) (changed bool) {
  730. // (no log message on function entry, because it clutters the logs
  731. // if endpoints haven't changed. newEndpoints() will log it.)
  732. return c.newEndpoints(endpoints)
  733. }
  734. // PollNetMap makes a /map request to download the network map, calling
  735. // NetmapUpdater on each update from the control plane.
  736. //
  737. // It always returns a non-nil error describing the reason for the failure or
  738. // why the request ended.
  739. func (c *Direct) PollNetMap(ctx context.Context, nu NetmapUpdater) error {
  740. return c.sendMapRequest(ctx, true, nu)
  741. }
  742. type rememberLastNetmapUpdater struct {
  743. last *netmap.NetworkMap
  744. }
  745. func (nu *rememberLastNetmapUpdater) UpdateFullNetmap(nm *netmap.NetworkMap) {
  746. nu.last = nm
  747. }
  748. // FetchNetMapForTest fetches the netmap once.
  749. func (c *Direct) FetchNetMapForTest(ctx context.Context) (*netmap.NetworkMap, error) {
  750. var nu rememberLastNetmapUpdater
  751. err := c.sendMapRequest(ctx, false, &nu)
  752. if err == nil && nu.last == nil {
  753. return nil, errors.New("[unexpected] sendMapRequest success without callback")
  754. }
  755. return nu.last, err
  756. }
  757. // SendUpdate makes a /map request to update the server of our latest state, but
  758. // does not fetch anything. It returns an error if the server did not return a
  759. // successful 200 OK response.
  760. func (c *Direct) SendUpdate(ctx context.Context) error {
  761. return c.sendMapRequest(ctx, false, nil)
  762. }
  763. // SetDiscoPublicKey updates the disco public key in local state.
  764. // It does not implicitly trigger [SendUpdate]; callers should arrange for that.
  765. func (c *Direct) SetDiscoPublicKey(key key.DiscoPublic) {
  766. c.mu.Lock()
  767. defer c.mu.Unlock()
  768. c.discoPubKey = key
  769. }
  770. // ClientID returns the controlClientID of the controlClient.
  771. func (c *Direct) ClientID() int64 {
  772. return c.controlClientID
  773. }
  774. // AutoUpdate is an eventbus value, reporting the value of tailcfg.MapResponse.DefaultAutoUpdate.
  775. type AutoUpdate struct {
  776. ClientID int64 // The ID field is used for consumers to differentiate instances of Direct.
  777. Value bool // The Value represents DefaultAutoUpdate from [tailcfg.MapResponse].
  778. }
  779. // ControlTime is an eventbus value, reporting the value of tailcfg.MapResponse.ControlTime.
  780. type ControlTime struct {
  781. ClientID int64 // The ID field is used for consumers to differentiate instances of Direct.
  782. Value time.Time // The Value represents ControlTime from [tailcfg.MapResponse].
  783. }
  784. // If we go more than watchdogTimeout without hearing from the server,
  785. // end the long poll. We should be receiving a keep alive ping
  786. // every minute.
  787. const watchdogTimeout = 120 * time.Second
  788. // sendMapRequest makes a /map request to download the network map, calling cb
  789. // with each new netmap. If isStreaming, it will poll forever and only returns
  790. // if the context expires or the server returns an error/closes the connection
  791. // and as such always returns a non-nil error.
  792. //
  793. // If nu is nil, OmitPeers will be set to true.
  794. func (c *Direct) sendMapRequest(ctx context.Context, isStreaming bool, nu NetmapUpdater) error {
  795. if c.panicOnUse {
  796. panic("tainted client")
  797. }
  798. if isStreaming && nu == nil {
  799. panic("cb must be non-nil if isStreaming is true")
  800. }
  801. metricMapRequests.Add(1)
  802. metricMapRequestsActive.Add(1)
  803. defer metricMapRequestsActive.Add(-1)
  804. if isStreaming {
  805. metricMapRequestsPoll.Add(1)
  806. } else {
  807. metricMapRequestsLite.Add(1)
  808. }
  809. c.mu.Lock()
  810. persist := c.persist
  811. serverURL := c.serverURL
  812. serverNoiseKey := c.serverNoiseKey
  813. discoKey := c.discoPubKey
  814. hi := c.hostInfoLocked()
  815. backendLogID := hi.BackendLogID
  816. connectionHandleForTest := c.connectionHandleForTest
  817. tkaHead := c.tkaHead
  818. var epStrs []string
  819. var eps []netip.AddrPort
  820. var epTypes []tailcfg.EndpointType
  821. for _, ep := range c.endpoints {
  822. eps = append(eps, ep.Addr)
  823. epStrs = append(epStrs, ep.Addr.String())
  824. epTypes = append(epTypes, ep.Type)
  825. }
  826. c.mu.Unlock()
  827. if serverNoiseKey.IsZero() {
  828. return errors.New("control server is too old; no noise key")
  829. }
  830. machinePrivKey, err := c.getMachinePrivKey()
  831. if err != nil {
  832. return fmt.Errorf("getMachinePrivKey: %w", err)
  833. }
  834. if machinePrivKey.IsZero() {
  835. return errors.New("getMachinePrivKey returned zero key")
  836. }
  837. if persist.PrivateNodeKey().IsZero() {
  838. return errors.New("privateNodeKey is zero")
  839. }
  840. if backendLogID == "" {
  841. return errors.New("hostinfo: BackendLogID missing")
  842. }
  843. c.logf("[v1] PollNetMap: stream=%v ep=%v", isStreaming, epStrs)
  844. vlogf := logger.Discard
  845. if DevKnob.DumpNetMapsVerbose() {
  846. // TODO(bradfitz): update this to use "[v2]" prefix perhaps? but we don't
  847. // want to upload it always.
  848. vlogf = c.logf
  849. }
  850. nodeKey := persist.PublicNodeKey()
  851. request := &tailcfg.MapRequest{
  852. Version: tailcfg.CurrentCapabilityVersion,
  853. KeepAlive: true,
  854. NodeKey: nodeKey,
  855. DiscoKey: discoKey,
  856. Endpoints: eps,
  857. EndpointTypes: epTypes,
  858. Stream: isStreaming,
  859. Hostinfo: hi,
  860. DebugFlags: c.debugFlags,
  861. OmitPeers: nu == nil,
  862. TKAHead: tkaHead,
  863. ConnectionHandleForTest: connectionHandleForTest,
  864. }
  865. // If we have a hardware attestation key, sign the node key with it and send
  866. // the key & signature in the map request.
  867. if buildfeatures.HasTPM {
  868. if k := persist.AsStruct().AttestationKey; k != nil && !k.IsZero() {
  869. hwPub := key.HardwareAttestationPublicFromPlatformKey(k)
  870. request.HardwareAttestationKey = hwPub
  871. t := c.clock.Now()
  872. msg := fmt.Sprintf("%d|%s", t.Unix(), nodeKey.String())
  873. digest := sha256.Sum256([]byte(msg))
  874. sig, err := k.Sign(nil, digest[:], crypto.SHA256)
  875. if err != nil {
  876. c.logf("failed to sign node key with hardware attestation key: %v", err)
  877. } else {
  878. request.HardwareAttestationKeySignature = sig
  879. request.HardwareAttestationKeySignatureTimestamp = t
  880. }
  881. }
  882. }
  883. var extraDebugFlags []string
  884. if buildfeatures.HasAdvertiseRoutes && hi != nil && c.netMon != nil && !c.skipIPForwardingCheck &&
  885. ipForwardingBroken(hi.RoutableIPs, c.netMon.InterfaceState()) {
  886. extraDebugFlags = append(extraDebugFlags, "warn-ip-forwarding-off")
  887. }
  888. if c.health.RouterHealth() != nil {
  889. extraDebugFlags = append(extraDebugFlags, "warn-router-unhealthy")
  890. }
  891. extraDebugFlags = c.health.AppendWarnableDebugFlags(extraDebugFlags)
  892. if hostinfo.DisabledEtcAptSource() {
  893. extraDebugFlags = append(extraDebugFlags, "warn-etc-apt-source-disabled")
  894. }
  895. if len(extraDebugFlags) > 0 {
  896. old := request.DebugFlags
  897. request.DebugFlags = append(old[:len(old):len(old)], extraDebugFlags...)
  898. }
  899. request.Compress = "zstd"
  900. bodyData, err := encode(request)
  901. if err != nil {
  902. vlogf("netmap: encode: %v", err)
  903. return err
  904. }
  905. ctx, cancel := context.WithCancel(ctx)
  906. defer cancel()
  907. machinePubKey := machinePrivKey.Public()
  908. t0 := c.clock.Now()
  909. httpc, err := c.getNoiseClient()
  910. if err != nil {
  911. return fmt.Errorf("getNoiseClient: %w", err)
  912. }
  913. url := fmt.Sprintf("%s/machine/map", serverURL)
  914. url = strings.Replace(url, "http:", "https:", 1)
  915. // Create a watchdog timer that breaks the connection if we don't receive a
  916. // MapResponse from the network at least once every two minutes. The
  917. // watchdog timer is stopped every time we receive a MapResponse (so it
  918. // doesn't run when we're processing a MapResponse message, including any
  919. // long-running requested operations like Debug.Sleep) and is reset whenever
  920. // we go back to blocking on network reads.
  921. // The watchdog timer also covers the initial request (effectively the
  922. // pre-body and initial-body read timeouts) as we do not have any other
  923. // keep-alive mechanism for the initial request.
  924. watchdogTimer, watchdogTimedOut := c.clock.NewTimer(watchdogTimeout)
  925. defer watchdogTimer.Stop()
  926. go func() {
  927. select {
  928. case <-ctx.Done():
  929. vlogf("netmap: ending timeout goroutine")
  930. return
  931. case <-watchdogTimedOut:
  932. c.logf("map response long-poll timed out!")
  933. cancel()
  934. return
  935. }
  936. }()
  937. req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(bodyData))
  938. if err != nil {
  939. return err
  940. }
  941. ts2021.AddLBHeader(req, nodeKey)
  942. res, err := httpc.Do(req)
  943. if err != nil {
  944. vlogf("netmap: Do: %v", err)
  945. return err
  946. }
  947. vlogf("netmap: Do = %v after %v", res.StatusCode, time.Since(t0).Round(time.Millisecond))
  948. if res.StatusCode != 200 {
  949. msg, _ := io.ReadAll(res.Body)
  950. res.Body.Close()
  951. return fmt.Errorf("initial fetch failed %d: %.200s",
  952. res.StatusCode, strings.TrimSpace(string(msg)))
  953. }
  954. defer res.Body.Close()
  955. c.health.NoteMapRequestHeard(request)
  956. watchdogTimer.Reset(watchdogTimeout)
  957. if nu == nil {
  958. io.Copy(io.Discard, res.Body)
  959. return nil
  960. }
  961. sess := newMapSession(persist.PrivateNodeKey(), nu, c.controlKnobs)
  962. defer sess.Close()
  963. sess.cancel = cancel
  964. sess.logf = c.logf
  965. sess.vlogf = vlogf
  966. sess.altClock = c.clock
  967. sess.machinePubKey = machinePubKey
  968. sess.onDebug = c.handleDebugMessage
  969. sess.onSelfNodeChanged = func(nm *netmap.NetworkMap) {
  970. c.mu.Lock()
  971. defer c.mu.Unlock()
  972. // If we are the ones who last updated persist, then we can update it
  973. // again. Otherwise, we should not touch it. Also, it's only worth
  974. // change it if the Node info changed.
  975. if persist == c.persist {
  976. newPersist := persist.AsStruct()
  977. newPersist.NodeID = nm.SelfNode.StableID()
  978. if up, ok := nm.UserProfiles[nm.User()]; ok {
  979. newPersist.UserProfile = *up.AsStruct()
  980. }
  981. c.persist = newPersist.View()
  982. persist = c.persist
  983. }
  984. c.expiry = nm.SelfKeyExpiry()
  985. }
  986. // gotNonKeepAliveMessage is whether we've yet received a MapResponse message without
  987. // KeepAlive set.
  988. var gotNonKeepAliveMessage bool
  989. // If allowStream, then the server will use an HTTP long poll to
  990. // return incremental results. There is always one response right
  991. // away, followed by a delay, and eventually others.
  992. // If !allowStream, it'll still send the first result in exactly
  993. // the same format before just closing the connection.
  994. // We can use this same read loop either way.
  995. var msg []byte
  996. for mapResIdx := 0; mapResIdx == 0 || isStreaming; mapResIdx++ {
  997. watchdogTimer.Reset(watchdogTimeout)
  998. vlogf("netmap: starting size read after %v (poll %v)", time.Since(t0).Round(time.Millisecond), mapResIdx)
  999. var siz [4]byte
  1000. if _, err := io.ReadFull(res.Body, siz[:]); err != nil {
  1001. vlogf("netmap: size read error after %v: %v", time.Since(t0).Round(time.Millisecond), err)
  1002. return err
  1003. }
  1004. size := binary.LittleEndian.Uint32(siz[:])
  1005. vlogf("netmap: read size %v after %v", size, time.Since(t0).Round(time.Millisecond))
  1006. msg = append(msg[:0], make([]byte, size)...)
  1007. if _, err := io.ReadFull(res.Body, msg); err != nil {
  1008. vlogf("netmap: body read error: %v", err)
  1009. return err
  1010. }
  1011. vlogf("netmap: read body after %v", time.Since(t0).Round(time.Millisecond))
  1012. var resp tailcfg.MapResponse
  1013. if err := sess.decodeMsg(msg, &resp); err != nil {
  1014. vlogf("netmap: decode error: %v", err)
  1015. return err
  1016. }
  1017. watchdogTimer.Stop()
  1018. metricMapResponseMessages.Add(1)
  1019. if isStreaming {
  1020. c.health.GotStreamedMapResponse()
  1021. }
  1022. if pr := resp.PingRequest; pr != nil && c.isUniquePingRequest(pr) {
  1023. metricMapResponsePings.Add(1)
  1024. go c.answerPing(pr)
  1025. }
  1026. if u := resp.PopBrowserURL; u != "" && u != sess.lastPopBrowserURL {
  1027. sess.lastPopBrowserURL = u
  1028. if c.popBrowser != nil {
  1029. c.logf("netmap: control says to open URL %v; opening...", u)
  1030. c.popBrowser(u)
  1031. } else {
  1032. c.logf("netmap: control says to open URL %v; no popBrowser func", u)
  1033. }
  1034. }
  1035. if resp.ClientVersion != nil {
  1036. c.clientVersionPub.Publish(*resp.ClientVersion)
  1037. }
  1038. if resp.ControlTime != nil && !resp.ControlTime.IsZero() {
  1039. c.logf.JSON(1, "controltime", resp.ControlTime.UTC())
  1040. c.controlTimePub.Publish(ControlTime{c.controlClientID, *resp.ControlTime})
  1041. }
  1042. if resp.KeepAlive {
  1043. vlogf("netmap: got keep-alive")
  1044. } else {
  1045. vlogf("netmap: got new map")
  1046. }
  1047. if resp.ControlDialPlan != nil && !ignoreDialPlan() {
  1048. if c.dialPlan != nil {
  1049. c.logf("netmap: got new dial plan from control")
  1050. c.dialPlan.Store(resp.ControlDialPlan)
  1051. } else {
  1052. c.logf("netmap: [unexpected] new dial plan; nowhere to store it")
  1053. }
  1054. }
  1055. if resp.KeepAlive {
  1056. metricMapResponseKeepAlives.Add(1)
  1057. continue
  1058. }
  1059. // DefaultAutoUpdate in its CapMap and deprecated top-level field forms.
  1060. if self := resp.Node; self != nil {
  1061. for _, v := range self.CapMap[tailcfg.NodeAttrDefaultAutoUpdate] {
  1062. switch v {
  1063. case "true", "false":
  1064. c.autoUpdatePub.Publish(AutoUpdate{c.controlClientID, v == "true"})
  1065. default:
  1066. c.logf("netmap: [unexpected] unknown %s in CapMap: %q", tailcfg.NodeAttrDefaultAutoUpdate, v)
  1067. }
  1068. }
  1069. }
  1070. if au, ok := resp.DeprecatedDefaultAutoUpdate.Get(); ok {
  1071. c.autoUpdatePub.Publish(AutoUpdate{c.controlClientID, au})
  1072. }
  1073. metricMapResponseMap.Add(1)
  1074. if gotNonKeepAliveMessage {
  1075. // If we've already seen a non-keep-alive message, this is a delta update.
  1076. metricMapResponseMapDelta.Add(1)
  1077. } else if resp.Node == nil {
  1078. // The very first non-keep-alive message should have Node populated.
  1079. c.logf("initial MapResponse lacked Node")
  1080. return errors.New("initial MapResponse lacked node")
  1081. }
  1082. gotNonKeepAliveMessage = true
  1083. if err := sess.HandleNonKeepAliveMapResponse(ctx, &resp); err != nil {
  1084. return err
  1085. }
  1086. }
  1087. if ctx.Err() != nil {
  1088. return ctx.Err()
  1089. }
  1090. return nil
  1091. }
  1092. // NetmapFromMapResponseForDebug returns a NetworkMap from the given MapResponse.
  1093. // It is intended for debugging only.
  1094. func NetmapFromMapResponseForDebug(ctx context.Context, pr persist.PersistView, resp *tailcfg.MapResponse) (*netmap.NetworkMap, error) {
  1095. if resp == nil {
  1096. return nil, errors.New("nil MapResponse")
  1097. }
  1098. if resp.Node == nil {
  1099. return nil, errors.New("MapResponse lacks Node")
  1100. }
  1101. if !pr.Valid() {
  1102. return nil, errors.New("PersistView invalid")
  1103. }
  1104. nu := &rememberLastNetmapUpdater{}
  1105. sess := newMapSession(pr.PrivateNodeKey(), nu, nil)
  1106. defer sess.Close()
  1107. if err := sess.HandleNonKeepAliveMapResponse(ctx, resp); err != nil {
  1108. return nil, fmt.Errorf("HandleNonKeepAliveMapResponse: %w", err)
  1109. }
  1110. return sess.netmap(), nil
  1111. }
  1112. func (c *Direct) handleDebugMessage(ctx context.Context, debug *tailcfg.Debug) error {
  1113. if code := debug.Exit; code != nil {
  1114. c.logf("exiting process with status %v per controlplane", *code)
  1115. os.Exit(*code)
  1116. }
  1117. if buildfeatures.HasLogTail && debug.DisableLogTail {
  1118. logtail.Disable()
  1119. envknob.SetNoLogsNoSupport()
  1120. }
  1121. if sleep := time.Duration(debug.SleepSeconds * float64(time.Second)); sleep > 0 {
  1122. if err := sleepAsRequested(ctx, c.logf, sleep, c.clock); err != nil {
  1123. return err
  1124. }
  1125. }
  1126. return nil
  1127. }
  1128. // initDisplayNames mutates any tailcfg.Nodes in resp to populate their display names,
  1129. // calling InitDisplayNames on each.
  1130. //
  1131. // The magicDNSSuffix used is based on selfNode.
  1132. func initDisplayNames(selfNode tailcfg.NodeView, resp *tailcfg.MapResponse) {
  1133. if resp.Node == nil && len(resp.Peers) == 0 && len(resp.PeersChanged) == 0 {
  1134. // Fast path for a common case (delta updates). No need to compute
  1135. // magicDNSSuffix.
  1136. return
  1137. }
  1138. magicDNSSuffix := netmap.MagicDNSSuffixOfNodeName(selfNode.Name())
  1139. if resp.Node != nil {
  1140. resp.Node.InitDisplayNames(magicDNSSuffix)
  1141. }
  1142. for _, n := range resp.Peers {
  1143. n.InitDisplayNames(magicDNSSuffix)
  1144. }
  1145. for _, n := range resp.PeersChanged {
  1146. n.InitDisplayNames(magicDNSSuffix)
  1147. }
  1148. }
  1149. // decode JSON decodes the res.Body into v.
  1150. func decode(res *http.Response, v any) error {
  1151. defer res.Body.Close()
  1152. msg, err := io.ReadAll(io.LimitReader(res.Body, 1<<20))
  1153. if err != nil {
  1154. return err
  1155. }
  1156. if res.StatusCode != 200 {
  1157. return fmt.Errorf("%d: %v", res.StatusCode, string(msg))
  1158. }
  1159. return json.Unmarshal(msg, v)
  1160. }
  1161. var jsonEscapedZero = []byte(`\u0000`)
  1162. const justKeepAliveStr = `{"KeepAlive":true}`
  1163. // decodeMsg is responsible for uncompressing msg and unmarshaling into v.
  1164. func (sess *mapSession) decodeMsg(compressedMsg []byte, v *tailcfg.MapResponse) error {
  1165. // Fast path for common case of keep-alive message.
  1166. // See tailscale/tailscale#17343.
  1167. if sess.keepAliveZ != nil && bytes.Equal(compressedMsg, sess.keepAliveZ) {
  1168. v.KeepAlive = true
  1169. return nil
  1170. }
  1171. b, err := zstdframe.AppendDecode(nil, compressedMsg)
  1172. if err != nil {
  1173. return err
  1174. }
  1175. sess.ztdDecodesForTest++
  1176. if DevKnob.DumpNetMaps() {
  1177. var buf bytes.Buffer
  1178. json.Indent(&buf, b, "", " ")
  1179. log.Printf("MapResponse: %s", buf.Bytes())
  1180. }
  1181. if bytes.Contains(b, jsonEscapedZero) {
  1182. log.Printf("[unexpected] zero byte in controlclient.Direct.decodeMsg into %T: %q", v, b)
  1183. }
  1184. if err := json.Unmarshal(b, v); err != nil {
  1185. return fmt.Errorf("response: %v", err)
  1186. }
  1187. if v.KeepAlive && string(b) == justKeepAliveStr {
  1188. sess.keepAliveZ = compressedMsg
  1189. }
  1190. return nil
  1191. }
  1192. // encode JSON encodes v as JSON, logging tailcfg.MapRequest values if
  1193. // debugMap is set.
  1194. func encode(v any) ([]byte, error) {
  1195. b, err := json.Marshal(v)
  1196. if err != nil {
  1197. return nil, err
  1198. }
  1199. if DevKnob.DumpNetMaps() {
  1200. if _, ok := v.(*tailcfg.MapRequest); ok {
  1201. log.Printf("MapRequest: %s", b)
  1202. }
  1203. }
  1204. return b, nil
  1205. }
  1206. func loadServerPubKeys(ctx context.Context, httpc *http.Client, serverURL string) (*tailcfg.OverTLSPublicKeyResponse, error) {
  1207. keyURL := fmt.Sprintf("%v/key?v=%d", serverURL, tailcfg.CurrentCapabilityVersion)
  1208. req, err := http.NewRequestWithContext(ctx, "GET", keyURL, nil)
  1209. if err != nil {
  1210. return nil, fmt.Errorf("create control key request: %v", err)
  1211. }
  1212. res, err := httpc.Do(req)
  1213. if err != nil {
  1214. return nil, fmt.Errorf("fetch control key: %v", err)
  1215. }
  1216. defer res.Body.Close()
  1217. b, err := io.ReadAll(io.LimitReader(res.Body, 64<<10))
  1218. if err != nil {
  1219. return nil, fmt.Errorf("fetch control key response: %v", err)
  1220. }
  1221. if res.StatusCode != 200 {
  1222. return nil, fmt.Errorf("fetch control key: %v", res.Status)
  1223. }
  1224. var out tailcfg.OverTLSPublicKeyResponse
  1225. jsonErr := json.Unmarshal(b, &out)
  1226. if jsonErr == nil {
  1227. return &out, nil
  1228. }
  1229. // Some old control servers might not be updated to send the new format.
  1230. // Accept the old pre-JSON format too.
  1231. out = tailcfg.OverTLSPublicKeyResponse{}
  1232. k, err := key.ParseMachinePublicUntyped(mem.B(b))
  1233. if err != nil {
  1234. return nil, errors.Join(jsonErr, err)
  1235. }
  1236. out.LegacyPublicKey = k
  1237. return &out, nil
  1238. }
  1239. // DevKnob contains temporary internal-only debug knobs.
  1240. // They're unexported to not draw attention to them.
  1241. var DevKnob = initDevKnob()
  1242. type devKnobs struct {
  1243. DumpRegister func() bool
  1244. DumpNetMaps func() bool
  1245. DumpNetMapsVerbose func() bool
  1246. ForceProxyDNS func() bool
  1247. StripEndpoints func() bool // strip endpoints from control (only use disco messages)
  1248. StripHomeDERP func() bool // strip Home DERP from control
  1249. StripCaps func() bool // strip all local node's control-provided capabilities
  1250. }
  1251. func initDevKnob() devKnobs {
  1252. nm := envknob.RegisterInt("TS_DEBUG_MAP")
  1253. return devKnobs{
  1254. DumpNetMaps: func() bool { return nm() > 0 },
  1255. DumpNetMapsVerbose: func() bool { return nm() > 1 },
  1256. DumpRegister: envknob.RegisterBool("TS_DEBUG_REGISTER"),
  1257. ForceProxyDNS: envknob.RegisterBool("TS_DEBUG_PROXY_DNS"),
  1258. StripEndpoints: envknob.RegisterBool("TS_DEBUG_STRIP_ENDPOINTS"),
  1259. StripHomeDERP: envknob.RegisterBool("TS_DEBUG_STRIP_HOME_DERP"),
  1260. StripCaps: envknob.RegisterBool("TS_DEBUG_STRIP_CAPS"),
  1261. }
  1262. }
  1263. var clock tstime.Clock = tstime.StdClock{}
  1264. // ipForwardingBroken reports whether the system's IP forwarding is disabled
  1265. // and will definitely not work for the routes provided.
  1266. //
  1267. // It should not return false positives.
  1268. //
  1269. // TODO(bradfitz): Change controlclient.Options.SkipIPForwardingCheck into a
  1270. // func([]netip.Prefix) error signature instead.
  1271. func ipForwardingBroken(routes []netip.Prefix, state *netmon.State) bool {
  1272. warn, err := netutil.CheckIPForwarding(routes, state)
  1273. if err != nil {
  1274. // Oh well, we tried. This is just for debugging.
  1275. // We don't want false positives.
  1276. // TODO: maybe we want a different warning for inability to check?
  1277. return false
  1278. }
  1279. return warn != nil
  1280. }
  1281. // isUniquePingRequest reports whether pr contains a new PingRequest.URL
  1282. // not already handled, noting its value when returning true.
  1283. func (c *Direct) isUniquePingRequest(pr *tailcfg.PingRequest) bool {
  1284. if pr == nil || pr.URL == "" {
  1285. // Bogus.
  1286. return false
  1287. }
  1288. c.mu.Lock()
  1289. defer c.mu.Unlock()
  1290. if pr.URL == c.lastPingURL {
  1291. return false
  1292. }
  1293. c.lastPingURL = pr.URL
  1294. return true
  1295. }
  1296. // HookAnswerC2NPing is where feature/c2n conditionally registers support
  1297. // for handling C2N (control-to-node) HTTP requests.
  1298. var HookAnswerC2NPing feature.Hook[func(logger.Logf, http.Handler, *http.Client, *tailcfg.PingRequest)]
  1299. func (c *Direct) answerPing(pr *tailcfg.PingRequest) {
  1300. httpc := c.httpc
  1301. useNoise := pr.URLIsNoise || pr.Types == "c2n"
  1302. if useNoise {
  1303. nc, err := c.getNoiseClient()
  1304. if err != nil {
  1305. c.logf("failed to get noise client for ping request: %v", err)
  1306. return
  1307. }
  1308. httpc = nc.Client
  1309. }
  1310. if pr.URL == "" {
  1311. c.logf("invalid PingRequest with no URL")
  1312. return
  1313. }
  1314. switch pr.Types {
  1315. case "":
  1316. answerHeadPing(c.logf, httpc, pr)
  1317. return
  1318. case "c2n":
  1319. if !buildfeatures.HasC2N {
  1320. return
  1321. }
  1322. if !useNoise && !envknob.Bool("TS_DEBUG_PERMIT_HTTP_C2N") {
  1323. c.logf("refusing to answer c2n ping without noise")
  1324. return
  1325. }
  1326. if f, ok := HookAnswerC2NPing.GetOk(); ok {
  1327. f(c.logf, c.c2nHandler, httpc, pr)
  1328. }
  1329. return
  1330. }
  1331. for _, t := range strings.Split(pr.Types, ",") {
  1332. switch pt := tailcfg.PingType(t); pt {
  1333. case tailcfg.PingTSMP, tailcfg.PingDisco, tailcfg.PingICMP, tailcfg.PingPeerAPI:
  1334. go doPingerPing(c.logf, httpc, pr, c.pinger, pt)
  1335. default:
  1336. c.logf("unsupported ping request type: %q", t)
  1337. }
  1338. }
  1339. }
  1340. func answerHeadPing(logf logger.Logf, c *http.Client, pr *tailcfg.PingRequest) {
  1341. ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
  1342. defer cancel()
  1343. req, err := http.NewRequestWithContext(ctx, "HEAD", pr.URL, nil)
  1344. if err != nil {
  1345. logf("answerHeadPing: NewRequestWithContext: %v", err)
  1346. return
  1347. }
  1348. if pr.Log {
  1349. logf("answerHeadPing: sending HEAD ping to %v ...", pr.URL)
  1350. }
  1351. t0 := clock.Now()
  1352. _, err = c.Do(req)
  1353. d := clock.Since(t0).Round(time.Millisecond)
  1354. if err != nil {
  1355. logf("answerHeadPing error: %v to %v (after %v)", err, pr.URL, d)
  1356. } else if pr.Log {
  1357. logf("answerHeadPing complete to %v (after %v)", pr.URL, d)
  1358. }
  1359. }
  1360. // sleepAsRequest implements the sleep for a tailcfg.Debug message requesting
  1361. // that the client sleep. The complication is that while we're sleeping (if for
  1362. // a long time), we need to periodically reset the watchdog timer before it
  1363. // expires.
  1364. func sleepAsRequested(ctx context.Context, logf logger.Logf, d time.Duration, clock tstime.Clock) error {
  1365. const maxSleep = 5 * time.Minute
  1366. if d > maxSleep {
  1367. logf("sleeping for %v, capped from server-requested %v ...", maxSleep, d)
  1368. d = maxSleep
  1369. } else {
  1370. logf("sleeping for server-requested %v ...", d)
  1371. }
  1372. timer, timerChannel := clock.NewTimer(d)
  1373. defer timer.Stop()
  1374. select {
  1375. case <-ctx.Done():
  1376. return ctx.Err()
  1377. case <-timerChannel:
  1378. return nil
  1379. }
  1380. }
  1381. // getNoiseClient returns the noise client, creating one if one doesn't exist.
  1382. func (c *Direct) getNoiseClient() (*ts2021.Client, error) {
  1383. c.mu.Lock()
  1384. serverNoiseKey := c.serverNoiseKey
  1385. nc := c.noiseClient
  1386. c.mu.Unlock()
  1387. if serverNoiseKey.IsZero() {
  1388. return nil, errors.New("zero serverNoiseKey")
  1389. }
  1390. if nc != nil {
  1391. return nc, nil
  1392. }
  1393. var dp func() *tailcfg.ControlDialPlan
  1394. if c.dialPlan != nil {
  1395. dp = c.dialPlan.Load
  1396. }
  1397. nc, err, _ := c.sfGroup.Do(struct{}{}, func() (*ts2021.Client, error) {
  1398. k, err := c.getMachinePrivKey()
  1399. if err != nil {
  1400. return nil, err
  1401. }
  1402. c.logf("[v1] creating new noise client")
  1403. nc, err := ts2021.NewClient(ts2021.ClientOpts{
  1404. PrivKey: k,
  1405. ServerPubKey: serverNoiseKey,
  1406. ServerURL: c.serverURL,
  1407. Dialer: c.dialer,
  1408. DNSCache: c.dnsCache,
  1409. Logf: c.logf,
  1410. NetMon: c.netMon,
  1411. HealthTracker: c.health,
  1412. DialPlan: dp,
  1413. })
  1414. if err != nil {
  1415. return nil, err
  1416. }
  1417. c.mu.Lock()
  1418. defer c.mu.Unlock()
  1419. c.noiseClient = nc
  1420. return nc, nil
  1421. })
  1422. if err != nil {
  1423. return nil, err
  1424. }
  1425. return nc, nil
  1426. }
  1427. // setDNSNoise sends the SetDNSRequest request to the control plane server over Noise,
  1428. // requesting a DNS record be created or updated.
  1429. func (c *Direct) setDNSNoise(ctx context.Context, req *tailcfg.SetDNSRequest) error {
  1430. newReq := *req
  1431. newReq.Version = tailcfg.CurrentCapabilityVersion
  1432. nc, err := c.getNoiseClient()
  1433. if err != nil {
  1434. return err
  1435. }
  1436. res, err := nc.Post(ctx, "/machine/set-dns", newReq.NodeKey, &newReq)
  1437. if err != nil {
  1438. return err
  1439. }
  1440. defer res.Body.Close()
  1441. if res.StatusCode != 200 {
  1442. msg, _ := io.ReadAll(res.Body)
  1443. return fmt.Errorf("set-dns response: %v, %.200s", res.Status, strings.TrimSpace(string(msg)))
  1444. }
  1445. var setDNSRes tailcfg.SetDNSResponse
  1446. if err := json.NewDecoder(res.Body).Decode(&setDNSRes); err != nil {
  1447. c.logf("error decoding SetDNSResponse: %v", err)
  1448. return fmt.Errorf("set-dns-response: %w", err)
  1449. }
  1450. return nil
  1451. }
  1452. // SetDNS sends the SetDNSRequest request to the control plane server,
  1453. // requesting a DNS record be created or updated.
  1454. func (c *Direct) SetDNS(ctx context.Context, req *tailcfg.SetDNSRequest) (err error) {
  1455. if !buildfeatures.HasACME {
  1456. return feature.ErrUnavailable
  1457. }
  1458. metricSetDNS.Add(1)
  1459. defer func() {
  1460. if err != nil {
  1461. metricSetDNSError.Add(1)
  1462. }
  1463. }()
  1464. return c.setDNSNoise(ctx, req)
  1465. }
  1466. func (c *Direct) DoNoiseRequest(req *http.Request) (*http.Response, error) {
  1467. if c.panicOnUse {
  1468. panic("tainted client")
  1469. }
  1470. nc, err := c.getNoiseClient()
  1471. if err != nil {
  1472. return nil, err
  1473. }
  1474. return nc.Do(req)
  1475. }
  1476. // doPingerPing sends a Ping to pr.IP using pinger, and sends an http request back to
  1477. // pr.URL with ping response data.
  1478. func doPingerPing(logf logger.Logf, c *http.Client, pr *tailcfg.PingRequest, pinger Pinger, pingType tailcfg.PingType) {
  1479. if pr.URL == "" || !pr.IP.IsValid() || pinger == nil {
  1480. logf("invalid ping request: missing url, ip or pinger")
  1481. return
  1482. }
  1483. start := clock.Now()
  1484. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  1485. defer cancel()
  1486. res, err := pinger.Ping(ctx, pr.IP, pingType, 0)
  1487. if err != nil {
  1488. d := time.Since(start).Round(time.Millisecond)
  1489. logf("doPingerPing: ping error of type %q to %v after %v: %v", pingType, pr.IP, d, err)
  1490. return
  1491. }
  1492. postPingResult(start, logf, c, pr, res.ToPingResponse(pingType))
  1493. }
  1494. func postPingResult(start time.Time, logf logger.Logf, c *http.Client, pr *tailcfg.PingRequest, res *tailcfg.PingResponse) error {
  1495. duration := time.Since(start)
  1496. if pr.Log {
  1497. if res.Err == "" {
  1498. logf("ping to %v completed in %v. pinger.Ping took %v seconds", pr.IP, res.LatencySeconds, duration)
  1499. } else {
  1500. logf("ping to %v failed after %v: %v", pr.IP, duration, res.Err)
  1501. }
  1502. }
  1503. ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
  1504. defer cancel()
  1505. jsonPingRes, err := json.Marshal(res)
  1506. if err != nil {
  1507. return err
  1508. }
  1509. // Send the results of the Ping, back to control URL.
  1510. req, err := http.NewRequestWithContext(ctx, "POST", pr.URL, bytes.NewReader(jsonPingRes))
  1511. if err != nil {
  1512. return fmt.Errorf("http.NewRequestWithContext(%q): %w", pr.URL, err)
  1513. }
  1514. if pr.Log {
  1515. logf("postPingResult: sending ping results to %v ...", pr.URL)
  1516. }
  1517. t0 := clock.Now()
  1518. _, err = c.Do(req)
  1519. d := time.Since(t0).Round(time.Millisecond)
  1520. if err != nil {
  1521. return fmt.Errorf("postPingResult error: %w to %v (after %v)", err, pr.URL, d)
  1522. } else if pr.Log {
  1523. logf("postPingResult complete to %v (after %v)", pr.URL, d)
  1524. }
  1525. return nil
  1526. }
  1527. // SetDeviceAttrs does a synchronous call to the control plane to update
  1528. // the node's attributes.
  1529. //
  1530. // See docs on [tailcfg.SetDeviceAttributesRequest] for background.
  1531. func (c *Auto) SetDeviceAttrs(ctx context.Context, attrs tailcfg.AttrUpdate) error {
  1532. return c.direct.SetDeviceAttrs(ctx, attrs)
  1533. }
  1534. // SetDeviceAttrs does a synchronous call to the control plane to update
  1535. // the node's attributes.
  1536. //
  1537. // See docs on [tailcfg.SetDeviceAttributesRequest] for background.
  1538. func (c *Direct) SetDeviceAttrs(ctx context.Context, attrs tailcfg.AttrUpdate) error {
  1539. nc, err := c.getNoiseClient()
  1540. if err != nil {
  1541. return fmt.Errorf("%w: %w", errNoNoiseClient, err)
  1542. }
  1543. nodeKey, ok := c.GetPersist().PublicNodeKeyOK()
  1544. if !ok {
  1545. return errNoNodeKey
  1546. }
  1547. if c.panicOnUse {
  1548. panic("tainted client")
  1549. }
  1550. req := &tailcfg.SetDeviceAttributesRequest{
  1551. NodeKey: nodeKey,
  1552. Version: tailcfg.CurrentCapabilityVersion,
  1553. Update: attrs,
  1554. }
  1555. // TODO(bradfitz): unify the callers using doWithBody vs those using
  1556. // DoNoiseRequest. There seems to be a ~50/50 split and they're very close,
  1557. // but doWithBody sets the load balancing header and auto-JSON-encodes the
  1558. // body, but DoNoiseRequest is exported. Clean it up so they're consistent
  1559. // one way or another.
  1560. ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
  1561. defer cancel()
  1562. res, err := nc.DoWithBody(ctx, "PATCH", "/machine/set-device-attr", nodeKey, req)
  1563. if err != nil {
  1564. return err
  1565. }
  1566. defer res.Body.Close()
  1567. all, _ := io.ReadAll(res.Body)
  1568. if res.StatusCode != 200 {
  1569. return fmt.Errorf("HTTP error from control plane: %v: %s", res.Status, all)
  1570. }
  1571. return nil
  1572. }
  1573. // SendAuditLog implements [auditlog.Transport] by sending an audit log synchronously to the control plane.
  1574. //
  1575. // See docs on [tailcfg.AuditLogRequest] and [auditlog.Logger] for background.
  1576. func (c *Auto) SendAuditLog(ctx context.Context, auditLog tailcfg.AuditLogRequest) (err error) {
  1577. return c.direct.sendAuditLog(ctx, auditLog)
  1578. }
  1579. func (c *Direct) sendAuditLog(ctx context.Context, auditLog tailcfg.AuditLogRequest) (err error) {
  1580. nc, err := c.getNoiseClient()
  1581. if err != nil {
  1582. return fmt.Errorf("%w: %w", errNoNoiseClient, err)
  1583. }
  1584. nodeKey, ok := c.GetPersist().PublicNodeKeyOK()
  1585. if !ok {
  1586. return errNoNodeKey
  1587. }
  1588. req := &tailcfg.AuditLogRequest{
  1589. Version: tailcfg.CurrentCapabilityVersion,
  1590. NodeKey: nodeKey,
  1591. Action: auditLog.Action,
  1592. Details: auditLog.Details,
  1593. }
  1594. if c.panicOnUse {
  1595. panic("tainted client")
  1596. }
  1597. res, err := nc.Post(ctx, "/machine/audit-log", nodeKey, req)
  1598. if err != nil {
  1599. return fmt.Errorf("%w: %w", errHTTPPostFailure, err)
  1600. }
  1601. defer res.Body.Close()
  1602. if res.StatusCode != 200 {
  1603. all, _ := io.ReadAll(res.Body)
  1604. return errBadHTTPResponse(res.StatusCode, string(all))
  1605. }
  1606. return nil
  1607. }
  1608. // makeScreenTimeDetectingDialFunc returns dialFunc, optionally wrapped (on
  1609. // Apple systems) with a func that sets the returned atomic.Bool for whether
  1610. // Screen Time seemed to intercept the connection.
  1611. //
  1612. // The returned *atomic.Bool is nil on non-Apple systems.
  1613. func makeScreenTimeDetectingDialFunc(dial netx.DialFunc) (netx.DialFunc, *atomic.Bool) {
  1614. switch runtime.GOOS {
  1615. case "darwin", "ios":
  1616. // Continue below.
  1617. default:
  1618. return dial, nil
  1619. }
  1620. ab := new(atomic.Bool)
  1621. return func(ctx context.Context, network, addr string) (net.Conn, error) {
  1622. c, err := dial(ctx, network, addr)
  1623. if err != nil {
  1624. return nil, err
  1625. }
  1626. ab.Store(isTCPLoopback(c.LocalAddr()) && isTCPLoopback(c.RemoteAddr()))
  1627. return c, nil
  1628. }, ab
  1629. }
  1630. func ignoreDialPlan() bool {
  1631. // If we're running in v86 (a JavaScript-based emulation of a 32-bit x86)
  1632. // our networking is very limited. Let's ignore the dial plan since it's too
  1633. // complicated to race that many IPs anyway.
  1634. return hostinfo.IsInVM86()
  1635. }
  1636. func isTCPLoopback(a net.Addr) bool {
  1637. if ta, ok := a.(*net.TCPAddr); ok {
  1638. return ta.IP.IsLoopback()
  1639. }
  1640. return false
  1641. }
  1642. var (
  1643. metricMapRequestsActive = clientmetric.NewGauge("controlclient_map_requests_active")
  1644. metricMapRequests = clientmetric.NewCounter("controlclient_map_requests")
  1645. metricMapRequestsLite = clientmetric.NewCounter("controlclient_map_requests_lite")
  1646. metricMapRequestsPoll = clientmetric.NewCounter("controlclient_map_requests_poll")
  1647. metricMapResponseMessages = clientmetric.NewCounter("controlclient_map_response_message") // any message type
  1648. metricMapResponsePings = clientmetric.NewCounter("controlclient_map_response_ping")
  1649. metricMapResponseKeepAlives = clientmetric.NewCounter("controlclient_map_response_keepalive")
  1650. metricMapResponseMap = clientmetric.NewCounter("controlclient_map_response_map") // any non-keepalive map response
  1651. metricMapResponseMapDelta = clientmetric.NewCounter("controlclient_map_response_map_delta") // 2nd+ non-keepalive map response
  1652. metricSetDNS = clientmetric.NewCounter("controlclient_setdns")
  1653. metricSetDNSError = clientmetric.NewCounter("controlclient_setdns_error")
  1654. )