direct.go 54 KB

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