cloudenv.go 5.0 KB

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