forked from QuantumNous/new-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprotected_fetch_client.go
More file actions
239 lines (210 loc) · 6.38 KB
/
Copy pathprotected_fetch_client.go
File metadata and controls
239 lines (210 loc) · 6.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
package service
import (
"context"
"fmt"
"net"
"net/http"
"net/url"
"strconv"
"sync"
"time"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/setting/system_setting"
)
type ssrfResolver interface {
LookupIPAddr(ctx context.Context, host string) ([]net.IPAddr, error)
}
type protectedFetchDialer struct {
resolver ssrfResolver
dialContext func(ctx context.Context, network, address string) (net.Conn, error)
getProtection func() (*common.SSRFProtection, bool, error)
}
type ssrfProtectedRoundTripper struct {
resolver ssrfResolver
dialContext func(ctx context.Context, network, address string) (net.Conn, error)
getProtection func() (*common.SSRFProtection, bool, error)
proxy func(*http.Request) (*url.URL, error)
mutex sync.Mutex
transports map[string]*http.Transport
}
func currentFetchProtection() (*common.SSRFProtection, bool, error) {
fetchSetting := system_setting.GetFetchSetting()
if !fetchSetting.EnableSSRFProtection {
return nil, false, nil
}
protection, err := common.NewSSRFProtectionFromFetchSetting(
fetchSetting.AllowPrivateIp,
fetchSetting.DomainFilterMode,
fetchSetting.IpFilterMode,
fetchSetting.DomainList,
fetchSetting.IpList,
fetchSetting.AllowedPorts,
fetchSetting.ApplyIPFilterForDomain,
)
if err != nil {
return nil, true, err
}
return protection, true, nil
}
func newProtectedFetchHTTPClient() *http.Client {
return newProtectedFetchHTTPClientWithDialer(nil, nil, nil)
}
func newProtectedFetchHTTPClientWithDialer(resolver ssrfResolver, dialContext func(ctx context.Context, network, address string) (net.Conn, error), getProtection func() (*common.SSRFProtection, bool, error)) *http.Client {
return newProtectedFetchHTTPClientWithProxy(resolver, dialContext, getProtection, http.ProxyFromEnvironment)
}
func newProtectedFetchHTTPClientWithProxy(resolver ssrfResolver, dialContext func(ctx context.Context, network, address string) (net.Conn, error), getProtection func() (*common.SSRFProtection, bool, error), proxy func(*http.Request) (*url.URL, error)) *http.Client {
if resolver == nil {
resolver = net.DefaultResolver
}
if dialContext == nil {
netDialer := &net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}
dialContext = netDialer.DialContext
}
if getProtection == nil {
getProtection = currentFetchProtection
}
if proxy == nil {
proxy = http.ProxyFromEnvironment
}
client := &http.Client{
Transport: &ssrfProtectedRoundTripper{
resolver: resolver,
dialContext: dialContext,
getProtection: getProtection,
proxy: proxy,
transports: make(map[string]*http.Transport),
},
CheckRedirect: checkProtectedFetchRedirect,
}
if common.RelayTimeout != 0 {
client.Timeout = time.Duration(common.RelayTimeout) * time.Second
}
return client
}
func (t *ssrfProtectedRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
if req == nil || req.URL == nil {
return nil, fmt.Errorf("invalid request")
}
if err := ValidateSSRFProtectedFetchURL(req.URL.String()); err != nil {
return nil, err
}
proxyURL, err := t.proxy(req)
if err != nil {
return nil, err
}
return t.transportFor(proxyURL).RoundTrip(req)
}
func (t *ssrfProtectedRoundTripper) CloseIdleConnections() {
t.mutex.Lock()
defer t.mutex.Unlock()
for _, transport := range t.transports {
transport.CloseIdleConnections()
}
}
func (t *ssrfProtectedRoundTripper) transportFor(proxyURL *url.URL) *http.Transport {
// 只按代理地址分组:代理来自环境变量,取值有限,map 有界;
// 目标 origin 是用户可控输入,不能作为缓存 key。
key := "direct"
if proxyURL != nil {
key = proxyURL.String()
}
t.mutex.Lock()
defer t.mutex.Unlock()
if transport, ok := t.transports[key]; ok {
return transport
}
transport := t.newTransport(proxyURL)
t.transports[key] = transport
return transport
}
func (t *ssrfProtectedRoundTripper) newTransport(proxyURL *url.URL) *http.Transport {
dialContext := t.dialContext
proxyFunc := http.ProxyURL(proxyURL)
if proxyURL == nil {
protectedDialer := &protectedFetchDialer{
resolver: t.resolver,
dialContext: t.dialContext,
getProtection: t.getProtection,
}
dialContext = protectedDialer.DialContext
proxyFunc = nil
}
transport := &http.Transport{
MaxIdleConns: common.RelayMaxIdleConns,
MaxIdleConnsPerHost: common.RelayMaxIdleConnsPerHost,
IdleConnTimeout: time.Duration(common.RelayIdleConnTimeout) * time.Second,
ForceAttemptHTTP2: true,
Proxy: proxyFunc,
DialContext: dialContext,
}
if common.TLSInsecureSkipVerify {
transport.TLSClientConfig = common.InsecureTLSConfig
}
return transport
}
func (d *protectedFetchDialer) DialContext(ctx context.Context, network, addr string) (net.Conn, error) {
protection, enabled, err := d.getProtection()
if err != nil {
return nil, err
}
if !enabled {
return d.dialContext(ctx, network, addr)
}
host, portText, err := net.SplitHostPort(addr)
if err != nil {
return nil, fmt.Errorf("invalid dial address %s: %w", addr, err)
}
port, err := strconv.Atoi(portText)
if err != nil {
return nil, fmt.Errorf("invalid port: %s", portText)
}
if err := protection.ValidateNetworkTarget(host, port); err != nil {
return nil, err
}
if ip := net.ParseIP(host); ip != nil {
return d.dialContext(ctx, network, net.JoinHostPort(ip.String(), portText))
}
if !protection.ApplyIPFilterForDomain {
return d.dialContext(ctx, network, addr)
}
resolved, err := d.resolver.LookupIPAddr(ctx, host)
if err != nil {
return nil, fmt.Errorf("DNS resolution failed for %s: %v", host, err)
}
var candidateIPs []net.IP
for _, ipAddr := range resolved {
ip := ipAddr.IP
if ip == nil || !networkAllowsIP(network, ip) {
continue
}
if err := protection.ValidateResolvedIP(host, ip); err != nil {
return nil, err
}
candidateIPs = append(candidateIPs, ip)
}
var lastDialErr error
for _, ip := range candidateIPs {
conn, err := d.dialContext(ctx, network, net.JoinHostPort(ip.String(), portText))
if err == nil {
return conn, nil
}
lastDialErr = err
}
if lastDialErr != nil {
return nil, lastDialErr
}
return nil, fmt.Errorf("DNS resolution for %s returned no usable IP addresses", host)
}
func networkAllowsIP(network string, ip net.IP) bool {
switch network {
case "tcp4":
return ip.To4() != nil
case "tcp6":
return ip.To4() == nil
default:
return true
}
}