netmap.go 10 KB

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