/
grpc_fuzzer.go
1586 lines (1456 loc) · 49.1 KB
/
grpc_fuzzer.go
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 yakgrpc
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/davecgh/go-spew/spew"
"github.com/samber/lo"
"github.com/yaklang/yaklang/common/consts"
filter2 "github.com/yaklang/yaklang/common/filter"
"github.com/yaklang/yaklang/common/go-funk"
"github.com/yaklang/yaklang/common/log"
"github.com/yaklang/yaklang/common/mutate"
"github.com/yaklang/yaklang/common/utils"
"github.com/yaklang/yaklang/common/utils/lowhttp"
"github.com/yaklang/yaklang/common/utils/lowhttp/poc"
"github.com/yaklang/yaklang/common/yak"
"github.com/yaklang/yaklang/common/yak/cartesian"
"github.com/yaklang/yaklang/common/yak/httptpl"
"github.com/yaklang/yaklang/common/yak/yaklib/codec"
"github.com/yaklang/yaklang/common/yakgrpc/yakit"
"github.com/yaklang/yaklang/common/yakgrpc/ypb"
uuid "github.com/google/uuid"
"github.com/saintfish/chardet"
)
var _FuzzerTaskSwitchMap = new(sync.Map)
func Chardet(raw []byte) string {
res, err := chardet.NewTextDetector().DetectBest(raw)
if err != nil {
return "utf-8"
}
return res.Charset
}
func (s *Server) ExtractUrl(ctx context.Context, req *ypb.FuzzerRequest) (*ypb.ExtractedUrl, error) {
res, err := mutate.FuzzTagExec(req.GetRequest(), mutate.Fuzz_WithEnableDangerousTag())
if err != nil {
return nil, err
}
var u *url.URL
if err != nil {
u, err = lowhttp.ExtractURLFromHTTPRequestRaw([]byte(req.Request), req.GetIsHTTPS())
if err != nil {
return nil, err
}
} else {
render, err := lowhttp.ParseStringToHttpRequest(res[0])
if err != nil {
return nil, err
}
u, err = lowhttp.ExtractURLFromHTTPRequest(render, req.GetIsHTTPS())
if err != nil {
return nil, err
}
}
return &ypb.ExtractedUrl{Url: u.String()}, nil
}
func (s *Server) StringFuzzer(rootCtx context.Context, req *ypb.StringFuzzerRequest) (*ypb.StringFuzzerResponse, error) {
max := req.GetLimit()
timeoutSeconds := req.GetTimeoutSeconds()
ctx := rootCtx
cancel := func() {}
if timeoutSeconds > 0 {
ctx, cancel = context.WithTimeout(rootCtx, time.Duration(timeoutSeconds)*time.Second)
}
defer cancel()
var res [][]byte
var counter int64
mutate.FuzzTagExec(
req.GetTemplate(),
mutate.Fuzz_WithResultHandler(func(origin string, payloads []string) bool {
select {
case <-ctx.Done():
return false
default:
if max > 0 && counter >= max {
return false
}
}
counter++
res = append(res, []byte(origin))
return true
}),
yak.Fuzz_WithHotPatch(rootCtx, req.GetHotPatchCode()),
mutate.Fuzz_WithEnableDangerousTag(),
)
return &ypb.StringFuzzerResponse{Results: res}, nil
}
func (s *Server) RedirectRequest(ctx context.Context, req *ypb.RedirectRequestParams) (*ypb.FuzzerResponse, error) {
result := lowhttp.GetRedirectFromHTTPResponse([]byte(req.GetResponse()), false)
if result == "" {
return nil, utils.Error("cannot find redirect url")
}
isHttps := req.GetIsHttps()
if strings.HasPrefix(result, "https://") {
isHttps = true
}
_ = isHttps
newUrl := lowhttp.MergeUrlFromHTTPRequest([]byte(req.GetRequest()), result, isHttps)
resultRequest := lowhttp.UrlToGetRequestPacket(newUrl, []byte(req.GetRequest()), isHttps, lowhttp.ExtractCookieJarFromHTTPResponse([]byte(req.GetResponse()))...)
if resultRequest == nil {
return nil, utils.Errorf("cannot merge request packet. redirect url: %s", newUrl)
}
start := time.Now()
host, port, _ := utils.ParseStringToHostPort(newUrl)
rspIns, err := lowhttp.HTTPWithoutRedirect(
lowhttp.WithHttps(isHttps),
lowhttp.WithHost(host),
lowhttp.WithPort(port),
lowhttp.WithRequest(resultRequest),
lowhttp.WithTimeoutFloat(req.GetPerRequestTimeoutSeconds()),
lowhttp.WithGmTLS(req.GetIsGmTLS()),
lowhttp.WithProxy(utils.PrettifyListFromStringSplited(req.GetProxy(), ",")...),
)
if err != nil {
return nil, err
}
rspRaw := rspIns.RawPacket
// 提取响应
extractHTTPResponseResult, err := s.ExtractHTTPResponse(ctx, &ypb.ExtractHTTPResponseParams{
HTTPResponse: string(rspRaw),
Extractors: req.GetExtractors(),
})
var extractResults []*ypb.KVPair
if err == nil && extractHTTPResponseResult != nil && extractHTTPResponseResult.GetValues() != nil {
for _, value := range extractHTTPResponseResult.GetValues() {
extractResults = append(extractResults, &ypb.KVPair{
Key: value.GetKey(),
Value: value.GetValue(),
})
}
}
// 匹配响应
var httpTPLmatchersResult bool
if len(req.GetMatchers()) != 0 {
httpTplMatcher := make([]*httptpl.YakMatcher, 0)
for _, matcher := range req.GetMatchers() {
httpTplMatcher = append(httpTplMatcher, httptpl.NewMatcherFromGRPCModel(matcher))
}
cond := "and"
switch ret := strings.ToLower(req.GetMatchersCondition()); ret {
case "or", "and":
cond = ret
default:
}
ins := &httptpl.YakMatcher{
SubMatcherCondition: cond,
SubMatchers: httpTplMatcher,
}
mergedParams := make(map[string]interface{})
renderedParams, err := s.RenderVariables(ctx, &ypb.RenderVariablesRequest{
Params: funk.Map(req.GetParams(), func(i *ypb.FuzzerParamItem) *ypb.KVPair {
return &ypb.KVPair{Key: i.GetKey(), Value: i.GetValue()}
}).([]*ypb.KVPair),
IsHTTPS: req.GetIsHttps(),
IsGmTLS: req.GetIsGmTLS(),
})
if err != nil {
return nil, utils.Errorf("render variables failed: %v", err)
}
for _, kv := range renderedParams.GetResults() {
mergedParams[kv.GetKey()] = kv.GetValue()
}
matcherParams := utils.CopyMapInterface(mergedParams)
httpTPLmatchersResult, err = ins.Execute(&lowhttp.LowhttpResponse{RawPacket: rspRaw}, matcherParams)
if err != nil {
log.Errorf("httptpl.YakMatcher execute failed: %s", err)
}
}
rsp := &ypb.FuzzerResponse{
Method: "GET",
ResponseRaw: rspRaw,
GuessResponseEncoding: Chardet(rspRaw),
RequestRaw: resultRequest,
ExtractedResults: extractResults,
MatchedByMatcher: httpTPLmatchersResult,
HitColor: req.GetHitColor(),
}
rsp.UUID = uuid.New().String()
rsp.Timestamp = start.Unix()
rsp.DurationMs = time.Now().Sub(start).Milliseconds()
requestIns, err := lowhttp.ParseBytesToHttpRequest(resultRequest)
if err != nil {
return nil, err
}
rsp.Host = requestIns.Header.Get("Host")
if rsp.Host == "" {
rsp.Host = requestIns.Host
}
responseIns, err := lowhttp.ParseBytesToHTTPResponse(rspRaw)
if responseIns != nil {
rsp.Ok = true
rsp.StatusCode = int32(responseIns.StatusCode)
rsp.ContentType = responseIns.Header.Get("Content-Type")
var bodyLen int64 = 0
if responseIns.Body != nil {
raw, _ := ioutil.ReadAll(responseIns.Body)
bodyLen = int64(len(raw))
}
rsp.BodyLength = bodyLen
// 解析 Headers
for k, vs := range responseIns.Header {
for _, v := range vs {
rsp.Headers = append(rsp.Headers, &ypb.HTTPHeader{
Header: k,
Value: v,
})
}
}
}
return rsp, nil
}
func (s *Server) PreloadHTTPFuzzerParams(ctx context.Context, req *ypb.PreloadHTTPFuzzerParamsRequest) (*ypb.PreloadHTTPFuzzerParamsResponse, error) {
vars := httptpl.NewVars()
for _, k := range req.GetParams() {
if k.GetType() == "raw" {
vars.Set(k.GetKey(), k.GetValue())
continue
}
vars.AutoSet(k.GetKey(), k.GetValue())
}
var results []*ypb.FuzzerParamItem
for k, v := range vars.ToMap() {
results = append(results, &ypb.FuzzerParamItem{
Key: k,
Value: utils.InterfaceToString(v),
Type: "raw",
})
}
return &ypb.PreloadHTTPFuzzerParamsResponse{Values: results}, nil
}
func (s *Server) HTTPFuzzer(req *ypb.FuzzerRequest, stream ypb.Yak_HTTPFuzzerServer) (finalError error) {
defer func() {
if err := recover(); err != nil {
finalError = utils.Errorf("panic from httpfuzzer: %v", err)
utils.PrintCurrentGoroutineRuntimeStack()
}
}()
// retry
isRetry := req.GetRetryTaskID() > 0
// pause
pauseTaskID := req.GetPauseTaskID()
isPause := pauseTaskID > 0
// 暂停任务
var sw *utils.Switch
if !isPause {
sw = utils.NewSwitch(true)
go func() {
select {
case <-stream.Context().Done():
sw.SwitchTo(true)
}
}()
} else {
i, ok := _FuzzerTaskSwitchMap.Load(uint(pauseTaskID))
if ok {
sw = i.(*utils.Switch)
sw.SwitchTo(!req.GetIsPause())
return nil
} else {
return utils.Errorf("pause task[%d] not found", pauseTaskID)
}
}
// hot code
var extraOpt []mutate.FuzzConfigOpt
if strings.TrimSpace(req.GetHotPatchCode()) != "" {
extraOpt = append(extraOpt, yak.Fuzz_WithHotPatch(stream.Context(), req.GetHotPatchCode()))
}
/*
Plugins
*/
var pocs []*yakit.YakScript
for _, i := range req.GetYamlPoCNames() {
poc, err := yakit.GetYakScriptByName(consts.GetGormProfileDatabase(), i)
if err != nil {
log.Errorf("get yaml poc[%v] failed: %s", i, err)
continue
}
if poc.Type != "nuclei" {
log.Errorf("poc[%s] is not yaml poc: %s", i, poc.Type)
continue
}
pocs = append(pocs, poc)
}
var batchTarget string
if req.GetBatchTargetFile() {
if ret := utils.GetFirstExistedFile(string(req.BatchTarget)); ret != "" {
fp, err := os.Open(ret)
if err != nil {
return utils.Errorf("open batch target file failed: %s", err)
}
raw, _ := io.ReadAll(fp)
fp.Close()
batchTarget = strings.TrimSpace(string(raw))
} else {
return utils.Errorf("batch target file not found: %s", req.GetBatchTarget())
}
} else {
batchTarget = string(req.GetBatchTarget())
}
swg := utils.NewSizedWaitGroup(int(req.GetConcurrent()))
defer swg.Wait()
feedbackWg := new(sync.WaitGroup)
defer func() {
feedbackWg.Wait()
}()
feedbackResponse := func(rsp *ypb.FuzzerResponse, skipPoC bool) error {
sw.WaitUntilOpen()
err := stream.Send(rsp)
if err != nil {
return err
}
if skipPoC {
return nil
}
feedbackWg.Add(1)
defer func() {
defer feedbackWg.Done()
for _, p := range pocs {
poc := p
err := swg.AddWithContext(stream.Context())
if err != nil {
break
}
go func() {
defer swg.Done()
defer func() {
if err := recover(); err != nil {
spew.Dump(err)
utils.PrintCurrentGoroutineRuntimeStack()
}
}()
httptpl.ScanPacket(
rsp.RequestRaw, lowhttp.WithHttps(rsp.IsHTTPS),
httptpl.WithTemplateRaw(poc.Content),
lowhttp.WithResponseCallback(func(i *lowhttp.LowhttpResponse) {
err := stream.Send(ConvertLowhttpResponseToFuzzerResponseBase(i))
if err != nil {
log.Errorf("yaml poc send failed")
}
}),
httptpl.WithOnRisk(rsp.Url, func(i *yakit.Risk) {
log.Infof("found risk: %s", i.Title)
}),
)
}()
}
}()
return nil
}
historyID := req.GetHistoryWebFuzzerId()
reMatch := req.GetReMatch()
if historyID > 0 {
// 回溯找到所有之前的包,进行整合
oldIDs, err := yakit.GetWebFuzzerTasksIDByRetryRootID(s.GetProjectDatabase(), uint(historyID))
// 找到最新的任务并排除
latestID := lo.Max(oldIDs)
if !reMatch {
oldIDs = lo.Filter(oldIDs, func(item uint, _ int) bool {
return item != latestID
})
}
if err != nil {
log.Errorf("get old web fuzzer success response failed: %s", err)
} else {
// 重匹配的分支
if reMatch {
if len(oldIDs) == 0 { // 尝试修复
oldIDs = []uint{uint(historyID)}
}
newHitColor := req.GetHitColor()
httpTplMatcher := make([]*httptpl.YakMatcher, len(req.GetMatchers()))
httpTplExtractor := make([]*httptpl.YakExtractor, len(req.GetExtractors()))
haveHTTPTplMatcher := len(httpTplMatcher) > 0
haveHTTPTplExtractor := len(httpTplExtractor) > 0
if haveHTTPTplExtractor {
for i, e := range req.GetExtractors() {
httpTplExtractor[i] = httptpl.NewExtractorFromGRPCModel(e)
}
}
if haveHTTPTplMatcher {
for i, m := range req.GetMatchers() {
httpTplMatcher[i] = httptpl.NewMatcherFromGRPCModel(m)
}
}
cond := "and"
if ret := strings.ToLower(req.GetMatchersCondition()); ret == "or" {
cond = ret
}
// new Matcher
ins := &httptpl.YakMatcher{
SubMatcherCondition: cond,
SubMatchers: httpTplMatcher,
}
_, _, getMirrorHTTPFlowParams := yak.MutateHookCaller(req.GetHotPatchCode())
var extractorResults []*ypb.KVPair
for resp := range yakit.YieldWebFuzzerResponseByTaskIDs(s.GetProjectDatabase(), stream.Context(), oldIDs, true) {
respModel, _ := resp.ToGRPCModel()
if haveHTTPTplExtractor { // 提取器提取参数
params := make(map[string]any)
for _, extractor := range httpTplExtractor {
vars, err := extractor.Execute(respModel.ResponseRaw, params)
if err != nil {
log.Errorf("extractor execute failed: %s", err)
continue
}
for k, v := range vars {
params[k] = v
extractorResults = append(extractorResults, &ypb.KVPair{Key: k, Value: httptpl.ExtractResultToString(v)}) // 提取器 参数
}
}
}
for mergedParams := range s.PreRenderVariables(stream.Context(), req.GetParams(), req.GetIsHTTPS(), req.GetIsGmTLS(), false) {
existedParams := make(map[string]string) // 传入的参数
if mergedParams != nil {
for k, v := range utils.InterfaceToMap(mergedParams) {
existedParams[k] = strings.Join(v, ",")
}
}
if respModel != nil && getMirrorHTTPFlowParams != nil {
for k, v := range getMirrorHTTPFlowParams(respModel.RequestRaw, respModel.ResponseRaw, existedParams) { // 热加载的参数
extractorResults = append(extractorResults, &ypb.KVPair{Key: utils.EscapeInvalidUTF8Byte([]byte(k)), Value: utils.EscapeInvalidUTF8Byte([]byte(v))})
}
}
matcherParams := utils.CopyMapInterface(mergedParams)
for _, kv := range extractorResults { // 合并
matcherParams[kv.GetKey()] = kv.GetValue()
}
httpTPLmatchersResult, err := ins.Execute(
&lowhttp.LowhttpResponse{
RawPacket: respModel.ResponseRaw,
TraceInfo: &lowhttp.LowhttpTraceInfo{
ServerTime: time.Duration(respModel.DurationMs),
},
},
matcherParams)
if err != nil {
log.Errorf("convert web fuzzer response to grpc model failed: %s", err)
continue
}
if httpTPLmatchersResult {
respModel.MatchedByMatcher = true
respModel.HitColor = newHitColor
break
}
}
respModel.TaskId = int64(historyID)
feedbackResponse(respModel, true)
}
} else {
// 只展示之前成功的包
if len(oldIDs) > 0 {
for resp := range yakit.YieldWebFuzzerResponseByTaskIDs(s.GetProjectDatabase(), stream.Context(), oldIDs, true) {
respModel, err := resp.ToGRPCModel()
if err != nil {
log.Errorf("convert web fuzzer response to grpc model failed: %s", err)
continue
}
feedbackResponse(respModel, true)
}
}
// 展示最新任务的所有包
for resp := range yakit.YieldWebFuzzerResponses(s.GetProjectDatabase(), stream.Context(), int(latestID)) {
respModel, err := resp.ToGRPCModel()
if err != nil {
log.Errorf("convert web fuzzer response to grpc model failed: %s", err)
continue
}
feedbackResponse(respModel, true)
}
}
}
return nil
}
if !isRetry && req.GetRequest() == "" && len(req.GetRequestRaw()) <= 0 {
return utils.Errorf("empty request is not allowed")
}
proxies := utils.StringArrayFilterEmpty(utils.PrettifyListFromStringSplited(req.GetProxy(), ","))
concurrent := req.GetConcurrent()
if concurrent <= 0 {
concurrent = 20
}
timeoutSeconds := req.GetPerRequestTimeoutSeconds()
if timeoutSeconds <= 0 {
timeoutSeconds = 10
}
task, err := yakit.SaveWebFuzzerTask(s.GetProjectDatabase(), req, 0, false, "executing...")
if err != nil {
return utils.Errorf("save to web fuzzer to database failed: %s", err)
}
// 重试任务
var retryRootID uint
taskID := task.ID
task.FuzzerIndex = req.GetFuzzerIndex()
task.FuzzerTabIndex = req.GetFuzzerTabIndex()
if !isRetry {
task.RetryRootID = task.ID
} else {
retryRootID, err = yakit.GetWebFuzzerRetryRootID(s.GetProjectDatabase(), uint(req.RetryTaskID))
if err != nil {
return err
}
task.RetryRootID = retryRootID
}
// 存储重试任务的开关
_FuzzerTaskSwitchMap.Store(task.ID, sw)
defer func() {
if db := s.GetProjectDatabase().Save(task); db.Error != nil {
log.Errorf("update web fuzzer task failed: %s", db.Error)
}
}()
/* 丢包过滤器 */
includeStatusCodeFilter := utils.NewPortsFilter()
var maxBody, minBody int64
var regexps, keywords []string
filter := req.GetFilter()
if filter != nil {
includeStatusCodeFilter.Add(filter.GetStatusCode()...)
regexps = filter.GetRegexps()
keywords = filter.GetKeywords()
minBody = filter.GetMinBodySize()
maxBody = filter.GetMaxBodySize()
}
var rawRequest []byte
if !isRetry {
if len(req.GetRequestRaw()) > 0 {
rawRequest = req.GetRequestRaw()
} else {
rawRequest = []byte(req.GetRequest())
}
}
// 保存 request 中 host/port
defer func() {
if req.GetActualAddr() != "" {
task.Host = req.GetActualAddr()
} else {
results := extractHostRegexp.FindStringSubmatch(string(rawRequest))
if len(results) > 1 {
task.Host = results[1]
if len(task.Host) > 40 {
task.Host = task.Host[:40] + "..."
}
}
}
_, task.Port, _ = utils.ParseStringToHostPort(task.Host)
}()
inStatusCode := utils.ParseStringToPorts(req.GetRetryInStatusCode())
notInStatusCode := utils.ParseStringToPorts(req.GetRetryNotInStatusCode())
httpTplMatcher := make([]*httptpl.YakMatcher, len(req.GetMatchers()))
httpTplExtractor := make([]*httptpl.YakExtractor, len(req.GetExtractors()))
haveHTTPTplMatcher := len(httpTplMatcher) > 0
haveHTTPTplExtractor := len(httpTplExtractor) > 0
if haveHTTPTplExtractor {
for i, e := range req.GetExtractors() {
httpTplExtractor[i] = httptpl.NewExtractorFromGRPCModel(e)
}
}
if haveHTTPTplMatcher {
for i, m := range req.GetMatchers() {
httpTplMatcher[i] = httptpl.NewMatcherFromGRPCModel(m)
}
}
// 重试处理,通过taskid找到所有失败的发送包
var iInput any
retryPayloadsMap := make(map[string][]string, 0) // key 是原始请求报文,value 是重试的payload,我们需要将重试的payload绑定回去
// 这里可能会出现原始请求报文一样的情况,但是这样也是因为payload没有而导致的,例如{{repeat(10)}}
if !isRetry {
// 插入 {{repeat(n)}}的fuzz标签
if req.GetRepeatTimes() > 0 {
var buf bytes.Buffer
buf.WriteString("{{repeat(" + fmt.Sprint(req.GetRepeatTimes()) + ")}}")
buf.Write(rawRequest)
rawRequest = buf.Bytes()
}
iInput = rawRequest
} else {
// 找到上次任务的包
failedResponses := make([]*yakit.WebFuzzerResponse, 0)
for resp := range yakit.YieldWebFuzzerResponses(s.GetProjectDatabase(), stream.Context(), int(req.RetryTaskID)) {
if !resp.OK {
failedResponses = append(failedResponses, resp)
retryPayloadsMap[resp.Request] = strings.Split(resp.Payload, ",")
}
}
if len(failedResponses) == 0 {
return utils.Errorf("no failed web fuzzer request found")
}
// 回溯找到所有之前重试成功的包
oldIDs, err := yakit.GetWebFuzzerTasksIDByRetryRootID(s.GetProjectDatabase(), retryRootID)
if err != nil {
log.Errorf("get old web fuzzer success response failed: %s", err)
} else {
for resp := range yakit.YieldWebFuzzerResponseByTaskIDs(s.GetProjectDatabase(), stream.Context(), oldIDs, true) {
respModel, err := resp.ToGRPCModel()
if err != nil {
log.Errorf("convert web fuzzer response to grpc model failed: %s", err)
continue
}
feedbackResponse(respModel, true)
}
}
iInput = lo.Map(failedResponses, func(i *yakit.WebFuzzerResponse, _ int) []byte {
return utils.UnsafeStringToBytes(i.Request)
})
}
requestCount := 0
if req.GetForceOnlyOneResponse() {
requestCount = 1
}
maxBodySize := 5 * 1024 * 1024
if req.GetMaxBodySize() > 1024 {
maxBodySize = int(req.GetMaxBodySize())
}
fuzzerRequestSwg := utils.NewSizedWaitGroup(int(concurrent))
executeBatchRequestsWithParams := func(mergedParams map[string]any) (retErr error) {
defer func() {
if err := recover(); err != nil {
retErr = utils.Errorf("panic from grpc.httpfuzzer executeBatchRequestsWithParams: %v", err)
utils.Debug(func() {
utils.PrintCurrentGoroutineRuntimeStack()
})
}
}()
httpPoolOpts := []mutate.HttpPoolConfigOption{
mutate.WithPoolOpt_FuzzParams(mergedParams),
mutate.WithPoolOpt_ExtraFuzzOptions(extraOpt...),
mutate.WithPoolOpt_Timeout(timeoutSeconds),
mutate.WithPoolOpt_Proxy(proxies...),
mutate.WithPoolOpt_BatchTarget(batchTarget),
// mutate.WithPoolOpt_Concurrent(int(concurrent)),
mutate.WithPoolOpt_SizedWaitGroup(fuzzerRequestSwg),
mutate.WithPoolOpt_Addr(req.GetActualAddr(), req.GetIsHTTPS()),
mutate.WithPoolOpt_RawMode(true),
mutate.WithPoolOpt_Https(req.GetIsHTTPS()),
mutate.WithPoolOpt_GmTLS(req.GetIsGmTLS()),
mutate.WithPoolOpt_Context(stream.Context()),
mutate.WithPoolOpt_FollowJSRedirect(req.GetFollowJSRedirect()),
mutate.WithPoolOpt_RedirectTimes(int(req.GetRedirectTimes())),
mutate.WithPoolOpt_NoFollowRedirect(req.GetNoFollowRedirect()),
mutate.WithPoolOpt_noFixContentLength(req.GetNoFixContentLength()),
// mutate.WithPoolOpt_ExtraMutateConditionGetter(yak.MutateWithParamsGetter(req.GetHotPatchCodeWithParamGetter())),
// mutate.WithPoolOpt_ExtraMutateCondition(yak.MutateWithYaklang(req.GetHotPatchCode())),
mutate.WithPoolOpt_DelayMinSeconds(req.GetDelayMinSeconds()),
mutate.WithPoolOPt_DelayMaxSeconds(req.GetDelayMaxSeconds()),
mutate.WithPoolOpt_HookCodeCaller(yak.MutateHookCaller(req.GetHotPatchCode())),
mutate.WithPoolOpt_Source("webfuzzer"),
mutate.WithPoolOpt_RetryTimes(int(req.GetMaxRetryTimes())),
mutate.WithPoolOpt_MaxContentLength(maxBodySize),
mutate.WithPoolOpt_RetryInStatusCode(inStatusCode),
mutate.WithPoolOpt_RetryNotInStatusCode(notInStatusCode),
mutate.WithPoolOpt_RetryWaitTime(req.GetRetryWaitSeconds()),
mutate.WithPoolOpt_RetryMaxWaitTime(req.GetRetryMaxWaitSeconds()),
mutate.WithPoolOpt_DNSServers(req.GetDNSServers()),
mutate.WithPoolOpt_EtcHosts(req.GetEtcHosts()),
mutate.WithPoolOpt_NoSystemProxy(req.GetNoSystemProxy()),
mutate.WithPoolOpt_RequestCountLimiter(requestCount),
mutate.WithPoolOpt_MutateWithMethods(req.GetMutateMethods()),
}
fuzzMode := req.GetFuzzTagMode() // ""/"close"/"standard"/"legacy"
forceFuzz := req.GetForceFuzz() // true/false
if fuzzMode == "" { // 以forceFuzz为准
if forceFuzz {
fuzzMode = "standard"
} else {
fuzzMode = "close"
}
}
mutate.WithPoolOpt_ForceFuzzDangerous(req.GetForceFuzz())
if isRetry {
// 重试的时候,不需要渲染fuzztag
fuzzMode = "close"
}
switch fuzzMode {
case "close":
httpPoolOpts = append(httpPoolOpts, mutate.WithPoolOpt_ForceFuzz(false))
case "standard":
httpPoolOpts = append(httpPoolOpts, mutate.WithPoolOpt_ForceFuzz(true))
httpPoolOpts = append(httpPoolOpts, mutate.WithPoolOpt_ForceFuzzDangerous(true))
case "simple", "legacy":
httpPoolOpts = append(httpPoolOpts, mutate.WithPoolOpt_ForceFuzz(true))
httpPoolOpts = append(httpPoolOpts, mutate.WithPoolOpt_ForceFuzzDangerous(true))
httpPoolOpts = append(httpPoolOpts, mutate.WithPoolOpt_ExtraFuzzOptions(mutate.Fuzz_WithSimple(true)))
}
if req.GetFuzzTagSyncIndex() {
httpPoolOpts = append(httpPoolOpts, mutate.WithPoolOpt_ExtraFuzzOptions(mutate.Fuzz_SyncTag(true)))
}
if !isPause {
httpPoolOpts = append(httpPoolOpts, mutate.WithPoolOpt_ExternSwitch(sw))
}
res, err := mutate.ExecPool(
iInput,
httpPoolOpts...,
)
if err != nil {
task.Ok = false
task.Reason = utils.Errorf("exec http pool failed: %s", err).Error()
return err
}
// 可以用于计算相似度
var firstHeader, firstBody []byte
for result := range res {
task.HTTPFlowTotal++
var payloads []string
if !isRetry {
payloads = make([]string, len(result.Payloads))
for i, payload := range result.Payloads {
if len(payload) > 100 {
payload = payload[:100] + "..."
}
payloads[i] = utils.ParseStringToVisible(payload)
}
} else {
payloads, _ = retryPayloadsMap[utils.UnsafeBytesToString(result.RequestRaw)]
}
var extractorResults []*ypb.KVPair
if result != nil && result.ExtraInfo != nil {
for k, v := range result.ExtraInfo {
extractorResults = append(extractorResults, &ypb.KVPair{Key: utils.EscapeInvalidUTF8Byte([]byte(k)), Value: utils.EscapeInvalidUTF8Byte([]byte(v))})
}
}
if result.Error != nil {
rsp := &ypb.FuzzerResponse{}
rsp.RequestRaw = result.RequestRaw
rsp.UUID = uuid.New().String()
rsp.Url = utils.EscapeInvalidUTF8Byte([]byte(result.Url))
rsp.Ok = false
rsp.Reason = result.Error.Error()
rsp.TaskId = int64(taskID)
rsp.Payloads = payloads
if result.LowhttpResponse != nil && result.LowhttpResponse.TraceInfo != nil {
rsp.TotalDurationMs = result.LowhttpResponse.TraceInfo.TotalTime.Milliseconds()
rsp.DurationMs = result.LowhttpResponse.TraceInfo.ServerTime.Milliseconds()
rsp.FirstByteDurationMs = result.LowhttpResponse.TraceInfo.ServerTime.Milliseconds()
rsp.DNSDurationMs = result.LowhttpResponse.TraceInfo.DNSTime.Milliseconds()
rsp.Proxy = result.LowhttpResponse.Proxy
rsp.RemoteAddr = result.LowhttpResponse.RemoteAddr
}
task.HTTPFlowFailedCount++
yakit.SaveWebFuzzerResponse(s.GetProjectDatabase(), int(task.ID), rsp)
_ = feedbackResponse(rsp, false)
continue
}
if haveHTTPTplExtractor {
params := make(map[string]any)
for _, extractor := range httpTplExtractor {
vars, err := extractor.Execute(result.ResponseRaw, params)
if err != nil {
log.Errorf("extractor execute failed: %s", err)
continue
}
for k, v := range vars {
params[k] = v
extractorResults = append(extractorResults, &ypb.KVPair{Key: k, Value: httptpl.ExtractResultToString(v)})
}
}
}
extractorResultsOrigin := extractorResults
for k, v := range mergedParams {
extractorResults = append(extractorResults, &ypb.KVPair{
Key: k, Value: utils.EscapeInvalidUTF8Byte(codec.AnyToBytes(v)),
},
)
}
var httpTPLmatchersResult bool
if haveHTTPTplMatcher && result.LowhttpResponse != nil {
cond := "and"
switch ret := strings.ToLower(req.GetMatchersCondition()); ret {
case "or", "and":
cond = ret
default:
}
ins := &httptpl.YakMatcher{
SubMatcherCondition: cond,
SubMatchers: httpTplMatcher,
}
matcherParams := utils.CopyMapInterface(mergedParams)
for _, kv := range extractorResultsOrigin {
matcherParams[kv.GetKey()] = kv.GetValue()
}
httpTPLmatchersResult, err = ins.Execute(result.LowhttpResponse, matcherParams)
if finalError != nil {
log.Errorf("httptpl.YakMatcher execute failed: %s", err)
}
}
_, body := lowhttp.SplitHTTPHeadersAndBodyFromPacket(result.ResponseRaw)
var tooLarge bool
var tooLargeBodyFile string
var tooLargeHeaderFile string
if bodyLength := len(body); bodyLength > maxBodySize {
tooLarge = true
uid := uuid.New().String()
suffix := fmt.Sprintf("%v_%v",
time.Now().Format(utils.DatetimePretty()),
uid,
)
bodyFp, _ := consts.TempFile(fmt.Sprintf("webfuzzer_large_body_%v.txt", suffix))
if bodyFp != nil {
bodyFp.Write(body)
bodyFp.Close()
tooLargeBodyFile = bodyFp.Name()
}
headerFp, _ := consts.TempFile(fmt.Sprintf("webfuzzer_large_header_%v.txt", suffix))
if headerFp != nil {
headerFp.Write(result.ResponseRaw)
headerFp.Close()
tooLargeHeaderFile = headerFp.Name()
}
if bodyLength > 5*1024*1024 {
var buf bytes.Buffer
buf.Write(body[:1024*1024])
buf.WriteString("...\n...\n...\n(response > 5M)\n...\n...\n...")
buf.Write(body[bodyLength-1024*1024:])
body = buf.Bytes()
}
}
if !req.GetNoFixContentLength() && (result.Request != nil && result.Request.ProtoMajor != 2) { // no fix for h2 rsp
result.ResponseRaw = lowhttp.ReplaceHTTPPacketBody(result.ResponseRaw, body, false)
result.Response, _ = lowhttp.ParseStringToHTTPResponse(string(result.ResponseRaw))
}
if len(result.RequestRaw) > 1*1024*1024 {
result.RequestRaw = result.RequestRaw[:1*1024*1024]
result.RequestRaw = append(result.RequestRaw, []byte("...(request > 1M) chunked by yakit web fuzzer")...)
}
task.HTTPFlowSuccessCount++
rsp := &ypb.FuzzerResponse{
Url: utils.EscapeInvalidUTF8Byte([]byte(result.Url)),
Method: utils.EscapeInvalidUTF8Byte([]byte(result.Request.Method)),
ResponseRaw: result.ResponseRaw,
GuessResponseEncoding: Chardet(result.ResponseRaw),
RequestRaw: result.RequestRaw,
Payloads: payloads,
IsHTTPS: strings.HasPrefix(strings.ToLower(result.Url), "https://"),
ExtractedResults: extractorResults,
MatchedByMatcher: httpTPLmatchersResult,
HitColor: req.GetHitColor(),
IsTooLargeResponse: tooLarge,
TooLargeResponseBodyFile: tooLargeBodyFile,
TooLargeResponseHeaderFile: tooLargeHeaderFile,
DisableRenderStyles: len(body) > 1024*1024*2,
}
redirectPacket := result.LowhttpResponse.RedirectRawPackets
if result.LowhttpResponse != nil {
// redirect
for _, f := range redirectPacket {
rsp.RedirectFlows = append(rsp.RedirectFlows, &ypb.RedirectHTTPFlow{
IsHttps: f.IsHttps,
Request: f.Request,
Response: f.Response,
})
}
}
// 处理额外时间
if result.LowhttpResponse != nil && result.LowhttpResponse.TraceInfo != nil {
rsp.TotalDurationMs = result.LowhttpResponse.TraceInfo.TotalTime.Milliseconds()
rsp.DurationMs = result.LowhttpResponse.TraceInfo.ServerTime.Milliseconds()
rsp.FirstByteDurationMs = result.LowhttpResponse.TraceInfo.ServerTime.Milliseconds()
rsp.DNSDurationMs = result.LowhttpResponse.TraceInfo.DNSTime.Milliseconds()
rsp.Proxy = result.LowhttpResponse.Proxy
rsp.RemoteAddr = result.LowhttpResponse.RemoteAddr
}
if rsp.ResponseRaw != nil {
// 处理结果,相似度
header, body := lowhttp.SplitHTTPHeadersAndBodyFromPacket(rsp.ResponseRaw)
if firstHeader == nil {
log.Debugf("start to set first header[%v]...", result.Url)
firstHeader = []byte(header)
rsp.HeaderSimilarity = 1.0
} else {
rsp.HeaderSimilarity = utils.CalcSimilarity(firstHeader, []byte(header))
}
if firstBody == nil {
log.Debugf("start to set first body[%v]...", result.Url)
firstBody = body
rsp.BodySimilarity = 1.0
} else {
rsp.BodySimilarity = utils.CalcSimilarity(firstBody, body)
}
}
rsp.UUID = uuid.New().String()
rsp.Timestamp = result.Timestamp
rsp.DurationMs = result.DurationMs
rsp.Host = utils.EscapeInvalidUTF8Byte([]byte(result.Request.Header.Get("Host")))
if rsp.Host == "" {
rsp.Host = result.Request.Host
}
rsp.Host = utils.EscapeInvalidUTF8Byte([]byte(utils.ParseStringToVisible(result.Request.Host)))
if result.Response != nil {
rsp.Ok = true
rsp.StatusCode = int32(result.Response.StatusCode)
rsp.ContentType = utils.ParseStringToVisible(result.Response.Header.Get("Content-Type"))
var bodyLen int64 = 0
if result.Response.Body != nil {
raw, _ := ioutil.ReadAll(result.Response.Body)
bodyLen = int64(len(raw))
}
rsp.BodyLength = bodyLen
// 解析 Headers
for k, vs := range result.Response.Header {
for _, v := range vs {
rsp.Headers = append(rsp.Headers, &ypb.HTTPHeader{
Header: utils.ParseStringToVisible(k),
Value: utils.ParseStringToVisible(v),
})
}
}
}
if rsp.StatusCode > 0 {
// 通过长度过滤
if minBody <= maxBody && (minBody > 0 || maxBody > 0) {
if maxBody >= rsp.BodyLength && minBody <= rsp.BodyLength {
rsp.MatchedByFilter = true
}
}