netmap.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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. // ControlHealth 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. ControlHealth []string
  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 map[tailcfg.UserID]tailcfg.UserProfile
  66. // MaxKeyDuration describes the MaxKeyDuration setting for the tailnet.
  67. MaxKeyDuration time.Duration
  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. // AnyPeersAdvertiseRoutes reports whether any peer is advertising non-exit node routes.
  87. func (nm *NetworkMap) AnyPeersAdvertiseRoutes() bool {
  88. for _, p := range nm.Peers {
  89. if p.PrimaryRoutes().Len() > 0 {
  90. return true
  91. }
  92. }
  93. return false
  94. }
  95. // GetMachineStatus returns the MachineStatus of the local node.
  96. func (nm *NetworkMap) GetMachineStatus() tailcfg.MachineStatus {
  97. if !nm.SelfNode.Valid() {
  98. return tailcfg.MachineUnknown
  99. }
  100. if nm.SelfNode.MachineAuthorized() {
  101. return tailcfg.MachineAuthorized
  102. }
  103. return tailcfg.MachineUnauthorized
  104. }
  105. // HasCap reports whether nm is non-nil and nm.AllCaps contains c.
  106. func (nm *NetworkMap) HasCap(c tailcfg.NodeCapability) bool {
  107. return nm != nil && nm.AllCaps.Contains(c)
  108. }
  109. // PeerByTailscaleIP returns a peer's Node based on its Tailscale IP.
  110. //
  111. // If nm is nil or no peer is found, ok is false.
  112. func (nm *NetworkMap) PeerByTailscaleIP(ip netip.Addr) (peer tailcfg.NodeView, ok bool) {
  113. // TODO(bradfitz):
  114. if nm == nil {
  115. return tailcfg.NodeView{}, false
  116. }
  117. for _, n := range nm.Peers {
  118. ad := n.Addresses()
  119. for i := range ad.Len() {
  120. a := ad.At(i)
  121. if a.Addr() == ip {
  122. return n, true
  123. }
  124. }
  125. }
  126. return tailcfg.NodeView{}, false
  127. }
  128. // PeerIndexByNodeID returns the index of the peer with the given nodeID
  129. // in nm.Peers, or -1 if nm is nil or not found.
  130. //
  131. // It assumes nm.Peers is sorted by Node.ID.
  132. func (nm *NetworkMap) PeerIndexByNodeID(nodeID tailcfg.NodeID) int {
  133. if nm == nil {
  134. return -1
  135. }
  136. idx, ok := sort.Find(len(nm.Peers), func(i int) int {
  137. return cmp.Compare(nodeID, nm.Peers[i].ID())
  138. })
  139. if !ok {
  140. return -1
  141. }
  142. return idx
  143. }
  144. // MagicDNSSuffix returns the domain's MagicDNS suffix (even if MagicDNS isn't
  145. // necessarily in use) of the provided Node.Name value.
  146. //
  147. // It will neither start nor end with a period.
  148. func MagicDNSSuffixOfNodeName(nodeName string) string {
  149. name := strings.Trim(nodeName, ".")
  150. if _, rest, ok := strings.Cut(name, "."); ok {
  151. return rest
  152. }
  153. return name
  154. }
  155. // MagicDNSSuffix returns the domain's MagicDNS suffix (even if
  156. // MagicDNS isn't necessarily in use).
  157. //
  158. // It will neither start nor end with a period.
  159. func (nm *NetworkMap) MagicDNSSuffix() string {
  160. if nm == nil {
  161. return ""
  162. }
  163. return MagicDNSSuffixOfNodeName(nm.Name)
  164. }
  165. // DomainName returns the name of the NetworkMap's
  166. // current tailnet. If the map is nil, it returns
  167. // an empty string.
  168. func (nm *NetworkMap) DomainName() string {
  169. if nm == nil {
  170. return ""
  171. }
  172. return nm.Domain
  173. }
  174. // HasSelfCapability reports whether nm.SelfNode contains capability c.
  175. //
  176. // It exists to satisify an unused (as of 2025-01-04) interface in the logknob package.
  177. func (nm *NetworkMap) HasSelfCapability(c tailcfg.NodeCapability) bool {
  178. return nm.AllCaps.Contains(c)
  179. }
  180. func (nm *NetworkMap) String() string {
  181. return nm.Concise()
  182. }
  183. func (nm *NetworkMap) Concise() string {
  184. buf := new(strings.Builder)
  185. nm.printConciseHeader(buf)
  186. for _, p := range nm.Peers {
  187. printPeerConcise(buf, p)
  188. }
  189. return buf.String()
  190. }
  191. func (nm *NetworkMap) VeryConcise() string {
  192. buf := new(strings.Builder)
  193. nm.printConciseHeader(buf)
  194. return buf.String()
  195. }
  196. // PeerWithStableID finds and returns the peer associated to the inputted StableNodeID.
  197. func (nm *NetworkMap) PeerWithStableID(pid tailcfg.StableNodeID) (_ tailcfg.NodeView, ok bool) {
  198. for _, p := range nm.Peers {
  199. if p.StableID() == pid {
  200. return p, true
  201. }
  202. }
  203. return tailcfg.NodeView{}, false
  204. }
  205. // printConciseHeader prints a concise header line representing nm to buf.
  206. //
  207. // If this function is changed to access different fields of nm, keep
  208. // in equalConciseHeader in sync.
  209. func (nm *NetworkMap) printConciseHeader(buf *strings.Builder) {
  210. fmt.Fprintf(buf, "netmap: self: %v auth=%v",
  211. nm.NodeKey.ShortString(), nm.GetMachineStatus())
  212. login := nm.UserProfiles[nm.User()].LoginName
  213. if login == "" {
  214. if nm.User().IsZero() {
  215. login = "?"
  216. } else {
  217. login = fmt.Sprint(nm.User())
  218. }
  219. }
  220. fmt.Fprintf(buf, " u=%s", login)
  221. fmt.Fprintf(buf, " %v", nm.GetAddresses().AsSlice())
  222. buf.WriteByte('\n')
  223. }
  224. // equalConciseHeader reports whether a and b are equal for the fields
  225. // used by printConciseHeader.
  226. func (a *NetworkMap) equalConciseHeader(b *NetworkMap) bool {
  227. return a.NodeKey == b.NodeKey &&
  228. a.GetMachineStatus() == b.GetMachineStatus() &&
  229. a.User() == b.User() &&
  230. views.SliceEqual(a.GetAddresses(), b.GetAddresses())
  231. }
  232. // printPeerConcise appends to buf a line representing the peer p.
  233. //
  234. // If this function is changed to access different fields of p, keep
  235. // in nodeConciseEqual in sync.
  236. func printPeerConcise(buf *strings.Builder, p tailcfg.NodeView) {
  237. aip := make([]string, p.AllowedIPs().Len())
  238. for i, a := range p.AllowedIPs().All() {
  239. s := strings.TrimSuffix(a.String(), "/32")
  240. aip[i] = s
  241. }
  242. epStrs := make([]string, p.Endpoints().Len())
  243. for i, ep := range p.Endpoints().All() {
  244. e := ep.String()
  245. // Align vertically on the ':' between IP and port
  246. colon := strings.IndexByte(e, ':')
  247. spaces := 0
  248. for colon > 0 && len(e)+spaces-colon < 6 {
  249. spaces++
  250. colon--
  251. }
  252. epStrs[i] = fmt.Sprintf("%21v", e+strings.Repeat(" ", spaces))
  253. }
  254. derp := p.DERP()
  255. const derpPrefix = "127.3.3.40:"
  256. if strings.HasPrefix(derp, derpPrefix) {
  257. derp = "D" + derp[len(derpPrefix):]
  258. }
  259. var discoShort string
  260. if !p.DiscoKey().IsZero() {
  261. discoShort = p.DiscoKey().ShortString() + " "
  262. }
  263. // Most of the time, aip is just one element, so format the
  264. // table to look good in that case. This will also make multi-
  265. // subnet nodes stand out visually.
  266. fmt.Fprintf(buf, " %v %s%-2v %-15v : %v\n",
  267. p.Key().ShortString(),
  268. discoShort,
  269. derp,
  270. strings.Join(aip, " "),
  271. strings.Join(epStrs, " "))
  272. }
  273. // nodeConciseEqual reports whether a and b are equal for the fields accessed by printPeerConcise.
  274. func nodeConciseEqual(a, b tailcfg.NodeView) bool {
  275. return a.Key() == b.Key() &&
  276. a.DERP() == b.DERP() &&
  277. a.DiscoKey() == b.DiscoKey() &&
  278. views.SliceEqual(a.AllowedIPs(), b.AllowedIPs()) &&
  279. views.SliceEqual(a.Endpoints(), b.Endpoints())
  280. }
  281. func (b *NetworkMap) ConciseDiffFrom(a *NetworkMap) string {
  282. var diff strings.Builder
  283. // See if header (non-peers, "bare") part of the network map changed.
  284. // If so, print its diff lines first.
  285. if !a.equalConciseHeader(b) {
  286. diff.WriteByte('-')
  287. a.printConciseHeader(&diff)
  288. diff.WriteByte('+')
  289. b.printConciseHeader(&diff)
  290. }
  291. aps, bps := a.Peers, b.Peers
  292. for len(aps) > 0 && len(bps) > 0 {
  293. pa, pb := aps[0], bps[0]
  294. switch {
  295. case pa.ID() == pb.ID():
  296. if !nodeConciseEqual(pa, pb) {
  297. diff.WriteByte('-')
  298. printPeerConcise(&diff, pa)
  299. diff.WriteByte('+')
  300. printPeerConcise(&diff, pb)
  301. }
  302. aps, bps = aps[1:], bps[1:]
  303. case pa.ID() > pb.ID():
  304. // New peer in b.
  305. diff.WriteByte('+')
  306. printPeerConcise(&diff, pb)
  307. bps = bps[1:]
  308. case pb.ID() > pa.ID():
  309. // Deleted peer in b.
  310. diff.WriteByte('-')
  311. printPeerConcise(&diff, pa)
  312. aps = aps[1:]
  313. }
  314. }
  315. for _, pa := range aps {
  316. diff.WriteByte('-')
  317. printPeerConcise(&diff, pa)
  318. }
  319. for _, pb := range bps {
  320. diff.WriteByte('+')
  321. printPeerConcise(&diff, pb)
  322. }
  323. return diff.String()
  324. }
  325. func (nm *NetworkMap) JSON() string {
  326. b, err := json.MarshalIndent(*nm, "", " ")
  327. if err != nil {
  328. return fmt.Sprintf("[json error: %v]", err)
  329. }
  330. return string(b)
  331. }
  332. // WGConfigFlags is a bitmask of flags to control the behavior of the
  333. // wireguard configuration generation done by NetMap.WGCfg.
  334. type WGConfigFlags int
  335. const (
  336. _ WGConfigFlags = 1 << iota
  337. AllowSubnetRoutes
  338. )