netmap.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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. // SelfCapabilities returns SelfNode.Capabilities if nm and nm.SelfNode are
  175. // non-nil. This is a method so we can use it in envknob/logknob without a
  176. // circular dependency.
  177. func (nm *NetworkMap) SelfCapabilities() views.Slice[tailcfg.NodeCapability] {
  178. var zero views.Slice[tailcfg.NodeCapability]
  179. if nm == nil || !nm.SelfNode.Valid() {
  180. return zero
  181. }
  182. out := nm.SelfNode.Capabilities().AsSlice()
  183. nm.SelfNode.CapMap().Range(func(k tailcfg.NodeCapability, _ views.Slice[tailcfg.RawMessage]) (cont bool) {
  184. out = append(out, k)
  185. return true
  186. })
  187. return views.SliceOf(out)
  188. }
  189. func (nm *NetworkMap) String() string {
  190. return nm.Concise()
  191. }
  192. func (nm *NetworkMap) Concise() string {
  193. buf := new(strings.Builder)
  194. nm.printConciseHeader(buf)
  195. for _, p := range nm.Peers {
  196. printPeerConcise(buf, p)
  197. }
  198. return buf.String()
  199. }
  200. func (nm *NetworkMap) VeryConcise() string {
  201. buf := new(strings.Builder)
  202. nm.printConciseHeader(buf)
  203. return buf.String()
  204. }
  205. // PeerWithStableID finds and returns the peer associated to the inputted StableNodeID.
  206. func (nm *NetworkMap) PeerWithStableID(pid tailcfg.StableNodeID) (_ tailcfg.NodeView, ok bool) {
  207. for _, p := range nm.Peers {
  208. if p.StableID() == pid {
  209. return p, true
  210. }
  211. }
  212. return tailcfg.NodeView{}, false
  213. }
  214. // printConciseHeader prints a concise header line representing nm to buf.
  215. //
  216. // If this function is changed to access different fields of nm, keep
  217. // in equalConciseHeader in sync.
  218. func (nm *NetworkMap) printConciseHeader(buf *strings.Builder) {
  219. fmt.Fprintf(buf, "netmap: self: %v auth=%v",
  220. nm.NodeKey.ShortString(), nm.GetMachineStatus())
  221. login := nm.UserProfiles[nm.User()].LoginName
  222. if login == "" {
  223. if nm.User().IsZero() {
  224. login = "?"
  225. } else {
  226. login = fmt.Sprint(nm.User())
  227. }
  228. }
  229. fmt.Fprintf(buf, " u=%s", login)
  230. fmt.Fprintf(buf, " %v", nm.GetAddresses().AsSlice())
  231. buf.WriteByte('\n')
  232. }
  233. // equalConciseHeader reports whether a and b are equal for the fields
  234. // used by printConciseHeader.
  235. func (a *NetworkMap) equalConciseHeader(b *NetworkMap) bool {
  236. return a.NodeKey == b.NodeKey &&
  237. a.GetMachineStatus() == b.GetMachineStatus() &&
  238. a.User() == b.User() &&
  239. views.SliceEqual(a.GetAddresses(), b.GetAddresses())
  240. }
  241. // printPeerConcise appends to buf a line representing the peer p.
  242. //
  243. // If this function is changed to access different fields of p, keep
  244. // in nodeConciseEqual in sync.
  245. func printPeerConcise(buf *strings.Builder, p tailcfg.NodeView) {
  246. aip := make([]string, p.AllowedIPs().Len())
  247. for i := range aip {
  248. a := p.AllowedIPs().At(i)
  249. s := strings.TrimSuffix(fmt.Sprint(a), "/32")
  250. aip[i] = s
  251. }
  252. ep := make([]string, p.Endpoints().Len())
  253. for i := range ep {
  254. e := p.Endpoints().At(i).String()
  255. // Align vertically on the ':' between IP and port
  256. colon := strings.IndexByte(e, ':')
  257. spaces := 0
  258. for colon > 0 && len(e)+spaces-colon < 6 {
  259. spaces++
  260. colon--
  261. }
  262. ep[i] = fmt.Sprintf("%21v", e+strings.Repeat(" ", spaces))
  263. }
  264. derp := p.DERP()
  265. const derpPrefix = "127.3.3.40:"
  266. if strings.HasPrefix(derp, derpPrefix) {
  267. derp = "D" + derp[len(derpPrefix):]
  268. }
  269. var discoShort string
  270. if !p.DiscoKey().IsZero() {
  271. discoShort = p.DiscoKey().ShortString() + " "
  272. }
  273. // Most of the time, aip is just one element, so format the
  274. // table to look good in that case. This will also make multi-
  275. // subnet nodes stand out visually.
  276. fmt.Fprintf(buf, " %v %s%-2v %-15v : %v\n",
  277. p.Key().ShortString(),
  278. discoShort,
  279. derp,
  280. strings.Join(aip, " "),
  281. strings.Join(ep, " "))
  282. }
  283. // nodeConciseEqual reports whether a and b are equal for the fields accessed by printPeerConcise.
  284. func nodeConciseEqual(a, b tailcfg.NodeView) bool {
  285. return a.Key() == b.Key() &&
  286. a.DERP() == b.DERP() &&
  287. a.DiscoKey() == b.DiscoKey() &&
  288. views.SliceEqual(a.AllowedIPs(), b.AllowedIPs()) &&
  289. views.SliceEqual(a.Endpoints(), b.Endpoints())
  290. }
  291. func (b *NetworkMap) ConciseDiffFrom(a *NetworkMap) string {
  292. var diff strings.Builder
  293. // See if header (non-peers, "bare") part of the network map changed.
  294. // If so, print its diff lines first.
  295. if !a.equalConciseHeader(b) {
  296. diff.WriteByte('-')
  297. a.printConciseHeader(&diff)
  298. diff.WriteByte('+')
  299. b.printConciseHeader(&diff)
  300. }
  301. aps, bps := a.Peers, b.Peers
  302. for len(aps) > 0 && len(bps) > 0 {
  303. pa, pb := aps[0], bps[0]
  304. switch {
  305. case pa.ID() == pb.ID():
  306. if !nodeConciseEqual(pa, pb) {
  307. diff.WriteByte('-')
  308. printPeerConcise(&diff, pa)
  309. diff.WriteByte('+')
  310. printPeerConcise(&diff, pb)
  311. }
  312. aps, bps = aps[1:], bps[1:]
  313. case pa.ID() > pb.ID():
  314. // New peer in b.
  315. diff.WriteByte('+')
  316. printPeerConcise(&diff, pb)
  317. bps = bps[1:]
  318. case pb.ID() > pa.ID():
  319. // Deleted peer in b.
  320. diff.WriteByte('-')
  321. printPeerConcise(&diff, pa)
  322. aps = aps[1:]
  323. }
  324. }
  325. for _, pa := range aps {
  326. diff.WriteByte('-')
  327. printPeerConcise(&diff, pa)
  328. }
  329. for _, pb := range bps {
  330. diff.WriteByte('+')
  331. printPeerConcise(&diff, pb)
  332. }
  333. return diff.String()
  334. }
  335. func (nm *NetworkMap) JSON() string {
  336. b, err := json.MarshalIndent(*nm, "", " ")
  337. if err != nil {
  338. return fmt.Sprintf("[json error: %v]", err)
  339. }
  340. return string(b)
  341. }
  342. // WGConfigFlags is a bitmask of flags to control the behavior of the
  343. // wireguard configuration generation done by NetMap.WGCfg.
  344. type WGConfigFlags int
  345. const (
  346. _ WGConfigFlags = 1 << iota
  347. AllowSubnetRoutes
  348. )