Repository navigation
Expand file tree
/
Copy pathrequest.go
More file actions
2081 lines (1907 loc) · 77.2 KB
/
Copy pathrequest.go
File metadata and controls
2081 lines (1907 loc) · 77.2 KB
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package http
import (
"bytes"
"context"
"encoding/hex"
stderrors "errors"
"fmt"
"io"
"maps"
"net"
"net/http"
"reflect"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/pkg/errors"
"go.uber.org/multierr"
"moul.io/http2curl"
"github.com/projectdiscovery/gologger"
"github.com/projectdiscovery/nuclei/v3/pkg/fuzz/analyzers"
"github.com/projectdiscovery/nuclei/v3/pkg/fuzz/component"
fuzzStats "github.com/projectdiscovery/nuclei/v3/pkg/fuzz/stats"
"github.com/projectdiscovery/nuclei/v3/pkg/operators"
"github.com/projectdiscovery/nuclei/v3/pkg/operators/extractors"
"github.com/projectdiscovery/nuclei/v3/pkg/output"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/contextargs"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/expressions"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/generators"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/helpers/eventcreator"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/helpers/responsehighlighter"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/hostbackoff"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/hostratelimit"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/interactsh"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/marker"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/protocolstate"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/utils/vardump"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/http/catchall"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/http/httpclientpool"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/http/httputils"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/http/signer"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/http/signerpool"
templateTypes "github.com/projectdiscovery/nuclei/v3/pkg/templates/types"
"github.com/projectdiscovery/nuclei/v3/pkg/types"
"github.com/projectdiscovery/nuclei/v3/pkg/types/nucleierr"
"github.com/projectdiscovery/nuclei/v3/pkg/utils/httpbody"
"github.com/projectdiscovery/rawhttp"
"github.com/projectdiscovery/retryablehttp-go"
convUtil "github.com/projectdiscovery/utils/conversion"
"github.com/projectdiscovery/utils/errkit"
httpUtils "github.com/projectdiscovery/utils/http"
iputil "github.com/projectdiscovery/utils/ip"
sliceutil "github.com/projectdiscovery/utils/slice"
stringsutil "github.com/projectdiscovery/utils/strings"
unitutils "github.com/projectdiscovery/utils/unit"
urlutil "github.com/projectdiscovery/utils/url"
)
const (
defaultMaxWorkers = 150
// max unique errors to store & combine
// when executing requests in parallel
maxErrorsWhenParallel = 3
)
var (
MaxBodyRead = 10 * unitutils.Mega
// ErrMissingVars is error occurred when variables are missing
ErrMissingVars = errkit.New("stop execution due to unresolved variables").SetKind(nucleierr.ErrTemplateLogic).Build()
// ErrHttpEngineRequestDeadline is error occurred when request deadline set by http request engine is exceeded
ErrHttpEngineRequestDeadline = errkit.New("http request engine deadline exceeded").SetKind(errkit.ErrKindDeadline).Build()
)
// Type returns the type of the protocol request
func (request *Request) Type() templateTypes.ProtocolType {
return templateTypes.HTTPProtocol
}
// hostBackoffKey is the identity shared by the pre-request wait and the
// post-response observation. It keeps the scheme, or an explicit port, so
// NormalizeHostPort does not record an https target under port 80.
func hostBackoffKey(req *generatedRequest, input *contextargs.Context) string {
if req != nil {
if key := req.URL(); key != "" {
return key
}
if req.request != nil && req.request.Request != nil && req.request.Request.URL != nil {
return req.request.Request.URL.String()
}
}
if input != nil && input.MetaInput != nil {
return input.MetaInput.Input
}
return ""
}
// observeHostBackoff reports one request outcome to the per-host governor.
func (request *Request) observeHostBackoff(host string, resp *http.Response, err error) {
if request.options == nil || request.options.HostBackoff == nil {
return
}
// A cancelled sibling, or a scan that is stopping, is not the host asking
// for less traffic. A real status on the response is still worth recording.
if resp == nil && err != nil && stderrors.Is(err, context.Canceled) {
return
}
statusCode := 0
var retryAfter time.Duration
if resp != nil {
statusCode = resp.StatusCode
retryAfter = hostbackoff.RetryAfter(resp.Header.Get("Retry-After"))
}
request.options.HostBackoff.Observe(hostratelimit.NormalizeHostPort(host), statusCode, retryAfter, err)
}
// waitHostBackoff pauses for the delay this host has already earned.
func (request *Request) waitHostBackoff(ctx context.Context, host string) error {
if request.options == nil {
return nil
}
return request.options.HostBackoffWait(ctx, host)
}
// rateLimitTake first honours any backoff the host earned by signalling it is
// overloaded, so a blocking target is paced regardless of which limiter is in play.
func (request *Request) rateLimitTake(ctx context.Context, hostname string) error {
if err := request.waitHostBackoff(ctx, hostname); err != nil {
return err
}
return request.options.RateLimitTakeContext(ctx, hostname)
}
// stopWithHandler ends when parent ends or the handler stops, so a backoff
// wait does not outlive stop-at-first-match.
func stopWithHandler[T comparable](parent context.Context, handler *httputils.StopAtFirstMatchHandler[T]) (context.Context, context.CancelFunc) {
ctx, cancel := context.WithCancel(parent)
if handler == nil {
return ctx, cancel
}
if handler.Context().Err() != nil {
cancel()
return ctx, func() {}
}
stop := context.AfterFunc(handler.Context(), cancel)
return ctx, func() {
stop()
cancel()
}
}
// executeRaceRequest executes race condition request for a URL
func (request *Request) executeRaceRequest(input *contextargs.Context, dynamicValues, previous output.InternalEvent, callback protocols.OutputEventCallback) error {
reqURL := input.MetaInput.Input
var generatedRequests []*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
generator := request.newGenerator(false)
inputData, payloads, ok := generator.nextValue()
if !ok {
return nil
}
ctx := input.Context()
requestForDump, err := generator.Make(ctx, input, inputData, payloads, dynamicValues)
if err != nil {
return err
}
request.setCustomHeaders(requestForDump)
// Auth is applied again on each raced request. The dump is what replay
// sends, so it has to include the same headers.
if !request.SkipSecretFile {
requestForDump.ApplyAuth(request.options.AuthProvider)
}
dumpedRequest, err := dump(requestForDump, reqURL, 0)
if err != nil {
return err
}
dumpedRequestString := convUtil.String(dumpedRequest.data)
savedRequest := convUtil.String(capDumpBody(dumpedRequest.data, request.options.Options.RequestSaveSize))
if request.options.Options.Debug || request.options.Options.DebugRequests || request.options.Options.StoreResponse {
msg := fmt.Sprintf("[%s] Dumped HTTP request for %s\n\n", request.options.TemplateID, reqURL)
if request.options.Options.Debug || request.options.Options.DebugRequests {
gologger.Info().Msg(msg)
gologger.Print().Msgf("%s", savedRequest)
}
if request.options.Options.StoreResponse {
request.options.Output.WriteStoreDebugData(reqURL, request.options.TemplateID, request.Type().String(), fmt.Sprintf("%s\n%s", msg, savedRequest))
}
}
previous["request"] = dumpedRequestString
// Pre-Generate requests
for i := 0; i < request.RaceNumberRequests; i++ {
generator := request.newGenerator(false)
inputData, payloads, ok := generator.nextValue()
if !ok {
break
}
ctx := input.Context()
generatedRequest, err := generator.Make(ctx, input, inputData, payloads, dynamicValues)
if err != nil {
return err
}
generatedRequests = append(generatedRequests, generatedRequest)
}
shouldStop := (request.options.Options.StopAtFirstMatch || request.StopAtFirstMatch || request.options.StopAtFirstMatch)
childCtx, cancel := context.WithCancel(input.Context())
defer cancel()
spmHandler := httputils.NewNonBlockingSPMHandler[error](childCtx, maxErrorsWhenParallel, shouldStop)
defer spmHandler.Cancel()
gotMatches := &atomic.Bool{}
// wrappedCallback is a callback that wraps the original callback
// to implement stop at first match logic
wrappedCallback := func(event *output.InternalWrappedEvent) {
if !event.HasOperatorResult() {
callback(event) // not required but we can allow it
return
}
// this will execute match condition such that if stop at first match is enabled
// this will be only executed once
spmHandler.MatchCallback(func() {
gotMatches.Store(true)
callback(event)
})
if shouldStop {
// stop all running requests and exit
spmHandler.Trigger()
}
}
for i := 0; i < request.RaceNumberRequests; i++ {
updatedInput := contextargs.GetCopyIfHostOutdated(input, generatedRequests[i].URL())
if spmHandler.FoundFirstMatch() || request.isUnresponsiveAddress(updatedInput) {
// stop sending more requests condition is met
break
}
if err := spmHandler.Acquire(); err != nil {
break
}
// execute http request
go func(httpRequest *generatedRequest, requestInput *contextargs.Context) {
defer spmHandler.Release()
if spmHandler.FoundFirstMatch() || request.isUnresponsiveAddress(requestInput) {
// stop sending more requests condition is met
return
}
waitCtx, cancelWait := stopWithHandler(requestInput.Context(), spmHandler)
err := request.waitHostBackoff(waitCtx, hostBackoffKey(httpRequest, requestInput))
cancelWait()
if err != nil || spmHandler.FoundFirstMatch() || spmHandler.Cancelled() {
if err != nil {
select {
case <-spmHandler.Done():
case spmHandler.ResultChan <- err:
}
}
return
}
err = request.executeRequest(requestInput, httpRequest, previous, false, wrappedCallback, 0)
select {
case <-spmHandler.Done():
return
case spmHandler.ResultChan <- err:
request.recordHostResultAndCancelIfUnresponsive(requestInput, err, spmHandler.Cancel)
return
}
}(generatedRequests[i], updatedInput)
request.options.Progress.IncrementRequests()
}
spmHandler.Wait()
if spmHandler.FoundFirstMatch() {
// ignore any context cancellation and in-transit execution errors
return nil
}
return multierr.Combine(spmHandler.CombinedResults()...)
}
// executeParallelHTTP executes parallel requests for a template
func (request *Request) executeParallelHTTP(input *contextargs.Context, dynamicValues output.InternalEvent, callback protocols.OutputEventCallback) error {
// Workers that keeps enqueuing new requests
maxWorkers := request.Threads
// if request threads matches global payload concurrency we follow it
shouldFollowGlobal := maxWorkers == request.options.Options.PayloadConcurrency
if protocolstate.IsLowOnMemory() {
maxWorkers = protocolstate.GuardThreadsOrDefault(request.Threads)
}
// Stop-at-first-match logic while executing requests
// parallelly using threads
shouldStop := (request.options.Options.StopAtFirstMatch || request.StopAtFirstMatch || request.options.StopAtFirstMatch)
workerCtx, cancelWorkers := context.WithCancel(input.Context())
defer cancelWorkers()
spmHandler := httputils.NewBlockingSPMHandler[error](context.Background(), maxWorkers, maxErrorsWhenParallel, shouldStop)
defer spmHandler.Cancel()
// wrappedCallback is a callback that wraps the original callback
// to implement stop at first match logic
wrappedCallback := func(event *output.InternalWrappedEvent) {
if !event.HasOperatorResult() {
callback(event) // not required but we can allow it
return
}
// this will execute match condition such that if stop at first match is enabled
// this will be only executed once
spmHandler.MatchCallback(func() {
callback(event)
})
if shouldStop {
// stop all running requests and exit
spmHandler.Trigger()
cancelWorkers()
}
}
// bounded worker-pool to avoid spawning one goroutine per payload
type task struct {
req *generatedRequest
body *bodyReservation
updatedInput *contextargs.Context
hasInteractMarkers bool
}
var workersWg sync.WaitGroup
currentWorkers := maxWorkers
tasks := make(chan task, maxWorkers)
// Workers exit on cancel without draining, and the budget is shared, so
// release what they left queued.
stopWorkers := func() {
close(tasks)
workersWg.Wait()
for t := range tasks {
t.body.done()
}
}
spawnWorker := func(ctx context.Context) {
workersWg.Add(1)
go func() {
defer workersWg.Done()
for t := range tasks {
if func() (exit bool) {
defer t.body.done()
select {
case <-ctx.Done():
return true
default:
}
if spmHandler.FoundFirstMatch() || request.isUnresponsiveAddress(t.updatedInput) || spmHandler.Cancelled() {
return false
}
if err := spmHandler.Acquire(); err != nil {
return false
}
if spmHandler.FoundFirstMatch() || request.isUnresponsiveAddress(t.updatedInput) || spmHandler.Cancelled() {
spmHandler.Release()
return false
}
// Full URL, so https and an explicit port stay on the same key the observation uses.
// The handler context ends the wait when stop-at-first-match fires.
waitCtx, cancelWait := stopWithHandler(ctx, spmHandler)
err := request.rateLimitTake(waitCtx, hostBackoffKey(t.req, t.updatedInput))
cancelWait()
if err != nil {
select {
case <-spmHandler.Done():
spmHandler.Release()
return false
case <-ctx.Done():
spmHandler.Release()
return false
case spmHandler.ResultChan <- err:
spmHandler.Release()
return false
}
}
if ctx.Err() != nil || spmHandler.FoundFirstMatch() || request.isUnresponsiveAddress(t.updatedInput) || spmHandler.Cancelled() {
spmHandler.Release()
return false
}
hasInteractMatchers := interactsh.HasMatchers(request.CompiledOperators)
needsRequestEvent := hasInteractMatchers && request.NeedsRequestCondition()
err = request.executeRequest(t.updatedInput, t.req, make(map[string]interface{}), hasInteractMatchers, func(event *output.InternalWrappedEvent) {
if (t.hasInteractMarkers || needsRequestEvent) && request.options.Interactsh != nil {
requestData := &interactsh.RequestData{
MakeResultFunc: request.MakeResultEvent,
Event: event,
Operators: request.CompiledOperators,
MatchFunc: request.Match,
ExtractFunc: request.Extract,
}
allOASTUrls := httputils.GetInteractshURLSFromEvent(event.InternalEvent)
allOASTUrls = append(allOASTUrls, t.req.interactshURLs...)
request.options.RegisterInteractshRequest(sliceutil.Dedupe(allOASTUrls), requestData)
}
wrappedCallback(event)
}, 0)
select {
case <-spmHandler.Done():
spmHandler.Release()
return false
case spmHandler.ResultChan <- err:
request.recordHostResultAndCancelIfUnresponsive(t.updatedInput, err, spmHandler.Cancel)
spmHandler.Release()
}
return false
}() {
return
}
}
}()
}
for i := 0; i < currentWorkers; i++ {
spawnWorker(workerCtx)
}
// iterate payloads and make requests
generator := request.newGenerator(false)
for {
inputData, payloads, ok := generator.nextValue()
if !ok {
break
}
select {
case <-input.Context().Done():
stopWorkers()
return input.Context().Err()
default:
}
// resize check point - nop if there are no changes
if shouldFollowGlobal && spmHandler.Size() != request.options.Options.PayloadConcurrency {
if err := spmHandler.Resize(input.Context(), request.options.Options.PayloadConcurrency); err != nil {
stopWorkers()
return err
}
// if payload concurrency increased, add more workers
if spmHandler.Size() > currentWorkers {
for i := 0; i < spmHandler.Size()-currentWorkers; i++ {
spawnWorker(workerCtx)
}
currentWorkers = spmHandler.Size()
}
}
// break if stop at first match is found or host is unresponsive
if spmHandler.FoundFirstMatch() || request.isUnresponsiveAddress(input) {
break
}
// Queued tasks hold budget and are only released once the workers
// stop, so the wait has to end with them.
generatedHttpRequest, reservation, err := request.makeReserved(workerCtx, generator, input, inputData, payloads, dynamicValues)
if err != nil {
if err == types.ErrNoMoreRequests {
break
}
if workerCtx.Err() != nil {
stopWorkers()
if spmHandler.FoundFirstMatch() {
return nil
}
return context.Cause(workerCtx)
}
request.options.Progress.IncrementFailedRequestsBy(int64(generator.Total()))
stopWorkers()
return err
}
hasInteractMarkers := interactsh.HasMarkers(inputData) || len(generatedHttpRequest.interactshURLs) > 0
if input.MetaInput.Input == "" {
input.MetaInput.Input = generatedHttpRequest.URL()
}
updatedInput := contextargs.GetCopyIfHostOutdated(input, generatedHttpRequest.URL())
if request.isUnresponsiveAddress(updatedInput) {
// skip on unresponsive host no need to continue
reservation.done()
spmHandler.Cancel()
stopWorkers()
return nil
}
select {
case <-spmHandler.Done():
reservation.done()
stopWorkers()
spmHandler.Wait()
if spmHandler.FoundFirstMatch() {
return nil
}
return multierr.Combine(spmHandler.CombinedResults()...)
case <-workerCtx.Done():
reservation.done()
stopWorkers()
if spmHandler.FoundFirstMatch() {
return nil
}
return context.Cause(workerCtx)
case tasks <- task{req: generatedHttpRequest, body: reservation, updatedInput: updatedInput, hasInteractMarkers: hasInteractMarkers}:
}
request.options.Progress.IncrementRequests()
}
stopWorkers()
spmHandler.Wait()
if spmHandler.FoundFirstMatch() {
// ignore any context cancellation and in-transit execution errors
return nil
}
return multierr.Combine(spmHandler.CombinedResults()...)
}
// executeTurboHTTP executes turbo http request for a URL
func (request *Request) executeTurboHTTP(input *contextargs.Context, dynamicValues, previous output.InternalEvent, callback protocols.OutputEventCallback) error {
generator := request.newGenerator(false)
// need to extract the target from the url
URL, err := urlutil.Parse(input.MetaInput.Input)
if err != nil {
return err
}
pipeOptions := rawhttp.DefaultPipelineOptions
pipeOptions.Host = URL.Host
pipeOptions.MaxConnections = 1
// route pipelined connections through the fastdialer so the network policy
// applies; without an explicit Dialer the pipeline client uses a raw dial.
if dialers := protocolstate.GetDialersWithId(request.options.Options.ExecutionId); dialers != nil && dialers.Fastdialer != nil {
fd := dialers.Fastdialer
pipeOptions.Dialer = func(addr string) (net.Conn, error) {
// the input context carries the pinned ip of the target, if any
return fd.Dial(input.Context(), "tcp", addr)
}
}
if request.PipelineConcurrentConnections > 0 {
pipeOptions.MaxConnections = request.PipelineConcurrentConnections
}
if request.PipelineRequestsPerConnection > 0 {
pipeOptions.MaxPendingRequests = request.PipelineRequestsPerConnection
}
pipeClient := rawhttp.NewPipelineClient(pipeOptions)
// defaultMaxWorkers should be a sufficient value to keep queues always full
// in case the queue is bigger increase the workers
maxWorkers := max(pipeOptions.MaxPendingRequests, defaultMaxWorkers)
// Stop-at-first-match logic while executing requests
// parallelly using threads
shouldStop := (request.options.Options.StopAtFirstMatch || request.StopAtFirstMatch || request.options.StopAtFirstMatch)
ctx, cancel := context.WithCancel(input.Context())
defer cancel()
spmHandler := httputils.NewBlockingSPMHandler[error](ctx, maxWorkers, maxErrorsWhenParallel, shouldStop)
defer spmHandler.Cancel()
// wrappedCallback is a callback that wraps the original callback
// to implement stop at first match logic
wrappedCallback := func(event *output.InternalWrappedEvent) {
if !event.HasOperatorResult() {
callback(event) // not required but we can allow it
return
}
// this will execute match condition such that if stop at first match is enabled
// this will be only executed once
spmHandler.MatchCallback(func() {
callback(event)
})
if shouldStop {
// stop all running requests and exit
spmHandler.Trigger()
}
}
for {
inputData, payloads, ok := generator.nextValue()
if !ok {
break
}
select {
case <-input.Context().Done():
return input.Context().Err()
default:
}
if spmHandler.FoundFirstMatch() || request.isUnresponsiveAddress(input) || spmHandler.Cancelled() {
// skip if first match is found
break
}
ctx := input.Context()
generatedHttpRequest, reservation, err := request.makeReserved(ctx, generator, input, inputData, payloads, dynamicValues)
if err != nil {
request.options.Progress.IncrementFailedRequestsBy(int64(generator.Total()))
return err
}
if input.MetaInput.Input == "" {
input.MetaInput.Input = generatedHttpRequest.URL()
}
updatedInput := contextargs.GetCopyIfHostOutdated(input, generatedHttpRequest.URL())
if request.isUnresponsiveAddress(updatedInput) {
// skip on unresponsive host no need to continue
reservation.done()
spmHandler.Cancel()
return nil
}
generatedHttpRequest.pipelinedClient = pipeClient
if err := spmHandler.Acquire(); err != nil {
reservation.done()
break
}
go func(httpRequest *generatedRequest, body *bodyReservation, requestInput *contextargs.Context) {
defer spmHandler.Release()
defer body.done()
if spmHandler.FoundFirstMatch() || request.isUnresponsiveAddress(requestInput) {
// skip if first match is found
return
}
waitCtx, cancelWait := stopWithHandler(requestInput.Context(), spmHandler)
err := request.waitHostBackoff(waitCtx, hostBackoffKey(httpRequest, requestInput))
cancelWait()
if err != nil || spmHandler.FoundFirstMatch() || spmHandler.Cancelled() {
if err != nil {
select {
case <-spmHandler.Done():
case spmHandler.ResultChan <- err:
}
}
return
}
err = request.executeRequest(requestInput, httpRequest, previous, false, wrappedCallback, 0)
select {
case <-spmHandler.Done():
return
case spmHandler.ResultChan <- err:
request.recordHostResultAndCancelIfUnresponsive(requestInput, err, spmHandler.Cancel)
return
}
}(generatedHttpRequest, reservation, updatedInput)
request.options.Progress.IncrementRequests()
}
spmHandler.Wait()
if spmHandler.FoundFirstMatch() {
// ignore any context cancellation and in-transit execution errors
return nil
}
return multierr.Combine(spmHandler.CombinedResults()...)
}
// ExecuteWithResults executes the final request on a URL
func (request *Request) ExecuteWithResults(input *contextargs.Context, dynamicValues, previous output.InternalEvent, callback protocols.OutputEventCallback) error {
// verify if pipeline was requested
if request.Pipeline {
return request.executeTurboHTTP(input, dynamicValues, previous, callback)
}
// verify if a basic race condition was requested
if request.Race && request.RaceNumberRequests > 0 {
return request.executeRaceRequest(input, dynamicValues, previous, callback)
}
// verify if fuzz elaboration was requested
if len(request.Fuzzing) > 0 {
return request.executeFuzzingRule(input, dynamicValues, callback)
}
// verify if parallel elaboration was requested
if request.Threads > 0 && (len(request.Payloads) > 0 || request.Race) {
return request.executeParallelHTTP(input, dynamicValues, callback)
}
generator := request.newGenerator(false)
initialContext := dynamicValueContext{
values: generators.CopyMap(dynamicValues),
previous: cloneInternalEvent(previous),
}
dynamicValueContexts := []dynamicValueContext{initialContext}
if request.IterateAll {
dynamicValueContexts = expandDynamicValueContexts(initialContext, generators.MergeMapsMany(dynamicValues), true)
}
var requestErr error
executionLoop:
for {
executeFunc := func(data string, payloads, dynamicValue map[string]interface{}, previousEvent output.InternalEvent) (skipBranch, stop bool, extracted map[string][]string, err error) {
hasInteractMatchers := interactsh.HasMatchers(request.CompiledOperators)
ctx := input.Context()
generatedHttpRequest, reservation, err := request.makeReserved(ctx, generator, input, data, payloads, dynamicValue)
if err != nil {
if err == types.ErrNoMoreRequests {
return false, true, nil, nil
}
return false, true, nil, err
}
defer reservation.done()
if generatedHttpRequest.customCancelFunction == nil {
generatedHttpRequest.sendTimeout = request.options.Options.GetTimeouts().HttpTimeout
}
// ideally if http template used a custom port or hostname
// we would want to update it in input but currently templateCtx logic
// is closely tied to contextargs.Context so we are temporarily creating
// a copy and using it to check for host errors etc
// but this should be replaced once templateCtx is refactored properly
updatedInput := contextargs.GetCopyIfHostOutdated(input, generatedHttpRequest.URL())
// Full URL, so https and an explicit port stay on the same key the observation uses.
if err := request.rateLimitTake(ctx, hostBackoffKey(generatedHttpRequest, input)); err != nil {
return false, true, nil, err
}
if generatedHttpRequest.customCancelFunction != nil {
defer generatedHttpRequest.customCancelFunction()
}
hasInteractMarkers := interactsh.HasMarkers(data) || len(generatedHttpRequest.interactshURLs) > 0
if input.MetaInput.Input == "" {
input.MetaInput.Input = generatedHttpRequest.URL()
}
// Check if hosts keep erroring
if request.isUnresponsiveAddress(updatedInput) {
return false, true, nil, nil
}
var gotMatches bool
var extractedDynamicValues map[string][]string
execReqErr := request.executeRequest(input, generatedHttpRequest, previousEvent, hasInteractMatchers, func(event *output.InternalWrappedEvent) {
// a special case where operators has interactsh matchers and multiple request are made
// ex: status_code_2 , interactsh_protocol (from 1st request) etc
needsRequestEvent := interactsh.HasMatchers(request.CompiledOperators) && request.NeedsRequestCondition()
if (hasInteractMarkers || needsRequestEvent) && request.options.Interactsh != nil {
requestData := &interactsh.RequestData{
MakeResultFunc: request.MakeResultEvent,
Event: event,
Operators: request.CompiledOperators,
MatchFunc: request.Match,
ExtractFunc: request.Extract,
}
allOASTUrls := httputils.GetInteractshURLSFromEvent(event.InternalEvent)
allOASTUrls = append(allOASTUrls, generatedHttpRequest.interactshURLs...)
request.options.RegisterInteractshRequest(sliceutil.Dedupe(allOASTUrls), requestData)
gotMatches = request.options.Interactsh.AlreadyMatched(requestData)
}
// Add the extracts to the dynamic values if any.
if event.OperatorsResult != nil {
gotMatches = event.OperatorsResult.Matched
extractedDynamicValues = generators.MergeMapsMany(
request.extractCurrentDynamicValues(event, generator.currentIndex),
extractedDynamicValues,
)
}
// Note: This is a race condition prone zone i.e when request has interactsh_matchers
// Interactsh.RequestEvent tries to access/update output.InternalWrappedEvent depending on logic
// to avoid conflicts with `callback` mutex is used here and in Interactsh.RequestEvent
// Note: this only happens if requests > 1 and interactsh matcher is used
// TODO: interactsh logic in nuclei needs to be refactored to avoid such situations
callback(event)
}, generator.currentIndex)
// A variable may be unresolved for one iterate-all branch while sibling
// branches remain executable.
if errors.Is(execReqErr, ErrMissingVars) {
return true, false, nil, nil
}
request.recordHostResult(updatedInput, execReqErr)
if execReqErr != nil {
reqKitErr := errkit.FromError(execReqErr)
reqKitErr.Msgf("got err while executing %v", generatedHttpRequest.URL())
requestErr = reqKitErr
request.options.Progress.IncrementFailedRequestsBy(1)
} else {
request.options.Progress.IncrementRequests()
}
// If this was a match, and we want to stop at first match, skip all further requests.
shouldStopAtFirstMatch := generatedHttpRequest.original.options.Options.StopAtFirstMatch || generatedHttpRequest.original.options.StopAtFirstMatch || request.StopAtFirstMatch
if shouldStopAtFirstMatch && gotMatches {
return false, true, nil, nil
}
return false, false, extractedDynamicValues, nil
}
inputData, payloads, ok := generator.nextValue()
if !ok {
break
}
select {
case <-input.Context().Done():
return input.Context().Err()
default:
}
isOnceRequest := generator.hasMarker(inputData, Once)
if isOnceRequest {
var onceExtracted map[string][]string
var oncePreviousDelta output.InternalEvent
executed := false
for _, branch := range dynamicValueContexts {
select {
case <-input.Context().Done():
return input.Context().Err()
default:
}
before := cloneInternalEvent(branch.previous)
after := cloneInternalEvent(branch.previous)
skipBranch, stop, extracted, gotErr := executeFunc(inputData, generators.CopyMap(payloads), branch.values, after)
if gotErr != nil {
if requestErr == nil {
requestErr = gotErr
}
request.options.Progress.SetRequests(uint64(generator.Remaining() + 1))
break executionLoop
}
if stop {
request.options.Progress.SetRequests(uint64(generator.Remaining() + 1))
break executionLoop
}
if skipBranch {
continue
}
executed = true
onceExtracted = extracted
oncePreviousDelta = changedEventValues(before, after)
break
}
if !executed {
dynamicValueContexts = nil
continue
}
nextDynamicValueContexts := make([]dynamicValueContext, 0, len(dynamicValueContexts))
for _, branch := range dynamicValueContexts {
maps.Copy(branch.previous, oncePreviousDelta)
nextDynamicValueContexts = append(nextDynamicValueContexts, expandDynamicValueContexts(branch, onceExtracted, request.IterateAll)...)
}
dynamicValueContexts = nextDynamicValueContexts
continue
}
nextDynamicValueContexts := make([]dynamicValueContext, 0, len(dynamicValueContexts))
for _, branch := range dynamicValueContexts {
select {
case <-input.Context().Done():
return input.Context().Err()
default:
}
skipBranch, stop, extractedDynamicValues, gotErr := executeFunc(inputData, generators.CopyMap(payloads), branch.values, branch.previous)
if gotErr != nil {
if requestErr == nil {
requestErr = gotErr
}
request.options.Progress.SetRequests(uint64(generator.Remaining() + 1))
break executionLoop
}
if stop {
request.options.Progress.SetRequests(uint64(generator.Remaining() + 1))
break executionLoop
}
if skipBranch {
continue
}
nextDynamicValueContexts = append(nextDynamicValueContexts, expandDynamicValueContexts(branch, extractedDynamicValues, request.IterateAll)...)
}
dynamicValueContexts = nextDynamicValueContexts
}
return requestErr
}
type dynamicValueContext struct {
values map[string]interface{}
seen map[string]map[string]struct{}
previous output.InternalEvent
}
func expandDynamicValueContexts(parent dynamicValueContext, extracted map[string][]string, iterateAll bool) []dynamicValueContext {
if len(extracted) == 0 {
return []dynamicValueContext{parent}
}
nextValues := make(map[string][]string, len(extracted))
for key, values := range extracted {
values = sliceutil.Dedupe(values)
if len(values) == 0 {
continue
}
seen := parent.seen[key]
if len(seen) == 0 {
nextValues[key] = values
continue
}
current := types.ToString(parent.values[key])
for _, value := range values {
if value == current {
nextValues[key] = append(nextValues[key], value)
break
}
}
for _, value := range values {
if _, exists := seen[value]; !exists {
nextValues[key] = append(nextValues[key], value)
}
}
if len(nextValues[key]) == 0 {
nextValues[key] = values
}
}
if len(nextValues) == 0 {
return []dynamicValueContext{parent}
}
seen := cloneSeenValues(parent.seen)
for key, extractedValues := range extracted {
if seen[key] == nil {
seen[key] = make(map[string]struct{}, len(extractedValues))
}
for _, value := range extractedValues {
seen[key][value] = struct{}{}
}
}
var contexts []dynamicValueContext
operators.MakeDynamicValuesCallback(nextValues, iterateAll, func(values map[string]interface{}) bool {
contexts = append(contexts, dynamicValueContext{
values: generators.MergeMaps(parent.values, values),
seen: seen,
previous: cloneInternalEvent(parent.previous),
})
return false
})
return contexts
}
func cloneSeenValues(source map[string]map[string]struct{}) map[string]map[string]struct{} {
cloned := make(map[string]map[string]struct{}, len(source))
for key, values := range source {
cloned[key] = maps.Clone(values)
}
return cloned
}
func cloneInternalEvent(source output.InternalEvent) output.InternalEvent {
cloned := make(output.InternalEvent, len(source))
maps.Copy(cloned, source)
return cloned
}
func changedEventValues(before, after output.InternalEvent) output.InternalEvent {
changed := make(output.InternalEvent)
for key, value := range after {
if previousValue, ok := before[key]; !ok || !reflect.DeepEqual(previousValue, value) {
changed[key] = value
}
}
return changed
}
func (request *Request) extractCurrentDynamicValues(event *output.InternalWrappedEvent, requestIndex int) map[string][]string {
if request.CompiledOperators == nil {
return nil
}
values := make(map[string][]string)
for _, extractor := range request.CompiledOperators.Extractors {
if !extractor.Internal || extractor.Name == "" || !extractorAppliesToRequest(extractor.Part, requestIndex) {
continue
}
if extractor.GetType() == extractors.LLMExtractor {
if event.OperatorsResult != nil {
values[extractor.Name] = append(values[extractor.Name], event.OperatorsResult.DynamicValues[extractor.Name]...)
}
if len(values[extractor.Name]) == 0 {
switch extracted := event.InternalEvent[extractor.Name].(type) {
case []string:
values[extractor.Name] = append(values[extractor.Name], extracted...)
case string:
values[extractor.Name] = append(values[extractor.Name], extracted)
}
}
continue
}