direct.go 56 KB

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