forked from senghoo/modsecurity-go
-
Notifications
You must be signed in to change notification settings - Fork 1
/
scanner.go
599 lines (546 loc) · 11.6 KB
/
scanner.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
// Seclang Parser.
// Thanks to the go-lua project. The scanner referenced some of the go-lua scanner implementations. https://github.com/Shopify/go-lua
package parser
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"strconv"
"strings"
"unicode"
)
const (
// begin of stream
BOS = -1
// end of stream
EOS = -2
)
var escapes map[rune]rune = map[rune]rune{}
var ErrEOS = errors.New("EOS")
type Directive interface {
Token() int
}
type Scanner struct {
buffer *bytes.Buffer
r *bufio.Reader
current rune
LineNumber, LastLine int
}
func NewSecLangScanner(r io.Reader) *Scanner {
return &Scanner{
buffer: bytes.NewBuffer(nil),
r: bufio.NewReader(r),
LastLine: 1,
LineNumber: 1,
current: BOS,
}
}
func NewSecLangScannerFromString(s string) *Scanner {
return NewSecLangScanner(strings.NewReader(s))
}
func (s *Scanner) ReadWord() string {
for {
if isAlphabet(s.current) {
s.saveAndAdvance()
} else {
str := s.buffer.String()
s.buffer.Reset()
return str
}
}
}
func (s *Scanner) ReadString() (string, error) {
s.SkipBlank()
if isNewLine(s.current) {
s.incrementLineNumber()
return "", nil
}
if s.current == '"' {
return s.readString('"')
}
if s.current == '\'' {
return s.readString('\'')
}
if s.current == EOS {
return "", ErrEOS
}
return s.readString(' ', '\f', '\t', '\v', '\n', '\r', EOS)
}
func (s *Scanner) readString(delimiter ...rune) (string, error) {
if runeInSlice(s.current, delimiter) {
s.advance()
}
for !runeInSlice(s.current, delimiter) {
switch s.current {
case EOS:
if s.buffer.Len() > 0 {
return "", fmt.Errorf("unexpected EOS after %s", s.buffer.String())
}
return "", nil
case '\n', '\r':
return "", errors.New("unfinished string got newline")
case '\\':
s.advance()
c := s.current
switch esc, ok := escapes[c]; {
case ok:
s.advanceAndSave(esc)
case isNewLine(c):
s.incrementLineNumber()
s.save('\n')
case c == EOS:
return "", fmt.Errorf("unexpected EOS after %s", s.buffer.String())
default:
s.save('\\')
s.saveAndAdvance()
}
default:
s.saveAndAdvance()
}
}
s.advance()
str := s.buffer.String()
s.buffer.Reset()
return str, nil
}
func (s *Scanner) ReadDirective() (Directive, error) {
if s.current == BOS {
s.advance()
}
for {
switch c := s.current; c {
case '\n', '\r':
s.incrementLineNumber()
case ' ', '\f', '\t', '\v':
s.advance()
case 0:
s.advance()
case EOS:
return nil, ErrEOS
default:
dir, err := s.readDirective()
if err == ErrEOS {
return nil, errors.New("unexpected EOS")
}
return dir, err
}
}
}
func (s *Scanner) AllDirective() ([]Directive, error) {
var dirs []Directive
for {
d, err := s.ReadDirective()
if err == ErrEOS {
break
}
if err != nil {
return nil, err
}
dirs = append(dirs, d)
}
return dirs, nil
}
func (s *Scanner) readDirective() (Directive, error) {
dir := s.ReadWord()
td := DirectiveFromString(dir)
if td == nil {
return nil, fmt.Errorf("string %s is not directive", dir)
}
return td.Func(s)
}
func (s *Scanner) ReadVariables() ([]*Variable, error) {
res := make([]*Variable, 0, 1)
argString, err := s.ReadString()
if err != nil {
return nil, err
}
if len(argString) == 0 {
return nil, errors.New("expected variable bug got empty")
}
args := splitMulti(argString, ",|")
for _, a := range args {
if len(a) < 1 {
return nil, errors.New("unexpected ',' or '|' in argument")
}
arg := &Variable{}
if a[0] == '!' {
arg.Exclusion = true
a = a[1:]
} else if a[0] == '&' {
arg.Count = true
a = a[1:]
}
i := strings.IndexAny(a, ".:")
if i > 0 {
arg.Index = a[i+1:]
a = a[:i]
}
tk, has := VariableMap[a]
if !has {
return nil, fmt.Errorf("unknown variable %s\n", a)
}
arg.Tk = tk
res = append(res, arg)
}
return res, nil
}
func (s *Scanner) ReadOperator() (*Operator, error) {
res := new(Operator)
opString, err := s.ReadString()
if err != nil {
return nil, err
}
if len(opString) == 0 {
return nil, errors.New("expected operator bug got empty")
}
if len(opString) > 0 && opString[0] == '!' {
res.Not = true
opString = opString[1:]
}
if len(opString) == 0 {
return nil, fmt.Errorf("expecting operator bug get %s", opString)
}
if opString[0] != '@' {
res.Tk = TkOpRx
res.Argument = opString
return res, nil
}
opWithArg := strings.SplitN(opString, " ", 2)
op := opWithArg[0]
if len(opWithArg) > 1 {
res.Argument = opWithArg[1]
}
op = op[1:] // skip @
tk, has := OperatorMap[op]
if !has {
return nil, fmt.Errorf("expect operator got @%s", op)
}
res.Tk = tk
return res, nil
}
var actionProcessors = map[int]func(*Actions, string) error{
0: func(a *Actions, arg string) error {
return errors.New("unexpected action type")
},
TkActionId: func(a *Actions, arg string) (err error) {
arg = trimQuote(arg)
a.Id, err = strconv.Atoi(arg)
if err != nil {
return fmt.Errorf("cannot parse id %s, err: %s", arg, err.Error())
}
return
},
TkActionSeverity: func(a *Actions, arg string) (err error) {
arg = trimQuote(arg)
if severity, has := SeverityMap[arg]; has {
a.Action = append(a.Action, &Action{TkActionSeverity, strconv.Itoa(severity)})
} else if severity, err := strconv.Atoi(arg); err == nil && severity >= 0 && severity <= 7 {
a.Action = append(a.Action, &Action{TkActionSeverity, strconv.Itoa(severity)})
} else {
return fmt.Errorf("unknown severity %s", arg)
}
return
},
TkActionT: func(a *Actions, arg string) (err error) {
arg = trimQuote(arg)
if tt, has := TransformationMap[arg]; has {
a.Trans = append(a.Trans, &Trans{tt})
} else {
return fmt.Errorf("unknown trans formation %s", arg)
}
return
},
TkActionPhase: func(a *Actions, arg string) (err error) {
arg = trimQuote(arg)
p, has := PhaseAlias[arg]
if has {
a.Phase = p
return
}
p, err = strconv.Atoi(arg)
if err != nil {
return fmt.Errorf("cannot parse phase %s, err: %s", arg, err.Error())
}
if p < PhaseRequestHeaders || p > PhaseLogging {
return fmt.Errorf("unsupported phase %d", p)
}
a.Phase = p
return
},
TkActionChain: func(a *Actions, arg string) (err error) {
a.Chain = true
return
},
}
func processAction(a *Actions, str string) error {
tk, arg, err := parseAction(str)
if err != nil {
return err
}
if processor, has := actionProcessors[tk]; has {
if err = processor(a, arg); err != nil {
return err
}
return nil
}
a.Action = append(a.Action, &Action{tk, arg})
return nil
}
func mergeActions(actions []string) []string {
res := []string{}
for i := 0; i < len(actions); i++ {
if strings.Count(actions[i], "'") == 1 {
flag := false
for j := i + 1; j < len(actions); j++ {
if strings.Count(actions[j], "'") == 1 {
token := strings.Join(actions[i:j+1], ",")
res = append(res, token)
i = j
flag = true
break
}
}
if !flag {
panic("mergeActions(): should not be here")
}
} else {
res = append(res, actions[i])
}
}
return res
}
func (s *Scanner) ReadActions() (*Actions, error) {
res := new(Actions)
str, err := s.ReadString()
if err != nil {
return nil, err
}
str = strings.TrimSpace(str)
// str = strings.Trim(str, "\r\n\t\f\v ")
if len(str) == 0 {
// chain rule in REQUEST-910-IP-REPUTATION.conf
return nil, nil
//return nil, errors.New("expected actions bug got empty")
}
actions := strings.Split(str, ",")
actions = mergeActions(actions)
for _, action := range actions {
err := processAction(res, action)
if err != nil {
return nil, err
}
}
return res, nil
}
func parseAction(act string) (int, string, error) {
var arg string
s := strings.SplitN(act, ":", 2)
action := strings.TrimSpace(s[0])
tk, has := ActionMap[action]
if !has {
return 0, "", fmt.Errorf("unknown action %s", s[0])
}
if len(s) > 1 {
arg = s[1]
}
return tk, arg, nil
}
func (s *Scanner) SkipBlank() error {
for {
switch {
case s.current == BOS:
s.advance()
case isBlank(s.current):
s.advance()
case s.current == '\\':
if s.next() == '\n' {
s.advance() //skip '\\'
s.incrementLineNumber() // skip newlines
}
default:
return nil
}
}
}
func (s *Scanner) ReadValue(tks ...int) (int, string, error) {
var expected []string
str, err := s.ReadString()
if err != nil {
return 0, "", err
}
for _, tk := range tks {
v, ok := Values[tk]
if !ok {
return 0, "", fmt.Errorf("value token %d not found", tk)
}
if v.regex.MatchString(str) {
return tk, str, nil
}
expected = append(expected, v.Regex)
}
return 0, "", fmt.Errorf("expect %s got %s", strings.Join(expected, "|"), str)
}
func (s *Scanner) StartsWith(str string) bool {
for _, r := range str {
if unicode.ToLower(s.current) == unicode.ToLower(r) {
s.saveAndAdvance()
continue
}
return false
}
return true
}
func (s *Scanner) incrementLineNumber() {
old := s.current
if s.advance(); isNewLine(s.current) && s.current != old {
s.advance()
}
s.LineNumber++
}
func (s *Scanner) advance() {
if c, err := s.r.ReadByte(); err != nil {
s.current = EOS
} else {
s.current = rune(c)
}
}
func (s *Scanner) next() rune {
if c, err := s.r.ReadByte(); err != nil {
return EOS
} else {
s.r.UnreadByte()
return rune(c)
}
}
func (s *Scanner) saveAndAdvance() {
s.save(s.current)
s.advance()
}
func (s *Scanner) advanceAndSave(c rune) {
s.advance()
s.save(c)
}
func (s *Scanner) save(c rune) {
s.buffer.WriteByte(byte(c))
}
type StringArgDirective struct {
Tk int
Value string
}
func (d *StringArgDirective) Token() int {
return d.Tk
}
func StringArgDirectiveFactory(tk int) DirectiveFactory {
return func(s *Scanner) (Directive, error) {
str, err := s.ReadString()
if err != nil {
return nil, err
}
return &StringArgDirective{
Tk: tk,
Value: str,
}, nil
}
}
type BoolArgDirective struct {
Tk int
Value bool
}
func (d *BoolArgDirective) Token() int {
return d.Tk
}
func BoolArgDirectiveFactory(tk int) DirectiveFactory {
return func(s *Scanner) (Directive, error) {
tkVal, _, err := s.ReadValue(TkValueOn, TkValueOff)
if err != nil {
return nil, err
}
return &BoolArgDirective{
Tk: tk,
Value: tkVal == TkValueOn,
}, nil
}
}
const (
TriBoolTrue = 1
TriBoolElse = 2
TriBoolFalse = 0
)
type TriBoolArgDirective struct {
Tk int
Value int // 1: on; 2: DetectionOnly; 0: off
}
func (d *TriBoolArgDirective) Token() int {
return d.Tk
}
func TriBoolArgDirectiveFactory(tk int) DirectiveFactory {
val := map[int]int{
TkValueOn: TriBoolTrue,
TkValueElse: TriBoolElse,
TkValueOff: TriBoolFalse,
}
return func(s *Scanner) (Directive, error) {
tkVal, _, err := s.ReadValue(TkValueOn, TkValueOff, TkValueElse)
if err != nil {
return nil, err
}
return &TriBoolArgDirective{
Tk: tk,
Value: val[tkVal],
}, nil
}
}
type Variable struct {
Tk int
Index string
Count bool
Exclusion bool
}
type Operator struct {
Tk int
Not bool
Argument string
}
type Action struct {
Tk int
Argument string
}
type Trans struct {
Tk int
}
type Actions struct {
Id int
Phase int
Chain bool
Trans []*Trans
Action []*Action
}
type RuleDirective struct {
Variable []*Variable
Operator *Operator
Actions *Actions
}
func (d *RuleDirective) Token() int {
return TkDirRule
}
func RuleDirectiveScaner(s *Scanner) (Directive, error) {
rule := &RuleDirective{}
vars, err := s.ReadVariables()
if err != nil {
return nil, err
}
rule.Variable = vars
op, err := s.ReadOperator()
if err != nil {
return nil, err
}
rule.Operator = op
actions, err := s.ReadActions()
if err != nil {
return nil, err
}
rule.Actions = actions
return rule, nil
}