map.go 11 KB

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