netmap.go 13 KB

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