Files
vHost/backend/internal/dnsprovider/public_endpoint.go
T

63 lines
2.3 KiB
Go

package dnsprovider
import (
"context"
"errors"
"net"
"net/http"
"net/netip"
"net/url"
"strings"
"time"
)
func publicEndpoint(raw string) (*url.URL, error) {
u, e := url.Parse(raw)
if e != nil || len(raw) > 512 || u.Scheme != "https" || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Port() != "" && u.Port() != "443") || strings.ContainsAny(raw, "\r\n\x00") || strings.ContainsAny(u.Path, "?#\\") || strings.EqualFold(u.Hostname(), "localhost") {
return nil, errors.New("DNS API 地址必须为 HTTPS 公网地址,端口为 443,不能包含查询参数或身份信息")
}
if ip, e := netip.ParseAddr(u.Hostname()); e == nil && !publicIP(ip) {
return nil, errors.New("DNS API 禁止访问内网或保留地址")
}
return u, nil
}
func publicIP(ip netip.Addr) bool {
ip = ip.Unmap()
if !ip.IsGlobalUnicast() || ip.IsPrivate() || ip.IsLoopback() || ip.IsLinkLocalUnicast() {
return false
}
for _, v := range []string{"0.0.0.0/8", "100.64.0.0/10", "192.0.0.0/24", "192.0.2.0/24", "198.18.0.0/15", "198.51.100.0/24", "203.0.113.0/24", "240.0.0.0/4", "::/96", "64:ff9b::/96", "64:ff9b:1::/48", "2001:db8::/32", "2001::/32", "2002::/16"} {
if netip.MustParsePrefix(v).Contains(ip) {
return false
}
}
return true
}
func publicClient() *http.Client {
transport := &http.Transport{Proxy: nil, TLSHandshakeTimeout: 8 * time.Second, ResponseHeaderTimeout: 15 * time.Second, MaxIdleConnsPerHost: 2, IdleConnTimeout: 20 * time.Second, DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
host, port, e := net.SplitHostPort(address)
if e != nil || port != "443" {
return nil, errors.New("restricted DNS endpoint")
}
ips, e := net.DefaultResolver.LookupNetIP(ctx, "ip", host)
if e != nil || len(ips) == 0 {
return nil, errors.New("DNS API 域名无法解析")
}
for _, ip := range ips {
if !publicIP(ip) {
return nil, errors.New("DNS API 域名解析到受限地址")
}
}
var last error
for _, ip := range ips {
conn, e := (&net.Dialer{Timeout: 5 * time.Second}).DialContext(ctx, "tcp", net.JoinHostPort(ip.String(), port))
if e == nil {
return conn, nil
}
last = e
}
return nil, last
}}
return &http.Client{Transport: transport, Timeout: 20 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
}