netmap.go 10 KB

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