map.go 11 KB

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