direct.go 58 KB

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