mirror of
https://github.com/OJ/gobuster.git
synced 2026-12-01 07:54:51 +01:00
341 lines
9.4 KiB
Go
341 lines
9.4 KiB
Go
package libgobuster
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/tls"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
"net/http/httputil"
|
|
"net/url"
|
|
"strings"
|
|
)
|
|
|
|
const defaultMaxResponseBodySize int64 = 10 * 1024 * 1024
|
|
|
|
// HTTPHeader holds a single key value pair of a HTTP header
|
|
type HTTPHeader struct {
|
|
Name string
|
|
Value string
|
|
}
|
|
|
|
// HTTPClient represents a http object
|
|
type HTTPClient struct {
|
|
client *http.Client
|
|
userAgent string
|
|
defaultUserAgent string
|
|
username string
|
|
password string
|
|
headers []HTTPHeader
|
|
noCanonicalizeHeaders bool
|
|
cookies string
|
|
method string
|
|
host string
|
|
logger *Logger
|
|
maxResponseBodySize int64
|
|
rateLimit *rateLimitGate
|
|
}
|
|
|
|
// RequestOptions is used to pass options to a single individual request
|
|
type RequestOptions struct {
|
|
Host string
|
|
Body io.Reader
|
|
ReturnBody bool
|
|
ModifiedHeaders []HTTPHeader
|
|
UpdatedBasicAuthUsername string
|
|
UpdatedBasicAuthPassword string
|
|
// Progress is used to report rate limit pauses to the user. If nil the
|
|
// messages are written to the logger instead.
|
|
Progress *Progress
|
|
}
|
|
|
|
// NewHTTPClient returns a new HTTPClient
|
|
func NewHTTPClient(opt *HTTPOptions, logger *Logger) (*HTTPClient, error) {
|
|
var proxyURLFunc func(*http.Request) (*url.URL, error)
|
|
var client HTTPClient
|
|
proxyURLFunc = http.ProxyFromEnvironment
|
|
|
|
if opt == nil {
|
|
return nil, errors.New("options is nil")
|
|
}
|
|
|
|
if opt.Proxy != "" {
|
|
proxyURL, err := url.Parse(opt.Proxy)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("proxy URL is invalid (%w)", err)
|
|
}
|
|
proxyURLFunc = http.ProxyURL(proxyURL)
|
|
}
|
|
|
|
var redirectFunc func(req *http.Request, via []*http.Request) error
|
|
if !opt.FollowRedirect {
|
|
redirectFunc = func(_ *http.Request, _ []*http.Request) error {
|
|
return http.ErrUseLastResponse
|
|
}
|
|
} else {
|
|
redirectFunc = nil
|
|
}
|
|
|
|
tlsConfig := tls.Config{
|
|
InsecureSkipVerify: opt.NoTLSValidation, // nolint:gosec
|
|
// enable TLS1.0 and TLS1.1 support
|
|
MinVersion: tls.VersionTLS10,
|
|
}
|
|
if opt.TLSCertificate != nil {
|
|
tlsConfig.Certificates = []tls.Certificate{*opt.TLSCertificate}
|
|
}
|
|
if opt.TLSRenegotiation {
|
|
tlsConfig.Renegotiation = tls.RenegotiateOnceAsClient
|
|
}
|
|
|
|
transport := &http.Transport{
|
|
Proxy: proxyURLFunc,
|
|
MaxIdleConns: 100,
|
|
MaxIdleConnsPerHost: 100,
|
|
TLSClientConfig: &tlsConfig,
|
|
}
|
|
|
|
// set specific network interface
|
|
if opt.LocalAddr != nil {
|
|
logger.Debugf("Setting local address to %s", opt.LocalAddr.String())
|
|
dialer := &net.Dialer{
|
|
Timeout: opt.Timeout,
|
|
LocalAddr: opt.LocalAddr,
|
|
}
|
|
transport.DialContext = dialer.DialContext
|
|
}
|
|
|
|
client.client = &http.Client{
|
|
Timeout: opt.Timeout,
|
|
CheckRedirect: redirectFunc,
|
|
Transport: transport,
|
|
}
|
|
|
|
client.username = opt.Username
|
|
client.password = opt.Password
|
|
client.userAgent = opt.UserAgent
|
|
client.defaultUserAgent = DefaultUserAgent()
|
|
client.headers = opt.Headers
|
|
client.noCanonicalizeHeaders = opt.NoCanonicalizeHeaders
|
|
client.cookies = opt.Cookies
|
|
client.method = opt.Method
|
|
if client.method == "" {
|
|
client.method = http.MethodGet
|
|
}
|
|
// Host header needs to be set separately
|
|
for _, h := range opt.Headers {
|
|
if http.CanonicalHeaderKey(h.Name) == "Host" {
|
|
client.host = h.Value
|
|
break
|
|
}
|
|
}
|
|
client.logger = logger
|
|
client.maxResponseBodySize = defaultMaxResponseBodySize
|
|
if opt.RateLimitSleep > 0 {
|
|
client.rateLimit = newRateLimitGate(opt.RateLimitSleep)
|
|
}
|
|
return &client, nil
|
|
}
|
|
|
|
// Request makes a http request and returns the status, the content length, the headers, the body and an error
|
|
// if you want the body returned set the corresponding property inside RequestOptions.
|
|
// If a rate limit sleep is configured, 429 responses pause all requests made with this client
|
|
// and the request is retried once the rate limit is gone.
|
|
func (client *HTTPClient) Request(ctx context.Context, fullURL url.URL, opts RequestOptions) (int, int64, http.Header, []byte, error) {
|
|
if client.rateLimit == nil {
|
|
return client.request(ctx, fullURL, opts)
|
|
}
|
|
return client.requestWithRateLimit(ctx, fullURL, opts)
|
|
}
|
|
|
|
func (client *HTTPClient) requestWithRateLimit(ctx context.Context, fullURL url.URL, opts RequestOptions) (int, int64, http.Header, []byte, error) {
|
|
gate := client.rateLimit
|
|
|
|
// the body needs to be sent again on every retry so buffer it
|
|
var reqBody []byte
|
|
if opts.Body != nil {
|
|
var err error
|
|
reqBody, err = io.ReadAll(opts.Body)
|
|
if err != nil {
|
|
return 0, 0, nil, nil, fmt.Errorf("could not read request body: %w", err)
|
|
}
|
|
}
|
|
|
|
leader := false
|
|
defer func() {
|
|
if leader {
|
|
gate.resume()
|
|
}
|
|
}()
|
|
|
|
var gen uint64
|
|
for attempt := 1; ; attempt++ {
|
|
if !leader {
|
|
var err error
|
|
gen, err = gate.wait(ctx)
|
|
if err != nil {
|
|
// context canceled while waiting
|
|
return 0, 0, nil, nil, nil
|
|
}
|
|
}
|
|
|
|
if opts.Body != nil {
|
|
opts.Body = bytes.NewReader(reqBody)
|
|
}
|
|
|
|
statusCode, length, header, body, err := client.request(ctx, fullURL, opts)
|
|
if err != nil || statusCode != http.StatusTooManyRequests {
|
|
if leader && err == nil {
|
|
client.rateLimitMessage(opts.Progress, LevelInfo, fmt.Sprintf("rate limit is gone (status %d on %s), resuming requests", statusCode, fullURL.String()))
|
|
}
|
|
// the deferred resume releases all other workers if we are the leader
|
|
return statusCode, length, header, body, err
|
|
}
|
|
|
|
if !leader {
|
|
leader = gate.tryPause(gen)
|
|
if !leader {
|
|
// another worker is handling the pause (or already did), wait and retry
|
|
continue
|
|
}
|
|
}
|
|
|
|
client.rateLimitMessage(opts.Progress, LevelWarn, fmt.Sprintf("received status %d on %s (attempt %d), pausing all requests for %s", statusCode, fullURL.String(), attempt, gate.sleep))
|
|
if err := gate.sleepFor(ctx); err != nil {
|
|
return 0, 0, nil, nil, nil
|
|
}
|
|
}
|
|
}
|
|
|
|
func (client *HTTPClient) rateLimitMessage(progress *Progress, level MessageLevel, msg string) {
|
|
if progress != nil {
|
|
progress.MessageChan <- Message{Level: level, Message: msg}
|
|
return
|
|
}
|
|
if level == LevelWarn {
|
|
client.logger.Warn(msg)
|
|
} else {
|
|
client.logger.Info(msg)
|
|
}
|
|
}
|
|
|
|
func (client *HTTPClient) request(ctx context.Context, fullURL url.URL, opts RequestOptions) (int, int64, http.Header, []byte, error) {
|
|
resp, err := client.makeRequest(ctx, fullURL, opts)
|
|
if err != nil {
|
|
// ignore context canceled errors
|
|
if errors.Is(ctx.Err(), context.Canceled) {
|
|
return 0, 0, nil, nil, nil
|
|
}
|
|
return 0, 0, nil, nil, err
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
var body []byte
|
|
var length int64
|
|
if opts.ReturnBody {
|
|
body, err = io.ReadAll(io.LimitReader(resp.Body, client.maxResponseBodySize+1))
|
|
if err != nil {
|
|
return 0, 0, nil, nil, fmt.Errorf("could not read body %w", err)
|
|
}
|
|
if int64(len(body)) > client.maxResponseBodySize {
|
|
return 0, 0, nil, nil, fmt.Errorf("response body exceeds maximum size of %d bytes", client.maxResponseBodySize)
|
|
}
|
|
length = int64(len(body))
|
|
} else {
|
|
// DO NOT REMOVE!
|
|
// absolutely needed so golang will reuse connections!
|
|
length, err = io.Copy(io.Discard, resp.Body)
|
|
if err != nil {
|
|
return 0, 0, nil, nil, err
|
|
}
|
|
}
|
|
|
|
return resp.StatusCode, length, resp.Header, body, nil
|
|
}
|
|
|
|
func (client *HTTPClient) makeRequest(ctx context.Context, fullURL url.URL, opts RequestOptions) (*http.Response, error) {
|
|
req, err := http.NewRequestWithContext(ctx, client.method, fullURL.String(), opts.Body)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if client.cookies != "" {
|
|
req.Header.Set("Cookie", client.cookies)
|
|
}
|
|
|
|
// Use host for VHOST mode on a per-request basis, otherwise the one provided from headers
|
|
if opts.Host != "" {
|
|
req.Host = opts.Host
|
|
} else if client.host != "" {
|
|
req.Host = client.host
|
|
}
|
|
|
|
if client.userAgent != "" {
|
|
req.Header.Set("User-Agent", client.userAgent)
|
|
} else {
|
|
req.Header.Set("User-Agent", client.defaultUserAgent)
|
|
}
|
|
|
|
// add custom headers
|
|
// if ModifiedHeaders are supplied use those, otherwise use the original ones
|
|
// currently only relevant on fuzzing
|
|
if len(opts.ModifiedHeaders) > 0 {
|
|
for _, h := range opts.ModifiedHeaders {
|
|
// empty headers are not valid (happens when fuzzing the host header for example because the slice is initialized with the provided header length)
|
|
if h.Name == "" {
|
|
continue
|
|
}
|
|
|
|
if client.noCanonicalizeHeaders {
|
|
// https://stackoverflow.com/questions/26351716/how-to-keep-key-case-sensitive-in-request-header-using-golang
|
|
req.Header[h.Name] = []string{h.Value}
|
|
} else {
|
|
req.Header.Set(h.Name, h.Value)
|
|
}
|
|
}
|
|
} else {
|
|
for _, h := range client.headers {
|
|
// the Host header is already set via req.Host
|
|
if http.CanonicalHeaderKey(h.Name) == "Host" {
|
|
continue
|
|
}
|
|
|
|
if client.noCanonicalizeHeaders {
|
|
// https://stackoverflow.com/questions/26351716/how-to-keep-key-case-sensitive-in-request-header-using-golang
|
|
req.Header[h.Name] = []string{h.Value}
|
|
} else {
|
|
req.Header.Set(h.Name, h.Value)
|
|
}
|
|
}
|
|
}
|
|
|
|
if opts.UpdatedBasicAuthUsername != "" {
|
|
req.SetBasicAuth(opts.UpdatedBasicAuthUsername, opts.UpdatedBasicAuthPassword)
|
|
} else if client.username != "" {
|
|
req.SetBasicAuth(client.username, client.password)
|
|
}
|
|
|
|
if client.logger.debug {
|
|
dump, err := httputil.DumpRequestOut(req, false)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
client.logger.Debugf("%s", dump)
|
|
}
|
|
|
|
resp, err := client.client.Do(req) // nolint:gosec
|
|
if err != nil {
|
|
if ue, ok := errors.AsType[*url.Error](err); ok {
|
|
if strings.HasPrefix(ue.Err.Error(), "x509") {
|
|
return nil, fmt.Errorf("invalid certificate: %w", ue.Err)
|
|
}
|
|
}
|
|
return nil, err
|
|
}
|
|
|
|
return resp, nil
|
|
}
|