-
Notifications
You must be signed in to change notification settings - Fork 46
/
yaktpl_matcher.go
374 lines (344 loc) · 9.42 KB
/
yaktpl_matcher.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
package httptpl
import (
"fmt"
"regexp"
"strings"
"time"
"github.com/yaklang/yaklang/common/go-funk"
"github.com/yaklang/yaklang/common/log"
"github.com/yaklang/yaklang/common/utils"
"github.com/yaklang/yaklang/common/utils/lowhttp"
"github.com/yaklang/yaklang/common/yak/yaklib/codec"
"github.com/yaklang/yaklang/common/yakgrpc/ypb"
)
func NewMatcherFromGRPCModel(m *ypb.HTTPResponseMatcher) *YakMatcher {
return &YakMatcher{
MatcherType: m.GetMatcherType(),
ExprType: m.GetExprType(),
Scope: m.GetScope(),
Condition: m.GetCondition(),
Group: m.GetGroup(),
GroupEncoding: m.GetGroupEncoding(),
Negative: m.GetNegative(),
SubMatcherCondition: m.GetSubMatcherCondition(),
SubMatchers: funk.Map(m.GetSubMatchers(), NewMatcherFromGRPCModel).([]*YakMatcher),
}
}
type YakMatcher struct {
// status
// content_length
// binary
// word
// regexp
// expr
Id int // first request means 1 second request means 2
MatcherType string
/*
nuclei-dsl
all_headers
status_code
content_length
body
raw
*/
ExprType string
// status
// header
// body
// raw
// interactsh_protocol
Scope string
// or
// and
Condition string
Group []string
GroupEncoding string
Negative bool
// or / and
SubMatcherCondition string
SubMatchers []*YakMatcher
// record poc name / script name or some verbose
TemplateName string
}
var matcherResponseCache = utils.NewTTLCache[string](1 * time.Minute)
func cacheHash(rsp []byte, location string) string {
return utils.CalcSha1(rsp, location)
}
func (y *YakMatcher) ExecuteRawResponse(rsp []byte, vars map[string]interface{}, suf ...string) (bool, error) {
return y.Execute(&RespForMatch{RawPacket: rsp}, vars, suf...)
}
func (y *YakMatcher) ExecuteRaw(rsp []byte, vars map[string]interface{}, suf ...string) (bool, error) {
return y.ExecuteRawWithConfig(nil, rsp, vars, suf...)
}
func (y *YakMatcher) ExecuteRawWithConfig(config *Config, rsp []byte, vars map[string]interface{}, suf ...string) (bool, error) {
if len(y.SubMatchers) > 0 {
if strings.TrimSpace(strings.ToLower(y.SubMatcherCondition)) == "or" {
for _, matcher := range y.SubMatchers {
if b, _ := matcher.ExecuteRawWithConfig(config, rsp, vars, suf...); b {
return true, nil
}
}
return false, nil
} else {
for _, matcher := range y.SubMatchers {
if b, _ := matcher.ExecuteRawWithConfig(config, rsp, vars, suf...); !b {
return false, nil
}
}
return true, nil
}
}
if y.Negative {
res, err := y.executeRaw(y.TemplateName, config, rsp, 0, vars, suf...)
if err != nil {
return false, err
}
return !res, err
}
return y.executeRaw(y.TemplateName, config, rsp, 0, vars, suf...)
}
type RespForMatch struct {
RawPacket []byte
Duration float64
}
func (y *YakMatcher) Execute(rsp *RespForMatch, vars map[string]interface{}, suf ...string) (bool, error) {
return y.ExecuteWithConfig(nil, rsp, vars, suf...)
}
func (y *YakMatcher) ExecuteWithConfig(config *Config, rsp *RespForMatch, vars map[string]interface{}, suf ...string) (bool, error) {
if len(y.SubMatchers) > 0 {
if strings.TrimSpace(strings.ToLower(y.SubMatcherCondition)) == "or" {
for _, matcher := range y.SubMatchers {
if b, _ := matcher.ExecuteWithConfig(config, rsp, vars, suf...); b {
return true, nil
}
}
return false, nil
} else {
for _, matcher := range y.SubMatchers {
if b, _ := matcher.ExecuteWithConfig(config, rsp, vars, suf...); !b {
return false, nil
}
}
return true, nil
}
}
if y.Negative {
res, err := y.execute(config, rsp, vars, suf...)
if err != nil {
return false, err
}
return !res, err
}
return y.execute(config, rsp, vars, suf...)
}
func (y *YakMatcher) executeRaw(name string, config *Config, rsp []byte, duration float64, vars map[string]any, sufs ...string) (bool, error) {
isExpr := false
var reverseProto []string
getMaterial := func() string {
if isExpr {
return string(rsp)
}
var material string
scope := strings.ToLower(y.Scope)
scopeHash := cacheHash(rsp, scope)
material, ok := matcherResponseCache.Get(scopeHash)
if !ok {
switch scope {
case "status", "status_code":
material = utils.InterfaceToString(lowhttp.ExtractStatusCodeFromResponse(rsp))
case "header":
header, _ := lowhttp.SplitHTTPHeadersAndBodyFromPacket(rsp)
material = header
case "body":
_, body := lowhttp.SplitHTTPHeadersAndBodyFromPacket(rsp)
material = string(body)
case "interactsh_protocol", "oob_protocol":
var oobTimeout float64
if config == nil || config.OOBTimeout <= 0 {
oobTimeout = 5
}
if config == nil {
log.Errorf("oob feature need config is nil")
return ""
}
if !utils.StringSliceContain(reverseProto, "dns") {
var checkingDNS func(string, ...float64) bool
if config == nil || config.OOBRequireCheckingTrigger == nil {
checkingDNS = CheckingDNSLogOOB
} else {
checkingDNS = config.OOBRequireCheckingTrigger
}
token, ok := vars["reverse_dnslog_token"]
if ok {
if checkingDNS(strings.ToLower(fmt.Sprint(token)), oobTimeout) {
reverseProto = append(reverseProto, "dns")
}
}
}
material = strings.Join(reverseProto, ",")
case "raw":
fallthrough
default:
material = string(rsp)
}
}
matcherResponseCache.Set(scopeHash, material)
return material
}
matcherFunc := func(s string, sub string) bool {
return strings.Contains(s, sub)
}
condition := strings.TrimSpace(strings.ToLower(y.Condition))
switch y.MatcherType {
case "status_code", "status":
statusCode := lowhttp.ExtractStatusCodeFromResponse(rsp)
if statusCode == 0 {
return false, utils.Errorf("extract status code failed: %s", string(rsp))
}
ints := utils.ParseStringToInts(strings.Join(y.Group, ","))
if len(ints) <= 0 {
return false, nil
}
switch condition {
case "and":
for _, i := range ints {
if i != statusCode {
return false, nil
}
}
return true, nil
case "or":
fallthrough
default:
for _, i := range ints {
if i == statusCode {
return true, nil
}
}
return false, nil
}
case "size", "content_length", "content-length":
log.Warnf("content-length is untrusted, you should avoid using content-length!")
header, body := lowhttp.SplitHTTPHeadersAndBodyFromPacket(rsp)
_ = header
contentLength := len(body)
ints := utils.ParseStringToInts(strings.Join(y.Group, ","))
if len(ints) <= 0 {
return false, nil
}
switch strings.TrimSpace(strings.ToLower(y.Condition)) {
case "and":
for _, i := range ints {
if i != contentLength {
return false, nil
}
}
return true, nil
case "or":
fallthrough
default:
for _, i := range ints {
if i == contentLength {
return true, nil
}
}
return false, nil
}
case "binary":
y.GroupEncoding = "hex"
fallthrough
case "word", "contains":
matcherFunc = func(s string, sub string) bool {
if vars == nil {
return strings.Contains(s, sub)
} else {
if strings.Contains(sub, "{{") && strings.Contains(sub, "}}") {
results, err := ExecNucleiTag(sub, vars)
if err != nil {
return strings.Contains(s, results)
}
}
}
return strings.Contains(s, sub)
}
case "regexp", "re", "regex":
matcherFunc = func(s string, sub string) bool {
result, err := regexp.MatchString(sub, s)
if err != nil {
log.Errorf("[%v] regexp match failed: %s, origin regex: %v", name, err, sub)
return false
}
return result
}
case "expr", "dsl", "cel":
isExpr = true
switch y.ExprType {
case "nuclei-dsl", "nuclei":
dslEngine := NewNucleiDSLYakSandbox()
matcherFunc = func(fullResponse string, sub string) bool {
loadVars := LoadVarFromRawResponse(rsp, duration, sufs...)
// 加载 resp 中的变量
for k, v := range vars { // 合并若有重名以 vars 为准
loadVars[k] = v
}
result, err := dslEngine.ExecuteAsBool(sub, loadVars)
if err != nil {
log.Errorf("[%v] dsl engine execute as bool failed: %s", name, err)
return false
}
return result
}
case "xray-cel":
return false, utils.Errorf("xray-cel is not supported")
default:
return false, utils.Errorf("unknown expr type: %s", y.ExprType)
}
default:
return false, utils.Errorf("unknown matcher type: %s", y.MatcherType)
}
material := getMaterial()
var groups []string
for _, wordRaw := range y.Group {
word := wordRaw
switch strings.TrimSpace(strings.ToLower(y.GroupEncoding)) {
case "hex":
raw, err := codec.DecodeHex(wordRaw)
if err != nil {
log.Warnf("decode yak matcher hex failed: %s", err)
continue
}
word = string(raw)
case "base64":
raw, err := codec.DecodeBase64(wordRaw)
if err != nil {
log.Warnf("decode yak matcher base64 failed: %s", err)
continue
}
word = string(raw)
}
groups = append(groups, word)
}
switch condition {
case "and":
for _, word := range groups {
if !matcherFunc(material, word) {
return false, nil
}
}
return true, nil
case "or":
fallthrough
default:
for _, word := range groups {
if matcherFunc(material, word) {
return true, nil
}
}
return false, nil
}
}
func (y *YakMatcher) execute(config *Config, rspIns *RespForMatch, vars map[string]interface{}, sufs ...string) (bool, error) {
rsp := utils.CopyBytes(rspIns.RawPacket)
duration := rspIns.Duration
return y.executeRaw(y.TemplateName, config, rsp, duration, vars, sufs...)
}