validator.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. package urlvalidator
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "net"
  7. "net/url"
  8. "strconv"
  9. "strings"
  10. "time"
  11. )
  12. type ValidationOptions struct {
  13. AllowedHosts []string
  14. RequireAllowlist bool
  15. AllowPrivate bool
  16. }
  17. // ValidateHTTPURL validates an outbound HTTP/HTTPS URL.
  18. //
  19. // It provides a single validation entry point that supports:
  20. // - scheme 校验(https 或可选允许 http)
  21. // - 可选 allowlist(支持 *.example.com 通配)
  22. // - allow_private_hosts 策略(阻断 localhost/私网字面量 IP)
  23. //
  24. // 注意:DNS Rebinding 防护(解析后 IP 校验)应在实际发起请求时执行,避免 TOCTOU。
  25. func ValidateHTTPURL(raw string, allowInsecureHTTP bool, opts ValidationOptions) (string, error) {
  26. trimmed := strings.TrimSpace(raw)
  27. if trimmed == "" {
  28. return "", errors.New("url is required")
  29. }
  30. parsed, err := url.Parse(trimmed)
  31. if err != nil || parsed.Scheme == "" || parsed.Host == "" {
  32. return "", fmt.Errorf("invalid url: %s", trimmed)
  33. }
  34. scheme := strings.ToLower(parsed.Scheme)
  35. if scheme != "https" && (!allowInsecureHTTP || scheme != "http") {
  36. return "", fmt.Errorf("invalid url scheme: %s", parsed.Scheme)
  37. }
  38. host := strings.ToLower(strings.TrimSpace(parsed.Hostname()))
  39. if host == "" {
  40. return "", errors.New("invalid host")
  41. }
  42. if !opts.AllowPrivate && isBlockedHost(host) {
  43. return "", fmt.Errorf("host is not allowed: %s", host)
  44. }
  45. if port := parsed.Port(); port != "" {
  46. num, err := strconv.Atoi(port)
  47. if err != nil || num <= 0 || num > 65535 {
  48. return "", fmt.Errorf("invalid port: %s", port)
  49. }
  50. }
  51. allowlist := normalizeAllowlist(opts.AllowedHosts)
  52. if opts.RequireAllowlist && len(allowlist) == 0 {
  53. return "", errors.New("allowlist is not configured")
  54. }
  55. if len(allowlist) > 0 && !isAllowedHost(host, allowlist) {
  56. return "", fmt.Errorf("host is not allowed: %s", host)
  57. }
  58. parsed.Path = strings.TrimRight(parsed.Path, "/")
  59. parsed.RawPath = ""
  60. return strings.TrimRight(parsed.String(), "/"), nil
  61. }
  62. func ValidateURLFormat(raw string, allowInsecureHTTP bool) (string, error) {
  63. // 最小格式校验:仅保证 URL 可解析且 scheme 合规,不做白名单/私网/SSRF 校验
  64. trimmed := strings.TrimSpace(raw)
  65. if trimmed == "" {
  66. return "", errors.New("url is required")
  67. }
  68. parsed, err := url.Parse(trimmed)
  69. if err != nil || parsed.Scheme == "" || parsed.Host == "" {
  70. return "", fmt.Errorf("invalid url: %s", trimmed)
  71. }
  72. scheme := strings.ToLower(parsed.Scheme)
  73. if scheme != "https" && (!allowInsecureHTTP || scheme != "http") {
  74. return "", fmt.Errorf("invalid url scheme: %s", parsed.Scheme)
  75. }
  76. host := strings.TrimSpace(parsed.Hostname())
  77. if host == "" {
  78. return "", errors.New("invalid host")
  79. }
  80. if port := parsed.Port(); port != "" {
  81. num, err := strconv.Atoi(port)
  82. if err != nil || num <= 0 || num > 65535 {
  83. return "", fmt.Errorf("invalid port: %s", port)
  84. }
  85. }
  86. return strings.TrimRight(trimmed, "/"), nil
  87. }
  88. func ValidateHTTPSURL(raw string, opts ValidationOptions) (string, error) {
  89. return ValidateHTTPURL(raw, false, opts)
  90. }
  91. // ValidateResolvedIP 验证 DNS 解析后的 IP 地址是否安全
  92. // 用于防止 DNS Rebinding 攻击:在实际 HTTP 请求时调用此函数验证解析后的 IP
  93. func ValidateResolvedIP(host string) error {
  94. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  95. defer cancel()
  96. ips, err := net.DefaultResolver.LookupIP(ctx, "ip", host)
  97. if err != nil {
  98. return fmt.Errorf("dns resolution failed: %w", err)
  99. }
  100. for _, ip := range ips {
  101. if ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() ||
  102. ip.IsLinkLocalMulticast() || ip.IsUnspecified() {
  103. return fmt.Errorf("resolved ip %s is not allowed", ip.String())
  104. }
  105. }
  106. return nil
  107. }
  108. func normalizeAllowlist(values []string) []string {
  109. if len(values) == 0 {
  110. return nil
  111. }
  112. normalized := make([]string, 0, len(values))
  113. for _, v := range values {
  114. entry := strings.ToLower(strings.TrimSpace(v))
  115. if entry == "" {
  116. continue
  117. }
  118. if host, _, err := net.SplitHostPort(entry); err == nil {
  119. entry = host
  120. }
  121. normalized = append(normalized, entry)
  122. }
  123. return normalized
  124. }
  125. func isAllowedHost(host string, allowlist []string) bool {
  126. for _, entry := range allowlist {
  127. if entry == "" {
  128. continue
  129. }
  130. if strings.HasPrefix(entry, "*.") {
  131. suffix := strings.TrimPrefix(entry, "*.")
  132. if host == suffix || strings.HasSuffix(host, "."+suffix) {
  133. return true
  134. }
  135. continue
  136. }
  137. if host == entry {
  138. return true
  139. }
  140. }
  141. return false
  142. }
  143. // IsBlockedHost 报告 host 是否为 localhost、*.localhost,或回环、私网、链路本地、未指定地址的字面量 IP。
  144. // 只判断字面量,域名的解析结果由 ValidateResolvedIP 校验。
  145. func IsBlockedHost(host string) bool {
  146. return isBlockedHost(strings.ToLower(strings.TrimSpace(host)))
  147. }
  148. func isBlockedHost(host string) bool {
  149. if host == "localhost" || strings.HasSuffix(host, ".localhost") {
  150. return true
  151. }
  152. if ip := net.ParseIP(host); ip != nil {
  153. if ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() || ip.IsUnspecified() {
  154. return true
  155. }
  156. }
  157. return false
  158. }