direct.go 55 KB

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