-
Notifications
You must be signed in to change notification settings - Fork 8
/
client.go
315 lines (245 loc) · 6.76 KB
/
client.go
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
package safeurl
import (
"context"
"crypto/tls"
"fmt"
"io"
"net"
"net/http"
"net/http/httptrace"
urllib "net/url"
"strings"
"syscall"
)
func buildHttpClient(wc *WrappedClient) *http.Client {
client := &http.Client{
Timeout: wc.config.Timeout,
CheckRedirect: wc.config.CheckRedirect,
Jar: wc.config.Jar,
Transport: &http.Transport{
TLSClientConfig: wc.tlsConfig,
DialContext: (&net.Dialer{
Resolver: wc.resolver,
Control: buildRunFunc(wc),
}).DialContext,
},
}
return client
}
func buildRunFunc(wc *WrappedClient) func(network, address string, c syscall.RawConn) error {
return func(network, address string, _ syscall.RawConn) error {
wc.log(fmt.Sprintf("connection to address: %v", address))
if !wc.config.IsIPv6Enabled && network == "tcp6" {
wc.log("ipv6 is disabled")
return &IPv6BlockedError{ip: address}
}
host, port, _ := net.SplitHostPort(address)
if !isPortAllowed(port, wc.config.AllowedPorts) {
wc.log(fmt.Sprintf("disallowed port: %v", port))
return &AllowedPortError{port: port}
}
ip := net.ParseIP(host)
if ip == nil {
panic(fmt.Sprintf("invalid ip: %v", host))
}
if isIPAllowed(ip, wc.config.AllowedIPs, wc.config.AllowedIPsCIDR) {
return nil
}
// allowlist set in the config, but target IP was not found on the list
isConfigAllowListSet := wc.config.AllowedIPs != nil || wc.config.AllowedIPsCIDR != nil
if isConfigAllowListSet {
wc.log(fmt.Sprintf("ip: %v not found in allowlist", ip))
return &AllowedIPError{ip: ip.String()}
}
if isIPBlocked(ip, wc.config.BlockedIPs, wc.config.BlockedIPsCIDR) {
wc.log(fmt.Sprintf("ip: %v found in blocklist", ip))
return &AllowedIPError{ip: ip.String()}
}
return nil
}
}
/* validators */
func validateCredentials(parsed *urllib.URL, config *Config, debugLogFunc func(string)) error {
if config.AllowSendingCredentials {
return nil
}
username := strings.TrimSpace(parsed.User.Username())
password, _ := parsed.User.Password()
password = strings.TrimSpace(password)
if username != "" || password != "" {
debugLogFunc("credentials found in supplied url.")
return &SendingCredentialsBlockedError{}
}
return nil
}
func isSchemeValid(parsed *urllib.URL, config *Config, debugLogFunc func(string)) error {
scheme := parsed.Scheme
if len(scheme) > 0 && !isSchemeAllowed(scheme, config.AllowedSchemes) {
debugLogFunc(fmt.Sprintf("disallowed scheme: %v", scheme))
return &AllowedSchemeError{scheme: scheme}
}
return nil
}
func isHostValid(parsed *urllib.URL, config *Config, debugLogFunc func(string)) error {
host := parsed.Hostname()
if host == "" {
debugLogFunc("empty host received")
return &InvalidHostError{host: ""}
}
if config.AllowedHosts != nil && !isAllowedHost(host, config.AllowedHosts) {
debugLogFunc(fmt.Sprintf("disallowed host: %s", host))
return &AllowedHostError{host: host}
}
return nil
}
/* wrapper */
type WrappedClient struct {
Client *http.Client
config *Config
tlsConfig *tls.Config
resolver *net.Resolver
// used for track DNS resolutions for testing purposes
tracer *tracer
}
func Client(config *Config) *WrappedClient {
tlsConfig := config.TlsConfig
var resolver *net.Resolver = nil
if config.InTestMode {
resolver = &net.Resolver{
PreferGo: true,
Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
d := net.Dialer{}
return d.DialContext(ctx, "udp", "localhost:8053")
},
}
}
wc := &WrappedClient{
config: config,
tlsConfig: tlsConfig,
resolver: resolver,
}
wc.Client = buildHttpClient(wc)
return wc
}
func (wc *WrappedClient) Head(url string) (resp *http.Response, err error) {
wc.log("calling proxied Head...")
req, err := http.NewRequest("HEAD", url, nil)
if err != nil {
return nil, err
}
return wc.Do(req)
}
func (wc *WrappedClient) Get(url string) (resp *http.Response, err error) {
wc.log("calling proxied Get...")
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
return wc.Do(req)
}
func (wc *WrappedClient) Post(url string, contentType string, body io.Reader) (resp *http.Response, err error) {
wc.log("calling proxied Post...")
req, err := http.NewRequest("POST", url, body)
if err != nil {
return nil, err
}
return wc.Do(req)
}
func (wc *WrappedClient) PostForm(url string, data urllib.Values) (resp *http.Response, err error) {
return wc.Post(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
}
func (wc *WrappedClient) Do(req *http.Request) (resp *http.Response, err error) {
wc.log("calling proxied Do...")
if wc.config.InTestMode {
wc.tracer = &tracer{}
req = req.WithContext(httptrace.WithClientTrace(req.Context(), wc.tracer.buildTracer()))
}
url := req.URL.String()
parsedURL, err := urllib.Parse(url)
if err != nil {
return nil, err
}
err = validateCredentials(parsedURL, wc.config, wc.log)
if err != nil {
return nil, err
}
err = isSchemeValid(parsedURL, wc.config, wc.log)
if err != nil {
return nil, err
}
err = isHostValid(parsedURL, wc.config, wc.log)
if err != nil {
return nil, err
}
return wc.Client.Do(req)
}
func (wc *WrappedClient) CloseIdleConnections() {
wc.Client.CloseIdleConnections()
}
/* testing */
type tracer struct {
dnsResolutionsCount int
}
func (t *tracer) buildTracer() *httptrace.ClientTrace {
return &httptrace.ClientTrace{
DNSDone: func(dnsInfo httptrace.DNSDoneInfo) {
t.dnsResolutionsCount++
},
}
}
/* error */
type AllowedPortError struct {
port string
}
func (e *AllowedPortError) Error() string {
return fmt.Sprintf("port: %v not found in allowlist", e.port)
}
type AllowedSchemeError struct {
scheme string
}
func (e *AllowedSchemeError) Error() string {
return fmt.Sprintf("scheme: %v not found in allowlist", e.scheme)
}
type InvalidHostError struct {
host string
}
func (e *InvalidHostError) Error() string {
return fmt.Sprintf("host: %v is not valid", e.host)
}
type AllowedHostError struct {
host string
}
func (e *AllowedHostError) Error() string {
return fmt.Sprintf("host: %v not found in allowlist", e.host)
}
type AllowedIPError struct {
ip string
}
func (e *AllowedIPError) Error() string {
return fmt.Sprintf("ip: %v not found in allowlist", e.ip)
}
type IPv6BlockedError struct {
ip string
}
func (e *IPv6BlockedError) Error() string {
return fmt.Sprintf("ipv6 blocked. connection to %v dropped", e.ip)
}
type SendingCredentialsBlockedError struct {
}
func (e *SendingCredentialsBlockedError) Error() string {
return fmt.Sprintf("sending credentials blocked.")
}
func unwrap(err error) error {
wrapped, ok := err.(interface{ Unwrap() error })
if !ok {
return err
}
inner := wrapped.Unwrap()
return unwrap(inner)
}
/* debug */
func (wc *WrappedClient) log(msg string) {
if wc.config.IsDebugLoggingEnabled {
fmt.Printf("[safeurl] %v\n", msg)
}
}