nuclei/pkg/executer/executer_http.go

386 lines
10 KiB
Go
Raw Normal View History

2020-07-16 10:57:28 +02:00
package executer
2020-04-26 05:50:33 +05:30
import (
"context"
2020-04-26 05:50:33 +05:30
"crypto/tls"
2020-04-28 22:15:26 +02:00
"fmt"
2020-04-26 05:50:33 +05:30
"io"
"io/ioutil"
"net"
2020-04-26 05:50:33 +05:30
"net/http"
2020-07-16 16:15:24 +02:00
"net/http/cookiejar"
2020-06-22 19:30:01 +05:30
"net/http/httputil"
2020-04-27 23:49:53 +05:30
"net/url"
2020-06-22 19:30:01 +05:30
"os"
"regexp"
2020-05-22 00:23:38 +02:00
"strings"
2020-04-26 05:50:33 +05:30
"time"
"github.com/logrusorgru/aurora"
"github.com/pkg/errors"
2020-06-22 19:30:01 +05:30
"github.com/projectdiscovery/gologger"
2020-09-10 16:32:01 +05:30
"github.com/projectdiscovery/nuclei/v2/internal/bufwriter"
2020-07-23 20:19:19 +02:00
"github.com/projectdiscovery/nuclei/v2/internal/progress"
2020-07-01 16:17:24 +05:30
"github.com/projectdiscovery/nuclei/v2/pkg/matchers"
"github.com/projectdiscovery/nuclei/v2/pkg/requests"
"github.com/projectdiscovery/nuclei/v2/pkg/templates"
2020-04-26 05:50:33 +05:30
"github.com/projectdiscovery/retryablehttp-go"
2020-04-28 04:01:25 +02:00
"golang.org/x/net/proxy"
2020-04-26 05:50:33 +05:30
)
const (
two = 2
ten = 10
)
2020-07-16 10:57:28 +02:00
// HTTPExecuter is client for performing HTTP requests
2020-04-26 05:50:33 +05:30
// for a template.
2020-07-16 10:57:28 +02:00
type HTTPExecuter struct {
coloredOutput bool
2020-07-18 21:42:23 +02:00
debug bool
Results bool
jsonOutput bool
jsonRequest bool
2020-07-18 21:42:23 +02:00
httpClient *retryablehttp.Client
template *templates.Template
bulkHTTPRequest *requests.BulkHTTPRequest
2020-09-10 16:32:01 +05:30
writer *bufwriter.Writer
2020-07-18 21:42:23 +02:00
customHeaders requests.CustomHeaders
CookieJar *cookiejar.Jar
colorizer aurora.Aurora
decolorizer *regexp.Regexp
}
2020-07-16 10:57:28 +02:00
// HTTPOptions contains configuration options for the HTTP executer.
type HTTPOptions struct {
Debug bool
JSON bool
JSONRequests bool
CookieReuse bool
ColoredOutput bool
2020-07-18 21:42:23 +02:00
Template *templates.Template
BulkHTTPRequest *requests.BulkHTTPRequest
2020-09-10 16:32:01 +05:30
Writer *bufwriter.Writer
2020-07-18 21:42:23 +02:00
Timeout int
Retries int
ProxyURL string
ProxySocksURL string
CustomHeaders requests.CustomHeaders
CookieJar *cookiejar.Jar
Colorizer aurora.Aurora
Decolorizer *regexp.Regexp
2020-04-26 05:50:33 +05:30
}
2020-07-16 10:57:28 +02:00
// NewHTTPExecuter creates a new HTTP executer from a template
2020-04-26 05:50:33 +05:30
// and a HTTP request query.
2020-07-16 10:57:28 +02:00
func NewHTTPExecuter(options *HTTPOptions) (*HTTPExecuter, error) {
2020-04-28 00:29:57 +05:30
var proxyURL *url.URL
2020-04-28 00:29:57 +05:30
var err error
2020-04-26 05:50:33 +05:30
2020-04-28 00:29:57 +05:30
if options.ProxyURL != "" {
proxyURL, err = url.Parse(options.ProxyURL)
}
2020-04-27 23:49:53 +05:30
if err != nil {
return nil, err
}
2020-04-26 05:50:33 +05:30
// Create the HTTP Client
2020-04-28 00:29:57 +05:30
client := makeHTTPClient(proxyURL, options)
// nolint:bodyclose // false positive there is no body to close yet
2020-04-26 05:50:33 +05:30
client.CheckRetry = retryablehttp.HostSprayRetryPolicy()
2020-07-16 16:15:24 +02:00
if options.CookieJar != nil {
client.HTTPClient.Jar = options.CookieJar
} else if options.CookieReuse {
jar, err := cookiejar.New(nil)
if err != nil {
return nil, err
}
client.HTTPClient.Jar = jar
}
2020-04-26 05:50:33 +05:30
2020-07-16 10:57:28 +02:00
executer := &HTTPExecuter{
2020-07-18 21:42:23 +02:00
debug: options.Debug,
jsonOutput: options.JSON,
2020-07-23 23:28:34 +02:00
jsonRequest: options.JSONRequests,
2020-07-18 21:42:23 +02:00
httpClient: client,
template: options.Template,
bulkHTTPRequest: options.BulkHTTPRequest,
2020-07-18 21:42:23 +02:00
writer: options.Writer,
customHeaders: options.CustomHeaders,
CookieJar: options.CookieJar,
coloredOutput: options.ColoredOutput,
colorizer: options.Colorizer,
decolorizer: options.Decolorizer,
2020-04-26 05:50:33 +05:30
}
2020-07-24 13:37:01 +02:00
2020-04-27 23:49:53 +05:30
return executer, nil
2020-04-26 05:50:33 +05:30
}
// ExecuteHTTP executes the HTTP request on a URL
func (e *HTTPExecuter) ExecuteHTTP(ctx context.Context, p progress.IProgress, reqURL string) (result Result) {
2020-07-10 09:04:38 +02:00
result.Matches = make(map[string]interface{})
result.Extractions = make(map[string]interface{})
2020-07-19 03:14:19 +02:00
dynamicvalues := make(map[string]interface{})
2020-04-26 05:50:33 +05:30
2020-07-25 22:25:21 +02:00
// verify if the URL is already being processed
if e.bulkHTTPRequest.HasGenerator(reqURL) {
2020-07-25 22:25:21 +02:00
return
}
2020-07-26 15:10:03 +02:00
remaining := e.bulkHTTPRequest.GetRequestCount()
e.bulkHTTPRequest.CreateGenerator(reqURL)
2020-07-23 20:19:19 +02:00
for e.bulkHTTPRequest.Next(reqURL) && !result.Done {
httpRequest, err := e.bulkHTTPRequest.MakeHTTPRequest(ctx, reqURL, dynamicvalues, e.bulkHTTPRequest.Current(reqURL))
2020-07-18 21:42:23 +02:00
if err != nil {
2020-07-23 20:19:19 +02:00
result.Error = errors.Wrap(err, "could not build http request")
p.Drop(remaining)
2020-07-10 09:04:38 +02:00
return
}
2020-06-22 19:30:01 +05:30
err = e.handleHTTP(reqURL, httpRequest, dynamicvalues, &result)
2020-07-19 03:14:19 +02:00
if err != nil {
2020-07-23 20:19:19 +02:00
result.Error = errors.Wrap(err, "could not handle http request")
p.Drop(remaining)
2020-07-19 03:14:19 +02:00
return
}
2020-07-18 21:42:23 +02:00
e.bulkHTTPRequest.Increment(reqURL)
p.Update()
2020-07-23 20:19:19 +02:00
remaining--
2020-07-18 21:42:23 +02:00
}
gologger.Verbosef("Sent for [%s] to %s\n", "http-request", e.template.ID, reqURL)
2020-07-18 21:42:23 +02:00
return result
2020-07-18 21:42:23 +02:00
}
func (e *HTTPExecuter) handleHTTP(reqURL string, request *requests.HTTPRequest, dynamicvalues map[string]interface{}, result *Result) error {
2020-07-18 21:42:23 +02:00
e.setCustomHeaders(request)
req := request.Request
if e.debug {
dumpedRequest, err := httputil.DumpRequest(req.Request, true)
2020-04-26 05:50:33 +05:30
if err != nil {
2020-07-18 21:42:23 +02:00
return errors.Wrap(err, "could not make http request")
2020-04-26 05:50:33 +05:30
}
gologger.Infof("Dumped HTTP request for %s (%s)\n\n", reqURL, e.template.ID)
2020-07-18 21:42:23 +02:00
fmt.Fprintf(os.Stderr, "%s", string(dumpedRequest))
}
2020-07-18 21:42:23 +02:00
resp, err := e.httpClient.Do(req)
2020-07-18 21:42:23 +02:00
if err != nil {
if resp != nil {
resp.Body.Close()
2020-06-22 19:30:01 +05:30
}
2020-07-20 21:23:04 +02:00
return errors.Wrap(err, "Could not do request")
2020-07-18 21:42:23 +02:00
}
2020-06-22 19:30:01 +05:30
2020-07-18 21:42:23 +02:00
if e.debug {
dumpedResponse, dumpErr := httputil.DumpResponse(resp, true)
if dumpErr != nil {
return errors.Wrap(dumpErr, "could not dump http response")
2020-04-26 05:50:33 +05:30
}
gologger.Infof("Dumped HTTP response for %s (%s)\n\n", reqURL, e.template.ID)
2020-07-20 21:23:04 +02:00
fmt.Fprintf(os.Stderr, "%s\n", string(dumpedResponse))
2020-07-18 21:42:23 +02:00
}
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
_, copyErr := io.Copy(ioutil.Discard, resp.Body)
if copyErr != nil {
resp.Body.Close()
return copyErr
}
2020-04-26 05:50:33 +05:30
resp.Body.Close()
2020-07-18 21:42:23 +02:00
return errors.Wrap(err, "could not read http body")
}
2020-07-18 21:42:23 +02:00
resp.Body.Close()
2020-04-26 05:50:33 +05:30
2020-07-18 21:42:23 +02:00
// net/http doesn't automatically decompress the response body if an encoding has been specified by the user in the request
// so in case we have to manually do it
data, err = requests.HandleDecompression(req, data)
if err != nil {
return errors.Wrap(err, "could not decompress http body")
}
2020-07-18 21:42:23 +02:00
// Convert response body from []byte to string with zero copy
body := unsafeToString(data)
headers := headersToString(resp.Header)
matcherCondition := e.bulkHTTPRequest.GetMatchersCondition()
for _, matcher := range e.bulkHTTPRequest.Matchers {
2020-07-18 21:42:23 +02:00
// Check if the matcher matched
if !matcher.Match(resp, body, headers) {
// If the condition is AND we haven't matched, try next request.
if matcherCondition == matchers.ANDCondition {
return nil
2020-04-26 05:50:33 +05:30
}
2020-07-18 21:42:23 +02:00
} else {
// If the matcher has matched, and its an OR
// write the first output then move to next matcher.
2020-07-25 21:15:28 +02:00
if matcherCondition == matchers.ORCondition {
2020-07-18 21:42:23 +02:00
result.Matches[matcher.Name] = nil
// probably redundant but ensures we snapshot current payload values when matchers are valid
result.Meta = request.Meta
e.writeOutputHTTP(request, resp, body, matcher, nil)
2020-07-25 20:45:31 +02:00
result.GotResults = true
2020-04-27 23:34:08 +05:30
}
}
2020-07-18 21:42:23 +02:00
}
2020-07-18 21:42:23 +02:00
// All matchers have successfully completed so now start with the
// next task which is extraction of input from matchers.
2020-07-25 21:15:28 +02:00
var extractorResults, outputExtractorResults []string
for _, extractor := range e.bulkHTTPRequest.Extractors {
2020-07-18 21:42:23 +02:00
for match := range extractor.Extract(resp, body, headers) {
if _, ok := dynamicvalues[extractor.Name]; !ok {
dynamicvalues[extractor.Name] = match
}
2020-07-18 21:42:23 +02:00
extractorResults = append(extractorResults, match)
2020-07-25 21:15:28 +02:00
if !extractor.Internal {
outputExtractorResults = append(outputExtractorResults, match)
}
}
2020-07-18 21:42:23 +02:00
// probably redundant but ensures we snapshot current payload values when extractors are valid
result.Meta = request.Meta
result.Extractions[extractor.Name] = extractorResults
2020-04-26 05:50:33 +05:30
}
2020-06-22 19:30:01 +05:30
2020-07-18 21:42:23 +02:00
// Write a final string of output if matcher type is
// AND or if we have extractors for the mechanism too.
2020-07-25 21:44:43 +02:00
if len(outputExtractorResults) > 0 || matcherCondition == matchers.ANDCondition {
2020-07-25 21:15:28 +02:00
e.writeOutputHTTP(request, resp, body, nil, outputExtractorResults)
2020-07-25 20:45:31 +02:00
result.GotResults = true
2020-07-18 21:42:23 +02:00
}
2020-06-22 19:30:01 +05:30
2020-07-18 21:42:23 +02:00
return nil
}
2020-07-16 10:57:28 +02:00
// Close closes the http executer for a template.
2020-09-10 16:32:01 +05:30
func (e *HTTPExecuter) Close() {}
2020-04-28 00:29:57 +05:30
// makeHTTPClient creates a http client
func makeHTTPClient(proxyURL *url.URL, options *HTTPOptions) *retryablehttp.Client {
retryablehttpOptions := retryablehttp.DefaultOptionsSpraying
retryablehttpOptions.RetryWaitMax = 10 * time.Second
retryablehttpOptions.RetryMax = options.Retries
followRedirects := options.BulkHTTPRequest.Redirects
maxRedirects := options.BulkHTTPRequest.MaxRedirects
2020-04-28 00:29:57 +05:30
transport := &http.Transport{
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
2020-04-28 00:29:57 +05:30
MaxIdleConnsPerHost: -1,
TLSClientConfig: &tls.Config{
Renegotiation: tls.RenegotiateOnceAsClient,
InsecureSkipVerify: true,
},
DisableKeepAlives: true,
}
2020-04-28 04:01:25 +02:00
// Attempts to overwrite the dial function with the socks proxied version
if options.ProxySocksURL != "" {
2020-04-28 22:15:26 +02:00
var proxyAuth *proxy.Auth
2020-04-28 22:15:26 +02:00
socksURL, err := url.Parse(options.ProxySocksURL)
2020-04-28 22:15:26 +02:00
if err == nil {
proxyAuth = &proxy.Auth{}
proxyAuth.User = socksURL.User.Username()
proxyAuth.Password, _ = socksURL.User.Password()
}
2020-04-28 22:15:26 +02:00
dialer, err := proxy.SOCKS5("tcp", fmt.Sprintf("%s:%s", socksURL.Hostname(), socksURL.Port()), proxyAuth, proxy.Direct)
dc := dialer.(interface {
DialContext(ctx context.Context, network, addr string) (net.Conn, error)
})
2020-04-28 04:01:25 +02:00
if err == nil {
transport.DialContext = dc.DialContext
2020-04-28 04:01:25 +02:00
}
}
2020-04-28 00:29:57 +05:30
if proxyURL != nil {
transport.Proxy = http.ProxyURL(proxyURL)
}
2020-04-28 00:29:57 +05:30
return retryablehttp.NewWithHTTPClient(&http.Client{
Transport: transport,
Timeout: time.Duration(options.Timeout) * time.Second,
CheckRedirect: makeCheckRedirectFunc(followRedirects, maxRedirects),
}, retryablehttpOptions)
}
type checkRedirectFunc func(_ *http.Request, requests []*http.Request) error
func makeCheckRedirectFunc(followRedirects bool, maxRedirects int) checkRedirectFunc {
return func(_ *http.Request, requests []*http.Request) error {
if !followRedirects {
return http.ErrUseLastResponse
}
2020-04-28 00:29:57 +05:30
if maxRedirects == 0 {
if len(requests) > ten {
2020-04-28 00:29:57 +05:30
return http.ErrUseLastResponse
}
2020-04-28 00:29:57 +05:30
return nil
}
2020-04-28 00:29:57 +05:30
if len(requests) > maxRedirects {
return http.ErrUseLastResponse
}
2020-04-28 00:29:57 +05:30
return nil
}
}
2020-05-22 00:23:38 +02:00
func (e *HTTPExecuter) setCustomHeaders(r *requests.HTTPRequest) {
2020-05-22 00:23:38 +02:00
for _, customHeader := range e.customHeaders {
// This should be pre-computed somewhere and done only once
tokens := strings.SplitN(customHeader, ":", 2)
2020-05-22 00:23:38 +02:00
// if it's an invalid header skip it
if len(tokens) < two {
2020-05-22 00:23:38 +02:00
continue
}
headerName, headerValue := tokens[0], strings.Join(tokens[1:], "")
headerName = strings.TrimSpace(headerName)
headerValue = strings.TrimSpace(headerValue)
2020-07-17 16:04:13 +02:00
r.Request.Header[headerName] = []string{headerValue}
2020-05-22 00:23:38 +02:00
}
}
2020-07-10 09:04:38 +02:00
type Result struct {
GotResults bool
Done bool
Meta map[string]interface{}
2020-07-10 09:04:38 +02:00
Matches map[string]interface{}
Extractions map[string]interface{}
Error error
}