/
transaction.go
992 lines (906 loc) · 34.2 KB
/
transaction.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
// Copyright 2022 Juan Pablo Tosso
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http:// www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package coraza
import (
"bufio"
"fmt"
"io"
"mime"
"net/http"
"net/url"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/corazawaf/coraza/v2/bodyprocessors"
"github.com/corazawaf/coraza/v2/loggers"
"github.com/corazawaf/coraza/v2/types"
"github.com/corazawaf/coraza/v2/types/variables"
utils "github.com/corazawaf/coraza/v2/utils/strings"
url2 "github.com/corazawaf/coraza/v2/utils/url"
"go.uber.org/zap"
)
// Transaction is created from a WAF instance to handle web requests and responses,
// it contains a copy of most WAF configurations that can be safely changed.
// Transactions are used to store all data like URLs, request and response
// headers. Transactions are used to evaluate rules by phase and generate disruptive
// actions. Disruptive actions can be read from *tx.Interruption.
// It is safe to manage multiple transactions but transactions themself are not
// thread safe
type Transaction struct {
// Transaction ID
ID string
// Contains the list of matched rules and associated match information
MatchedRules []MatchedRule
// True if the transaction has been disrupted by any rule
Interruption *types.Interruption
// Contains all collections, including persistent
collections [types.VariablesCount]*Collection
// This is used to store log messages
Logdata string
// Rules will be skipped after a rule with this SecMarker is found
SkipAfter string
// Copies from the WafInstance that may be overwritten by the ctl action
AuditEngine types.AuditEngineStatus
AuditLogParts types.AuditLogParts
ForceRequestBodyVariable bool
RequestBodyAccess bool
RequestBodyLimit int64
ResponseBodyAccess bool
ResponseBodyLimit int64
RuleEngine types.RuleEngineStatus
HashEngine bool
HashEnforcement bool
// Stores the last phase that was evaluated
// Used by allow to skip phases
LastPhase types.RulePhase
// Handles request body buffers
RequestBodyBuffer *BodyBuffer
// Handles response body buffers
ResponseBodyBuffer *BodyBuffer
// Body processor used to parse JSON, XML, etc
bodyProcessor bodyprocessors.BodyProcessor
// Rules with this id are going to be skipped while processing a phase
ruleRemoveByID []int
// ruleRemoveTargetByID is used by ctl to remove rule targets by id during the
// transaction. All other "target removers" like "ByTag" are an abstraction of "ById"
// For example, if you want to remove REQUEST_HEADERS:User-Agent from rule 85:
// {85: {variables.RequestHeaders, "user-agent"}}
ruleRemoveTargetByID map[int][]ruleVariableParams
// Will skip this number of rules, this value will be decreased on each skip
Skip int
// Actions with capture features will read the capture state from this field
// We have currently removed this feature as Capture will always run
// We must reuse it in the future
Capture bool
// Contains duration in useconds per phase
stopWatches map[types.RulePhase]int64
// Contains a Waf instance for the current transaction
Waf *Waf
// Timestamp of the request
Timestamp int64
// When a rule matches and contains r.Audit = true, this will be set to true
// it will write to the audit log
audit bool
}
// AddRequestHeader Adds a request header
//
// With this method it is possible to feed Coraza with a request header.
// Note: Golang's *http.Request object will not contain a "Host" header,
// and you might have to force it
func (tx *Transaction) AddRequestHeader(key string, value string) {
if key == "" {
return
}
keyl := strings.ToLower(key)
tx.GetCollection(variables.RequestHeadersNames).AddUniqueCS(keyl, key, keyl)
tx.GetCollection(variables.RequestHeaders).AddCS(keyl, key, value)
if keyl == "content-type" {
val := strings.ToLower(value)
if val == "application/x-www-form-urlencoded" {
tx.GetCollection(variables.ReqbodyProcessor).Set("", []string{"URLENCODED"})
} else if strings.HasPrefix(val, "multipart/form-data") {
tx.GetCollection(variables.ReqbodyProcessor).Set("", []string{"MULTIPART"})
}
} else if keyl == "cookie" {
// Cookies use the same syntax as GET params but with semicolon (;) separator
values, err := url2.ParseQuery(value, ";")
if err != nil {
// if cookie parsing fails we create a urlencoded_error
// TODO maybe we should have another variable for this
tx.GetCollection(variables.UrlencodedError).Set("", []string{err.Error()})
return
}
for k, vr := range values {
kl := strings.ToLower(k)
tx.GetCollection(variables.RequestCookiesNames).AddUniqueCS(kl, k, kl)
for _, v := range vr {
tx.GetCollection(variables.RequestCookies).AddCS(kl, k, v)
}
}
}
}
// AddResponseHeader Adds a response header variable
//
// With this method it is possible to feed Coraza with a response header.
func (tx *Transaction) AddResponseHeader(key string, value string) {
if key == "" {
return
}
keyl := strings.ToLower(key)
tx.GetCollection(variables.ResponseHeadersNames).AddUniqueCS(keyl, key, keyl)
tx.GetCollection(variables.ResponseHeaders).AddCS(keyl, key, value)
// Most headers can be managed like that
if keyl == "content-type" {
spl := strings.SplitN(value, ";", 2)
tx.GetCollection(variables.ResponseContentType).SetIndex("", 0, spl[0])
}
}
// CaptureField is used to set the TX:[index] variables by operators
// that supports capture, like @rx
func (tx *Transaction) CaptureField(index int, value string) {
tx.Waf.Logger.Debug("Capturing field", zap.String("txid", tx.ID),
zap.Int("index", index), zap.String("value", value))
i := strconv.Itoa(index)
tx.GetCollection(variables.TX).SetIndex(i, 0, value)
}
// this function is used to control which variables are reset after a new rule is evaluated
func (tx *Transaction) resetCaptures() {
tx.Waf.Logger.Debug("Reseting captured variables", zap.String("txid", tx.ID))
// We reset capture 0-9
ctx := tx.GetCollection(variables.TX)
// RUNE 48 = 0
// RUNE 57 = 9
for i := rune(48); i <= 57; i++ {
ctx.SetIndex(string(i), 0, "")
}
}
// ParseRequestReader Parses binary request including body,
// it does only support http/1.1 and http/1.0
// This function does not run ProcessConnection
// This function will store in memory the whole reader,
// DON't USE IT FOR PRODUCTION yet
func (tx *Transaction) ParseRequestReader(data io.Reader) (*types.Interruption, error) {
// For dumb reasons we must read the headers and look for the Host header,
// this function is intended for proxies and the RFC says that a Host must not be parsed...
// Maybe some time I will create a prettier fix
scanner := bufio.NewScanner(data)
// read request line
scanner.Scan()
spl := strings.SplitN(scanner.Text(), " ", 3)
if len(spl) != 3 {
return nil, fmt.Errorf("invalid request line")
}
tx.ProcessURI(spl[1], spl[0], spl[2])
for scanner.Scan() {
l := scanner.Text()
if l == "" {
// It should mean we are now in the request body...
break
}
spl := strings.SplitN(l, ":", 2)
if len(spl) != 2 {
return nil, fmt.Errorf("invalid request header")
}
k := strings.Trim(spl[0], " ")
v := strings.Trim(spl[1], " ")
tx.AddRequestHeader(k, v)
}
if it := tx.ProcessRequestHeaders(); it != nil {
return it, nil
}
ct := tx.GetCollection(variables.RequestHeaders).GetFirstString("content-type")
ct = strings.Split(ct, ";")[0]
for scanner.Scan() {
if _, err := tx.RequestBodyBuffer.Write(scanner.Bytes()); err != nil {
return nil, fmt.Errorf("cannot write to request body to buffer")
}
// urlencoded cannot end with CRLF
if ct != "application/x-www-form-urlencoded" {
if _, err := tx.RequestBodyBuffer.Write([]byte{'\r', '\n'}); err != nil {
return nil, fmt.Errorf("cannot write to request body to buffer")
}
}
}
return tx.ProcessRequestBody()
}
// matchVariable Creates the MATCHED_ variables required by chains and macro expansion
// MATCHED_VARS, MATCHED_VAR, MATCHED_VAR_NAME, MATCHED_VARS_NAMES
func (tx *Transaction) matchVariable(match *MatchData) {
varName := strings.Builder{}
varNamel := strings.Builder{}
varName.WriteString(match.VariableName)
varNamel.WriteString(match.VariableName)
if match.Key != "" {
varName.WriteByte(':')
varName.WriteString(match.Key)
varNamel.WriteByte(':')
varNamel.WriteString(strings.ToLower(match.Key))
}
// Array of values
matchedVars := tx.GetCollection(variables.MatchedVars)
// Last value
matchedVar := tx.GetCollection(variables.MatchedVar)
matchedVar.Reset()
// Last key
matchedVarName := tx.GetCollection(variables.MatchedVarName)
matchedVarName.Reset()
// Array of keys
matchedVarsNames := tx.GetCollection(variables.MatchedVarsNames)
// We add the key in lowercase for ease of lookup in chains
// This is similar to args handling
matchedVars.AddCS(varNamel.String(), varName.String(), match.Value)
matchedVar.SetIndexCS("", 0, varName.String(), match.Value)
// We add the key in lowercase for ease of lookup in chains
// This is similar to args handling
matchedVarsNames.AddCS(varNamel.String(), varName.String(), varName.String())
matchedVarName.SetIndexCS("", 0, varName.String(), varName.String())
}
// MatchRule Matches a rule to be logged
func (tx *Transaction) MatchRule(r *Rule, mds []MatchData) {
tx.Waf.Logger.Debug("rule matched", zap.String("txid", tx.ID), zap.Int("rule", r.ID))
// tx.MatchedRules = append(tx.MatchedRules, mr)
// If the rule is set to audit, we log the transaction to the audit log
if r.Audit {
tx.audit = true
}
// set highest_severity
hs := tx.GetCollection(variables.HighestSeverity)
maxSeverity, _ := types.ParseRuleSeverity(hs.GetFirstString(""))
if r.Severity > maxSeverity {
hs.SetIndex("", 0, strconv.Itoa(r.Severity.Int()))
tx.Waf.Logger.Debug("Set highest severity", zap.Int("severity", r.Severity.Int()))
}
mr := MatchedRule{
URI: tx.GetCollection(variables.RequestURI).GetFirstString(""),
ID: tx.ID,
ServerIPAddress: tx.GetCollection(variables.ServerAddr).GetFirstString(""),
ClientIPAddress: tx.GetCollection(variables.RemoteAddr).GetFirstString(""),
Rule: r,
MatchedDatas: mds,
}
for _, md := range mds {
// Use 1st set message of rule chain as message
if md.Message != "" {
mr.Message = md.Message
mr.Data = md.Data
break
}
}
tx.MatchedRules = append(tx.MatchedRules, mr)
if tx.Waf.errorLogCb != nil && r.Log {
tx.Waf.errorLogCb(mr)
}
}
// GetStopWatch is used to debug phase durations
// Normally it should be named StopWatch() but it would be confusing
func (tx *Transaction) GetStopWatch() string {
ts := tx.Timestamp
sum := int64(0)
for _, r := range tx.stopWatches {
sum += r
}
diff := time.Now().UnixNano() - ts
sw := fmt.Sprintf("%d %d; combined=%d, p1=%d, p2=%d, p3=%d, p4=%d, p5=%d",
ts, diff, sum, tx.stopWatches[1], tx.stopWatches[2], tx.stopWatches[3], tx.stopWatches[4], tx.stopWatches[5])
return sw
}
// GetField Retrieve data from collections applying exceptions
// In future releases we may remove de exceptions slice and
// make it easier to use
func (tx *Transaction) GetField(rv ruleVariableParams) []MatchData {
collection := rv.Variable
col := tx.GetCollection(collection)
if col == nil {
return []MatchData{}
}
matches := []MatchData{}
// In this case we are going to use the bodyprocessor to get the data
// It requires the VariableHook() function to match the current variable
if tx.bodyProcessor != nil && tx.bodyProcessor.VariableHook() == collection {
m, err := tx.bodyProcessor.Find(rv.KeyStr)
if err != nil {
tx.Waf.Logger.Error("error getting variable", zap.String("collection", collection.Name()),
zap.String("key", rv.KeyStr), zap.Error(err))
return []MatchData{}
}
if len(m) == 0 {
return []MatchData{}
}
for key, values := range m {
for _, value := range values {
matches = append(matches, MatchData{
VariableName: collection.Name(),
Variable: collection,
Key: key,
Value: value,
})
}
}
} else {
// in case we are not using a variable hook
// Now that we have access to the collection, we can apply the exceptions
if rv.KeyRx == nil {
matches = col.FindString(rv.KeyStr)
} else {
matches = col.FindRegex(rv.KeyRx)
}
}
rmi := []int{}
for i, c := range matches {
for _, ex := range rv.Exceptions {
lkey := strings.ToLower(c.Key)
// in case it matches the regex or the keyStr
// Since keys are case sensitive we need to check with lower case
if (ex.KeyRx != nil && ex.KeyRx.MatchString(lkey)) || strings.ToLower(ex.KeyStr) == lkey {
tx.Waf.Logger.Debug("Variable exception triggered", zap.String("var", rv.Variable.Name()),
zap.String("key", ex.KeyStr), zap.String("txid", tx.ID), zap.String("match", c.Key),
zap.Bool("regex", ex.KeyRx != nil))
// we remove the exception from the list of values
// we tried with standard append, but it fails... let's do some hacking
// m2 := append(matches[:i], matches[i+1:]...)
rmi = append(rmi, i)
}
}
}
// we read the list of indexes backwards
// then we remove each one of them because of the exceptions
for i := len(rmi) - 1; i >= 0; i-- {
if len(matches) < rmi[i]+1 {
matches = matches[:rmi[i]-1]
} else {
matches = append(matches[:rmi[i]], matches[rmi[i]+1:]...)
}
}
if rv.Count {
count := len(matches)
matches = []MatchData{
{
VariableName: collection.Name(),
Variable: collection,
Key: rv.KeyStr,
Value: strconv.Itoa(count),
},
}
tx.Waf.Logger.Debug("Transforming match to count", zap.String("tx", tx.ID),
zap.String("count", matches[0].Value))
}
return matches
}
// GetCollection transforms a VARIABLE_ constant into a
// *Collection used to get VARIABLES data
func (tx *Transaction) GetCollection(variable variables.RuleVariable) *Collection {
return tx.collections[variable]
}
// RemoveRuleTargetByID Removes the VARIABLE:KEY from the rule ID
// It's mostly used by CTL to dynamically remove targets from rules
func (tx *Transaction) RemoveRuleTargetByID(id int, variable variables.RuleVariable, key string) {
c := ruleVariableParams{
Variable: variable,
KeyStr: key,
}
tx.ruleRemoveTargetByID[id] = append(tx.ruleRemoveTargetByID[id], c)
}
// RemoveRuleByID Removes a rule from the transaction
// It does not affect the WAF rules
func (tx *Transaction) RemoveRuleByID(id int) {
tx.ruleRemoveByID = append(tx.ruleRemoveByID, id)
}
// ProcessRequest fills all transaction variables from an http.Request object
// Most implementations of Coraza will probably use http.Request objects
// so this will implement all phase 0, 1 and 2 variables
// Note: This function will stop after an interruption
// Note: Do not manually fill any request variables
func (tx *Transaction) ProcessRequest(req *http.Request) (*types.Interruption, error) {
var client string
cport := 0
// IMPORTANT: Some http.Request.RemoteAddr implementations will not contain port or contain IPV6: [2001:db8::1]:8080
spl := strings.Split(req.RemoteAddr, ":")
if len(spl) > 1 {
client = strings.Join(spl[0:len(spl)-1], "")
cport, _ = strconv.Atoi(spl[len(spl)-1])
}
var in *types.Interruption
// There is no socket access in the request object so we don't know the server client or port
tx.ProcessConnection(client, cport, "", 0)
tx.ProcessURI(req.URL.String(), req.Method, req.Proto)
for k, vr := range req.Header {
for _, v := range vr {
tx.AddRequestHeader(k, v)
}
}
// Host will always be removed from req.Headers(), so we manually add it
if req.Host != "" {
tx.AddRequestHeader("Host", req.Host)
}
in = tx.ProcessRequestHeaders()
if in != nil {
return in, nil
}
if req.Body != nil {
_, err := io.Copy(tx.RequestBodyBuffer, req.Body)
if err != nil {
return tx.Interruption, err
}
reader, err := tx.RequestBodyBuffer.Reader()
if err != nil {
return tx.Interruption, err
}
req.Body = io.NopCloser(reader)
}
return tx.ProcessRequestBody()
}
// ProcessConnection should be called at very beginning of a request process, it is
// expected to be executed prior to the virtual host resolution, when the
// connection arrives on the server.
// Important: Remember to check for a possible intervention.
func (tx *Transaction) ProcessConnection(client string, cPort int, server string, sPort int) {
p := strconv.Itoa(cPort)
p2 := strconv.Itoa(sPort)
// Modsecurity removed this, so maybe we do the same, such a copycat
// addr, err := net.LookupAddr(client)
// if err == nil {
// tx.GetCollection(VARIABLE_REMOTE_HOST).Set("", []string{addr[0]})
// }else{
// tx.GetCollection(VARIABLE_REMOTE_HOST).Set("", []string{client})
// }
tx.GetCollection(variables.RemoteAddr).SetIndex("", 0, client)
tx.GetCollection(variables.RemotePort).SetIndex("", 0, p)
tx.GetCollection(variables.ServerAddr).SetIndex("", 0, server)
tx.GetCollection(variables.ServerPort).SetIndex("", 0, p2)
}
// ExtractArguments transforms an url encoded string to a map and creates
// ARGS_POST|GET
func (tx *Transaction) ExtractArguments(orig string, uri string) {
sep := "&"
if tx.Waf.ArgumentSeparator != "" {
sep = tx.Waf.ArgumentSeparator
}
data, err := url2.ParseQuery(uri, sep)
// we create a URLENCODED_ERROR if we fail to parse the URL
if err != nil {
tx.GetCollection(variables.UrlencodedError).Set("", []string{err.Error()})
}
for k, vs := range data {
for _, v := range vs {
tx.AddArgument(orig, k, v)
}
}
}
// AddArgument Add arguments GET or POST
// This will set ARGS_(GET|POST), ARGS, ARGS_NAMES, ARGS_COMBINED_SIZE and
// ARGS_(GET|POST)_NAMES
func (tx *Transaction) AddArgument(orig string, key string, value string) {
// TODO implement ARGS value limit using ArgumentsLimit
var vals, names variables.RuleVariable
if orig == "GET" {
vals = variables.ArgsGet
names = variables.ArgsGetNames
} else {
vals = variables.ArgsPost
names = variables.ArgsPostNames
}
keyl := strings.ToLower(key)
tx.GetCollection(variables.Args).AddCS(keyl, key, value)
// Do not change case for Names: Modsecurity compatibility
tx.GetCollection(variables.ArgsNames).Add(key, key)
tx.GetCollection(vals).AddCS(keyl, key, value)
// Do not change case for Names: Modsecurity compatibility
tx.GetCollection(names).Add(key, key)
col := tx.GetCollection(variables.ArgsCombinedSize)
i := col.GetFirstInt64("") + int64(len(key)+len(value))
istr := strconv.FormatInt(i, 10)
col.Set("", []string{istr})
}
// ProcessURI Performs the analysis on the URI and all the query string variables.
// This method should be called at very beginning of a request process, it is
// expected to be executed prior to the virtual host resolution, when the
// connection arrives on the server.
// note: There is no direct connection between this function and any phase of
// the SecLanguages phases. It is something that may occur between the
// SecLanguage phase 1 and 2.
// note: This function won't add GET arguments, they must be added with AddArgument
func (tx *Transaction) ProcessURI(uri string, method string, httpVersion string) {
tx.GetCollection(variables.RequestMethod).SetIndex("", 0, method)
tx.GetCollection(variables.RequestProtocol).SetIndex("", 0, httpVersion)
tx.GetCollection(variables.RequestURIRaw).SetIndex("", 0, uri)
// TODO modsecurity uses HTTP/${VERSION} instead of just version, let's check it out
tx.GetCollection(variables.RequestLine).SetIndex("", 0, fmt.Sprintf("%s %s %s", method, uri, httpVersion))
var err error
// we remove anchors
if in := strings.Index(uri, "#"); in != -1 {
uri = uri[:in]
}
path := ""
parsedURL, err := url.Parse(uri)
query := ""
if err != nil {
tx.GetCollection(variables.UrlencodedError).Set("", []string{err.Error()})
path = uri
tx.GetCollection(variables.RequestURI).Set("", []string{uri})
/*
tx.GetCollection(VARIABLE_URI_PARSE_ERROR).Set("", []string{"1"})
posRawQuery := strings.Index(uri, "?")
if posRawQuery != -1 {
tx.ExtractArguments("GET", uri[posRawQuery+1:])
path = uri[:posRawQuery]
query = uri[posRawQuery+1:]
} else {
path = uri
}
tx.GetCollection(variables.RequestUri).Set("", []string{uri})
*/
} else {
tx.ExtractArguments("GET", parsedURL.RawQuery)
tx.GetCollection(variables.RequestURI).Set("", []string{parsedURL.String()})
path = parsedURL.Path
query = parsedURL.RawQuery
}
offset := strings.LastIndexAny(path, "/\\")
if offset != -1 && len(path) > offset+1 {
tx.GetCollection(variables.RequestBasename).Set("", []string{path[offset+1:]})
} else {
tx.GetCollection(variables.RequestBasename).Set("", []string{path})
}
tx.GetCollection(variables.RequestFilename).Set("", []string{path})
tx.GetCollection(variables.QueryString).Set("", []string{query})
}
// ProcessRequestHeaders Performs the analysis on the request readers.
//
// This method perform the analysis on the request headers, notice however
// that the headers should be added prior to the execution of this function.
//
// note: Remember to check for a possible intervention.
func (tx *Transaction) ProcessRequestHeaders() *types.Interruption {
if tx.RuleEngine == types.RuleEngineOff {
// RUle engine is disabled
return nil
}
tx.Waf.Rules.Eval(types.PhaseRequestHeaders, tx)
return tx.Interruption
}
// ProcessRequestBody Performs the request body (if any)
//
// This method perform the analysis on the request body. It is optional to
// call that function. If this API consumer already know that there isn't a
// body for inspect it is recommended to skip this step.
//
// Remember to check for a possible intervention.
func (tx *Transaction) ProcessRequestBody() (*types.Interruption, error) {
if tx.RuleEngine == types.RuleEngineOff {
return nil, nil
}
// we won't process empty request bodies or disabled RequestBodyAccess
if !tx.RequestBodyAccess || tx.RequestBodyBuffer.Size() == 0 {
tx.Waf.Rules.Eval(types.PhaseRequestBody, tx)
return tx.Interruption, nil
}
mime := ""
if m := tx.GetCollection(variables.RequestHeaders).Get("content-type"); len(m) > 0 {
mime = m[0]
}
reader, err := tx.RequestBodyBuffer.Reader()
if err != nil {
return nil, err
}
// Chunked requests will always be written to a temporary file
if tx.RequestBodyBuffer.Size() >= tx.RequestBodyLimit {
tx.GetCollection(variables.InboundErrorData).Set("", []string{"1"})
if tx.Waf.RequestBodyLimitAction == types.RequestBodyLimitActionReject {
// We interrupt this transaction in case RequestBodyLimitAction is Reject
tx.Interruption = &types.Interruption{
Status: 403,
Action: "deny",
}
return tx.Interruption, nil
}
if tx.Waf.RequestBodyLimitAction == types.RequestBodyLimitActionProcessPartial {
tx.GetCollection(variables.InboundErrorData).Set("", []string{"1"})
// we limit our reader to tx.RequestBodyLimit bytes
reader = io.LimitReader(reader, tx.RequestBodyLimit)
}
}
rbp := tx.GetCollection(variables.ReqbodyProcessor).GetFirstString("")
// Default variables.ReqbodyProcessor values
// XML and JSON must be forced with ctl:requestBodyProcessor=JSON
if tx.ForceRequestBodyVariable {
// We force URLENCODED if mime is x-www... or we have an empty RBP and ForceRequestBodyVariable
rbp = "URLENCODED"
tx.GetCollection(variables.ReqbodyProcessor).Set("", []string{rbp})
}
tx.Waf.Logger.Debug("Attempting to process request body", zap.String("txid", tx.ID),
zap.String("bodyprocessor", rbp))
rbp = strings.ToLower(rbp)
if rbp == "" {
// so there is no bodyprocessor, we don't want to generate an error
tx.Waf.Rules.Eval(types.PhaseRequestBody, tx)
return tx.Interruption, nil
}
bodyprocessor, err := bodyprocessors.GetBodyProcessor(rbp)
if err != nil {
tx.generateReqbodyError(err)
tx.Waf.Rules.Eval(types.PhaseRequestBody, tx)
return tx.Interruption, nil
}
if err := bodyprocessor.Read(reader, bodyprocessors.Options{
Mime: mime,
StoragePath: tx.Waf.UploadDir,
}); err != nil {
tx.generateReqbodyError(err)
tx.Waf.Rules.Eval(types.PhaseRequestBody, tx)
return tx.Interruption, nil
}
tx.bodyProcessor = bodyprocessor
// we insert the collections from the bodyprocessor into the collections map
for k, m := range tx.bodyProcessor.Collections() {
if k == variables.Args {
// for ARGS we make a different process, as ARGS are POST + GET and it requires ARGS_COMBINED_SIZE
size := 0
for _, vv := range m {
for _, v := range vv {
size += len(v)
}
}
tx.GetCollection(variables.ArgsCombinedSize).Set("", []string{strconv.Itoa(size)})
// in case we receive Args, we must add manually the args and argsnames, otherwise it will be overwritten
for kk, vv := range m {
tx.GetCollection(variables.Args).Set(kk, vv)
tx.GetCollection(variables.ArgsNames).AddUnique(kk, kk)
}
} else {
for mk, mv := range m {
tx.GetCollection(k).Set(mk, mv)
}
}
}
tx.Waf.Rules.Eval(types.PhaseRequestBody, tx)
return tx.Interruption, nil
}
// ProcessResponseHeaders Perform the analysis on the response readers.
//
// This method perform the analysis on the response headers, notice however
// that the headers should be added prior to the execution of this function.
//
// note: Remember to check for a possible intervention.
//
func (tx *Transaction) ProcessResponseHeaders(code int, proto string) *types.Interruption {
c := strconv.Itoa(code)
tx.GetCollection(variables.ResponseStatus).Set("", []string{c})
tx.GetCollection(variables.ResponseProtocol).Set("", []string{proto})
if tx.RuleEngine == types.RuleEngineOff {
return nil
}
tx.Waf.Rules.Eval(types.PhaseResponseHeaders, tx)
return tx.Interruption
}
// IsProcessableResponseBody returns true if the response body meets the
// criteria to be processed, response headers must be set before this.
// The content-type response header must be in the SecRequestBodyMime
// This is used by webservers to choose whether tostream response buffers
// directly to the client or write them to Coraza
func (tx *Transaction) IsProcessableResponseBody() bool {
// TODO add more validations
ct := tx.GetCollection(variables.ResponseContentType).GetFirstString("")
return utils.InSlice(ct, tx.Waf.ResponseBodyMimeTypes)
}
// ProcessResponseBody Perform the request body (if any)
//
// This method perform the analysis on the request body. It is optional to
// call that method. If this API consumer already know that there isn't a
// body for inspect it is recommended to skip this step.
//
// note Remember to check for a possible intervention.
func (tx *Transaction) ProcessResponseBody() (*types.Interruption, error) {
if tx.RuleEngine == types.RuleEngineOff {
return tx.Interruption, nil
}
if !tx.ResponseBodyAccess || !tx.IsProcessableResponseBody() {
tx.Waf.Rules.Eval(types.PhaseResponseBody, tx)
return tx.Interruption, nil
}
reader, err := tx.ResponseBodyBuffer.Reader()
if err != nil {
return nil, err
}
reader = io.LimitReader(reader, tx.Waf.ResponseBodyLimit)
buf := new(strings.Builder)
length, _ := io.Copy(buf, reader)
if tx.ResponseBodyBuffer.Size() >= tx.Waf.ResponseBodyLimit {
tx.GetCollection(variables.OutboundDataError).Set("", []string{"1"})
}
tx.GetCollection(variables.ResponseContentLength).Set("", []string{strconv.FormatInt(length, 10)})
tx.GetCollection(variables.ResponseBody).Set("", []string{buf.String()})
tx.Waf.Rules.Eval(types.PhaseResponseBody, tx)
return tx.Interruption, nil
}
// ProcessLogging Logging all information relative to this transaction.
// An error log
// At this point there is not need to hold the connection, the response can be
// delivered prior to the execution of this method.
func (tx *Transaction) ProcessLogging() {
// I'm not sure why but modsecurity won't log if RuleEngine is disabled
// if tx.RuleEngine == RULE_ENGINE_OFF {
// return
// }
tx.Waf.Rules.Eval(types.PhaseLogging, tx)
if tx.AuditEngine == types.AuditEngineOff {
// Audit engine disabled
tx.Waf.Logger.Debug("Transaction not marked for audit logging, AuditEngine is disabled",
zap.String("tx", tx.ID),
)
return
}
if tx.AuditEngine == types.AuditEngineRelevantOnly && !tx.audit {
// Transaction marked not for audit logging
tx.Waf.Logger.Debug("Transaction not marked for audit logging, AuditEngine is RelevantOnly and we got noauditlog")
return
}
if tx.AuditEngine == types.AuditEngineRelevantOnly && tx.audit {
re := tx.Waf.AuditLogRelevantStatus
status := tx.GetCollection(variables.ResponseStatus).GetFirstString("")
if re != nil && !re.Match([]byte(status)) {
// Not relevant status
tx.Waf.Logger.Debug("Transaction status not marked for audit logging",
zap.String("tx", tx.ID),
)
return
}
}
tx.Waf.Logger.Debug("Transaction marked for audit logging",
zap.String("tx", tx.ID),
)
if writer := tx.Waf.AuditLogWriter; writer != nil {
// we don't log if there is an empty audit logger
if err := writer.Write(tx.AuditLog()); err != nil {
tx.Waf.Logger.Error(err.Error())
}
}
}
// Interrupted will return true if the transaction was interrupted
func (tx *Transaction) Interrupted() bool {
return tx.Interruption != nil
}
// PrintLog prints the detection log for detection to stderr
func (tx *Transaction) PrintLog() {
for _, mr := range tx.MatchedRules {
r := mr.Rule
fmt.Println("Rule:", r.ID, "Message:", mr.Message, "Data:", mr.Data)
for _, matchData := range mr.MatchedDatas {
fmt.Println(
"Variable:", matchData.Variable,
" Key:", matchData.Key,
" Value:", matchData.Value,
" Message:", matchData.Message,
" Data:", matchData.Data,
)
}
}
}
// AuditLog returns an AuditLog struct, used to write audit logs
func (tx *Transaction) AuditLog() *loggers.AuditLog {
al := &loggers.AuditLog{}
al.Messages = []loggers.AuditMessage{}
// YYYY/MM/DD HH:mm:ss
ts := time.Unix(0, tx.Timestamp).Format("2006/01/02 15:04:05")
al.Parts = tx.AuditLogParts
al.Transaction = loggers.AuditTransaction{
Timestamp: ts,
UnixTimestamp: tx.Timestamp,
ID: tx.ID,
ClientIP: tx.GetCollection(variables.RemoteAddr).GetFirstString(""),
ClientPort: tx.GetCollection(variables.RemotePort).GetFirstInt(""),
HostIP: tx.GetCollection(variables.ServerAddr).GetFirstString(""),
HostPort: tx.GetCollection(variables.ServerPort).GetFirstInt(""),
ServerID: tx.GetCollection(variables.ServerName).GetFirstString(""), // TODO check
Request: loggers.AuditTransactionRequest{
Method: tx.GetCollection(variables.RequestMethod).GetFirstString(""),
Protocol: tx.GetCollection(variables.RequestProtocol).GetFirstString(""),
URI: tx.GetCollection(variables.RequestURI).GetFirstString(""),
HTTPVersion: tx.GetCollection(variables.RequestProtocol).GetFirstString(""),
// Body and headers are audit variables.RequestUriRaws
},
Response: loggers.AuditTransactionResponse{
Status: tx.GetCollection(variables.ResponseStatus).GetFirstInt(""),
// body and headers are audit parts
},
}
rengine := tx.RuleEngine.String()
al.Transaction.Request.Headers = tx.GetCollection(variables.RequestHeaders).Data()
al.Transaction.Request.Body = tx.GetCollection(variables.RequestBody).GetFirstString("")
// TODO maybe change to:
// al.Transaction.Request.Body = tx.RequestBodyBuffer.String()
al.Transaction.Response.Headers = tx.GetCollection(variables.ResponseHeaders).Data()
al.Transaction.Response.Body = tx.GetCollection(variables.ResponseBody).GetFirstString("")
al.Transaction.Producer = loggers.AuditTransactionProducer{
Connector: tx.Waf.ProducerConnector,
Version: tx.Waf.ProducerConnectorVersion,
Server: "",
RuleEngine: rengine,
Stopwatch: tx.GetStopWatch(),
Rulesets: tx.Waf.ComponentNames,
}
/*
* TODO:
* This part is a replacement for part C. It will log the same data as C in
* all cases except when multipart/form-data encoding in used. In this case,
* it will log a fake application/x-www-form-urlencoded body that contains
* the information about parameters but not about the files. This is handy
* if you don’t want to have (often large) files stored in your audit logs.
*/
// upload data
files := []loggers.AuditTransactionRequestFiles{}
al.Transaction.Request.Files = []loggers.AuditTransactionRequestFiles{}
for i, name := range tx.GetCollection(variables.Files).Get("") {
// TODO we kind of assume there is a file_size for each file with the same index
size, _ := strconv.ParseInt(tx.GetCollection(variables.FilesSizes).Get("")[i], 10, 64)
ext := filepath.Ext(name)
at := loggers.AuditTransactionRequestFiles{
Size: size,
Name: name,
Mime: mime.TypeByExtension(ext),
}
files = append(files, at)
}
al.Transaction.Request.Files = files
mrs := []loggers.AuditMessage{}
for _, mr := range tx.MatchedRules {
r := mr.Rule
for _, matchData := range mr.MatchedDatas {
mrs = append(mrs, loggers.AuditMessage{
Actionset: strings.Join(tx.Waf.ComponentNames, " "),
Message: matchData.Message,
Data: loggers.AuditMessageData{
File: mr.Rule.File,
Line: mr.Rule.Line,
ID: r.ID,
Rev: r.Rev,
Msg: matchData.Message,
Data: matchData.Data,
Severity: r.Severity,
Ver: r.Version,
Maturity: r.Maturity,
Accuracy: r.Accuracy,
Tags: r.Tags,
Raw: r.Raw,
},
})
}
}
al.Messages = mrs
return al
}
// Clean the transaction after phase 5
// This method helps the GC to clean up the transaction faster and release resources
// It also allows caches the transaction back into the sync.Pool
func (tx *Transaction) Clean() error {
defer transactionPool.Put(tx)
for k := range tx.collections {
tx.collections[k] = nil
}
if err := tx.RequestBodyBuffer.Close(); err != nil {
return err
}
if err := tx.ResponseBodyBuffer.Close(); err != nil {
return err
}
tx.Waf.Logger.Debug("Transaction finished", zap.String("event", "FINISH_TRANSACTION"), zap.String("txid", tx.ID), zap.Bool("interrupted", tx.Interrupted()))
return nil
}
// generateReqbodyError generates all the error variables for the request body parser
func (tx *Transaction) generateReqbodyError(err error) {
tx.GetCollection(variables.ReqbodyError).Set("", []string{"1"})
tx.GetCollection(variables.ReqbodyErrorMsg).Set("", []string{string(err.Error())})
tx.GetCollection(variables.ReqbodyProcessorError).Set("", []string{"1"})
tx.GetCollection(variables.ReqbodyProcessorErrorMsg).Set("", []string{string(err.Error())})
}