netmap.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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. "encoding/json"
  7. "fmt"
  8. "net/netip"
  9. "sort"
  10. "strings"
  11. "time"
  12. "tailscale.com/tailcfg"
  13. "tailscale.com/tka"
  14. "tailscale.com/types/key"
  15. "tailscale.com/types/views"
  16. "tailscale.com/util/cmpx"
  17. "tailscale.com/wgengine/filter"
  18. )
  19. // NetworkMap is the current state of the world.
  20. //
  21. // The fields should all be considered read-only. They might
  22. // alias parts of previous NetworkMap values.
  23. type NetworkMap struct {
  24. SelfNode tailcfg.NodeView
  25. NodeKey key.NodePublic
  26. PrivateKey key.NodePrivate
  27. Expiry time.Time
  28. // Name is the DNS name assigned to this node.
  29. // It is the MapResponse.Node.Name value and ends with a period.
  30. Name string
  31. MachineKey key.MachinePublic
  32. Peers []tailcfg.NodeView // sorted by Node.ID
  33. DNS tailcfg.DNSConfig
  34. PacketFilter []filter.Match
  35. PacketFilterRules views.Slice[tailcfg.FilterRule]
  36. SSHPolicy *tailcfg.SSHPolicy // or nil, if not enabled/allowed
  37. // CollectServices reports whether this node's Tailnet has
  38. // requested that info about services be included in HostInfo.
  39. // If set, Hostinfo.ShieldsUp blocks services collection; that
  40. // takes precedence over this field.
  41. CollectServices bool
  42. // DERPMap is the last DERP server map received. It's reused
  43. // between updates and should not be modified.
  44. DERPMap *tailcfg.DERPMap
  45. // ControlHealth are the list of health check problems for this
  46. // node from the perspective of the control plane.
  47. // If empty, there are no known problems from the control plane's
  48. // point of view, but the node might know about its own health
  49. // check problems.
  50. ControlHealth []string
  51. // TKAEnabled indicates whether the tailnet key authority should be
  52. // enabled, from the perspective of the control plane.
  53. TKAEnabled bool
  54. // TKAHead indicates the control plane's understanding of 'head' (the
  55. // hash of the latest update message to tick through TKA).
  56. TKAHead tka.AUMHash
  57. // Domain is the current Tailnet name.
  58. Domain string
  59. // DomainAuditLogID is an audit log ID provided by control and
  60. // only populated if the domain opts into data-plane audit logging.
  61. // If this is empty, then data-plane audit logging is disabled.
  62. DomainAuditLogID string
  63. UserProfiles map[tailcfg.UserID]tailcfg.UserProfile
  64. }
  65. // User returns nm.SelfNode.User if nm.SelfNode is non-nil, otherwise it returns
  66. // 0.
  67. func (nm *NetworkMap) User() tailcfg.UserID {
  68. if nm.SelfNode.Valid() {
  69. return nm.SelfNode.User()
  70. }
  71. return 0
  72. }
  73. // GetAddresses returns the self node's addresses, or the zero value
  74. // if SelfNode is invalid.
  75. func (nm *NetworkMap) GetAddresses() views.Slice[netip.Prefix] {
  76. var zero views.Slice[netip.Prefix]
  77. if !nm.SelfNode.Valid() {
  78. return zero
  79. }
  80. return nm.SelfNode.Addresses()
  81. }
  82. // AnyPeersAdvertiseRoutes reports whether any peer is advertising non-exit node routes.
  83. func (nm *NetworkMap) AnyPeersAdvertiseRoutes() bool {
  84. for _, p := range nm.Peers {
  85. if p.PrimaryRoutes().Len() > 0 {
  86. return true
  87. }
  88. }
  89. return false
  90. }
  91. // GetMachineStatus returns the MachineStatus of the local node.
  92. func (nm *NetworkMap) GetMachineStatus() tailcfg.MachineStatus {
  93. if !nm.SelfNode.Valid() {
  94. return tailcfg.MachineUnknown
  95. }
  96. if nm.SelfNode.MachineAuthorized() {
  97. return tailcfg.MachineAuthorized
  98. }
  99. return tailcfg.MachineUnauthorized
  100. }
  101. // PeerByTailscaleIP returns a peer's Node based on its Tailscale IP.
  102. //
  103. // If nm is nil or no peer is found, ok is false.
  104. func (nm *NetworkMap) PeerByTailscaleIP(ip netip.Addr) (peer tailcfg.NodeView, ok bool) {
  105. // TODO(bradfitz):
  106. if nm == nil {
  107. return tailcfg.NodeView{}, false
  108. }
  109. for _, n := range nm.Peers {
  110. ad := n.Addresses()
  111. for i := 0; i < ad.Len(); i++ {
  112. a := ad.At(i)
  113. if a.Addr() == ip {
  114. return n, true
  115. }
  116. }
  117. }
  118. return tailcfg.NodeView{}, false
  119. }
  120. // PeerIndexByNodeID returns the index of the peer with the given nodeID
  121. // in nm.Peers, or -1 if nm is nil or not found.
  122. //
  123. // It assumes nm.Peers is sorted by Node.ID.
  124. func (nm *NetworkMap) PeerIndexByNodeID(nodeID tailcfg.NodeID) int {
  125. if nm == nil {
  126. return -1
  127. }
  128. idx, ok := sort.Find(len(nm.Peers), func(i int) int {
  129. return cmpx.Compare(nodeID, nm.Peers[i].ID())
  130. })
  131. if !ok {
  132. return -1
  133. }
  134. return idx
  135. }
  136. // MagicDNSSuffix returns the domain's MagicDNS suffix (even if MagicDNS isn't
  137. // necessarily in use) of the provided Node.Name value.
  138. //
  139. // It will neither start nor end with a period.
  140. func MagicDNSSuffixOfNodeName(nodeName string) string {
  141. name := strings.Trim(nodeName, ".")
  142. if _, rest, ok := strings.Cut(name, "."); ok {
  143. return rest
  144. }
  145. return name
  146. }
  147. // MagicDNSSuffix returns the domain's MagicDNS suffix (even if
  148. // MagicDNS isn't necessarily in use).
  149. //
  150. // It will neither start nor end with a period.
  151. func (nm *NetworkMap) MagicDNSSuffix() string {
  152. if nm == nil {
  153. return ""
  154. }
  155. return MagicDNSSuffixOfNodeName(nm.Name)
  156. }
  157. // DomainName returns the name of the NetworkMap's
  158. // current tailnet. If the map is nil, it returns
  159. // an empty string.
  160. func (nm *NetworkMap) DomainName() string {
  161. if nm == nil {
  162. return ""
  163. }
  164. return nm.Domain
  165. }
  166. // SelfCapabilities returns SelfNode.Capabilities if nm and nm.SelfNode are
  167. // non-nil. This is a method so we can use it in envknob/logknob without a
  168. // circular dependency.
  169. func (nm *NetworkMap) SelfCapabilities() views.Slice[tailcfg.NodeCapability] {
  170. var zero views.Slice[tailcfg.NodeCapability]
  171. if nm == nil || !nm.SelfNode.Valid() {
  172. return zero
  173. }
  174. out := nm.SelfNode.Capabilities().AsSlice()
  175. nm.SelfNode.CapMap().Range(func(k tailcfg.NodeCapability, _ views.Slice[tailcfg.RawMessage]) (cont bool) {
  176. out = append(out, k)
  177. return true
  178. })
  179. return views.SliceOf(out)
  180. }
  181. func (nm *NetworkMap) String() string {
  182. return nm.Concise()
  183. }
  184. func (nm *NetworkMap) Concise() string {
  185. buf := new(strings.Builder)
  186. nm.printConciseHeader(buf)
  187. for _, p := range nm.Peers {
  188. printPeerConcise(buf, p)
  189. }
  190. return buf.String()
  191. }
  192. func (nm *NetworkMap) VeryConcise() string {
  193. buf := new(strings.Builder)
  194. nm.printConciseHeader(buf)
  195. return buf.String()
  196. }
  197. // PeerWithStableID finds and returns the peer associated to the inputted StableNodeID.
  198. func (nm *NetworkMap) PeerWithStableID(pid tailcfg.StableNodeID) (_ tailcfg.NodeView, ok bool) {
  199. for _, p := range nm.Peers {
  200. if p.StableID() == pid {
  201. return p, true
  202. }
  203. }
  204. return tailcfg.NodeView{}, false
  205. }
  206. // printConciseHeader prints a concise header line representing nm to buf.
  207. //
  208. // If this function is changed to access different fields of nm, keep
  209. // in equalConciseHeader in sync.
  210. func (nm *NetworkMap) printConciseHeader(buf *strings.Builder) {
  211. fmt.Fprintf(buf, "netmap: self: %v auth=%v",
  212. nm.NodeKey.ShortString(), nm.GetMachineStatus())
  213. login := nm.UserProfiles[nm.User()].LoginName
  214. if login == "" {
  215. if nm.User().IsZero() {
  216. login = "?"
  217. } else {
  218. login = fmt.Sprint(nm.User())
  219. }
  220. }
  221. fmt.Fprintf(buf, " u=%s", login)
  222. fmt.Fprintf(buf, " %v", nm.GetAddresses().AsSlice())
  223. buf.WriteByte('\n')
  224. }
  225. // equalConciseHeader reports whether a and b are equal for the fields
  226. // used by printConciseHeader.
  227. func (a *NetworkMap) equalConciseHeader(b *NetworkMap) bool {
  228. return a.NodeKey == b.NodeKey &&
  229. a.GetMachineStatus() == b.GetMachineStatus() &&
  230. a.User() == b.User() &&
  231. views.SliceEqual(a.GetAddresses(), b.GetAddresses())
  232. }
  233. // printPeerConcise appends to buf a line representing the peer p.
  234. //
  235. // If this function is changed to access different fields of p, keep
  236. // in nodeConciseEqual in sync.
  237. func printPeerConcise(buf *strings.Builder, p tailcfg.NodeView) {
  238. aip := make([]string, p.AllowedIPs().Len())
  239. for i := range aip {
  240. a := p.AllowedIPs().At(i)
  241. s := strings.TrimSuffix(fmt.Sprint(a), "/32")
  242. aip[i] = s
  243. }
  244. ep := make([]string, p.Endpoints().Len())
  245. for i := range ep {
  246. e := p.Endpoints().At(i).String()
  247. // Align vertically on the ':' between IP and port
  248. colon := strings.IndexByte(e, ':')
  249. spaces := 0
  250. for colon > 0 && len(e)+spaces-colon < 6 {
  251. spaces++
  252. colon--
  253. }
  254. ep[i] = fmt.Sprintf("%21v", e+strings.Repeat(" ", spaces))
  255. }
  256. derp := p.DERP()
  257. const derpPrefix = "127.3.3.40:"
  258. if strings.HasPrefix(derp, derpPrefix) {
  259. derp = "D" + derp[len(derpPrefix):]
  260. }
  261. var discoShort string
  262. if !p.DiscoKey().IsZero() {
  263. discoShort = p.DiscoKey().ShortString() + " "
  264. }
  265. // Most of the time, aip is just one element, so format the
  266. // table to look good in that case. This will also make multi-
  267. // subnet nodes stand out visually.
  268. fmt.Fprintf(buf, " %v %s%-2v %-15v : %v\n",
  269. p.Key().ShortString(),
  270. discoShort,
  271. derp,
  272. strings.Join(aip, " "),
  273. strings.Join(ep, " "))
  274. }
  275. // nodeConciseEqual reports whether a and b are equal for the fields accessed by printPeerConcise.
  276. func nodeConciseEqual(a, b tailcfg.NodeView) bool {
  277. return a.Key() == b.Key() &&
  278. a.DERP() == b.DERP() &&
  279. a.DiscoKey() == b.DiscoKey() &&
  280. views.SliceEqual(a.AllowedIPs(), b.AllowedIPs()) &&
  281. views.SliceEqual(a.Endpoints(), b.Endpoints())
  282. }
  283. func (b *NetworkMap) ConciseDiffFrom(a *NetworkMap) string {
  284. var diff strings.Builder
  285. // See if header (non-peers, "bare") part of the network map changed.
  286. // If so, print its diff lines first.
  287. if !a.equalConciseHeader(b) {
  288. diff.WriteByte('-')
  289. a.printConciseHeader(&diff)
  290. diff.WriteByte('+')
  291. b.printConciseHeader(&diff)
  292. }
  293. aps, bps := a.Peers, b.Peers
  294. for len(aps) > 0 && len(bps) > 0 {
  295. pa, pb := aps[0], bps[0]
  296. switch {
  297. case pa.ID() == pb.ID():
  298. if !nodeConciseEqual(pa, pb) {
  299. diff.WriteByte('-')
  300. printPeerConcise(&diff, pa)
  301. diff.WriteByte('+')
  302. printPeerConcise(&diff, pb)
  303. }
  304. aps, bps = aps[1:], bps[1:]
  305. case pa.ID() > pb.ID():
  306. // New peer in b.
  307. diff.WriteByte('+')
  308. printPeerConcise(&diff, pb)
  309. bps = bps[1:]
  310. case pb.ID() > pa.ID():
  311. // Deleted peer in b.
  312. diff.WriteByte('-')
  313. printPeerConcise(&diff, pa)
  314. aps = aps[1:]
  315. }
  316. }
  317. for _, pa := range aps {
  318. diff.WriteByte('-')
  319. printPeerConcise(&diff, pa)
  320. }
  321. for _, pb := range bps {
  322. diff.WriteByte('+')
  323. printPeerConcise(&diff, pb)
  324. }
  325. return diff.String()
  326. }
  327. func (nm *NetworkMap) JSON() string {
  328. b, err := json.MarshalIndent(*nm, "", " ")
  329. if err != nil {
  330. return fmt.Sprintf("[json error: %v]", err)
  331. }
  332. return string(b)
  333. }
  334. // WGConfigFlags is a bitmask of flags to control the behavior of the
  335. // wireguard configuration generation done by NetMap.WGCfg.
  336. type WGConfigFlags int
  337. const (
  338. AllowSingleHosts WGConfigFlags = 1 << iota
  339. AllowSubnetRoutes
  340. )