-
Notifications
You must be signed in to change notification settings - Fork 29
/
rule.go
711 lines (648 loc) · 18.7 KB
/
rule.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
package waf
import (
"bytes"
"encoding/base64"
"encoding/binary"
"errors"
"github.com/TeaOSLab/EdgeCommon/pkg/configutils"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/filterconfigs"
"github.com/TeaOSLab/EdgeNode/internal/re"
"github.com/TeaOSLab/EdgeNode/internal/remotelogs"
"github.com/TeaOSLab/EdgeNode/internal/waf/checkpoints"
"github.com/TeaOSLab/EdgeNode/internal/waf/requests"
"github.com/TeaOSLab/EdgeNode/internal/waf/utils"
"github.com/TeaOSLab/EdgeNode/internal/waf/values"
"github.com/iwind/TeaGo/lists"
"github.com/iwind/TeaGo/maps"
"github.com/iwind/TeaGo/types"
"github.com/iwind/TeaGo/utils/string"
"net"
"reflect"
"regexp"
"strings"
)
var singleParamRegexp = regexp.MustCompile("^\\${[\\w.-]+}$")
// Rule
type Rule struct {
Id int64
Description string `yaml:"description" json:"description"`
Param string `yaml:"param" json:"param"` // such as ${arg.name} or ${args}, can be composite as ${arg.firstName}${arg.lastName}
ParamFilters []*ParamFilter `yaml:"paramFilters" json:"paramFilters"`
Operator RuleOperator `yaml:"operator" json:"operator"` // such as contains, gt, ...
Value string `yaml:"value" json:"value"` // compared value
IsCaseInsensitive bool `yaml:"isCaseInsensitive" json:"isCaseInsensitive"`
CheckpointOptions map[string]interface{} `yaml:"checkpointOptions" json:"checkpointOptions"`
Priority int `yaml:"priority" json:"priority"`
checkpointFinder func(prefix string) checkpoints.CheckpointInterface
singleParam string // real param after prefix
singleCheckpoint checkpoints.CheckpointInterface // if is single check point
multipleCheckpoints map[string]checkpoints.CheckpointInterface
isIP bool
ipValue net.IP
ipRangeListValue *values.IPRangeList
stringValues []string
ipList *values.StringList
floatValue float64
reg *re.Regexp
}
func NewRule() *Rule {
return &Rule{}
}
func (this *Rule) Init() error {
// operator
switch this.Operator {
case RuleOperatorGt:
this.floatValue = types.Float64(this.Value)
case RuleOperatorGte:
this.floatValue = types.Float64(this.Value)
case RuleOperatorLt:
this.floatValue = types.Float64(this.Value)
case RuleOperatorLte:
this.floatValue = types.Float64(this.Value)
case RuleOperatorEq:
this.floatValue = types.Float64(this.Value)
case RuleOperatorNeq:
this.floatValue = types.Float64(this.Value)
case RuleOperatorContainsAny, RuleOperatorContainsAll:
this.stringValues = []string{}
if len(this.Value) > 0 {
var lines = strings.Split(this.Value, "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if len(line) > 0 {
if this.IsCaseInsensitive {
this.stringValues = append(this.stringValues, strings.ToLower(line))
} else {
this.stringValues = append(this.stringValues, line)
}
}
}
}
case RuleOperatorMatch:
v := this.Value
if this.IsCaseInsensitive && !strings.HasPrefix(v, "(?i)") {
v = "(?i)" + v
}
v = this.unescape(v)
reg, err := re.Compile(v)
if err != nil {
return err
}
this.reg = reg
case RuleOperatorNotMatch:
v := this.Value
if this.IsCaseInsensitive && !strings.HasPrefix(v, "(?i)") {
v = "(?i)" + v
}
v = this.unescape(v)
reg, err := re.Compile(v)
if err != nil {
return err
}
this.reg = reg
case RuleOperatorEqIP, RuleOperatorGtIP, RuleOperatorGteIP, RuleOperatorLtIP, RuleOperatorLteIP:
this.ipValue = net.ParseIP(this.Value)
this.isIP = this.ipValue != nil
if !this.isIP {
return errors.New("value should be a valid ip")
}
case RuleOperatorInIPList:
this.ipList = values.ParseStringList(this.Value, true)
case RuleOperatorIPRange, RuleOperatorNotIPRange:
this.ipRangeListValue = values.ParseIPRangeList(this.Value)
}
if singleParamRegexp.MatchString(this.Param) {
var param = this.Param[2 : len(this.Param)-1]
var pieces = strings.SplitN(param, ".", 2)
var prefix = pieces[0]
if len(pieces) == 1 {
this.singleParam = ""
} else {
this.singleParam = pieces[1]
}
if this.checkpointFinder != nil {
var checkpoint = this.checkpointFinder(prefix)
if checkpoint == nil {
return errors.New("no check point '" + prefix + "' found")
}
this.singleCheckpoint = checkpoint
this.Priority = checkpoint.Priority()
} else {
var checkpoint = checkpoints.FindCheckpoint(prefix)
if checkpoint == nil {
return errors.New("no check point '" + prefix + "' found")
}
checkpoint.Init()
this.singleCheckpoint = checkpoint
this.Priority = checkpoint.Priority()
}
return nil
}
this.multipleCheckpoints = map[string]checkpoints.CheckpointInterface{}
var err error = nil
configutils.ParseVariables(this.Param, func(varName string) (value string) {
var pieces = strings.SplitN(varName, ".", 2)
var prefix = pieces[0]
if this.checkpointFinder != nil {
var checkpoint = this.checkpointFinder(prefix)
if checkpoint == nil {
err = errors.New("no check point '" + prefix + "' found")
} else {
this.multipleCheckpoints[prefix] = checkpoint
this.Priority = checkpoint.Priority()
}
} else {
var checkpoint = checkpoints.FindCheckpoint(prefix)
if checkpoint == nil {
err = errors.New("no check point '" + prefix + "' found")
} else {
checkpoint.Init()
this.multipleCheckpoints[prefix] = checkpoint
this.Priority = checkpoint.Priority()
}
}
return ""
})
return err
}
func (this *Rule) MatchRequest(req requests.Request) (b bool, hasRequestBody bool, err error) {
if this.singleCheckpoint != nil {
value, hasCheckedRequestBody, err, _ := this.singleCheckpoint.RequestValue(req, this.singleParam, this.CheckpointOptions, this.Id)
if hasCheckedRequestBody {
hasRequestBody = true
}
if err != nil {
return false, hasRequestBody, err
}
// execute filters
if len(this.ParamFilters) > 0 {
value = this.execFilter(value)
}
// if is composed checkpoint, we just returns true or false
if this.singleCheckpoint.IsComposed() {
return types.Bool(value), hasRequestBody, nil
}
return this.Test(value), hasRequestBody, nil
}
value := configutils.ParseVariables(this.Param, func(varName string) (value string) {
pieces := strings.SplitN(varName, ".", 2)
prefix := pieces[0]
point, ok := this.multipleCheckpoints[prefix]
if !ok {
return ""
}
if len(pieces) == 1 {
value1, hasCheckRequestBody, err1, _ := point.RequestValue(req, "", this.CheckpointOptions, this.Id)
if hasCheckRequestBody {
hasRequestBody = true
}
if err1 != nil {
err = err1
}
return types.String(value1)
}
value1, hasCheckRequestBody, err1, _ := point.RequestValue(req, pieces[1], this.CheckpointOptions, this.Id)
if hasCheckRequestBody {
hasRequestBody = true
}
if err1 != nil {
err = err1
}
return types.String(value1)
})
if err != nil {
return false, hasRequestBody, err
}
return this.Test(value), hasRequestBody, nil
}
func (this *Rule) MatchResponse(req requests.Request, resp *requests.Response) (b bool, hasRequestBody bool, err error) {
if this.singleCheckpoint != nil {
// if is request param
if this.singleCheckpoint.IsRequest() {
value, hasCheckRequestBody, err, _ := this.singleCheckpoint.RequestValue(req, this.singleParam, this.CheckpointOptions, this.Id)
if hasCheckRequestBody {
hasRequestBody = true
}
if err != nil {
return false, hasRequestBody, err
}
// execute filters
if len(this.ParamFilters) > 0 {
value = this.execFilter(value)
}
return this.Test(value), hasRequestBody, nil
}
// response param
value, hasCheckRequestBody, err, _ := this.singleCheckpoint.ResponseValue(req, resp, this.singleParam, this.CheckpointOptions, this.Id)
if hasCheckRequestBody {
hasRequestBody = true
}
if err != nil {
return false, hasRequestBody, err
}
// if is composed checkpoint, we just returns true or false
if this.singleCheckpoint.IsComposed() {
return types.Bool(value), hasRequestBody, nil
}
return this.Test(value), hasRequestBody, nil
}
value := configutils.ParseVariables(this.Param, func(varName string) (value string) {
pieces := strings.SplitN(varName, ".", 2)
prefix := pieces[0]
point, ok := this.multipleCheckpoints[prefix]
if !ok {
return ""
}
if len(pieces) == 1 {
if point.IsRequest() {
value1, hasCheckRequestBody, err1, _ := point.RequestValue(req, "", this.CheckpointOptions, this.Id)
if hasCheckRequestBody {
hasRequestBody = true
}
if err1 != nil {
err = err1
}
return types.String(value1)
} else {
value1, hasCheckRequestBody, err1, _ := point.ResponseValue(req, resp, "", this.CheckpointOptions, this.Id)
if hasCheckRequestBody {
hasRequestBody = true
}
if err1 != nil {
err = err1
}
return types.String(value1)
}
}
if point.IsRequest() {
value1, hasCheckRequestBody, err1, _ := point.RequestValue(req, pieces[1], this.CheckpointOptions, this.Id)
if hasCheckRequestBody {
hasRequestBody = true
}
if err1 != nil {
err = err1
}
return types.String(value1)
} else {
value1, hasCheckRequestBody, err1, _ := point.ResponseValue(req, resp, pieces[1], this.CheckpointOptions, this.Id)
if hasCheckRequestBody {
hasRequestBody = true
}
if err1 != nil {
err = err1
}
return types.String(value1)
}
})
if err != nil {
return false, hasRequestBody, err
}
return this.Test(value), hasRequestBody, nil
}
func (this *Rule) Test(value interface{}) bool {
// operator
switch this.Operator {
case RuleOperatorGt:
return types.Float64(value) > this.floatValue
case RuleOperatorGte:
return types.Float64(value) >= this.floatValue
case RuleOperatorLt:
return types.Float64(value) < this.floatValue
case RuleOperatorLte:
return types.Float64(value) <= this.floatValue
case RuleOperatorEq:
return types.Float64(value) == this.floatValue
case RuleOperatorNeq:
return types.Float64(value) != this.floatValue
case RuleOperatorEqString:
if this.IsCaseInsensitive {
return strings.EqualFold(types.String(value), this.Value)
} else {
return types.String(value) == this.Value
}
case RuleOperatorNeqString:
if this.IsCaseInsensitive {
return !strings.EqualFold(types.String(value), this.Value)
} else {
return types.String(value) != this.Value
}
case RuleOperatorMatch:
if value == nil {
return false
}
// strings
stringList, ok := value.([]string)
if ok {
for _, s := range stringList {
if utils.MatchStringCache(this.reg, s) {
return true
}
}
return false
}
// bytes
byteSlice, ok := value.([]byte)
if ok {
return utils.MatchBytesCache(this.reg, byteSlice)
}
// string
return utils.MatchStringCache(this.reg, types.String(value))
case RuleOperatorNotMatch:
if value == nil {
return true
}
stringList, ok := value.([]string)
if ok {
for _, s := range stringList {
if utils.MatchStringCache(this.reg, s) {
return false
}
}
return true
}
// bytes
byteSlice, ok := value.([]byte)
if ok {
return !utils.MatchBytesCache(this.reg, byteSlice)
}
return !utils.MatchStringCache(this.reg, types.String(value))
case RuleOperatorContains:
if types.IsSlice(value) {
_, isBytes := value.([]byte)
if !isBytes {
ok := false
lists.Each(value, func(k int, v interface{}) {
if types.String(v) == this.Value {
ok = true
}
})
return ok
}
}
if types.IsMap(value) {
lowerValue := ""
if this.IsCaseInsensitive {
lowerValue = strings.ToLower(this.Value)
}
for _, v := range maps.NewMap(value) {
if this.IsCaseInsensitive {
if strings.ToLower(types.String(v)) == lowerValue {
return true
}
} else {
if types.String(v) == this.Value {
return true
}
}
}
return false
}
if this.IsCaseInsensitive {
return strings.Contains(strings.ToLower(types.String(value)), strings.ToLower(this.Value))
} else {
return strings.Contains(types.String(value), this.Value)
}
case RuleOperatorNotContains:
if this.IsCaseInsensitive {
return !strings.Contains(strings.ToLower(types.String(value)), strings.ToLower(this.Value))
} else {
return !strings.Contains(types.String(value), this.Value)
}
case RuleOperatorPrefix:
if this.IsCaseInsensitive {
return strings.HasPrefix(strings.ToLower(types.String(value)), strings.ToLower(this.Value))
} else {
return strings.HasPrefix(types.String(value), this.Value)
}
case RuleOperatorSuffix:
if this.IsCaseInsensitive {
return strings.HasSuffix(strings.ToLower(types.String(value)), strings.ToLower(this.Value))
} else {
return strings.HasSuffix(types.String(value), this.Value)
}
case RuleOperatorContainsAny:
var stringValue = types.String(value)
if this.IsCaseInsensitive {
stringValue = strings.ToLower(stringValue)
}
if len(stringValue) > 0 && len(this.stringValues) > 0 {
for _, v := range this.stringValues {
if strings.Contains(stringValue, v) {
return true
}
}
}
return false
case RuleOperatorContainsAll:
var stringValue = types.String(value)
if this.IsCaseInsensitive {
stringValue = strings.ToLower(stringValue)
}
if len(stringValue) > 0 && len(this.stringValues) > 0 {
for _, v := range this.stringValues {
if !strings.Contains(stringValue, v) {
return false
}
}
return true
}
return false
case RuleOperatorContainsBinary:
data, _ := base64.StdEncoding.DecodeString(types.String(this.Value))
if this.IsCaseInsensitive {
return bytes.Contains(bytes.ToUpper([]byte(types.String(value))), bytes.ToUpper(data))
} else {
return bytes.Contains([]byte(types.String(value)), data)
}
case RuleOperatorNotContainsBinary:
data, _ := base64.StdEncoding.DecodeString(types.String(this.Value))
if this.IsCaseInsensitive {
return !bytes.Contains(bytes.ToUpper([]byte(types.String(value))), bytes.ToUpper(data))
} else {
return !bytes.Contains([]byte(types.String(value)), data)
}
case RuleOperatorHasKey:
if types.IsSlice(value) {
index := types.Int(this.Value)
if index < 0 {
return false
}
return reflect.ValueOf(value).Len() > index
} else if types.IsMap(value) {
m := maps.NewMap(value)
if this.IsCaseInsensitive {
lowerValue := strings.ToLower(this.Value)
for k := range m {
if strings.ToLower(k) == lowerValue {
return true
}
}
} else {
return m.Has(this.Value)
}
} else {
return false
}
case RuleOperatorVersionGt:
return stringutil.VersionCompare(this.Value, types.String(value)) > 0
case RuleOperatorVersionLt:
return stringutil.VersionCompare(this.Value, types.String(value)) < 0
case RuleOperatorVersionRange:
if strings.Contains(this.Value, ",") {
versions := strings.SplitN(this.Value, ",", 2)
version1 := strings.TrimSpace(versions[0])
version2 := strings.TrimSpace(versions[1])
if len(version1) > 0 && stringutil.VersionCompare(types.String(value), version1) < 0 {
return false
}
if len(version2) > 0 && stringutil.VersionCompare(types.String(value), version2) > 0 {
return false
}
return true
} else {
return stringutil.VersionCompare(types.String(value), this.Value) >= 0
}
case RuleOperatorEqIP:
ip := net.ParseIP(types.String(value))
if ip == nil {
return false
}
return this.isIP && bytes.Equal(this.ipValue, ip)
case RuleOperatorGtIP:
ip := net.ParseIP(types.String(value))
if ip == nil {
return false
}
return this.isIP && bytes.Compare(ip, this.ipValue) > 0
case RuleOperatorGteIP:
ip := net.ParseIP(types.String(value))
if ip == nil {
return false
}
return this.isIP && bytes.Compare(ip, this.ipValue) >= 0
case RuleOperatorLtIP:
ip := net.ParseIP(types.String(value))
if ip == nil {
return false
}
return this.isIP && bytes.Compare(ip, this.ipValue) < 0
case RuleOperatorLteIP:
ip := net.ParseIP(types.String(value))
if ip == nil {
return false
}
return this.isIP && bytes.Compare(ip, this.ipValue) <= 0
case RuleOperatorIPRange:
return this.containsIP(value)
case RuleOperatorNotIPRange:
return !this.containsIP(value)
case RuleOperatorIPMod:
var pieces = strings.SplitN(this.Value, ",", 2)
if len(pieces) == 1 {
var rem = types.Int64(pieces[0])
return this.ipToInt64(net.ParseIP(types.String(value)))%10 == rem
}
var div = types.Int64(pieces[0])
if div == 0 {
return false
}
rem := types.Int64(pieces[1])
return this.ipToInt64(net.ParseIP(types.String(value)))%div == rem
case RuleOperatorIPMod10:
return this.ipToInt64(net.ParseIP(types.String(value)))%10 == types.Int64(this.Value)
case RuleOperatorIPMod100:
return this.ipToInt64(net.ParseIP(types.String(value)))%100 == types.Int64(this.Value)
case RuleOperatorInIPList:
if this.ipList != nil {
return this.ipList.Contains(types.String(value))
}
return false
}
return false
}
func (this *Rule) IsSingleCheckpoint() bool {
return this.singleCheckpoint != nil
}
func (this *Rule) SetCheckpointFinder(finder func(prefix string) checkpoints.CheckpointInterface) {
this.checkpointFinder = finder
}
var unescapeChars = [][2]string{
{`\s`, `(\s|%09|%0A|\+)`},
{`\(`, `(\(|%28)`},
{`=`, `(=|%3D)`},
{`<`, `(<|%3C)`},
{`\*`, `(\*|%2A)`},
{`\\`, `(\\|%2F)`},
{`!`, `(!|%21)`},
{`/`, `(/|%2F)`},
{`;`, `(;|%3B)`},
{`\+`, `(\+|%20)`},
}
func (this *Rule) unescape(v string) string {
// replace urlencoded characters
for _, c := range unescapeChars {
if !strings.Contains(v, c[0]) {
continue
}
var pieces = strings.Split(v, c[0])
// 修复piece中错误的\
for pieceIndex, piece := range pieces {
var l = len(piece)
if l == 0 {
continue
}
if piece[l-1] != '\\' {
continue
}
// 计算\的数量
var countBackSlashes = 0
for i := l - 1; i >= 0; i-- {
if piece[i] == '\\' {
countBackSlashes++
} else {
break
}
}
if countBackSlashes%2 == 1 {
// 去掉最后一个
pieces[pieceIndex] = piece[:len(piece)-1]
}
}
v = strings.Join(pieces, c[1])
}
return v
}
func (this *Rule) containsIP(value any) bool {
if this.ipRangeListValue == nil {
return false
}
return this.ipRangeListValue.Contains(types.String(value))
}
func (this *Rule) ipToInt64(ip net.IP) int64 {
if len(ip) == 0 {
return 0
}
if len(ip) == 16 {
return int64(binary.BigEndian.Uint32(ip[12:16]))
}
return int64(binary.BigEndian.Uint32(ip))
}
func (this *Rule) execFilter(value interface{}) interface{} {
var goNext bool
var err error
for _, filter := range this.ParamFilters {
filterInstance := filterconfigs.FindFilter(filter.Code)
if filterInstance == nil {
continue
}
value, goNext, err = filterInstance.Do(value, filter.Options)
if err != nil {
remotelogs.Error("WAF", "filter error: "+err.Error())
break
}
if !goNext {
break
}
}
return value
}