map.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. package controlclient
  4. import (
  5. "fmt"
  6. "log"
  7. "net/netip"
  8. "sort"
  9. "tailscale.com/envknob"
  10. "tailscale.com/tailcfg"
  11. "tailscale.com/types/key"
  12. "tailscale.com/types/logger"
  13. "tailscale.com/types/netmap"
  14. "tailscale.com/types/opt"
  15. "tailscale.com/types/views"
  16. "tailscale.com/wgengine/filter"
  17. )
  18. // mapSession holds the state over a long-polled "map" request to the
  19. // control plane.
  20. //
  21. // It accepts incremental tailcfg.MapResponse values to
  22. // netMapForResponse and returns fully inflated NetworkMaps, filling
  23. // in the omitted data implicit from prior MapResponse values from
  24. // within the same session (the same long-poll HTTP response to the
  25. // one MapRequest).
  26. type mapSession struct {
  27. // Immutable fields.
  28. privateNodeKey key.NodePrivate
  29. logf logger.Logf
  30. vlogf logger.Logf
  31. machinePubKey key.MachinePublic
  32. keepSharerAndUserSplit bool // see Options.KeepSharerAndUserSplit
  33. // Fields storing state over the course of multiple MapResponses.
  34. lastNode *tailcfg.Node
  35. lastDNSConfig *tailcfg.DNSConfig
  36. lastDERPMap *tailcfg.DERPMap
  37. lastUserProfile map[tailcfg.UserID]tailcfg.UserProfile
  38. lastPacketFilterRules views.Slice[tailcfg.FilterRule]
  39. lastParsedPacketFilter []filter.Match
  40. lastSSHPolicy *tailcfg.SSHPolicy
  41. collectServices bool
  42. previousPeers []*tailcfg.Node // for delta-purposes
  43. lastDomain string
  44. lastDomainAuditLogID string
  45. lastHealth []string
  46. lastPopBrowserURL string
  47. stickyDebug tailcfg.Debug // accumulated opt.Bool values
  48. lastTKAInfo *tailcfg.TKAInfo
  49. // netMapBuilding is non-nil during a netmapForResponse call,
  50. // containing the value to be returned, once fully populated.
  51. netMapBuilding *netmap.NetworkMap
  52. }
  53. func newMapSession(privateNodeKey key.NodePrivate) *mapSession {
  54. ms := &mapSession{
  55. privateNodeKey: privateNodeKey,
  56. logf: logger.Discard,
  57. vlogf: logger.Discard,
  58. lastDNSConfig: new(tailcfg.DNSConfig),
  59. lastUserProfile: map[tailcfg.UserID]tailcfg.UserProfile{},
  60. }
  61. return ms
  62. }
  63. func (ms *mapSession) addUserProfile(userID tailcfg.UserID) {
  64. nm := ms.netMapBuilding
  65. if _, dup := nm.UserProfiles[userID]; dup {
  66. // Already populated it from a previous peer.
  67. return
  68. }
  69. if up, ok := ms.lastUserProfile[userID]; ok {
  70. nm.UserProfiles[userID] = up
  71. }
  72. }
  73. // netmapForResponse returns a fully populated NetworkMap from a full
  74. // or incremental MapResponse within the session, filling in omitted
  75. // information from prior MapResponse values.
  76. func (ms *mapSession) netmapForResponse(resp *tailcfg.MapResponse) *netmap.NetworkMap {
  77. undeltaPeers(resp, ms.previousPeers)
  78. ms.previousPeers = cloneNodes(resp.Peers) // defensive/lazy clone, since this escapes to who knows where
  79. for _, up := range resp.UserProfiles {
  80. ms.lastUserProfile[up.ID] = up
  81. }
  82. if resp.DERPMap != nil {
  83. ms.vlogf("netmap: new map contains DERP map")
  84. ms.lastDERPMap = resp.DERPMap
  85. }
  86. if pf := resp.PacketFilter; pf != nil {
  87. var err error
  88. ms.lastPacketFilterRules = views.SliceOf(pf)
  89. ms.lastParsedPacketFilter, err = filter.MatchesFromFilterRules(pf)
  90. if err != nil {
  91. ms.logf("parsePacketFilter: %v", err)
  92. }
  93. }
  94. if c := resp.DNSConfig; c != nil {
  95. ms.lastDNSConfig = c
  96. }
  97. if p := resp.SSHPolicy; p != nil {
  98. ms.lastSSHPolicy = p
  99. }
  100. if v, ok := resp.CollectServices.Get(); ok {
  101. ms.collectServices = v
  102. }
  103. if resp.Domain != "" {
  104. ms.lastDomain = resp.Domain
  105. }
  106. if resp.DomainDataPlaneAuditLogID != "" {
  107. ms.lastDomainAuditLogID = resp.DomainDataPlaneAuditLogID
  108. }
  109. if resp.Health != nil {
  110. ms.lastHealth = resp.Health
  111. }
  112. if resp.TKAInfo != nil {
  113. ms.lastTKAInfo = resp.TKAInfo
  114. }
  115. debug := resp.Debug
  116. if debug != nil {
  117. if debug.RandomizeClientPort {
  118. debug.SetRandomizeClientPort.Set(true)
  119. }
  120. if debug.ForceBackgroundSTUN {
  121. debug.SetForceBackgroundSTUN.Set(true)
  122. }
  123. copyDebugOptBools(&ms.stickyDebug, debug)
  124. } else if ms.stickyDebug != (tailcfg.Debug{}) {
  125. debug = new(tailcfg.Debug)
  126. }
  127. if debug != nil {
  128. copyDebugOptBools(debug, &ms.stickyDebug)
  129. if !debug.ForceBackgroundSTUN {
  130. debug.ForceBackgroundSTUN, _ = ms.stickyDebug.SetForceBackgroundSTUN.Get()
  131. }
  132. if !debug.RandomizeClientPort {
  133. debug.RandomizeClientPort, _ = ms.stickyDebug.SetRandomizeClientPort.Get()
  134. }
  135. }
  136. nm := &netmap.NetworkMap{
  137. NodeKey: ms.privateNodeKey.Public(),
  138. PrivateKey: ms.privateNodeKey,
  139. MachineKey: ms.machinePubKey,
  140. Peers: resp.Peers,
  141. UserProfiles: make(map[tailcfg.UserID]tailcfg.UserProfile),
  142. Domain: ms.lastDomain,
  143. DomainAuditLogID: ms.lastDomainAuditLogID,
  144. DNS: *ms.lastDNSConfig,
  145. PacketFilter: ms.lastParsedPacketFilter,
  146. PacketFilterRules: ms.lastPacketFilterRules,
  147. SSHPolicy: ms.lastSSHPolicy,
  148. CollectServices: ms.collectServices,
  149. DERPMap: ms.lastDERPMap,
  150. Debug: debug,
  151. ControlHealth: ms.lastHealth,
  152. TKAEnabled: ms.lastTKAInfo != nil && !ms.lastTKAInfo.Disabled,
  153. }
  154. ms.netMapBuilding = nm
  155. if ms.lastTKAInfo != nil && ms.lastTKAInfo.Head != "" {
  156. if err := nm.TKAHead.UnmarshalText([]byte(ms.lastTKAInfo.Head)); err != nil {
  157. ms.logf("error unmarshalling TKAHead: %v", err)
  158. nm.TKAEnabled = false
  159. }
  160. }
  161. if resp.Node != nil {
  162. ms.lastNode = resp.Node
  163. }
  164. if node := ms.lastNode.Clone(); node != nil {
  165. nm.SelfNode = node
  166. nm.Expiry = node.KeyExpiry
  167. nm.Name = node.Name
  168. nm.Addresses = filterSelfAddresses(node.Addresses)
  169. nm.User = node.User
  170. if node.Hostinfo.Valid() {
  171. nm.Hostinfo = *node.Hostinfo.AsStruct()
  172. }
  173. if node.MachineAuthorized {
  174. nm.MachineStatus = tailcfg.MachineAuthorized
  175. } else {
  176. nm.MachineStatus = tailcfg.MachineUnauthorized
  177. }
  178. }
  179. ms.addUserProfile(nm.User)
  180. magicDNSSuffix := nm.MagicDNSSuffix()
  181. if nm.SelfNode != nil {
  182. nm.SelfNode.InitDisplayNames(magicDNSSuffix)
  183. }
  184. for _, peer := range resp.Peers {
  185. peer.InitDisplayNames(magicDNSSuffix)
  186. if !peer.Sharer.IsZero() {
  187. if ms.keepSharerAndUserSplit {
  188. ms.addUserProfile(peer.Sharer)
  189. } else {
  190. peer.User = peer.Sharer
  191. }
  192. }
  193. ms.addUserProfile(peer.User)
  194. }
  195. if DevKnob.ForceProxyDNS() {
  196. nm.DNS.Proxied = true
  197. }
  198. ms.netMapBuilding = nil
  199. return nm
  200. }
  201. // undeltaPeers updates mapRes.Peers to be complete based on the
  202. // provided previous peer list and the PeersRemoved and PeersChanged
  203. // fields in mapRes, as well as the PeerSeenChange and OnlineChange
  204. // maps.
  205. //
  206. // It then also nils out the delta fields.
  207. func undeltaPeers(mapRes *tailcfg.MapResponse, prev []*tailcfg.Node) {
  208. if len(mapRes.Peers) > 0 {
  209. // Not delta encoded.
  210. if !nodesSorted(mapRes.Peers) {
  211. log.Printf("netmap: undeltaPeers: MapResponse.Peers not sorted; sorting")
  212. sortNodes(mapRes.Peers)
  213. }
  214. return
  215. }
  216. var removed map[tailcfg.NodeID]bool
  217. if pr := mapRes.PeersRemoved; len(pr) > 0 {
  218. removed = make(map[tailcfg.NodeID]bool, len(pr))
  219. for _, id := range pr {
  220. removed[id] = true
  221. }
  222. }
  223. changed := mapRes.PeersChanged
  224. if !nodesSorted(changed) {
  225. log.Printf("netmap: undeltaPeers: MapResponse.PeersChanged not sorted; sorting")
  226. sortNodes(changed)
  227. }
  228. if !nodesSorted(prev) {
  229. // Internal error (unrelated to the network) if we get here.
  230. log.Printf("netmap: undeltaPeers: [unexpected] prev not sorted; sorting")
  231. sortNodes(prev)
  232. }
  233. newFull := prev
  234. if len(removed) > 0 || len(changed) > 0 {
  235. newFull = make([]*tailcfg.Node, 0, len(prev)-len(removed))
  236. for len(prev) > 0 && len(changed) > 0 {
  237. pID := prev[0].ID
  238. cID := changed[0].ID
  239. if removed[pID] {
  240. prev = prev[1:]
  241. continue
  242. }
  243. switch {
  244. case pID < cID:
  245. newFull = append(newFull, prev[0])
  246. prev = prev[1:]
  247. case pID == cID:
  248. newFull = append(newFull, changed[0])
  249. prev, changed = prev[1:], changed[1:]
  250. case cID < pID:
  251. newFull = append(newFull, changed[0])
  252. changed = changed[1:]
  253. }
  254. }
  255. newFull = append(newFull, changed...)
  256. for _, n := range prev {
  257. if !removed[n.ID] {
  258. newFull = append(newFull, n)
  259. }
  260. }
  261. sortNodes(newFull)
  262. }
  263. if len(mapRes.PeerSeenChange) != 0 || len(mapRes.OnlineChange) != 0 || len(mapRes.PeersChangedPatch) != 0 {
  264. peerByID := make(map[tailcfg.NodeID]*tailcfg.Node, len(newFull))
  265. for _, n := range newFull {
  266. peerByID[n.ID] = n
  267. }
  268. now := clockNow()
  269. for nodeID, seen := range mapRes.PeerSeenChange {
  270. if n, ok := peerByID[nodeID]; ok {
  271. if seen {
  272. n.LastSeen = &now
  273. } else {
  274. n.LastSeen = nil
  275. }
  276. }
  277. }
  278. for nodeID, online := range mapRes.OnlineChange {
  279. if n, ok := peerByID[nodeID]; ok {
  280. online := online
  281. n.Online = &online
  282. }
  283. }
  284. for _, ec := range mapRes.PeersChangedPatch {
  285. if n, ok := peerByID[ec.NodeID]; ok {
  286. if ec.DERPRegion != 0 {
  287. n.DERP = fmt.Sprintf("%s:%v", tailcfg.DerpMagicIP, ec.DERPRegion)
  288. }
  289. if ec.Cap != 0 {
  290. n.Cap = ec.Cap
  291. }
  292. if ec.Endpoints != nil {
  293. n.Endpoints = ec.Endpoints
  294. }
  295. if ec.Key != nil {
  296. n.Key = *ec.Key
  297. }
  298. if ec.DiscoKey != nil {
  299. n.DiscoKey = *ec.DiscoKey
  300. }
  301. if v := ec.Online; v != nil {
  302. n.Online = ptrCopy(v)
  303. }
  304. if v := ec.LastSeen; v != nil {
  305. n.LastSeen = ptrCopy(v)
  306. }
  307. if v := ec.KeyExpiry; v != nil {
  308. n.KeyExpiry = *v
  309. }
  310. if v := ec.Capabilities; v != nil {
  311. n.Capabilities = *v
  312. }
  313. if v := ec.KeySignature; v != nil {
  314. n.KeySignature = v
  315. }
  316. }
  317. }
  318. }
  319. mapRes.Peers = newFull
  320. mapRes.PeersChanged = nil
  321. mapRes.PeersRemoved = nil
  322. }
  323. // ptrCopy returns a pointer to a newly allocated shallow copy of *v.
  324. func ptrCopy[T any](v *T) *T {
  325. if v == nil {
  326. return nil
  327. }
  328. ret := new(T)
  329. *ret = *v
  330. return ret
  331. }
  332. func nodesSorted(v []*tailcfg.Node) bool {
  333. for i, n := range v {
  334. if i > 0 && n.ID <= v[i-1].ID {
  335. return false
  336. }
  337. }
  338. return true
  339. }
  340. func sortNodes(v []*tailcfg.Node) {
  341. sort.Slice(v, func(i, j int) bool { return v[i].ID < v[j].ID })
  342. }
  343. func cloneNodes(v1 []*tailcfg.Node) []*tailcfg.Node {
  344. if v1 == nil {
  345. return nil
  346. }
  347. v2 := make([]*tailcfg.Node, len(v1))
  348. for i, n := range v1 {
  349. v2[i] = n.Clone()
  350. }
  351. return v2
  352. }
  353. var debugSelfIPv6Only = envknob.RegisterBool("TS_DEBUG_SELF_V6_ONLY")
  354. func filterSelfAddresses(in []netip.Prefix) (ret []netip.Prefix) {
  355. switch {
  356. default:
  357. return in
  358. case debugSelfIPv6Only():
  359. for _, a := range in {
  360. if a.Addr().Is6() {
  361. ret = append(ret, a)
  362. }
  363. }
  364. return ret
  365. }
  366. }
  367. func copyDebugOptBools(dst, src *tailcfg.Debug) {
  368. copy := func(v *opt.Bool, s opt.Bool) {
  369. if s != "" {
  370. *v = s
  371. }
  372. }
  373. copy(&dst.DERPRoute, src.DERPRoute)
  374. copy(&dst.DisableSubnetsIfPAC, src.DisableSubnetsIfPAC)
  375. copy(&dst.DisableUPnP, src.DisableUPnP)
  376. copy(&dst.OneCGNATRoute, src.OneCGNATRoute)
  377. copy(&dst.SetForceBackgroundSTUN, src.SetForceBackgroundSTUN)
  378. copy(&dst.SetRandomizeClientPort, src.SetRandomizeClientPort)
  379. copy(&dst.TrimWGConfig, src.TrimWGConfig)
  380. }