direct.go 52 KB

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