direct.go 56 KB

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