-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
transaction.cc
2312 lines (2036 loc) · 72.8 KB
/
transaction.cc
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
/*
* ModSecurity, http://www.modsecurity.org/
* Copyright (c) 2015 - 2021 Trustwave Holdings, Inc. (http://www.trustwave.com/)
*
* 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
*
* If any of the files related to licensing are missing or if you have any
* other questions related to licensing please contact Trustwave Holdings, Inc.
* directly using the email address [email protected].
*
*/
#include "modsecurity/transaction.h"
#ifdef WITH_YAJL
#include <yajl/yajl_tree.h>
#include <yajl/yajl_gen.h>
#endif
#include <stdio.h>
#include <string.h>
#include <cstdio>
#include <ctime>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <set>
#include <unordered_map>
#include <vector>
#include "modsecurity/actions/action.h"
#include "src/actions/disruptive/deny.h"
#include "modsecurity/intervention.h"
#include "modsecurity/modsecurity.h"
#include "src/request_body_processor/multipart.h"
#include "src/request_body_processor/xml.h"
#ifdef WITH_YAJL
#include "src/request_body_processor/json.h"
#endif
#include "modsecurity/audit_log.h"
#include "src/unique_id.h"
#include "src/utils/string.h"
#include "src/utils/system.h"
#include "src/utils/decode.h"
#include "src/utils/random.h"
#include "modsecurity/rule.h"
#include "modsecurity/rule_message.h"
#include "modsecurity/rules_set_properties.h"
#include "src/actions/disruptive/allow.h"
#include "src/variables/remote_user.h"
using modsecurity::actions::Action;
using modsecurity::RequestBodyProcessor::Multipart;
using modsecurity::RequestBodyProcessor::XML;
namespace modsecurity {
/**
* @name Transaction
* @brief Represents the inspection on an entire request.
*
* An instance of the Transaction class represents an entire request, on its
* different phases.
*
* @param ms ModSecurity core instance.
* @param rules Rules instance.
*
* Example Usage:
* @code
*
* using ModSecurity::ModSecurity;
* using ModSecurity::Rules;
* using ModSecurity::Transaction;
*
* ModSecurity *modsec;
* ModSecurity::Rules *rules;
*
* modsec = new ModSecurity();
* rules = new Rules();
* rules->loadFromUri(rules_file);
*
* Transaction *modsecTransaction = new Transaction(modsec, rules);
* modsecTransaction->processConnection("127.0.0.1", 33333, "127.0.0.1", 8080);
*
* if (modsecTransaction->intervention()) {
* std::cout << "There is an intervention" << std::endl;
* }
*
* ...
*
* delete modsecTransaction;
*
* @endcode
*
*/
Transaction::Transaction(ModSecurity *ms, RulesSet *rules, void *logCbData)
: m_creationTimeStamp(utils::cpu_seconds()),
/* m_clientIpAddress(nullptr), */
m_httpVersion(""),
/* m_serverIpAddress(""), */
m_uri(""),
/* m_uri_no_query_string_decoded(""), */
m_ARGScombinedSizeDouble(0),
m_clientPort(0),
m_highestSeverityAction(255),
m_httpCodeReturned(200),
m_serverPort(0),
m_ms(ms),
m_requestBodyType(UnknownFormat),
m_requestBodyProcessor(UnknownFormat),
m_rules(rules),
m_ruleRemoveById(),
m_ruleRemoveByIdRange(),
m_ruleRemoveByTag(),
m_ruleRemoveTargetByTag(),
m_ruleRemoveTargetById(),
m_requestBodyAccess(RulesSet::PropertyNotSetConfigBoolean),
m_auditLogModifier(),
m_rulesMessages(),
m_requestBody(),
m_responseBody(),
/* m_id(), */
m_skip_next(0),
m_allowType(modsecurity::actions::disruptive::NoneAllowType),
m_uri_decoded(""),
m_actions(),
m_it(),
m_timeStamp(std::time(NULL)),
m_collections(ms->m_global_collection, ms->m_ip_collection,
ms->m_session_collection, ms->m_user_collection,
ms->m_resource_collection),
m_matched(),
#ifdef WITH_LIBXML2
m_xml(new RequestBodyProcessor::XML(this)),
#else
m_xml(NULL),
#endif
#ifdef WITH_YAJL
m_json(new RequestBodyProcessor::JSON(this)),
#else
m_json(NULL),
#endif
m_secRuleEngine(RulesSetProperties::PropertyNotSetRuleEngine),
m_variableDuration(""),
m_variableEnvs(),
m_variableHighestSeverityAction(""),
m_variableRemoteUser(""),
m_variableTime(""),
m_variableTimeDay(""),
m_variableTimeEpoch(""),
m_variableTimeHour(""),
m_variableTimeMin(""),
m_variableTimeSec(""),
m_variableTimeWDay(""),
m_variableTimeYear(""),
m_logCbData(logCbData),
TransactionAnchoredVariables(this) {
m_id = std::unique_ptr<std::string>(
new std::string(
std::to_string(m_timeStamp)));
m_variableUrlEncodedError.set("0", 0);
ms_dbg(4, "Initializing transaction");
intervention::clean(&m_it);
}
Transaction::Transaction(ModSecurity *ms, RulesSet *rules, char *id, void *logCbData)
: m_creationTimeStamp(utils::cpu_seconds()),
/* m_clientIpAddress(""), */
m_httpVersion(""),
/* m_serverIpAddress(""), */
m_uri(""),
/* m_uri_no_query_string_decoded(""), */
m_ARGScombinedSizeDouble(0),
m_clientPort(0),
m_highestSeverityAction(255),
m_httpCodeReturned(200),
m_serverPort(0),
m_ms(ms),
m_requestBodyType(UnknownFormat),
m_requestBodyProcessor(UnknownFormat),
m_rules(rules),
m_ruleRemoveById(),
m_ruleRemoveByIdRange(),
m_ruleRemoveByTag(),
m_ruleRemoveTargetByTag(),
m_ruleRemoveTargetById(),
m_requestBodyAccess(RulesSet::PropertyNotSetConfigBoolean),
m_auditLogModifier(),
m_rulesMessages(),
m_requestBody(),
m_responseBody(),
m_id(std::unique_ptr<std::string>(new std::string(id))),
m_skip_next(0),
m_allowType(modsecurity::actions::disruptive::NoneAllowType),
m_uri_decoded(""),
m_actions(),
m_it(),
m_timeStamp(std::time(NULL)),
m_collections(ms->m_global_collection, ms->m_ip_collection,
ms->m_session_collection, ms->m_user_collection,
ms->m_resource_collection),
m_matched(),
#ifdef WITH_LIBXML2
m_xml(new RequestBodyProcessor::XML(this)),
#else
m_xml(NULL),
#endif
#ifdef WITH_YAJL
m_json(new RequestBodyProcessor::JSON(this)),
#else
m_json(NULL),
#endif
m_secRuleEngine(RulesSetProperties::PropertyNotSetRuleEngine),
m_variableDuration(""),
m_variableEnvs(),
m_variableHighestSeverityAction(""),
m_variableRemoteUser(""),
m_variableTime(""),
m_variableTimeDay(""),
m_variableTimeEpoch(""),
m_variableTimeHour(""),
m_variableTimeMin(""),
m_variableTimeSec(""),
m_variableTimeWDay(""),
m_variableTimeYear(""),
m_logCbData(logCbData),
TransactionAnchoredVariables(this) {
m_variableUrlEncodedError.set("0", 0);
ms_dbg(4, "Initializing transaction");
intervention::clean(&m_it);
}
Transaction::~Transaction() {
m_responseBody.str(std::string());
m_responseBody.clear();
m_requestBody.str(std::string());
m_requestBody.clear();
m_rulesMessages.clear();
intervention::free(&m_it);
intervention::clean(&m_it);
#ifdef WITH_YAJL
delete m_json;
#endif
#ifdef WITH_LIBXML2
delete m_xml;
#endif
}
/**
* @name debug
* @brief Prints a message on the debug logs.
*
* Debug logs are important during the rules creation phase, this method can be
* used to print message on this debug log.
*
* @param level Debug level, current supported from 0 to 9.
* @param message Message to be logged.
*
*/
#ifndef NO_LOGS
void Transaction::debug(int level, std::string message) const {
if (m_rules == NULL) {
return;
}
m_rules->debug(level, *m_id.get(), m_uri, message);
}
#endif
/**
* @name processConnection
* @brief Perform the analysis on the connection.
*
* 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 Remember to check for a possible intervention.
*
* @param transaction ModSecurity Transaction.
* @param client Client's IP address in text format.
* @param cPort Client's port
* @param server Server's IP address in text format.
* @param sPort Server's port
*
* @returns If the operation was successful or not.
* @retval true Operation was successful.
* @retval false Operation failed.
*
*/
int Transaction::processConnection(const char *client, int cPort,
const char *server, int sPort) {
m_clientIpAddress = std::unique_ptr<std::string>(new std::string(client));
m_serverIpAddress = std::unique_ptr<std::string>(new std::string(server));
this->m_clientPort = cPort;
this->m_serverPort = sPort;
ms_dbg(4, "Transaction context created.");
ms_dbg(4, "Starting phase CONNECTION. (SecRules 0)");
m_variableRemoteHost.set(*m_clientIpAddress.get(), m_variableOffset);
m_variableUniqueID.set(*m_id.get(), m_variableOffset);
m_variableRemoteAddr.set(*m_clientIpAddress.get(), m_variableOffset);
m_variableServerAddr.set(*m_serverIpAddress.get(), m_variableOffset);
m_variableServerPort.set(std::to_string(this->m_serverPort),
m_variableOffset);
m_variableRemotePort.set(std::to_string(this->m_clientPort),
m_variableOffset);
this->m_rules->evaluate(modsecurity::ConnectionPhase, this);
return true;
}
bool Transaction::extractArguments(const std::string &orig,
const std::string& buf, size_t offset) {
char sep1 = '&';
if (m_rules->m_secArgumentSeparator.m_set) {
sep1 = m_rules->m_secArgumentSeparator.m_value.at(0);
}
std::vector<std::string> key_value_sets = utils::string::ssplit(buf, sep1);
for (std::string t : key_value_sets) {
char sep2 = '=';
size_t key_s = 0;
size_t value_s = 0;
int invalid = 0;
int changed = 0;
std::string key;
std::string value;
std::pair<std::string, std::string> key_value_pair = utils::string::ssplit_pair(t, sep2);
key = key_value_pair.first;
value = key_value_pair.second;
key_s = (key.length() + 1);
value_s = (value.length() + 1);
unsigned char *key_c = reinterpret_cast<unsigned char *>(
calloc(sizeof(char), key_s));
unsigned char *value_c = reinterpret_cast<unsigned char *>(
calloc(sizeof(char), value_s));
memcpy(key_c, key.c_str(), key_s);
memcpy(value_c, value.c_str(), value_s);
key_s = utils::urldecode_nonstrict_inplace(key_c, key_s,
&invalid, &changed);
value_s = utils::urldecode_nonstrict_inplace(value_c, value_s,
&invalid, &changed);
if (invalid) {
m_variableUrlEncodedError.set("1", m_variableOffset);
}
addArgument(orig, std::string(reinterpret_cast<char *>(key_c), key_s-1),
std::string(reinterpret_cast<char *>(value_c), value_s-1), offset);
offset = offset + t.size() + 1;
free(key_c);
free(value_c);
}
return true;
}
bool Transaction::addArgument(const std::string& orig, const std::string& key,
const std::string& value, size_t offset) {
ms_dbg(4, "Adding request argument (" + orig + "): name \"" + \
key + "\", value \"" + value + "\"");
if (m_rules->m_argumentsLimit.m_set
&& m_variableArgs.size() >= m_rules->m_argumentsLimit.m_value) {
ms_dbg(4, "Skipping request argument, over limit (" + std::to_string(m_rules->m_argumentsLimit.m_value) + ")")
return false;
}
offset = offset + key.size() + 1;
m_variableArgs.set(key, value, offset);
if (orig == "GET") {
m_variableArgsGet.set(key, value, offset);
} else if (orig == "POST") {
m_variableArgsPost.set(key, value, offset);
}
m_ARGScombinedSizeDouble = m_ARGScombinedSizeDouble + \
key.length() + value.length();
m_variableARGScombinedSize.set(std::to_string(m_ARGScombinedSizeDouble),
offset - key.size() - 1, key.size());
m_variableARGScombinedSize.set(std::to_string(m_ARGScombinedSizeDouble),
offset, value.length());
return true;
}
/**
* @name processURI
* @brief Perform 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 SecLanguage's phases. It is something that may occur between the
* SecLanguage phase 1 and 2.
* @note Remember to check for a possible intervention.
*
* @param transaction ModSecurity transaction.
* @param uri Uri.
* @param method Method (GET, POST, PUT).
* @param http_version Http version (1.0, 1.1, 2.0).
*
* @returns If the operation was successful or not.
* @retval true Operation was successful.
* @retval false Operation failed.
*
*/
int Transaction::processURI(const char *uri, const char *method,
const char *http_version) {
ms_dbg(4, "Starting phase URI. (SecRules 0 + 1/2)");
m_httpVersion = http_version;
m_uri = uri;
std::string uri_s(uri);
m_uri_decoded = utils::uri_decode(uri);
size_t pos = m_uri_decoded.find("?");
size_t pos_raw = uri_s.find("?");
size_t var_size = pos_raw;
m_variableRequestMethod.set(method, 0);
std::string requestLine(std::string(method) + " " + std::string(uri));
m_variableRequestLine.set(requestLine \
+ " HTTP/" + std::string(http_version), m_variableOffset);
m_variableRequestProtocol.set("HTTP/" + std::string(http_version),
m_variableOffset + requestLine.size() + 1);
if (pos != std::string::npos) {
m_uri_no_query_string_decoded = std::unique_ptr<std::string>(
new std::string(m_uri_decoded, 0, pos));
} else {
m_uri_no_query_string_decoded = std::unique_ptr<std::string>(
new std::string(m_uri_decoded));
}
if (pos_raw != std::string::npos) {
std::string qry = std::string(uri_s, pos_raw + 1,
uri_s.length() - (pos_raw + 1));
m_variableQueryString.set(qry, pos_raw + 1
+ std::string(method).size() + 1);
}
std::string path_info;
if (pos == std::string::npos) {
path_info = std::string(m_uri_decoded, 0);
} else {
path_info = std::string(m_uri_decoded, 0, pos);
}
if (var_size == std::string::npos) {
var_size = uri_s.size();
}
m_variablePathInfo.set(path_info, m_variableOffset + strlen(method) +
1, var_size);
m_variableRequestFilename.set(path_info, m_variableOffset +
strlen(method) + 1, var_size);
size_t offset = path_info.find_last_of("/\\");
if (offset != std::string::npos && path_info.length() > offset + 1) {
std::string basename = std::string(path_info, offset + 1,
path_info.length() - (offset + 1));
m_variableRequestBasename.set(basename, m_variableOffset +
strlen(method) + 1 + offset + 1);
}
m_variableOffset = m_variableRequestLine.m_value.size();
std::string parsedURI = m_uri_decoded;
// The more popular case is without domain
if (!m_uri_decoded.empty() && m_uri_decoded.at(0) != '/') {
bool fullDomain = true;
size_t scheme = m_uri_decoded.find(":")+1;
if (scheme == std::string::npos) {
fullDomain = false;
}
// Searching with a pos of -1 is undefined we also shortcut
if (scheme != std::string::npos && fullDomain == true) {
// Assuming we found a colon make sure its followed
size_t netloc = m_uri_decoded.find("//", scheme) + 2;
if (netloc == std::string::npos || (netloc != scheme + 2)) {
fullDomain = false;
}
if (netloc != std::string::npos && fullDomain == true) {
size_t path = m_uri_decoded.find("/", netloc);
if (path != std::string::npos && fullDomain == true) {
parsedURI = m_uri_decoded.substr(path);
}
}
}
}
m_variableRequestURI.set(parsedURI, std::string(method).size() + 1,
uri_s.size());
m_variableRequestURIRaw.set(uri, std::string(method).size() + 1);
if (m_variableQueryString.m_value.empty() == false) {
extractArguments("GET", m_variableQueryString.m_value,
m_variableQueryString.m_offset);
}
m_variableOffset = m_variableOffset + 1;
return true;
}
/**
* @name processRequestHeaders
* @brief Perform 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.
*
* @returns If the operation was successful or not.
* @retval true Operation was successful.
* @retval false Operation failed.
*
*/
int Transaction::processRequestHeaders() {
ms_dbg(4, "Starting phase REQUEST_HEADERS. (SecRules 1)");
if (getRuleEngineState() == RulesSet::DisabledRuleEngine) {
ms_dbg(4, "Rule engine disabled, returning...");
return true;
}
this->m_rules->evaluate(modsecurity::RequestHeadersPhase, this);
return true;
}
/**
* @name addRequestHeader
* @brief Adds a request header
*
* With this method it is possible to feed ModSecurity with a request header.
*
* @note This function expects a NULL terminated string, for both: key and
* value.
*
* @param key header name.
* @param value header value.
*
* @returns If the operation was successful or not.
* @retval true Operation was successful.
* @retval false Operation failed.
*
*/
int Transaction::addRequestHeader(const std::string& key,
const std::string& value) {
m_variableRequestHeadersNames.set(key, key, m_variableOffset);
m_variableOffset = m_variableOffset + key.size() + 2;
m_variableRequestHeaders.set(key, value, m_variableOffset);
std::string keyl = utils::string::tolower(key);
if (keyl == "authorization") {
std::vector<std::string> type = utils::string::split(value, ' ');
m_variableAuthType.set(type[0], m_variableOffset);
}
if (keyl == "cookie") {
size_t localOffset = m_variableOffset;
size_t pos;
std::vector<std::string> cookies = utils::string::ssplit(value, ';');
if (!cookies.empty()) {
// Get rid of any optional whitespace after the cookie-string
// (i.e. after the end of the final cookie-pair)
std::string& final_cookie_pair = cookies.back();
while (!final_cookie_pair.empty() && isspace(final_cookie_pair.back())) {
final_cookie_pair.pop_back();
}
}
for (const std::string &c : cookies) {
// skip empty substring, eg "Cookie: ;;foo=bar"
if (c.empty() == true) {
localOffset++; // add length of ';'
continue;
}
// find the first '='
pos = c.find_first_of("=", 0);
std::string ckey = "";
std::string cval = "";
// if the cookie doesn't contains '=', its just a key
if (pos == std::string::npos) {
ckey = c;
}
// else split to two substrings by first =
else {
ckey = c.substr(0, pos);
// value will contains the next '=' chars if exists
// eg. foo=bar=baz -> key: foo, value: bar=baz
cval = c.substr(pos+1);
}
// ltrim the key - following the modsec v2 way
while (ckey.empty() == false && isspace(ckey.at(0))) {
ckey.erase(0, 1);
localOffset++;
}
// if the key is empty (eg: "Cookie: =bar;") skip it
if (ckey.empty() == true) {
localOffset = localOffset + c.length() + 1;
continue;
}
else {
// handle cookie only if the key is not empty
// set cookie name
m_variableRequestCookiesNames.set(ckey,
ckey, localOffset);
localOffset = localOffset + ckey.size() + 1;
// set cookie value
m_variableRequestCookies.set(ckey, cval,
localOffset);
localOffset = localOffset + cval.size() + 1;
}
}
}
/**
* Simple check to decide the request body content. This is not the right
* place, the "body processor" should be able to tell what he is capable
* to deal with.
*
*/
if (keyl == "content-type") {
std::string multipart("multipart/form-data");
std::string urlencoded("application/x-www-form-urlencoded");
std::string l = utils::string::tolower(value);
if (l.compare(0, multipart.length(), multipart) == 0) {
this->m_requestBodyType = MultiPartRequestBody;
m_variableReqbodyProcessor.set("MULTIPART", m_variableOffset);
}
if (l.compare(0, urlencoded.length(), urlencoded) == 0) {
this->m_requestBodyType = WWWFormUrlEncoded;
m_variableReqbodyProcessor.set("URLENCODED", m_variableOffset);
}
}
if (keyl == "host") {
std::vector<std::string> host = utils::string::split(value, ':');
m_variableServerName.set(host[0], m_variableOffset);
}
m_variableOffset = m_variableOffset + value.size() + 1;
return 1;
}
/**
* @name addRequestHeader
* @brief Adds a request header
*
* With this method it is possible to feed ModSecurity with a request header.
*
* @note This function expects a NULL terminated string, for both: key and
* value.
*
* @param key header name.
* @param value header value.
*
* @returns If the operation was successful or not.
* @retval true Operation was successful.
* @retval false Operation failed.
*
*/
int Transaction::addRequestHeader(const unsigned char *key,
const unsigned char *value) {
return this->addRequestHeader(key,
strlen(reinterpret_cast<const char *>(key)),
value,
strlen(reinterpret_cast<const char *>(value)));
}
/**
* @name addRequestHeader
* @brief Adds a request header
*
* Do not expect a NULL terminated string, instead it expect the string and the
* string size, for the value and key.
*
* @param transaction ModSecurity transaction.
* @param key header name.
* @param key_n header name size.
* @param value header value.
* @param value_n header value size.
*
* @returns If the operation was successful or not.
* @retval 1 Operation was successful.
* @retval 0 Operation failed.
*
*/
int Transaction::addRequestHeader(const unsigned char *key, size_t key_n,
const unsigned char *value, size_t value_n) {
std::string keys;
std::string values;
keys.assign(reinterpret_cast<const char *>(key), key_n);
values.assign(reinterpret_cast<const char *>(value), value_n);
return this->addRequestHeader(keys, values);
}
/**
* @name processRequestBody
* @brief Perform 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.
*
* @note It is necessary to "append" the request body prior to the execution
* of this function.
* @note Remember to check for a possible intervention.
*
* @returns If the operation was successful or not.
* @retval true Operation was successful.
* @retval false Operation failed.
*
*/
int Transaction::processRequestBody() {
ms_dbg(4, "Starting phase REQUEST_BODY. (SecRules 2)");
if (getRuleEngineState() == RulesSetProperties::DisabledRuleEngine) {
ms_dbg(4, "Rule engine disabled, returning...");
return true;
}
if (m_variableInboundDataError.m_value.empty() == true) {
m_variableInboundDataError.set("0", 0);
}
/*
* Process the request body even if there is nothing to be done.
*
* if (m_requestBody.tellp() <= 0) {
* return true;
* }
*
*/
std::unique_ptr<std::string> a = m_variableRequestHeaders.resolveFirst(
"Content-Type");
#ifdef WITH_LIBXML2
if (m_requestBodyProcessor == XMLRequestBody) {
std::string error;
if (m_xml->init() == true) {
m_xml->processChunk(m_requestBody.str().c_str(),
m_requestBody.str().size(),
&error);
m_xml->complete(&error);
}
if (error.empty() == false) {
m_variableReqbodyError.set("1", m_variableOffset);
m_variableReqbodyErrorMsg.set("XML parsing error: " + error,
m_variableOffset);
m_variableReqbodyProcessorErrorMsg.set("XML parsing error: " \
+ error, m_variableOffset);
m_variableReqbodyProcessorError.set("1", m_variableOffset);
} else {
m_variableReqbodyError.set("0", m_variableOffset);
m_variableReqbodyProcessorError.set("0", m_variableOffset);
}
#endif
#if WITH_YAJL
#ifdef WITH_LIBXML2
} else if (m_requestBodyProcessor == JSONRequestBody) {
#else
if (m_requestBodyProcessor == JSONRequestBody) {
#endif
std::string error;
if (m_json->init() == true) {
m_json->processChunk(m_requestBody.str().c_str(),
m_requestBody.str().size(),
&error);
m_json->complete(&error);
}
if (error.empty() == false && m_requestBody.str().size() > 0) {
m_variableReqbodyError.set("1", m_variableOffset);
m_variableReqbodyProcessorError.set("1", m_variableOffset);
m_variableReqbodyErrorMsg.set("JSON parsing error: " + error,
m_variableOffset);
m_variableReqbodyProcessorErrorMsg.set("JSON parsing error: " \
+ error, m_variableOffset);
} else {
m_variableReqbodyError.set("0", m_variableOffset);
m_variableReqbodyProcessorError.set("0", m_variableOffset);
}
#endif
#if defined(WITH_LIBXML2) or defined(WITH_YAJL)
} else if (m_requestBodyType == MultiPartRequestBody) {
#else
if (m_requestBodyType == MultiPartRequestBody) {
#endif
std::string error;
if (a != NULL) {
Multipart m(*a, this);
if (m.init(&error) == true) {
m.process(m_requestBody.str(), &error, m_variableOffset);
}
m.multipart_complete(&error);
}
if (error.empty() == false) {
m_variableReqbodyError.set("1", m_variableOffset);
m_variableReqbodyProcessorError.set("1", m_variableOffset);
m_variableReqbodyErrorMsg.set("Multipart parsing error: " + error,
m_variableOffset);
m_variableReqbodyProcessorErrorMsg.set("Multipart parsing " \
"error: " + error, m_variableOffset);
} else {
m_variableReqbodyError.set("0", m_variableOffset);
m_variableReqbodyProcessorError.set("0", m_variableOffset);
}
} else if (m_requestBodyType == WWWFormUrlEncoded) {
m_variableOffset++;
extractArguments("POST", m_requestBody.str(), m_variableOffset);
} else if (m_requestBodyType != UnknownFormat) {
/**
* FIXME: double check to see if that is a valid scenario...
*
*/
std::string error;
if (a != NULL && a->empty() == false) {
error.assign(*a);
}
m_variableReqbodyError.set("1", m_variableOffset);
m_variableReqbodyProcessorError.set("1", m_variableOffset);
m_variableReqbodyErrorMsg.set("Unknown request body processor: " \
+ error, m_variableOffset);
m_variableReqbodyProcessorErrorMsg.set("Unknown request body " \
"processor: " + error, m_variableOffset);
} else {
m_variableReqbodyError.set("0", m_variableOffset);
m_variableReqbodyProcessorError.set("0", m_variableOffset);
}
if (m_rules->m_secRequestBodyAccess == RulesSetProperties::FalseConfigBoolean) {
if (m_requestBodyAccess != RulesSetProperties::TrueConfigBoolean) {
ms_dbg(4, "Request body processing is disabled");
return true;
} else {
ms_dbg(4, "Request body processing is disabled, but " \
"enabled to this transaction due to ctl:requestBodyAccess " \
"action");
}
} else {
if (m_requestBodyAccess == RulesSetProperties::FalseConfigBoolean) {
ms_dbg(4, "Request body processing is enabled, but " \
"disabled to this transaction due to ctl:requestBodyAccess " \
"action");
return true;
}
}
/**
* FIXME: This variable should be calculated on demand, it is
* computationally intensive.
*/
std::string fullRequest;
std::vector<const VariableValue *> l;
m_variableRequestHeaders.resolve(&l);
for (auto &h : l) {
fullRequest = fullRequest + h->getKey() + ": " + h->getValue() + "\n";
delete h;
}
fullRequest = fullRequest + "\n\n";
fullRequest = fullRequest + m_requestBody.str();
m_variableFullRequest.set(fullRequest, m_variableOffset);
m_variableFullRequestLength.set(std::to_string(fullRequest.size()),
m_variableOffset);
if (m_requestBody.tellp() > 0) {
m_variableRequestBody.set(m_requestBody.str(), m_variableOffset);
m_variableRequestBodyLength.set(std::to_string(
m_requestBody.str().size()),
m_variableOffset, m_requestBody.str().size());
}
this->m_rules->evaluate(modsecurity::RequestBodyPhase, this);
return true;
}
/**
* @name appendRequestBody
* @brief Adds request body to be inspected.
*
* With this method it is possible to feed ModSecurity with data for
* inspection regarding the request body. There are two possibilities here:
*
* 1 - Adds the buffer in a row;
* 2 - Adds it in chunks;
*
* A third option should be developed which is share your application buffer.
* In any case, remember that the utilization of this function may reduce your
* server throughput, as this buffer creations is computationally expensive.
*
* @note While feeding ModSecurity remember to keep checking if there is an
* intervention, Sec Language has the capability to set the maximum
* inspection size which may be reached, and the decision on what to do
* in this case is upon the rules.
*
* @returns If the operation was successful or not.
* @retval true Operation was successful.
* @retval false Operation failed.
*
*/
int Transaction::requestBodyFromFile(const char *path) {
std::ifstream request_body(path);
std::string str;
if (request_body.is_open() == false) {
ms_dbg(3, "Failed to open request body at: " + std::string(path));
return false;
}
request_body.seekg(0, std::ios::end);
try {
str.reserve(request_body.tellg());
} catch (...) {
ms_dbg(3, "Failed to allocate memory to load request body.");
return false;
}
request_body.seekg(0, std::ios::beg);
str.assign((std::istreambuf_iterator<char>(request_body)),
std::istreambuf_iterator<char>());
const char *buf = str.c_str();
int len = request_body.tellg();
ms_dbg(9, "Adding request body: " + std::to_string(len) + " bytes. " \
"Limit set to: "
+ std::to_string(this->m_rules->m_requestBodyLimit.m_value));
return appendRequestBody(reinterpret_cast<const unsigned char*>(buf), len);
}
int Transaction::appendRequestBody(const unsigned char *buf, size_t len) {
int current_size = this->m_requestBody.tellp();
ms_dbg(9, "Appending request body: " + std::to_string(len) + " bytes. " \
"Limit set to: "
+ std::to_string(this->m_rules->m_requestBodyLimit.m_value));
if (this->m_rules->m_requestBodyLimit.m_value > 0
&& this->m_rules->m_requestBodyLimit.m_value < len + current_size) {