2
0

netmap.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. // Package netmap contains the netmap.NetworkMap type.
  4. package netmap
  5. import (
  6. "cmp"
  7. "encoding/json"
  8. "fmt"
  9. "net/netip"
  10. "sort"
  11. "strings"
  12. "time"
  13. "tailscale.com/tailcfg"
  14. "tailscale.com/tka"
  15. "tailscale.com/types/key"
  16. "tailscale.com/types/views"
  17. "tailscale.com/util/set"
  18. "tailscale.com/wgengine/filter/filtertype"
  19. )
  20. // NetworkMap is the current state of the world.
  21. //
  22. // The fields should all be considered read-only. They might
  23. // alias parts of previous NetworkMap values.
  24. type NetworkMap struct {
  25. SelfNode tailcfg.NodeView
  26. AllCaps set.Set[tailcfg.NodeCapability] // set version of SelfNode.Capabilities + SelfNode.CapMap
  27. NodeKey key.NodePublic
  28. PrivateKey key.NodePrivate
  29. Expiry time.Time
  30. // Name is the DNS name assigned to this node.
  31. // It is the MapResponse.Node.Name value and ends with a period.
  32. Name string
  33. MachineKey key.MachinePublic
  34. Peers []tailcfg.NodeView // sorted by Node.ID
  35. DNS tailcfg.DNSConfig
  36. PacketFilter []filtertype.Match
  37. PacketFilterRules views.Slice[tailcfg.FilterRule]
  38. SSHPolicy *tailcfg.SSHPolicy // or nil, if not enabled/allowed
  39. // CollectServices reports whether this node's Tailnet has
  40. // requested that info about services be included in HostInfo.
  41. // If set, Hostinfo.ShieldsUp blocks services collection; that
  42. // takes precedence over this field.
  43. CollectServices bool
  44. // DERPMap is the last DERP server map received. It's reused
  45. // between updates and should not be modified.
  46. DERPMap *tailcfg.DERPMap
  47. // DisplayMessages are the list of health check problems for this
  48. // node from the perspective of the control plane.
  49. // If empty, there are no known problems from the control plane's
  50. // point of view, but the node might know about its own health
  51. // check problems.
  52. DisplayMessages map[tailcfg.DisplayMessageID]tailcfg.DisplayMessage
  53. // TKAEnabled indicates whether the tailnet key authority should be
  54. // enabled, from the perspective of the control plane.
  55. TKAEnabled bool
  56. // TKAHead indicates the control plane's understanding of 'head' (the
  57. // hash of the latest update message to tick through TKA).
  58. TKAHead tka.AUMHash
  59. // Domain is the current Tailnet name.
  60. Domain string
  61. // DomainAuditLogID is an audit log ID provided by control and
  62. // only populated if the domain opts into data-plane audit logging.
  63. // If this is empty, then data-plane audit logging is disabled.
  64. DomainAuditLogID string
  65. // UserProfiles contains the profile information of UserIDs referenced
  66. // in SelfNode and Peers.
  67. UserProfiles map[tailcfg.UserID]tailcfg.UserProfileView
  68. }
  69. // User returns nm.SelfNode.User if nm.SelfNode is non-nil, otherwise it returns
  70. // 0.
  71. func (nm *NetworkMap) User() tailcfg.UserID {
  72. if nm.SelfNode.Valid() {
  73. return nm.SelfNode.User()
  74. }
  75. return 0
  76. }
  77. // GetAddresses returns the self node's addresses, or the zero value
  78. // if SelfNode is invalid.
  79. func (nm *NetworkMap) GetAddresses() views.Slice[netip.Prefix] {
  80. var zero views.Slice[netip.Prefix]
  81. if !nm.SelfNode.Valid() {
  82. return zero
  83. }
  84. return nm.SelfNode.Addresses()
  85. }
  86. // GetVIPServiceIPMap returns a map of service names to the slice of
  87. // VIP addresses that correspond to the service. The service names are
  88. // with the prefix "svc:".
  89. //
  90. // TODO(tailscale/corp##25997): cache the result of decoding the capmap so that
  91. // we don't have to decode it multiple times after each netmap update.
  92. func (nm *NetworkMap) GetVIPServiceIPMap() tailcfg.ServiceIPMappings {
  93. if nm == nil {
  94. return nil
  95. }
  96. if !nm.SelfNode.Valid() {
  97. return nil
  98. }
  99. ipMaps, err := tailcfg.UnmarshalNodeCapViewJSON[tailcfg.ServiceIPMappings](nm.SelfNode.CapMap(), tailcfg.NodeAttrServiceHost)
  100. if len(ipMaps) != 1 || err != nil {
  101. return nil
  102. }
  103. return ipMaps[0]
  104. }
  105. // GetIPVIPServiceMap returns a map of VIP addresses to the service
  106. // names that has the VIP address. The service names are with the
  107. // prefix "svc:".
  108. func (nm *NetworkMap) GetIPVIPServiceMap() IPServiceMappings {
  109. var res IPServiceMappings
  110. if nm == nil {
  111. return res
  112. }
  113. if !nm.SelfNode.Valid() {
  114. return res
  115. }
  116. serviceIPMap := nm.GetVIPServiceIPMap()
  117. if serviceIPMap == nil {
  118. return res
  119. }
  120. res = make(IPServiceMappings)
  121. for svc, addrs := range serviceIPMap {
  122. for _, addr := range addrs {
  123. res[addr] = svc
  124. }
  125. }
  126. return res
  127. }
  128. // SelfNodeOrZero returns the self node, or a zero value if nm is nil.
  129. func (nm *NetworkMap) SelfNodeOrZero() tailcfg.NodeView {
  130. if nm == nil {
  131. return tailcfg.NodeView{}
  132. }
  133. return nm.SelfNode
  134. }
  135. // AnyPeersAdvertiseRoutes reports whether any peer is advertising non-exit node routes.
  136. func (nm *NetworkMap) AnyPeersAdvertiseRoutes() bool {
  137. for _, p := range nm.Peers {
  138. if p.PrimaryRoutes().Len() > 0 {
  139. return true
  140. }
  141. }
  142. return false
  143. }
  144. // GetMachineStatus returns the MachineStatus of the local node.
  145. func (nm *NetworkMap) GetMachineStatus() tailcfg.MachineStatus {
  146. if !nm.SelfNode.Valid() {
  147. return tailcfg.MachineUnknown
  148. }
  149. if nm.SelfNode.MachineAuthorized() {
  150. return tailcfg.MachineAuthorized
  151. }
  152. return tailcfg.MachineUnauthorized
  153. }
  154. // HasCap reports whether nm is non-nil and nm.AllCaps contains c.
  155. func (nm *NetworkMap) HasCap(c tailcfg.NodeCapability) bool {
  156. return nm != nil && nm.AllCaps.Contains(c)
  157. }
  158. // PeerByTailscaleIP returns a peer's Node based on its Tailscale IP.
  159. //
  160. // If nm is nil or no peer is found, ok is false.
  161. func (nm *NetworkMap) PeerByTailscaleIP(ip netip.Addr) (peer tailcfg.NodeView, ok bool) {
  162. // TODO(bradfitz):
  163. if nm == nil {
  164. return tailcfg.NodeView{}, false
  165. }
  166. for _, n := range nm.Peers {
  167. ad := n.Addresses()
  168. for i := range ad.Len() {
  169. a := ad.At(i)
  170. if a.Addr() == ip {
  171. return n, true
  172. }
  173. }
  174. }
  175. return tailcfg.NodeView{}, false
  176. }
  177. // PeerIndexByNodeID returns the index of the peer with the given nodeID
  178. // in nm.Peers, or -1 if nm is nil or not found.
  179. //
  180. // It assumes nm.Peers is sorted by Node.ID.
  181. func (nm *NetworkMap) PeerIndexByNodeID(nodeID tailcfg.NodeID) int {
  182. if nm == nil {
  183. return -1
  184. }
  185. idx, ok := sort.Find(len(nm.Peers), func(i int) int {
  186. return cmp.Compare(nodeID, nm.Peers[i].ID())
  187. })
  188. if !ok {
  189. return -1
  190. }
  191. return idx
  192. }
  193. // MagicDNSSuffix returns the domain's MagicDNS suffix (even if MagicDNS isn't
  194. // necessarily in use) of the provided Node.Name value.
  195. //
  196. // It will neither start nor end with a period.
  197. func MagicDNSSuffixOfNodeName(nodeName string) string {
  198. name := strings.Trim(nodeName, ".")
  199. if _, rest, ok := strings.Cut(name, "."); ok {
  200. return rest
  201. }
  202. return name
  203. }
  204. // MagicDNSSuffix returns the domain's MagicDNS suffix (even if
  205. // MagicDNS isn't necessarily in use).
  206. //
  207. // It will neither start nor end with a period.
  208. func (nm *NetworkMap) MagicDNSSuffix() string {
  209. if nm == nil {
  210. return ""
  211. }
  212. return MagicDNSSuffixOfNodeName(nm.Name)
  213. }
  214. // DomainName returns the name of the NetworkMap's
  215. // current tailnet. If the map is nil, it returns
  216. // an empty string.
  217. func (nm *NetworkMap) DomainName() string {
  218. if nm == nil {
  219. return ""
  220. }
  221. return nm.Domain
  222. }
  223. // HasSelfCapability reports whether nm.SelfNode contains capability c.
  224. //
  225. // It exists to satisify an unused (as of 2025-01-04) interface in the logknob package.
  226. func (nm *NetworkMap) HasSelfCapability(c tailcfg.NodeCapability) bool {
  227. return nm.AllCaps.Contains(c)
  228. }
  229. func (nm *NetworkMap) String() string {
  230. return nm.Concise()
  231. }
  232. func (nm *NetworkMap) Concise() string {
  233. buf := new(strings.Builder)
  234. nm.printConciseHeader(buf)
  235. for _, p := range nm.Peers {
  236. printPeerConcise(buf, p)
  237. }
  238. return buf.String()
  239. }
  240. func (nm *NetworkMap) VeryConcise() string {
  241. buf := new(strings.Builder)
  242. nm.printConciseHeader(buf)
  243. return buf.String()
  244. }
  245. // PeerWithStableID finds and returns the peer associated to the inputted StableNodeID.
  246. func (nm *NetworkMap) PeerWithStableID(pid tailcfg.StableNodeID) (_ tailcfg.NodeView, ok bool) {
  247. for _, p := range nm.Peers {
  248. if p.StableID() == pid {
  249. return p, true
  250. }
  251. }
  252. return tailcfg.NodeView{}, false
  253. }
  254. // printConciseHeader prints a concise header line representing nm to buf.
  255. //
  256. // If this function is changed to access different fields of nm, keep
  257. // in equalConciseHeader in sync.
  258. func (nm *NetworkMap) printConciseHeader(buf *strings.Builder) {
  259. fmt.Fprintf(buf, "netmap: self: %v auth=%v",
  260. nm.NodeKey.ShortString(), nm.GetMachineStatus())
  261. var login string
  262. up, ok := nm.UserProfiles[nm.User()]
  263. if ok {
  264. login = up.LoginName()
  265. }
  266. if login == "" {
  267. if nm.User().IsZero() {
  268. login = "?"
  269. } else {
  270. login = fmt.Sprint(nm.User())
  271. }
  272. }
  273. fmt.Fprintf(buf, " u=%s", login)
  274. fmt.Fprintf(buf, " %v", nm.GetAddresses().AsSlice())
  275. buf.WriteByte('\n')
  276. }
  277. // equalConciseHeader reports whether a and b are equal for the fields
  278. // used by printConciseHeader.
  279. func (a *NetworkMap) equalConciseHeader(b *NetworkMap) bool {
  280. return a.NodeKey == b.NodeKey &&
  281. a.GetMachineStatus() == b.GetMachineStatus() &&
  282. a.User() == b.User() &&
  283. views.SliceEqual(a.GetAddresses(), b.GetAddresses())
  284. }
  285. // printPeerConcise appends to buf a line representing the peer p.
  286. //
  287. // If this function is changed to access different fields of p, keep
  288. // in nodeConciseEqual in sync.
  289. func printPeerConcise(buf *strings.Builder, p tailcfg.NodeView) {
  290. aip := make([]string, p.AllowedIPs().Len())
  291. for i, a := range p.AllowedIPs().All() {
  292. s := strings.TrimSuffix(a.String(), "/32")
  293. aip[i] = s
  294. }
  295. epStrs := make([]string, p.Endpoints().Len())
  296. for i, ep := range p.Endpoints().All() {
  297. e := ep.String()
  298. // Align vertically on the ':' between IP and port
  299. colon := strings.IndexByte(e, ':')
  300. spaces := 0
  301. for colon > 0 && len(e)+spaces-colon < 6 {
  302. spaces++
  303. colon--
  304. }
  305. epStrs[i] = fmt.Sprintf("%21v", e+strings.Repeat(" ", spaces))
  306. }
  307. derp := fmt.Sprintf("D%d", p.HomeDERP())
  308. var discoShort string
  309. if !p.DiscoKey().IsZero() {
  310. discoShort = p.DiscoKey().ShortString() + " "
  311. }
  312. // Most of the time, aip is just one element, so format the
  313. // table to look good in that case. This will also make multi-
  314. // subnet nodes stand out visually.
  315. fmt.Fprintf(buf, " %v %s%-2v %-15v : %v\n",
  316. p.Key().ShortString(),
  317. discoShort,
  318. derp,
  319. strings.Join(aip, " "),
  320. strings.Join(epStrs, " "))
  321. }
  322. // nodeConciseEqual reports whether a and b are equal for the fields accessed by printPeerConcise.
  323. func nodeConciseEqual(a, b tailcfg.NodeView) bool {
  324. return a.Key() == b.Key() &&
  325. a.HomeDERP() == b.HomeDERP() &&
  326. a.DiscoKey() == b.DiscoKey() &&
  327. views.SliceEqual(a.AllowedIPs(), b.AllowedIPs()) &&
  328. views.SliceEqual(a.Endpoints(), b.Endpoints())
  329. }
  330. func (b *NetworkMap) ConciseDiffFrom(a *NetworkMap) string {
  331. var diff strings.Builder
  332. // See if header (non-peers, "bare") part of the network map changed.
  333. // If so, print its diff lines first.
  334. if !a.equalConciseHeader(b) {
  335. diff.WriteByte('-')
  336. a.printConciseHeader(&diff)
  337. diff.WriteByte('+')
  338. b.printConciseHeader(&diff)
  339. }
  340. aps, bps := a.Peers, b.Peers
  341. for len(aps) > 0 && len(bps) > 0 {
  342. pa, pb := aps[0], bps[0]
  343. switch {
  344. case pa.ID() == pb.ID():
  345. if !nodeConciseEqual(pa, pb) {
  346. diff.WriteByte('-')
  347. printPeerConcise(&diff, pa)
  348. diff.WriteByte('+')
  349. printPeerConcise(&diff, pb)
  350. }
  351. aps, bps = aps[1:], bps[1:]
  352. case pa.ID() > pb.ID():
  353. // New peer in b.
  354. diff.WriteByte('+')
  355. printPeerConcise(&diff, pb)
  356. bps = bps[1:]
  357. case pb.ID() > pa.ID():
  358. // Deleted peer in b.
  359. diff.WriteByte('-')
  360. printPeerConcise(&diff, pa)
  361. aps = aps[1:]
  362. }
  363. }
  364. for _, pa := range aps {
  365. diff.WriteByte('-')
  366. printPeerConcise(&diff, pa)
  367. }
  368. for _, pb := range bps {
  369. diff.WriteByte('+')
  370. printPeerConcise(&diff, pb)
  371. }
  372. return diff.String()
  373. }
  374. func (nm *NetworkMap) JSON() string {
  375. b, err := json.MarshalIndent(*nm, "", " ")
  376. if err != nil {
  377. return fmt.Sprintf("[json error: %v]", err)
  378. }
  379. return string(b)
  380. }
  381. // WGConfigFlags is a bitmask of flags to control the behavior of the
  382. // wireguard configuration generation done by NetMap.WGCfg.
  383. type WGConfigFlags int
  384. const (
  385. _ WGConfigFlags = 1 << iota
  386. AllowSubnetRoutes
  387. )
  388. // IPServiceMappings maps IP addresses to service names. This is the inverse of
  389. // [tailcfg.ServiceIPMappings], and is used to inform track which service a VIP
  390. // is associated with. This is set to b.ipVIPServiceMap every time the netmap is
  391. // updated. This is used to reduce the cost for looking up the service name for
  392. // the dst IP address in the netStack packet processing workflow.
  393. //
  394. // This is of the form:
  395. //
  396. // {
  397. // "100.65.32.1": "svc:samba",
  398. // "fd7a:115c:a1e0::1234": "svc:samba",
  399. // "100.102.42.3": "svc:web",
  400. // "fd7a:115c:a1e0::abcd": "svc:web",
  401. // }
  402. type IPServiceMappings map[netip.Addr]tailcfg.ServiceName