netmap.go 13 KB

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