endpoint.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. package push
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "errors"
  6. "fmt"
  7. "net"
  8. "net/http"
  9. "net/url"
  10. "strconv"
  11. "strings"
  12. "time"
  13. )
  14. const maxRedirects = 5
  15. // ValidateEndpoint accepts only HTTPS endpoints whose host is public. It is
  16. // used when a subscription is created and again before every send, so rows
  17. // stored by older versions cannot reach the LAN either.
  18. func ValidateEndpoint(raw string) error {
  19. u, err := url.Parse(raw)
  20. if err != nil {
  21. return fmt.Errorf("invalid endpoint: %w", err)
  22. }
  23. if !strings.EqualFold(u.Scheme, "https") {
  24. return errors.New("the endpoint must use https")
  25. }
  26. if u.User != nil {
  27. return errors.New("the endpoint must not include credentials")
  28. }
  29. host := u.Hostname()
  30. if host == "" {
  31. return errors.New("the endpoint has no host")
  32. }
  33. if port := u.Port(); port != "" {
  34. n, err := strconv.Atoi(port)
  35. if err != nil || n < 1 || n > 65535 {
  36. return errors.New("the endpoint has an invalid port")
  37. }
  38. }
  39. if ip := net.ParseIP(host); ip != nil {
  40. if blockedIP(ip) {
  41. return errors.New("the endpoint points to a non-public address")
  42. }
  43. return nil
  44. }
  45. name := strings.ToLower(strings.TrimSuffix(host, "."))
  46. if name == "localhost" || strings.HasSuffix(name, ".localhost") {
  47. return errors.New("the endpoint points to localhost")
  48. }
  49. return nil
  50. }
  51. func blockedIP(ip net.IP) bool {
  52. if ip == nil {
  53. return true
  54. }
  55. if ip.IsLoopback() || ip.IsPrivate() || ip.IsUnspecified() || ip.IsMulticast() ||
  56. ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() {
  57. return true
  58. }
  59. if v4 := ip.To4(); v4 != nil {
  60. switch {
  61. case v4[0] == 0:
  62. return true
  63. case v4[0] == 100 && v4[1] >= 64 && v4[1] <= 127:
  64. return true
  65. case v4[0] == 192 && v4[1] == 0 && v4[2] == 0:
  66. return true
  67. case v4[0] == 192 && v4[1] == 0 && v4[2] == 2:
  68. return true
  69. case v4[0] == 198 && (v4[1] == 18 || v4[1] == 19):
  70. return true
  71. case v4[0] == 198 && v4[1] == 51 && v4[2] == 100:
  72. return true
  73. case v4[0] == 203 && v4[1] == 0 && v4[2] == 113:
  74. return true
  75. case v4[0] >= 240:
  76. return true
  77. }
  78. return false
  79. }
  80. if len(ip) == net.IPv6len {
  81. // 2001:db8::/32 (documentation) and 64:ff9b::/96 / 64:ff9b:1::/48
  82. // (NAT64, which can map private IPv4 addresses).
  83. if ip[0] == 0x20 && ip[1] == 0x01 && ip[2] == 0x0d && ip[3] == 0xb8 {
  84. return true
  85. }
  86. if ip[0] == 0x00 && ip[1] == 0x64 && ip[2] == 0xff && ip[3] == 0x9b {
  87. return true
  88. }
  89. }
  90. return false
  91. }
  92. func resolvePushHost(ctx context.Context, host string) ([]net.IP, error) {
  93. if ip := net.ParseIP(host); ip != nil {
  94. return []net.IP{ip}, nil
  95. }
  96. addrs, err := net.DefaultResolver.LookupIPAddr(ctx, host)
  97. if err != nil {
  98. return nil, fmt.Errorf("resolver %s: %w", host, err)
  99. }
  100. ips := make([]net.IP, 0, len(addrs))
  101. for _, addr := range addrs {
  102. ips = append(ips, addr.IP)
  103. }
  104. if len(ips) == 0 {
  105. return nil, fmt.Errorf("resolve %s: no addresses", host)
  106. }
  107. return ips, nil
  108. }
  109. func safeDialContext(ctx context.Context, network, addr string) (net.Conn, error) {
  110. host, port, err := net.SplitHostPort(addr)
  111. if err != nil {
  112. return nil, fmt.Errorf("invalid push address: %w", err)
  113. }
  114. ips, err := resolvePushHost(ctx, host)
  115. if err != nil {
  116. return nil, err
  117. }
  118. dialer := &net.Dialer{Timeout: 10 * time.Second, KeepAlive: 30 * time.Second}
  119. var lastErr error
  120. for _, ip := range ips {
  121. if blockedIP(ip) {
  122. continue
  123. }
  124. conn, err := dialer.DialContext(ctx, network, net.JoinHostPort(ip.String(), port))
  125. if err == nil {
  126. return conn, nil
  127. }
  128. lastErr = err
  129. }
  130. if lastErr != nil {
  131. return nil, fmt.Errorf("connect to %s: %w", host, lastErr)
  132. }
  133. return nil, fmt.Errorf("the endpoint %s resolves to a non-public address", host)
  134. }
  135. func newSafeHTTPClient() *http.Client {
  136. return &http.Client{
  137. Timeout: sendTimeout,
  138. Transport: &http.Transport{
  139. Proxy: nil,
  140. DialContext: safeDialContext,
  141. ForceAttemptHTTP2: true,
  142. TLSHandshakeTimeout: 10 * time.Second,
  143. MaxIdleConns: 20,
  144. IdleConnTimeout: 90 * time.Second,
  145. TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS12},
  146. },
  147. CheckRedirect: func(req *http.Request, via []*http.Request) error {
  148. if len(via) >= maxRedirects {
  149. return errors.New("too many redirects")
  150. }
  151. return ValidateEndpoint(req.URL.String())
  152. },
  153. }
  154. }