Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
projectdiscovery
GitHub Repository: projectdiscovery/nuclei
Path: blob/dev/pkg/protocols/http/httpclientpool/clientpool.go
2073 views
1
package httpclientpool
2
3
import (
4
"context"
5
"crypto/tls"
6
"fmt"
7
"net"
8
"net/http"
9
"net/http/cookiejar"
10
"net/url"
11
"strconv"
12
"strings"
13
"sync"
14
"time"
15
16
"github.com/pkg/errors"
17
"golang.org/x/net/proxy"
18
"golang.org/x/net/publicsuffix"
19
20
"github.com/projectdiscovery/fastdialer/fastdialer/ja3/impersonate"
21
"github.com/projectdiscovery/nuclei/v3/pkg/protocols"
22
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/protocolstate"
23
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/utils"
24
"github.com/projectdiscovery/nuclei/v3/pkg/types"
25
"github.com/projectdiscovery/nuclei/v3/pkg/types/scanstrategy"
26
"github.com/projectdiscovery/rawhttp"
27
"github.com/projectdiscovery/retryablehttp-go"
28
urlutil "github.com/projectdiscovery/utils/url"
29
)
30
31
var (
32
forceMaxRedirects int
33
)
34
35
// Init initializes the clientpool implementation
36
func Init(options *types.Options) error {
37
if options.ShouldFollowHTTPRedirects() {
38
forceMaxRedirects = options.MaxRedirects
39
}
40
41
return nil
42
}
43
44
// ConnectionConfiguration contains the custom configuration options for a connection
45
type ConnectionConfiguration struct {
46
// DisableKeepAlive of the connection
47
DisableKeepAlive bool
48
// CustomMaxTimeout is the custom timeout for the connection
49
// This overrides all other timeouts and is used for accurate time based fuzzing.
50
CustomMaxTimeout time.Duration
51
cookiejar *cookiejar.Jar
52
mu sync.RWMutex
53
}
54
55
func (cc *ConnectionConfiguration) SetCookieJar(cookiejar *cookiejar.Jar) {
56
cc.mu.Lock()
57
defer cc.mu.Unlock()
58
59
cc.cookiejar = cookiejar
60
}
61
62
func (cc *ConnectionConfiguration) GetCookieJar() *cookiejar.Jar {
63
cc.mu.RLock()
64
defer cc.mu.RUnlock()
65
66
return cc.cookiejar
67
}
68
69
func (cc *ConnectionConfiguration) HasCookieJar() bool {
70
cc.mu.RLock()
71
defer cc.mu.RUnlock()
72
73
return cc.cookiejar != nil
74
}
75
76
// Configuration contains the custom configuration options for a client
77
type Configuration struct {
78
// Threads contains the threads for the client
79
Threads int
80
// MaxRedirects is the maximum number of redirects to follow
81
MaxRedirects int
82
// NoTimeout disables http request timeout for context based usage
83
NoTimeout bool
84
// DisableCookie disables cookie reuse for the http client (cookiejar impl)
85
DisableCookie bool
86
// FollowRedirects specifies the redirects flow
87
RedirectFlow RedirectFlow
88
// Connection defines custom connection configuration
89
Connection *ConnectionConfiguration
90
// ResponseHeaderTimeout is the timeout for response body to be read from the server
91
ResponseHeaderTimeout time.Duration
92
}
93
94
func (c *Configuration) Clone() *Configuration {
95
clone := *c
96
if c.Connection != nil {
97
cloneConnection := &ConnectionConfiguration{
98
DisableKeepAlive: c.Connection.DisableKeepAlive,
99
CustomMaxTimeout: c.Connection.CustomMaxTimeout,
100
}
101
if c.Connection.HasCookieJar() {
102
cookiejar := *c.Connection.GetCookieJar()
103
cloneConnection.SetCookieJar(&cookiejar)
104
}
105
clone.Connection = cloneConnection
106
}
107
108
return &clone
109
}
110
111
// Hash returns the hash of the configuration to allow client pooling
112
func (c *Configuration) Hash() string {
113
builder := &strings.Builder{}
114
builder.Grow(16)
115
builder.WriteString("t")
116
builder.WriteString(strconv.Itoa(c.Threads))
117
builder.WriteString("m")
118
builder.WriteString(strconv.Itoa(c.MaxRedirects))
119
builder.WriteString("n")
120
builder.WriteString(strconv.FormatBool(c.NoTimeout))
121
builder.WriteString("f")
122
builder.WriteString(strconv.Itoa(int(c.RedirectFlow)))
123
builder.WriteString("r")
124
builder.WriteString(strconv.FormatBool(c.DisableCookie))
125
builder.WriteString("c")
126
builder.WriteString(strconv.FormatBool(c.Connection != nil))
127
if c.Connection != nil && c.Connection.CustomMaxTimeout > 0 {
128
builder.WriteString("k")
129
builder.WriteString(c.Connection.CustomMaxTimeout.String())
130
}
131
builder.WriteString("r")
132
builder.WriteString(strconv.FormatInt(int64(c.ResponseHeaderTimeout.Seconds()), 10))
133
hash := builder.String()
134
return hash
135
}
136
137
// HasStandardOptions checks whether the configuration requires custom settings
138
func (c *Configuration) HasStandardOptions() bool {
139
return c.Threads == 0 && c.MaxRedirects == 0 && c.RedirectFlow == DontFollowRedirect && c.DisableCookie && c.Connection == nil && !c.NoTimeout && c.ResponseHeaderTimeout == 0
140
}
141
142
// GetRawHTTP returns the rawhttp request client
143
func GetRawHTTP(options *protocols.ExecutorOptions) *rawhttp.Client {
144
dialers := protocolstate.GetDialersWithId(options.Options.ExecutionId)
145
if dialers == nil {
146
panic("dialers not initialized for execution id: " + options.Options.ExecutionId)
147
}
148
149
// Lock the dialers to avoid a race when setting RawHTTPClient
150
dialers.Lock()
151
defer dialers.Unlock()
152
153
if dialers.RawHTTPClient != nil {
154
return dialers.RawHTTPClient
155
}
156
157
rawHttpOptionsCopy := *rawhttp.DefaultOptions
158
if options.Options.AliveHttpProxy != "" {
159
rawHttpOptionsCopy.Proxy = options.Options.AliveHttpProxy
160
} else if options.Options.AliveSocksProxy != "" {
161
rawHttpOptionsCopy.Proxy = options.Options.AliveSocksProxy
162
} else if dialers.Fastdialer != nil {
163
rawHttpOptionsCopy.FastDialer = dialers.Fastdialer
164
}
165
rawHttpOptionsCopy.Timeout = options.Options.GetTimeouts().HttpTimeout
166
dialers.RawHTTPClient = rawhttp.NewClient(&rawHttpOptionsCopy)
167
return dialers.RawHTTPClient
168
}
169
170
// Get creates or gets a client for the protocol based on custom configuration
171
func Get(options *types.Options, configuration *Configuration) (*retryablehttp.Client, error) {
172
if configuration.HasStandardOptions() {
173
dialers := protocolstate.GetDialersWithId(options.ExecutionId)
174
if dialers == nil {
175
return nil, fmt.Errorf("dialers not initialized for %s", options.ExecutionId)
176
}
177
return dialers.DefaultHTTPClient, nil
178
}
179
180
return wrappedGet(options, configuration)
181
}
182
183
// wrappedGet wraps a get operation without normal client check
184
func wrappedGet(options *types.Options, configuration *Configuration) (*retryablehttp.Client, error) {
185
var err error
186
187
dialers := protocolstate.GetDialersWithId(options.ExecutionId)
188
if dialers == nil {
189
return nil, fmt.Errorf("dialers not initialized for %s", options.ExecutionId)
190
}
191
192
hash := configuration.Hash()
193
if client, ok := dialers.HTTPClientPool.Get(hash); ok {
194
return client, nil
195
}
196
197
// Multiple Host
198
retryableHttpOptions := retryablehttp.DefaultOptionsSpraying
199
disableKeepAlives := true
200
maxIdleConns := 0
201
maxConnsPerHost := 0
202
maxIdleConnsPerHost := -1
203
// do not split given timeout into chunks for retry
204
// because this won't work on slow hosts
205
retryableHttpOptions.NoAdjustTimeout = true
206
207
if configuration.Threads > 0 || options.ScanStrategy == scanstrategy.HostSpray.String() {
208
// Single host
209
retryableHttpOptions = retryablehttp.DefaultOptionsSingle
210
disableKeepAlives = false
211
maxIdleConnsPerHost = 500
212
maxConnsPerHost = 500
213
}
214
215
retryableHttpOptions.RetryWaitMax = 10 * time.Second
216
retryableHttpOptions.RetryMax = options.Retries
217
redirectFlow := configuration.RedirectFlow
218
maxRedirects := configuration.MaxRedirects
219
220
if forceMaxRedirects > 0 {
221
// by default we enable general redirects following
222
switch {
223
case options.FollowHostRedirects:
224
redirectFlow = FollowSameHostRedirect
225
default:
226
redirectFlow = FollowAllRedirect
227
}
228
maxRedirects = forceMaxRedirects
229
}
230
if options.DisableRedirects {
231
options.FollowRedirects = false
232
options.FollowHostRedirects = false
233
redirectFlow = DontFollowRedirect
234
maxRedirects = 0
235
}
236
237
// override connection's settings if required
238
if configuration.Connection != nil {
239
disableKeepAlives = configuration.Connection.DisableKeepAlive
240
}
241
242
// Set the base TLS configuration definition
243
tlsConfig := &tls.Config{
244
Renegotiation: tls.RenegotiateOnceAsClient,
245
InsecureSkipVerify: true,
246
MinVersion: tls.VersionTLS10,
247
}
248
249
if options.SNI != "" {
250
tlsConfig.ServerName = options.SNI
251
}
252
253
// Add the client certificate authentication to the request if it's configured
254
tlsConfig, err = utils.AddConfiguredClientCertToRequest(tlsConfig, options)
255
if err != nil {
256
return nil, errors.Wrap(err, "could not create client certificate")
257
}
258
259
// responseHeaderTimeout is max timeout for response headers to be read
260
responseHeaderTimeout := options.GetTimeouts().HttpResponseHeaderTimeout
261
if configuration.ResponseHeaderTimeout != 0 {
262
responseHeaderTimeout = configuration.ResponseHeaderTimeout
263
}
264
if configuration.Connection != nil && configuration.Connection.CustomMaxTimeout > 0 {
265
responseHeaderTimeout = configuration.Connection.CustomMaxTimeout
266
}
267
268
transport := &http.Transport{
269
ForceAttemptHTTP2: options.ForceAttemptHTTP2,
270
DialContext: dialers.Fastdialer.Dial,
271
DialTLSContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
272
if options.TlsImpersonate {
273
return dialers.Fastdialer.DialTLSWithConfigImpersonate(ctx, network, addr, tlsConfig, impersonate.Random, nil)
274
}
275
if options.HasClientCertificates() || options.ForceAttemptHTTP2 {
276
return dialers.Fastdialer.DialTLSWithConfig(ctx, network, addr, tlsConfig)
277
}
278
return dialers.Fastdialer.DialTLS(ctx, network, addr)
279
},
280
MaxIdleConns: maxIdleConns,
281
MaxIdleConnsPerHost: maxIdleConnsPerHost,
282
MaxConnsPerHost: maxConnsPerHost,
283
TLSClientConfig: tlsConfig,
284
DisableKeepAlives: disableKeepAlives,
285
ResponseHeaderTimeout: responseHeaderTimeout,
286
}
287
288
if options.AliveHttpProxy != "" {
289
if proxyURL, err := url.Parse(options.AliveHttpProxy); err == nil {
290
transport.Proxy = http.ProxyURL(proxyURL)
291
}
292
} else if options.AliveSocksProxy != "" {
293
socksURL, proxyErr := url.Parse(options.AliveSocksProxy)
294
if proxyErr != nil {
295
return nil, proxyErr
296
}
297
298
dialer, err := proxy.FromURL(socksURL, proxy.Direct)
299
if err != nil {
300
return nil, err
301
}
302
303
dc := dialer.(interface {
304
DialContext(ctx context.Context, network, addr string) (net.Conn, error)
305
})
306
307
transport.DialContext = dc.DialContext
308
transport.DialTLSContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
309
// upgrade proxy connection to tls
310
conn, err := dc.DialContext(ctx, network, addr)
311
if err != nil {
312
return nil, err
313
}
314
if tlsConfig.ServerName == "" {
315
// addr should be in form of host:port already set from canonicalAddr
316
host, _, err := net.SplitHostPort(addr)
317
if err != nil {
318
return nil, err
319
}
320
tlsConfig.ServerName = host
321
}
322
return tls.Client(conn, tlsConfig), nil
323
}
324
}
325
326
var jar *cookiejar.Jar
327
if configuration.Connection != nil && configuration.Connection.HasCookieJar() {
328
jar = configuration.Connection.GetCookieJar()
329
} else if !configuration.DisableCookie {
330
if jar, err = cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List}); err != nil {
331
return nil, errors.Wrap(err, "could not create cookiejar")
332
}
333
}
334
335
httpclient := &http.Client{
336
Transport: transport,
337
CheckRedirect: makeCheckRedirectFunc(redirectFlow, maxRedirects),
338
}
339
if !configuration.NoTimeout {
340
httpclient.Timeout = options.GetTimeouts().HttpTimeout
341
if configuration.Connection != nil && configuration.Connection.CustomMaxTimeout > 0 {
342
httpclient.Timeout = configuration.Connection.CustomMaxTimeout
343
}
344
}
345
client := retryablehttp.NewWithHTTPClient(httpclient, retryableHttpOptions)
346
if jar != nil {
347
client.HTTPClient.Jar = jar
348
}
349
client.CheckRetry = retryablehttp.HostSprayRetryPolicy()
350
351
// Only add to client pool if we don't have a cookie jar in place.
352
if jar == nil {
353
if err := dialers.HTTPClientPool.Set(hash, client); err != nil {
354
return nil, err
355
}
356
}
357
return client, nil
358
}
359
360
type RedirectFlow uint8
361
362
const (
363
DontFollowRedirect RedirectFlow = iota
364
FollowSameHostRedirect
365
FollowAllRedirect
366
)
367
368
const defaultMaxRedirects = 10
369
370
type checkRedirectFunc func(req *http.Request, via []*http.Request) error
371
372
func makeCheckRedirectFunc(redirectType RedirectFlow, maxRedirects int) checkRedirectFunc {
373
return func(req *http.Request, via []*http.Request) error {
374
switch redirectType {
375
case DontFollowRedirect:
376
return http.ErrUseLastResponse
377
case FollowSameHostRedirect:
378
var newHost = req.URL.Host
379
var oldHost = via[0].Host
380
if oldHost == "" {
381
oldHost = via[0].URL.Host
382
}
383
if newHost != oldHost {
384
// Tell the http client to not follow redirect
385
return http.ErrUseLastResponse
386
}
387
return checkMaxRedirects(req, via, maxRedirects)
388
case FollowAllRedirect:
389
return checkMaxRedirects(req, via, maxRedirects)
390
}
391
return nil
392
}
393
}
394
395
func checkMaxRedirects(req *http.Request, via []*http.Request, maxRedirects int) error {
396
if maxRedirects == 0 {
397
if len(via) > defaultMaxRedirects {
398
return http.ErrUseLastResponse
399
}
400
return nil
401
}
402
403
if len(via) > maxRedirects {
404
return http.ErrUseLastResponse
405
}
406
407
// NOTE(dwisiswant0): rebuild request URL. See #5900.
408
if u := req.URL.String(); !isURLEncoded(u) {
409
parsed, err := urlutil.Parse(u)
410
if err != nil {
411
return fmt.Errorf("%w: %w", ErrRebuildURL, err)
412
}
413
414
req.URL = parsed.URL
415
}
416
417
return nil
418
}
419
420
// isURLEncoded is an helper function to check if the URL is already encoded
421
//
422
// NOTE(dwisiswant0): shall we move this under `projectdiscovery/utils/urlutil`?
423
func isURLEncoded(s string) bool {
424
decoded, err := url.QueryUnescape(s)
425
if err != nil {
426
// If decoding fails, it may indicate a malformed URL/invalid encoding.
427
return false
428
}
429
430
return decoded != s
431
}
432
433