nuclei/v2/pkg/protocols/http/request.go

435 lines
14 KiB
Go
Raw Normal View History

package http
import (
2021-02-07 20:25:53 +00:00
"bytes"
2021-03-08 13:31:40 +00:00
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httputil"
"net/url"
"strings"
"sync"
"time"
"github.com/pkg/errors"
"github.com/projectdiscovery/gologger"
"github.com/projectdiscovery/nuclei/v2/pkg/output"
"github.com/projectdiscovery/nuclei/v2/pkg/protocols"
"github.com/projectdiscovery/nuclei/v2/pkg/protocols/common/generators"
2021-04-18 10:40:10 +00:00
"github.com/projectdiscovery/nuclei/v2/pkg/protocols/common/interactsh"
2021-01-01 09:58:28 +00:00
"github.com/projectdiscovery/nuclei/v2/pkg/protocols/common/tostring"
"github.com/projectdiscovery/nuclei/v2/pkg/protocols/http/httpclientpool"
"github.com/projectdiscovery/rawhttp"
"github.com/remeh/sizedwaitgroup"
"go.uber.org/multierr"
)
const defaultMaxWorkers = 150
// executeRaceRequest executes race condition request for a URL
2021-02-26 07:43:11 +00:00
func (r *Request) executeRaceRequest(reqURL string, previous output.InternalEvent, callback protocols.OutputEventCallback) error {
var requests []*generatedRequest
// Requests within race condition should be dumped once and the output prefilled to allow DSL language to work
// This will introduce a delay and will populate in hacky way the field "request" of outputEvent
2021-02-04 16:30:09 +00:00
generator := r.newGenerator()
2021-04-16 11:26:41 +00:00
requestForDump, err := generator.Make(reqURL, nil, "")
if err != nil {
return err
}
r.setCustomHeaders(requestForDump)
dumpedRequest, err := dump(requestForDump, reqURL)
if err != nil {
return err
}
if r.options.Options.Debug || r.options.Options.DebugRequests {
gologger.Info().Msgf("[%s] Dumped HTTP request for %s\n\n", r.options.TemplateID, reqURL)
gologger.Print().Msgf("%s", string(dumpedRequest))
}
previous["request"] = string(dumpedRequest)
// Pre-Generate requests
for i := 0; i < r.RaceNumberRequests; i++ {
generator := r.newGenerator()
2021-04-16 11:26:41 +00:00
request, err := generator.Make(reqURL, nil, "")
if err != nil {
return err
}
requests = append(requests, request)
}
wg := sync.WaitGroup{}
var requestErr error
2020-12-30 11:19:45 +00:00
mutex := &sync.Mutex{}
2021-02-04 16:30:09 +00:00
for i := 0; i < r.RaceNumberRequests; i++ {
wg.Add(1)
go func(httpRequest *generatedRequest) {
defer wg.Done()
err := r.executeRequest(reqURL, httpRequest, previous, callback, 0)
mutex.Lock()
if err != nil {
requestErr = multierr.Append(requestErr, err)
}
mutex.Unlock()
}(requests[i])
r.options.Progress.IncrementRequests()
}
wg.Wait()
return requestErr
}
2021-02-04 16:30:09 +00:00
// executeRaceRequest executes parallel requests for a template
func (r *Request) executeParallelHTTP(reqURL string, dynamicValues, previous output.InternalEvent, callback protocols.OutputEventCallback) error {
generator := r.newGenerator()
// Workers that keeps enqueuing new requests
2021-02-04 16:30:09 +00:00
maxWorkers := r.Threads
swg := sizedwaitgroup.New(maxWorkers)
var requestErr error
2020-12-30 11:19:45 +00:00
mutex := &sync.Mutex{}
for {
2021-04-16 11:26:41 +00:00
request, err := generator.Make(reqURL, dynamicValues, "")
if err == io.EOF {
break
}
if err != nil {
r.options.Progress.IncrementFailedRequestsBy(int64(generator.Total()))
return err
}
swg.Add()
go func(httpRequest *generatedRequest) {
defer swg.Done()
2021-02-04 16:30:09 +00:00
r.options.RateLimiter.Take()
err := r.executeRequest(reqURL, httpRequest, previous, callback, 0)
mutex.Lock()
if err != nil {
requestErr = multierr.Append(requestErr, err)
}
mutex.Unlock()
}(request)
2021-02-04 16:30:09 +00:00
r.options.Progress.IncrementRequests()
}
swg.Wait()
return requestErr
}
2021-02-04 16:30:09 +00:00
// executeRaceRequest executes turbo http request for a URL
func (r *Request) executeTurboHTTP(reqURL string, dynamicValues, previous output.InternalEvent, callback protocols.OutputEventCallback) error {
generator := r.newGenerator()
// need to extract the target from the url
URL, err := url.Parse(reqURL)
if err != nil {
return err
}
pipeOptions := rawhttp.DefaultPipelineOptions
pipeOptions.Host = URL.Host
pipeOptions.MaxConnections = 1
2021-02-04 16:30:09 +00:00
if r.PipelineConcurrentConnections > 0 {
pipeOptions.MaxConnections = r.PipelineConcurrentConnections
}
2021-02-04 16:30:09 +00:00
if r.PipelineRequestsPerConnection > 0 {
pipeOptions.MaxPendingRequests = r.PipelineRequestsPerConnection
}
pipeclient := rawhttp.NewPipelineClient(pipeOptions)
// defaultMaxWorkers should be a sufficient value to keep queues always full
maxWorkers := defaultMaxWorkers
// in case the queue is bigger increase the workers
if pipeOptions.MaxPendingRequests > maxWorkers {
maxWorkers = pipeOptions.MaxPendingRequests
}
swg := sizedwaitgroup.New(maxWorkers)
var requestErr error
2020-12-30 11:19:45 +00:00
mutex := &sync.Mutex{}
for {
2021-04-16 11:26:41 +00:00
request, err := generator.Make(reqURL, dynamicValues, "")
if err == io.EOF {
break
}
if err != nil {
r.options.Progress.IncrementFailedRequestsBy(int64(generator.Total()))
return err
}
request.pipelinedClient = pipeclient
swg.Add()
go func(httpRequest *generatedRequest) {
defer swg.Done()
err := r.executeRequest(reqURL, httpRequest, previous, callback, 0)
mutex.Lock()
if err != nil {
requestErr = multierr.Append(requestErr, err)
}
mutex.Unlock()
}(request)
2021-02-04 16:30:09 +00:00
r.options.Progress.IncrementRequests()
}
swg.Wait()
return requestErr
}
2020-12-29 06:12:46 +00:00
// ExecuteWithResults executes the final request on a URL
2021-01-16 08:40:24 +00:00
func (r *Request) ExecuteWithResults(reqURL string, dynamicValues, previous output.InternalEvent, callback protocols.OutputEventCallback) error {
// verify if pipeline was requested
if r.Pipeline {
2021-01-16 08:40:24 +00:00
return r.executeTurboHTTP(reqURL, dynamicValues, previous, callback)
}
// verify if a basic race condition was requested
if r.Race && r.RaceNumberRequests > 0 {
2021-02-26 07:43:11 +00:00
return r.executeRaceRequest(reqURL, previous, callback)
}
// verify if parallel elaboration was requested
if r.Threads > 0 {
2021-01-16 08:40:24 +00:00
return r.executeParallelHTTP(reqURL, dynamicValues, previous, callback)
}
generator := r.newGenerator()
2021-03-08 13:31:40 +00:00
requestCount := 1
var requestErr error
for {
2021-04-16 11:26:41 +00:00
var interactURL string
if r.options.Interactsh != nil {
interactURL = r.options.Interactsh.URL()
}
request, err := generator.Make(reqURL, dynamicValues, interactURL)
if err == io.EOF {
break
}
if err != nil {
r.options.Progress.IncrementFailedRequestsBy(int64(generator.Total()))
return err
}
var gotOutput bool
r.options.RateLimiter.Take()
2021-02-26 07:43:11 +00:00
err = r.executeRequest(reqURL, request, previous, func(event *output.InternalWrappedEvent) {
// Add the extracts to the dynamic values if any.
if event.OperatorsResult != nil {
gotOutput = true
dynamicValues = generators.MergeMaps(dynamicValues, event.OperatorsResult.DynamicValues)
}
2021-04-18 10:40:10 +00:00
if interactsh.HasMatchers(r.CompiledOperators) {
if r.options.Interactsh != nil {
r.options.Interactsh.RequestEvent(interactURL, &interactsh.RequestData{
MakeResultFunc: r.MakeResultEvent,
Event: event,
Operators: r.CompiledOperators,
MatchFunc: r.Match,
ExtractFunc: r.Extract,
})
}
2021-04-16 11:26:41 +00:00
}
callback(event)
}, requestCount)
if err != nil {
requestErr = multierr.Append(requestErr, err)
}
2021-03-08 13:31:40 +00:00
requestCount++
r.options.Progress.IncrementRequests()
if request.original.options.Options.StopAtFirstMatch && gotOutput {
r.options.Progress.IncrementErrorsBy(int64(generator.Total()))
break
}
}
return requestErr
}
2021-02-04 16:39:32 +00:00
const drainReqSize = int64(8 * 1024)
2021-02-26 07:43:11 +00:00
// executeRequest executes the actual generated request and returns error if occurred
func (r *Request) executeRequest(reqURL string, request *generatedRequest, previous output.InternalEvent, callback protocols.OutputEventCallback, requestCount int) error {
r.setCustomHeaders(request)
var (
resp *http.Response
fromcache bool
dumpedRequest []byte
err error
)
2021-02-07 20:13:51 +00:00
// For race conditions we can't dump the request body at this point as it's already waiting the open-gate event, already handled with a similar code within the race function
if !request.original.Race {
dumpedRequest, err = dump(request, reqURL)
if err != nil {
return err
}
if r.options.Options.Debug || r.options.Options.DebugRequests {
gologger.Info().Msgf("[%s] Dumped HTTP request for %s\n\n", r.options.TemplateID, reqURL)
gologger.Print().Msgf("%s", string(dumpedRequest))
}
}
2021-01-11 14:29:12 +00:00
var formedURL string
var hostname string
timeStart := time.Now()
if request.original.Pipeline {
2021-01-11 14:29:12 +00:00
formedURL = request.rawRequest.FullURL
2021-02-26 07:43:11 +00:00
if parsed, parseErr := url.Parse(formedURL); parseErr == nil {
hostname = parsed.Host
}
resp, err = request.pipelinedClient.DoRaw(request.rawRequest.Method, reqURL, request.rawRequest.Path, generators.ExpandMapValues(request.rawRequest.Headers), ioutil.NopCloser(strings.NewReader(request.rawRequest.Data)))
} else if request.original.Unsafe && request.rawRequest != nil {
2021-01-11 14:29:12 +00:00
formedURL = request.rawRequest.FullURL
2021-02-26 07:43:11 +00:00
if parsed, parseErr := url.Parse(formedURL); parseErr == nil {
hostname = parsed.Host
}
options := request.original.rawhttpClient.Options
options.FollowRedirects = r.Redirects
2021-02-26 07:43:11 +00:00
options.CustomRawBytes = request.rawRequest.UnsafeRawBytes
resp, err = request.original.rawhttpClient.DoRawWithOptions(request.rawRequest.Method, reqURL, request.rawRequest.Path, generators.ExpandMapValues(request.rawRequest.Headers), ioutil.NopCloser(strings.NewReader(request.rawRequest.Data)), options)
} else {
2021-02-26 07:43:11 +00:00
hostname = request.request.URL.Host
2021-01-11 14:29:12 +00:00
formedURL = request.request.URL.String()
// if nuclei-project is available check if the request was already sent previously
if r.options.ProjectFile != nil {
// if unavailable fail silently
fromcache = true
resp, err = r.options.ProjectFile.Get(dumpedRequest)
if err != nil {
fromcache = false
}
}
if resp == nil {
resp, err = r.httpClient.Do(request.request)
}
}
if resp == nil {
err = errors.New("no response got for request")
}
if err != nil {
2021-01-11 20:35:41 +00:00
// rawhttp doesn't supports draining response bodies.
if resp != nil && resp.Body != nil && request.rawRequest == nil {
_, _ = io.CopyN(ioutil.Discard, resp.Body, drainReqSize)
resp.Body.Close()
}
2021-03-08 13:31:40 +00:00
r.options.Output.Request(r.options.TemplateID, formedURL, "http", err)
r.options.Progress.IncrementErrorsBy(1)
return err
}
2021-02-26 07:43:11 +00:00
defer func() {
_, _ = io.CopyN(ioutil.Discard, resp.Body, drainReqSize)
resp.Body.Close()
}()
2021-02-05 07:06:01 +00:00
2021-01-11 14:29:12 +00:00
gologger.Verbose().Msgf("[%s] Sent HTTP request to %s", r.options.TemplateID, formedURL)
2021-03-08 13:31:40 +00:00
r.options.Output.Request(r.options.TemplateID, formedURL, "http", err)
duration := time.Since(timeStart)
2021-02-05 07:06:01 +00:00
2021-02-07 20:25:53 +00:00
dumpedResponseHeaders, err := httputil.DumpResponse(resp, false)
2021-02-05 07:06:01 +00:00
if err != nil {
return errors.Wrap(err, "could not dump http response")
}
2021-02-04 16:39:32 +00:00
var bodyReader io.Reader
if r.MaxSize != 0 {
bodyReader = io.LimitReader(resp.Body, int64(r.MaxSize))
} else {
bodyReader = resp.Body
}
data, err := ioutil.ReadAll(bodyReader)
if err != nil {
return errors.Wrap(err, "could not read http body")
}
resp.Body.Close()
redirectedResponse, err := dumpResponseWithRedirectChain(resp, data)
if err != nil {
return errors.Wrap(err, "could not read http response with redirect chain")
}
// 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.
2021-02-07 20:25:53 +00:00
dataOrig := data
2021-02-08 10:43:55 +00:00
data, _ = handleDecompression(resp, data)
// Dump response - step 2 - replace gzip body with deflated one or with itself (NOP operation)
2021-02-07 20:25:53 +00:00
dumpedResponseBuilder := &bytes.Buffer{}
dumpedResponseBuilder.Write(dumpedResponseHeaders)
dumpedResponseBuilder.Write(data)
dumpedResponse := dumpedResponseBuilder.Bytes()
redirectedResponse = bytes.ReplaceAll(redirectedResponse, dataOrig, data)
2021-02-07 20:25:53 +00:00
// Dump response - step 2 - replace gzip body with deflated one or with itself (NOP operation)
if r.options.Options.Debug || r.options.Options.DebugResponse {
2021-01-11 14:29:12 +00:00
gologger.Info().Msgf("[%s] Dumped HTTP response for %s\n\n", r.options.TemplateID, formedURL)
gologger.Print().Msgf("%s", string(redirectedResponse))
}
// if nuclei-project is enabled store the response if not previously done
if r.options.ProjectFile != nil && !fromcache {
err := r.options.ProjectFile.Set(dumpedRequest, resp, data)
if err != nil {
return errors.Wrap(err, "could not store in project file")
}
}
2021-02-25 07:07:47 +00:00
matchedURL := reqURL
if request.rawRequest != nil && request.rawRequest.FullURL != "" {
2020-12-29 06:12:46 +00:00
matchedURL = request.rawRequest.FullURL
}
if request.request != nil {
matchedURL = request.request.URL.String()
}
finalEvent := make(output.InternalEvent)
outputEvent := r.responseToDSLMap(resp, reqURL, matchedURL, tostring.UnsafeToString(dumpedRequest), tostring.UnsafeToString(dumpedResponse), tostring.UnsafeToString(data), headersToString(resp.Header), duration, request.meta)
outputEvent["ip"] = httpclientpool.Dialer.GetDialedIP(hostname)
outputEvent["redirect-chain"] = tostring.UnsafeToString(redirectedResponse)
2021-01-16 08:40:24 +00:00
for k, v := range previous {
finalEvent[k] = v
}
for k, v := range outputEvent {
finalEvent[k] = v
}
// Add to history the current request number metadata if asked by the user.
if r.ReqCondition {
for k, v := range outputEvent {
key := fmt.Sprintf("%s_%d", k, requestCount)
previous[key] = v
finalEvent[key] = v
}
2021-01-16 08:40:24 +00:00
}
event := &output.InternalWrappedEvent{InternalEvent: outputEvent}
2021-04-18 10:40:10 +00:00
if !interactsh.HasMatchers(r.CompiledOperators) {
if r.CompiledOperators != nil {
var ok bool
event.OperatorsResult, ok = r.CompiledOperators.Execute(finalEvent, r.Match, r.Extract)
if ok && event.OperatorsResult != nil {
event.OperatorsResult.PayloadValues = request.meta
event.Results = r.MakeResultEvent(event)
}
event.InternalEvent = outputEvent
}
}
callback(event)
return nil
}
// setCustomHeaders sets the custom headers for generated request
2021-02-04 16:30:09 +00:00
func (r *Request) setCustomHeaders(req *generatedRequest) {
for k, v := range r.customHeaders {
if req.rawRequest != nil {
req.rawRequest.Headers[k] = v
} else {
2021-02-04 16:30:09 +00:00
req.request.Header.Set(strings.TrimSpace(k), strings.TrimSpace(v))
}
}
}