state.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. package netmon
  4. import (
  5. "bytes"
  6. "fmt"
  7. "net"
  8. "net/http"
  9. "net/netip"
  10. "runtime"
  11. "slices"
  12. "sort"
  13. "strings"
  14. "tailscale.com/envknob"
  15. "tailscale.com/feature"
  16. "tailscale.com/feature/buildfeatures"
  17. "tailscale.com/hostinfo"
  18. "tailscale.com/net/netaddr"
  19. "tailscale.com/net/tsaddr"
  20. "tailscale.com/util/mak"
  21. )
  22. // forceAllIPv6Endpoints is a debug knob that when set forces the client to
  23. // report all IPv6 endpoints rather than trim endpoints that are siblings on the
  24. // same interface and subnet.
  25. var forceAllIPv6Endpoints = envknob.RegisterBool("TS_DEBUG_FORCE_ALL_IPV6_ENDPOINTS")
  26. // LoginEndpointForProxyDetermination is the URL used for testing
  27. // which HTTP proxy the system should use.
  28. var LoginEndpointForProxyDetermination = "https://controlplane.tailscale.com/"
  29. func isUp(nif *net.Interface) bool { return nif.Flags&net.FlagUp != 0 }
  30. func isLoopback(nif *net.Interface) bool { return nif.Flags&net.FlagLoopback != 0 }
  31. func isProblematicInterface(nif *net.Interface) bool {
  32. name := nif.Name
  33. // Don't try to send disco/etc packets over zerotier; they effectively
  34. // DoS each other by doing traffic amplification, both of them
  35. // preferring/trying to use each other for transport. See:
  36. // https://github.com/tailscale/tailscale/issues/1208
  37. if strings.HasPrefix(name, "zt") || (runtime.GOOS == "windows" && strings.Contains(name, "ZeroTier")) {
  38. return true
  39. }
  40. return false
  41. }
  42. // LocalAddresses returns the machine's IP addresses, separated by
  43. // whether they're loopback addresses. If there are no regular addresses
  44. // it will return any IPv4 linklocal or IPv6 unique local addresses because we
  45. // know of environments where these are used with NAT to provide connectivity.
  46. func LocalAddresses() (regular, loopback []netip.Addr, err error) {
  47. // TODO(crawshaw): don't serve interface addresses that we are routing
  48. ifaces, err := netInterfaces()
  49. if err != nil {
  50. return nil, nil, err
  51. }
  52. var regular4, regular6, linklocal4, ula6 []netip.Addr
  53. for _, iface := range ifaces {
  54. stdIf := iface.Interface
  55. if !isUp(stdIf) || isProblematicInterface(stdIf) {
  56. // Skip down interfaces and ones that are
  57. // problematic that we don't want to try to
  58. // send Tailscale traffic over.
  59. continue
  60. }
  61. ifcIsLoopback := isLoopback(stdIf)
  62. addrs, err := iface.Addrs()
  63. if err != nil {
  64. return nil, nil, err
  65. }
  66. var subnets map[netip.Addr]int
  67. for _, a := range addrs {
  68. switch v := a.(type) {
  69. case *net.IPNet:
  70. ip, ok := netip.AddrFromSlice(v.IP)
  71. if !ok {
  72. continue
  73. }
  74. ip = ip.Unmap()
  75. // TODO(apenwarr): don't special case cgNAT.
  76. // In the general wireguard case, it might
  77. // very well be something we can route to
  78. // directly, because both nodes are
  79. // behind the same CGNAT router.
  80. if tsaddr.IsTailscaleIP(ip) {
  81. continue
  82. }
  83. if ip.IsLoopback() || ifcIsLoopback {
  84. loopback = append(loopback, ip)
  85. } else if ip.IsLinkLocalUnicast() {
  86. if ip.Is4() {
  87. linklocal4 = append(linklocal4, ip)
  88. }
  89. // We know of no cases where the IPv6 fe80:: addresses
  90. // are used to provide WAN connectivity. It is also very
  91. // common for users to have no IPv6 WAN connectivity,
  92. // but their OS supports IPv6 so they have an fe80::
  93. // address. We don't want to report all of those
  94. // IPv6 LL to Control.
  95. } else if ip.Is6() && ip.IsPrivate() {
  96. // Google Cloud Run uses NAT with IPv6 Unique
  97. // Local Addresses to provide IPv6 connectivity.
  98. ula6 = append(ula6, ip)
  99. } else {
  100. if ip.Is4() {
  101. regular4 = append(regular4, ip)
  102. } else {
  103. curMask, _ := netip.AddrFromSlice(v.IP.Mask(v.Mask))
  104. // Limit the number of addresses reported per subnet for
  105. // IPv6, as we have seen some nodes with extremely large
  106. // numbers of assigned addresses being carved out of
  107. // same-subnet allocations.
  108. if forceAllIPv6Endpoints() || subnets[curMask] < 2 {
  109. regular6 = append(regular6, ip)
  110. }
  111. mak.Set(&subnets, curMask, subnets[curMask]+1)
  112. }
  113. }
  114. }
  115. }
  116. }
  117. if len(regular4) == 0 && len(regular6) == 0 {
  118. // if we have no usable IP addresses then be willing to accept
  119. // addresses we otherwise wouldn't, like:
  120. // + 169.254.x.x (AWS Lambda and Azure App Services use NAT with these)
  121. // + IPv6 ULA (Google Cloud Run uses these with address translation)
  122. regular4 = linklocal4
  123. regular6 = ula6
  124. }
  125. regular = append(regular4, regular6...)
  126. sortIPs(regular)
  127. sortIPs(loopback)
  128. return regular, loopback, nil
  129. }
  130. func sortIPs(s []netip.Addr) {
  131. sort.Slice(s, func(i, j int) bool { return s[i].Less(s[j]) })
  132. }
  133. // Interface is a wrapper around Go's net.Interface with some extra methods.
  134. type Interface struct {
  135. *net.Interface
  136. AltAddrs []net.Addr // if non-nil, returned by Addrs
  137. Desc string // extra description (used on Windows)
  138. }
  139. func (i Interface) IsLoopback() bool { return isLoopback(i.Interface) }
  140. func (i Interface) IsUp() bool { return isUp(i.Interface) }
  141. func (i Interface) Addrs() ([]net.Addr, error) {
  142. if i.AltAddrs != nil {
  143. return i.AltAddrs, nil
  144. }
  145. return i.Interface.Addrs()
  146. }
  147. // ForeachInterfaceAddress is a wrapper for GetList, then
  148. // List.ForeachInterfaceAddress.
  149. func ForeachInterfaceAddress(fn func(Interface, netip.Prefix)) error {
  150. ifaces, err := GetInterfaceList()
  151. if err != nil {
  152. return err
  153. }
  154. return ifaces.ForeachInterfaceAddress(fn)
  155. }
  156. // ForeachInterfaceAddress calls fn for each interface in ifaces, with
  157. // all its addresses. The IPPrefix's IP is the IP address assigned to
  158. // the interface, and Bits are the subnet mask.
  159. func (ifaces InterfaceList) ForeachInterfaceAddress(fn func(Interface, netip.Prefix)) error {
  160. for _, iface := range ifaces {
  161. addrs, err := iface.Addrs()
  162. if err != nil {
  163. return err
  164. }
  165. for _, a := range addrs {
  166. switch v := a.(type) {
  167. case *net.IPNet:
  168. if pfx, ok := netaddr.FromStdIPNet(v); ok {
  169. fn(iface, pfx)
  170. }
  171. case *net.IPAddr:
  172. if ip, ok := netip.AddrFromSlice(v.IP); ok {
  173. fn(iface, netip.PrefixFrom(ip, ip.BitLen()))
  174. }
  175. }
  176. }
  177. }
  178. return nil
  179. }
  180. // ForeachInterface is a wrapper for GetList, then
  181. // List.ForeachInterface.
  182. func ForeachInterface(fn func(Interface, []netip.Prefix)) error {
  183. ifaces, err := GetInterfaceList()
  184. if err != nil {
  185. return err
  186. }
  187. return ifaces.ForeachInterface(fn)
  188. }
  189. // ForeachInterface calls fn for each interface in ifaces, with
  190. // all its addresses. The IPPrefix's IP is the IP address assigned to
  191. // the interface, and Bits are the subnet mask.
  192. func (ifaces InterfaceList) ForeachInterface(fn func(Interface, []netip.Prefix)) error {
  193. for _, iface := range ifaces {
  194. addrs, err := iface.Addrs()
  195. if err != nil {
  196. return err
  197. }
  198. var pfxs []netip.Prefix
  199. for _, a := range addrs {
  200. switch v := a.(type) {
  201. case *net.IPNet:
  202. if pfx, ok := netaddr.FromStdIPNet(v); ok {
  203. pfxs = append(pfxs, pfx)
  204. }
  205. case *net.IPAddr:
  206. if ip, ok := netip.AddrFromSlice(v.IP); ok {
  207. pfxs = append(pfxs, netip.PrefixFrom(ip, ip.BitLen()))
  208. }
  209. }
  210. }
  211. sort.Slice(pfxs, func(i, j int) bool {
  212. return pfxs[i].Addr().Less(pfxs[j].Addr())
  213. })
  214. fn(iface, pfxs)
  215. }
  216. return nil
  217. }
  218. // State is intended to store the state of the machine's network interfaces,
  219. // routing table, and other network configuration.
  220. // For now it's pretty basic.
  221. type State struct {
  222. // InterfaceIPs maps from an interface name to the IP addresses
  223. // configured on that interface. Each address is represented as an
  224. // IPPrefix, where the IP is the interface IP address and Bits is
  225. // the subnet mask.
  226. InterfaceIPs map[string][]netip.Prefix
  227. Interface map[string]Interface
  228. // HaveV6 is whether this machine has an IPv6 Global or Unique Local Address
  229. // which might provide connectivity on a non-Tailscale interface that's up.
  230. HaveV6 bool
  231. // HaveV4 is whether the machine has some non-localhost,
  232. // non-link-local IPv4 address on a non-Tailscale interface that's up.
  233. HaveV4 bool
  234. // IsExpensive is whether the current network interface is
  235. // considered "expensive", which currently means LTE/etc
  236. // instead of Wifi. This field is not populated by GetState.
  237. IsExpensive bool
  238. // DefaultRouteInterface is the interface name for the
  239. // machine's default route.
  240. //
  241. // It is not yet populated on all OSes.
  242. //
  243. // When non-empty, its value is the map key into Interface and
  244. // InterfaceIPs.
  245. DefaultRouteInterface string
  246. // HTTPProxy is the HTTP proxy to use, if any.
  247. HTTPProxy string
  248. // PAC is the URL to the Proxy Autoconfig URL, if applicable.
  249. PAC string
  250. }
  251. func (s *State) String() string {
  252. var sb strings.Builder
  253. fmt.Fprintf(&sb, "interfaces.State{defaultRoute=%v ", s.DefaultRouteInterface)
  254. if s.DefaultRouteInterface != "" {
  255. if iface, ok := s.Interface[s.DefaultRouteInterface]; ok && iface.Desc != "" {
  256. fmt.Fprintf(&sb, "(%s) ", iface.Desc)
  257. }
  258. }
  259. sb.WriteString("ifs={")
  260. var ifs []string
  261. for k := range s.Interface {
  262. if s.keepInterfaceInStringSummary(k) {
  263. ifs = append(ifs, k)
  264. }
  265. }
  266. sort.Slice(ifs, func(i, j int) bool {
  267. upi, upj := s.Interface[ifs[i]].IsUp(), s.Interface[ifs[j]].IsUp()
  268. if upi != upj {
  269. // Up sorts before down.
  270. return upi
  271. }
  272. return ifs[i] < ifs[j]
  273. })
  274. for i, ifName := range ifs {
  275. if i > 0 {
  276. sb.WriteString(" ")
  277. }
  278. iface := s.Interface[ifName]
  279. if iface.Interface == nil {
  280. fmt.Fprintf(&sb, "%s:nil", ifName)
  281. continue
  282. }
  283. if !iface.IsUp() {
  284. fmt.Fprintf(&sb, "%s:down", ifName)
  285. continue
  286. }
  287. fmt.Fprintf(&sb, "%s:[", ifName)
  288. needSpace := false
  289. for _, pfx := range s.InterfaceIPs[ifName] {
  290. a := pfx.Addr()
  291. if a.IsMulticast() {
  292. continue
  293. }
  294. fam := "4"
  295. if a.Is6() {
  296. fam = "6"
  297. }
  298. if needSpace {
  299. sb.WriteString(" ")
  300. }
  301. needSpace = true
  302. switch {
  303. case a.IsLoopback():
  304. fmt.Fprintf(&sb, "lo%s", fam)
  305. case a.IsLinkLocalUnicast():
  306. fmt.Fprintf(&sb, "llu%s", fam)
  307. default:
  308. fmt.Fprintf(&sb, "%s", pfx)
  309. }
  310. }
  311. sb.WriteString("]")
  312. }
  313. sb.WriteString("}")
  314. if s.IsExpensive {
  315. sb.WriteString(" expensive")
  316. }
  317. if s.HTTPProxy != "" {
  318. fmt.Fprintf(&sb, " httpproxy=%s", s.HTTPProxy)
  319. }
  320. if s.PAC != "" {
  321. fmt.Fprintf(&sb, " pac=%s", s.PAC)
  322. }
  323. fmt.Fprintf(&sb, " v4=%v v6=%v}", s.HaveV4, s.HaveV6)
  324. return sb.String()
  325. }
  326. // Equal reports whether s and s2 are exactly equal.
  327. func (s *State) Equal(s2 *State) bool {
  328. if s == nil && s2 == nil {
  329. return true
  330. }
  331. if s == nil || s2 == nil {
  332. return false
  333. }
  334. if s.HaveV6 != s2.HaveV6 ||
  335. s.HaveV4 != s2.HaveV4 ||
  336. s.IsExpensive != s2.IsExpensive ||
  337. s.DefaultRouteInterface != s2.DefaultRouteInterface ||
  338. s.HTTPProxy != s2.HTTPProxy ||
  339. s.PAC != s2.PAC {
  340. return false
  341. }
  342. // If s2 has more interfaces than s, it's not equal.
  343. if len(s.Interface) != len(s2.Interface) || len(s.InterfaceIPs) != len(s2.InterfaceIPs) {
  344. return false
  345. }
  346. // Now that we know that both states have the same number of
  347. // interfaces, we can check each interface in s against s2. If it's not
  348. // present or not exactly equal, then the states are not equal.
  349. for iname, i := range s.Interface {
  350. i2, ok := s2.Interface[iname]
  351. if !ok {
  352. return false
  353. }
  354. if !i.Equal(i2) {
  355. return false
  356. }
  357. }
  358. for iname, vv := range s.InterfaceIPs {
  359. if !slices.Equal(vv, s2.InterfaceIPs[iname]) {
  360. return false
  361. }
  362. }
  363. return true
  364. }
  365. // HasIP reports whether any interface has the provided IP address.
  366. func (s *State) HasIP(ip netip.Addr) bool {
  367. if s == nil {
  368. return false
  369. }
  370. for _, pv := range s.InterfaceIPs {
  371. for _, p := range pv {
  372. if p.Contains(ip) {
  373. return true
  374. }
  375. }
  376. }
  377. return false
  378. }
  379. func (a Interface) Equal(b Interface) bool {
  380. if (a.Interface == nil) != (b.Interface == nil) {
  381. return false
  382. }
  383. if !(a.Desc == b.Desc && netAddrsEqual(a.AltAddrs, b.AltAddrs)) {
  384. return false
  385. }
  386. if a.Interface != nil && !(a.Index == b.Index &&
  387. a.MTU == b.MTU &&
  388. a.Name == b.Name &&
  389. a.Flags == b.Flags &&
  390. bytes.Equal([]byte(a.HardwareAddr), []byte(b.HardwareAddr))) {
  391. return false
  392. }
  393. return true
  394. }
  395. func (s *State) HasPAC() bool { return s != nil && s.PAC != "" }
  396. // AnyInterfaceUp reports whether any interface seems like it has Internet access.
  397. func (s *State) AnyInterfaceUp() bool {
  398. if runtime.GOOS == "js" || runtime.GOOS == "tamago" {
  399. return true
  400. }
  401. return s != nil && (s.HaveV4 || s.HaveV6)
  402. }
  403. func netAddrsEqual(a, b []net.Addr) bool {
  404. if len(a) != len(b) {
  405. return false
  406. }
  407. for i, av := range a {
  408. if av.Network() != b[i].Network() || av.String() != b[i].String() {
  409. return false
  410. }
  411. }
  412. return true
  413. }
  414. func hasTailscaleIP(pfxs []netip.Prefix) bool {
  415. for _, pfx := range pfxs {
  416. if tsaddr.IsTailscaleIP(pfx.Addr()) {
  417. return true
  418. }
  419. }
  420. return false
  421. }
  422. func isTailscaleInterface(name string, ips []netip.Prefix) bool {
  423. if runtime.GOOS == "darwin" && strings.HasPrefix(name, "utun") && hasTailscaleIP(ips) {
  424. // On macOS in the sandboxed app (at least as of
  425. // 2021-02-25), we often see two utun devices
  426. // (e.g. utun4 and utun7) with the same IPv4 and IPv6
  427. // addresses. Just remove all utun devices with
  428. // Tailscale IPs until we know what's happening with
  429. // macOS NetworkExtensions and utun devices.
  430. return true
  431. }
  432. return name == "Tailscale" || // as it is on Windows
  433. strings.HasPrefix(name, "tailscale") // TODO: use --tun flag value, etc; see TODO in method doc
  434. }
  435. // getPAC, if non-nil, returns the current PAC file URL.
  436. var getPAC func() string
  437. // getState returns the state of all the current machine's network interfaces.
  438. //
  439. // It does not set the returned State.IsExpensive. The caller can populate that.
  440. //
  441. // optTSInterfaceName is the name of the Tailscale interface, if known.
  442. func getState(optTSInterfaceName string) (*State, error) {
  443. s := &State{
  444. InterfaceIPs: make(map[string][]netip.Prefix),
  445. Interface: make(map[string]Interface),
  446. }
  447. if err := ForeachInterface(func(ni Interface, pfxs []netip.Prefix) {
  448. isTSInterfaceName := optTSInterfaceName != "" && ni.Name == optTSInterfaceName
  449. ifUp := ni.IsUp()
  450. s.Interface[ni.Name] = ni
  451. s.InterfaceIPs[ni.Name] = append(s.InterfaceIPs[ni.Name], pfxs...)
  452. if !ifUp || isTSInterfaceName || isTailscaleInterface(ni.Name, pfxs) {
  453. return
  454. }
  455. for _, pfx := range pfxs {
  456. if pfx.Addr().IsLoopback() {
  457. continue
  458. }
  459. s.HaveV6 = s.HaveV6 || isUsableV6(pfx.Addr())
  460. s.HaveV4 = s.HaveV4 || isUsableV4(pfx.Addr())
  461. }
  462. }); err != nil {
  463. return nil, err
  464. }
  465. dr, _ := DefaultRoute()
  466. s.DefaultRouteInterface = dr.InterfaceName
  467. // Populate description (for Windows, primarily) if present.
  468. if desc := dr.InterfaceDesc; desc != "" {
  469. if iface, ok := s.Interface[dr.InterfaceName]; ok {
  470. iface.Desc = desc
  471. s.Interface[dr.InterfaceName] = iface
  472. }
  473. }
  474. if buildfeatures.HasUseProxy && s.AnyInterfaceUp() {
  475. req, err := http.NewRequest("GET", LoginEndpointForProxyDetermination, nil)
  476. if err != nil {
  477. return nil, err
  478. }
  479. if proxyFromEnv, ok := feature.HookProxyFromEnvironment.GetOk(); ok {
  480. if u, err := proxyFromEnv(req); err == nil && u != nil {
  481. s.HTTPProxy = u.String()
  482. }
  483. }
  484. if getPAC != nil {
  485. s.PAC = getPAC()
  486. }
  487. }
  488. return s, nil
  489. }
  490. // HTTPOfListener returns the HTTP address to ln.
  491. // If the listener is listening on the unspecified address, it
  492. // it tries to find a reasonable interface address on the machine to use.
  493. func HTTPOfListener(ln net.Listener) string {
  494. ta, ok := ln.Addr().(*net.TCPAddr)
  495. if !ok || !ta.IP.IsUnspecified() {
  496. return fmt.Sprintf("http://%v/", ln.Addr())
  497. }
  498. var goodIP string
  499. var privateIP string
  500. ForeachInterfaceAddress(func(i Interface, pfx netip.Prefix) {
  501. ip := pfx.Addr()
  502. if ip.IsPrivate() {
  503. if privateIP == "" {
  504. privateIP = ip.String()
  505. }
  506. return
  507. }
  508. goodIP = ip.String()
  509. })
  510. if privateIP != "" {
  511. goodIP = privateIP
  512. }
  513. if goodIP != "" {
  514. return fmt.Sprintf("http://%v/", net.JoinHostPort(goodIP, fmt.Sprint(ta.Port)))
  515. }
  516. return fmt.Sprintf("http://localhost:%v/", fmt.Sprint(ta.Port))
  517. }
  518. // likelyHomeRouterIP, if present, is a platform-specific function that is used
  519. // to determine the likely home router IP of the current system. The signature
  520. // of this function is:
  521. //
  522. // func() (homeRouter, localAddr netip.Addr, ok bool)
  523. //
  524. // It should return a homeRouter IP and ok=true, or no homeRouter IP and
  525. // ok=false. Optionally, an implementation can return the "self" IP address as
  526. // well, which will be used instead of attempting to determine it by reading
  527. // the system's interfaces.
  528. var likelyHomeRouterIP func() (netip.Addr, netip.Addr, bool)
  529. // For debugging the new behaviour where likelyHomeRouterIP can return the
  530. // "self" IP; should remove after we're confidant this won't cause issues.
  531. var disableLikelyHomeRouterIPSelf = envknob.RegisterBool("TS_DEBUG_DISABLE_LIKELY_HOME_ROUTER_IP_SELF")
  532. // LikelyHomeRouterIP returns the likely IP of the residential router,
  533. // which will always be an IPv4 private address, if found.
  534. // In addition, it returns the IP address of the current machine on
  535. // the LAN using that gateway.
  536. // This is used as the destination for UPnP, NAT-PMP, PCP, etc queries.
  537. func LikelyHomeRouterIP() (gateway, myIP netip.Addr, ok bool) {
  538. if !buildfeatures.HasPortMapper {
  539. return
  540. }
  541. // If we don't have a way to get the home router IP, then we can't do
  542. // anything; just return.
  543. if likelyHomeRouterIP == nil {
  544. return
  545. }
  546. // Get the gateway next; if that fails, we can't continue.
  547. gateway, myIP, ok = likelyHomeRouterIP()
  548. if !ok {
  549. return
  550. }
  551. // If the platform-specific implementation returned a valid myIP, then
  552. // we can return it as-is without needing to iterate through all
  553. // interface addresses.
  554. if disableLikelyHomeRouterIPSelf() {
  555. myIP = netip.Addr{}
  556. }
  557. if myIP.IsValid() {
  558. return
  559. }
  560. // The platform-specific implementation didn't return a valid myIP;
  561. // iterate through all interfaces and try to find the correct one.
  562. ForeachInterfaceAddress(func(i Interface, pfx netip.Prefix) {
  563. if !i.IsUp() {
  564. // Skip interfaces that aren't up.
  565. return
  566. } else if myIP.IsValid() {
  567. // We already have a valid self IP; skip this one.
  568. return
  569. }
  570. ip := pfx.Addr()
  571. if !ip.IsValid() || !ip.Is4() {
  572. // Skip IPs that aren't valid or aren't IPv4, since we
  573. // always return an IPv4 address.
  574. return
  575. }
  576. // If this prefix ("interface") doesn't contain the gateway,
  577. // then we skip it; this can happen if we have multiple valid
  578. // interfaces and the interface with the route to the internet
  579. // is ordered after another valid+running interface.
  580. if !pfx.Contains(gateway) {
  581. return
  582. }
  583. if gateway.IsPrivate() && ip.IsPrivate() {
  584. myIP = ip
  585. ok = true
  586. return
  587. }
  588. })
  589. return gateway, myIP, myIP.IsValid()
  590. }
  591. // isUsableV4 reports whether ip is a usable IPv4 address which could
  592. // conceivably be used to get Internet connectivity. Globally routable and
  593. // private IPv4 addresses are always Usable, and link local 169.254.x.x
  594. // addresses are in some environments.
  595. func isUsableV4(ip netip.Addr) bool {
  596. if !ip.Is4() || ip.IsLoopback() {
  597. return false
  598. }
  599. if ip.IsLinkLocalUnicast() {
  600. switch hostinfo.GetEnvType() {
  601. case hostinfo.AWSLambda:
  602. return true
  603. case hostinfo.AzureAppService:
  604. return true
  605. default:
  606. return false
  607. }
  608. }
  609. return true
  610. }
  611. // isUsableV6 reports whether ip is a usable IPv6 address which could
  612. // conceivably be used to get Internet connectivity. Globally routable
  613. // IPv6 addresses are always Usable, and Unique Local Addresses
  614. // (fc00::/7) are in some environments used with address translation.
  615. func isUsableV6(ip netip.Addr) bool {
  616. return v6Global1.Contains(ip) ||
  617. (ip.Is6() && ip.IsPrivate() && !tsaddr.TailscaleULARange().Contains(ip))
  618. }
  619. var (
  620. v6Global1 = netip.MustParsePrefix("2000::/3")
  621. )
  622. // keepInterfaceInStringSummary reports whether the named interface should be included
  623. // in the String method's summary string.
  624. func (s *State) keepInterfaceInStringSummary(ifName string) bool {
  625. iface, ok := s.Interface[ifName]
  626. if !ok || iface.Interface == nil {
  627. return false
  628. }
  629. if ifName == s.DefaultRouteInterface {
  630. return true
  631. }
  632. up := iface.IsUp()
  633. for _, p := range s.InterfaceIPs[ifName] {
  634. a := p.Addr()
  635. if a.IsLinkLocalUnicast() || a.IsLoopback() {
  636. continue
  637. }
  638. if up || a.IsGlobalUnicast() || a.IsPrivate() {
  639. return true
  640. }
  641. }
  642. return false
  643. }
  644. var altNetInterfaces func() ([]Interface, error)
  645. // RegisterInterfaceGetter sets the function that's used to query
  646. // the system network interfaces.
  647. func RegisterInterfaceGetter(getInterfaces func() ([]Interface, error)) {
  648. altNetInterfaces = getInterfaces
  649. }
  650. // InterfaceList is a list of interfaces on the machine.
  651. type InterfaceList []Interface
  652. // GetInterfaceList returns the list of interfaces on the machine.
  653. func GetInterfaceList() (InterfaceList, error) {
  654. return netInterfaces()
  655. }
  656. // netInterfaces is a wrapper around the standard library's net.Interfaces
  657. // that returns a []*Interface instead of a []net.Interface.
  658. // It exists because Android SDK 30 no longer permits Go's net.Interfaces
  659. // to work (Issue 2293); this wrapper lets us the Android app register
  660. // an alternate implementation.
  661. func netInterfaces() ([]Interface, error) {
  662. if altNetInterfaces != nil {
  663. return altNetInterfaces()
  664. }
  665. ifs, err := net.Interfaces()
  666. if err != nil {
  667. return nil, err
  668. }
  669. ret := make([]Interface, len(ifs))
  670. for i := range ifs {
  671. ret[i].Interface = &ifs[i]
  672. }
  673. return ret, nil
  674. }
  675. // DefaultRouteDetails are the details about a default route returned
  676. // by DefaultRoute.
  677. type DefaultRouteDetails struct {
  678. // InterfaceName is the interface name. It must always be populated.
  679. // It's like "eth0" (Linux), "Ethernet 2" (Windows), "en0" (macOS).
  680. InterfaceName string
  681. // InterfaceDesc is populated on Windows at least. It's a
  682. // longer description, like "Red Hat VirtIO Ethernet Adapter".
  683. InterfaceDesc string
  684. // InterfaceIndex is like net.Interface.Index.
  685. // Zero means not populated.
  686. InterfaceIndex int
  687. // TODO(bradfitz): break this out into v4-vs-v6 once that need arises.
  688. }
  689. // DefaultRouteInterface is like DefaultRoute but only returns the
  690. // interface name.
  691. func DefaultRouteInterface() (string, error) {
  692. dr, err := DefaultRoute()
  693. if err != nil {
  694. return "", err
  695. }
  696. return dr.InterfaceName, nil
  697. }
  698. // DefaultRoute returns details of the network interface that owns
  699. // the default route, not including any tailscale interfaces.
  700. func DefaultRoute() (DefaultRouteDetails, error) {
  701. return defaultRoute()
  702. }
  703. // HasCGNATInterface reports whether there are any non-Tailscale interfaces that
  704. // use a CGNAT IP range.
  705. func (m *Monitor) HasCGNATInterface() (bool, error) {
  706. hasCGNATInterface := false
  707. cgnatRange := tsaddr.CGNATRange()
  708. err := ForeachInterface(func(i Interface, pfxs []netip.Prefix) {
  709. isTSInterfaceName := m.tsIfName != "" && i.Name == m.tsIfName
  710. if hasCGNATInterface || !i.IsUp() || isTSInterfaceName || isTailscaleInterface(i.Name, pfxs) {
  711. return
  712. }
  713. for _, pfx := range pfxs {
  714. if cgnatRange.Overlaps(pfx) {
  715. hasCGNATInterface = true
  716. break
  717. }
  718. }
  719. })
  720. if err != nil {
  721. return false, err
  722. }
  723. return hasCGNATInterface, nil
  724. }
  725. var interfaceDebugExtras func(ifIndex int) (string, error)
  726. // InterfaceDebugExtras returns extra debugging information about an interface
  727. // if any (an empty string will be returned if there are no additional details).
  728. // Formatting is platform-dependent and should not be parsed.
  729. func InterfaceDebugExtras(ifIndex int) (string, error) {
  730. if interfaceDebugExtras != nil {
  731. return interfaceDebugExtras(ifIndex)
  732. }
  733. return "", nil
  734. }