cloudenv.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. // Copyright (c) Tailscale Inc & contributors
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. // Package cloudenv reports which known cloud environment we're running in.
  4. package cloudenv
  5. import (
  6. "context"
  7. "encoding/json"
  8. "log"
  9. "math/rand/v2"
  10. "net"
  11. "net/http"
  12. "os"
  13. "runtime"
  14. "strings"
  15. "time"
  16. "tailscale.com/feature/buildfeatures"
  17. "tailscale.com/syncs"
  18. "tailscale.com/types/lazy"
  19. )
  20. // CommonNonRoutableMetadataIP is the IP address of the metadata server
  21. // on Amazon EC2, Google Compute Engine, and Azure. It's not routable.
  22. // (169.254.0.0/16 is a Link Local range: RFC 3927)
  23. const CommonNonRoutableMetadataIP = "169.254.169.254"
  24. // GoogleMetadataAndDNSIP is the metadata IP used by Google Cloud.
  25. // It's also the *.internal DNS server, and proxies to 8.8.8.8.
  26. const GoogleMetadataAndDNSIP = "169.254.169.254"
  27. // AWSResolverIP is the IP address of the AWS DNS server.
  28. // See https://docs.aws.amazon.com/vpc/latest/userguide/vpc-dns.html
  29. const AWSResolverIP = "169.254.169.253"
  30. // AzureResolverIP is Azure's DNS resolver IP.
  31. // See https://docs.microsoft.com/en-us/azure/virtual-network/what-is-ip-address-168-63-129-16
  32. const AzureResolverIP = "168.63.129.16"
  33. // Cloud is a recognize cloud environment with properties that
  34. // Tailscale can specialize for in places.
  35. type Cloud string
  36. const (
  37. AWS = Cloud("aws") // Amazon Web Services (EC2 in particular)
  38. Azure = Cloud("azure") // Microsoft Azure
  39. GCP = Cloud("gcp") // Google Cloud
  40. DigitalOcean = Cloud("digitalocean") // DigitalOcean
  41. )
  42. // ResolverIP returns the cloud host's recursive DNS server or the
  43. // empty string if not available.
  44. func (c Cloud) ResolverIP() string {
  45. if !buildfeatures.HasCloud {
  46. return ""
  47. }
  48. switch c {
  49. case GCP:
  50. return GoogleMetadataAndDNSIP
  51. case AWS:
  52. return AWSResolverIP
  53. case Azure:
  54. return AzureResolverIP
  55. case DigitalOcean:
  56. return getDigitalOceanResolver()
  57. }
  58. return ""
  59. }
  60. var (
  61. // https://docs.digitalocean.com/support/check-your-droplets-network-configuration/
  62. digitalOceanResolvers = []string{"67.207.67.2", "67.207.67.3"}
  63. digitalOceanResolver lazy.SyncValue[string]
  64. )
  65. func getDigitalOceanResolver() string {
  66. // Randomly select one of the available resolvers so we don't overload
  67. // one of them by sending all traffic there.
  68. return digitalOceanResolver.Get(func() string {
  69. return digitalOceanResolvers[rand.IntN(len(digitalOceanResolvers))]
  70. })
  71. }
  72. // HasInternalTLD reports whether c is a cloud environment
  73. // whose ResolverIP serves *.internal records.
  74. func (c Cloud) HasInternalTLD() bool {
  75. switch c {
  76. case GCP, AWS:
  77. return true
  78. }
  79. return false
  80. }
  81. var cloudAtomic syncs.AtomicValue[Cloud]
  82. // Get returns the current cloud, or the empty string if unknown.
  83. func Get() Cloud {
  84. if !buildfeatures.HasCloud {
  85. return ""
  86. }
  87. if c, ok := cloudAtomic.LoadOk(); ok {
  88. return c
  89. }
  90. c := getCloud()
  91. cloudAtomic.Store(c) // even if empty
  92. return c
  93. }
  94. func readFileTrimmed(name string) string {
  95. v, _ := os.ReadFile(name)
  96. return strings.TrimSpace(string(v))
  97. }
  98. func getCloud() Cloud {
  99. var hitMetadata bool
  100. switch runtime.GOOS {
  101. case "android", "ios", "darwin":
  102. // Assume these aren't running on a cloud.
  103. return ""
  104. case "linux":
  105. biosVendor := readFileTrimmed("/sys/class/dmi/id/bios_vendor")
  106. if biosVendor == "Amazon EC2" || strings.HasSuffix(biosVendor, ".amazon") {
  107. return AWS
  108. }
  109. sysVendor := readFileTrimmed("/sys/class/dmi/id/sys_vendor")
  110. if sysVendor == "DigitalOcean" {
  111. return DigitalOcean
  112. }
  113. // TODO(andrew): "Vultr" is also valid if we need it
  114. prod := readFileTrimmed("/sys/class/dmi/id/product_name")
  115. if prod == "Google Compute Engine" {
  116. return GCP
  117. }
  118. if prod == "Google" { // old GCP VMs, it seems
  119. hitMetadata = true
  120. }
  121. if prod == "Virtual Machine" || biosVendor == "Microsoft Corporation" {
  122. // Azure, or maybe all Hyper-V?
  123. hitMetadata = true
  124. }
  125. default:
  126. // TODO(bradfitz): use Win32_SystemEnclosure from WMI or something on
  127. // Windows to see if it's a physical machine and skip the cloud check
  128. // early. Otherwise use similar clues as Linux about whether we should
  129. // burn up to 2 seconds waiting for a metadata server that might not be
  130. // there. And for BSDs, look where the /sys stuff is.
  131. return ""
  132. }
  133. if !hitMetadata {
  134. return ""
  135. }
  136. const maxWait = 2 * time.Second
  137. tr := &http.Transport{
  138. DisableKeepAlives: true,
  139. Dial: (&net.Dialer{
  140. Timeout: maxWait,
  141. }).Dial,
  142. }
  143. ctx, cancel := context.WithTimeout(context.Background(), maxWait)
  144. defer cancel()
  145. // We want to hit CommonNonRoutableMetadataIP to see if we're on AWS, GCP,
  146. // or Azure. All three (and many others) use the same metadata IP.
  147. //
  148. // But to avoid triggering the AWS CloudWatch "MetadataNoToken" metric (for which
  149. // there might be an alert registered?), make our initial request be a token
  150. // request. This only works on AWS, but the failing HTTP response on other clouds gives
  151. // us enough clues about which cloud we're on.
  152. req, err := http.NewRequestWithContext(ctx, "PUT", "http://"+CommonNonRoutableMetadataIP+"/latest/api/token", strings.NewReader(""))
  153. if err != nil {
  154. log.Printf("cloudenv: [unexpected] error creating request: %v", err)
  155. return ""
  156. }
  157. req.Header.Set("X-Aws-Ec2-Metadata-Token-Ttl-Seconds", "5")
  158. res, err := tr.RoundTrip(req)
  159. if err != nil {
  160. return ""
  161. }
  162. res.Body.Close()
  163. if res.Header.Get("Metadata-Flavor") == "Google" {
  164. return GCP
  165. }
  166. server := res.Header.Get("Server")
  167. if server == "EC2ws" {
  168. return AWS
  169. }
  170. if strings.HasPrefix(server, "Microsoft") {
  171. // e.g. "Microsoft-IIS/10.0"
  172. req, _ := http.NewRequestWithContext(ctx, "GET", "http://"+CommonNonRoutableMetadataIP+"/metadata/instance/compute?api-version=2021-02-01", nil)
  173. req.Header.Set("Metadata", "true")
  174. res, err := tr.RoundTrip(req)
  175. if err != nil {
  176. return ""
  177. }
  178. defer res.Body.Close()
  179. var meta struct {
  180. AzEnvironment string `json:"azEnvironment"`
  181. }
  182. if err := json.NewDecoder(res.Body).Decode(&meta); err != nil {
  183. return ""
  184. }
  185. if strings.HasPrefix(meta.AzEnvironment, "Azure") {
  186. return Azure
  187. }
  188. return ""
  189. }
  190. // TODO: more, as needed.
  191. return ""
  192. }