-
Notifications
You must be signed in to change notification settings - Fork 11
/
idsEventGenerator.cpp
1553 lines (1439 loc) · 62.5 KB
/
idsEventGenerator.cpp
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
/*
* Copyright (C) 2017 Felix Erlacher
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*
* Reads Snort rules and puts interesting fields in a struct for further usage.
* This is rather a READER than a parser, as it assumes a basic structure of rules and does not
* do in-depth checks of structure.
*
* REMARKS:
* -If hex chars are encountered (everything between two '|' signs) it is converted to ascii, but only if part of the first 128 ascii chars and only if printable
* -Whitespace in content patterns with http_uri modifier is generally converted to the + sign, if you want %20 as whitespace than change it in the rule.
*/
#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
#include <stdint.h>
#include <vector>
#include <locale>
#include <curl/curl.h>
#include <getopt.h>
#include <regex>
#include <algorithm>
#define VECTORRESERVE 10
class ruleBody{
public:
std::string msg;
std::vector<bool> negatedContent;
std::vector<std::string> contentOriginal;
std::vector<bool> containsHex;
std::vector<bool> contentNocase;
std::vector<std::string> content;
std::vector<int> contentModifierHTTP;
//content modifier are encoded for faster processing:
//1:http_method
//2:http_uri
//3:http_raw_uri
//4:http_stat_msg
//5:http_stat_code
std::vector<std::string> pcre;
std::vector<bool> negatedPcre;
std::vector<bool> pcreNocase;
std::string sid;
std::string rev;
};
class ruleHeader {
public:
std::string action;
std::string protocol;
std::string from;
std::string fromPort;
bool bidirectional;
std::string to;
std::string toPort;
};
class snortRule {
public:
ruleHeader header;
ruleBody body;
};
std::size_t bodyStartPosition;
bool printResponse=false;
bool continueOnError=false;
bool verbose=false;
int packetCounter=1;
/**
* writes error message to stderr
*/
void parsingError(int line, std::string parsingPart){
fprintf(stderr,"Error on line %d, failed to parse %s. This does not seem to be a valid Snort rule. Aborting!\n",line, parsingPart.c_str());
}
/**
* counts single rule fields (-->content vectors size) and checks if numbers match
* if this check fails something went terribly wrong while parsing!!!
*/
void plausabilityCheck(snortRule* rule, int *linenumber){
//plausability checks:
if(rule->body.content.size()==0&&rule->body.pcre.size()==0){
fprintf(stderr,"SnortRuleParser: There was an error in rule parsing: After parsing, rule with sid %s does not contain any content or pcre to check for. This should not have happened. Aborting!\n",rule->body.sid.c_str());
if(continueOnError==false){
exit(1);
}
}
if(rule->body.content.size()!=rule->body.contentOriginal.size()
||rule->body.content.size()!=rule->body.negatedContent.size()
||rule->body.content.size()!=rule->body.containsHex.size()
//the pcre http modifiers are written into the contentModifierHTTP
||(rule->body.content.size()+rule->body.pcre.size())!=rule->body.contentModifierHTTP.size()
||rule->body.content.size()!=rule->body.contentNocase.size()
||rule->body.negatedPcre.size()!=rule->body.pcre.size()
||rule->body.pcreNocase.size()!=rule->body.pcre.size()){
fprintf(stderr,"\n\nThere was an Error in rule parsing at line %d, parsed content vectors do not match in size. This should not have happened. Aborting!\n",*linenumber);
fprintf(stderr,"content: %lu, contentOriginal: %lu, pcre: %lu, negatedPcre: %lu, pcreNocase: %lu, negatedContent: %lu, containsHex: %lu, ContentModifierHttp: %lu\n",rule->body.content.size(),rule->body.contentOriginal.size(),rule->body.pcre.size(),rule->body.negatedPcre.size(),rule->body.pcreNocase.size(),rule->body.negatedContent.size(),rule->body.containsHex.size(),rule->body.contentModifierHTTP.size());
if(continueOnError==false){
exit(1);
}
}
}
/**
*prints snortRule struct to stdout
*/
void printSnortRule(snortRule* rule){
std::string modifierHttp;
//is already done in main(), so basically superfluous. But for some cases (mass checks) I might comment it there, so a "backup" here.
int dummyInt=-1;
plausabilityCheck(rule, &dummyInt);
fprintf(stdout,"Action:\t\t\t\t%s\n",rule->header.action.c_str());
fprintf(stdout,"Protocol:\t\t\t%s\n",rule->header.protocol.c_str());
fprintf(stdout,"From:\t\t\t\t\"%s\"\n",rule->header.from.c_str());
fprintf(stdout,"FromPort:\t\t\t\"%s\"\n",rule->header.fromPort.c_str());
fprintf(stdout,"To:\t\t\t\t\"%s\"\n",rule->header.to.c_str());
fprintf(stdout,"ToPort:\t\t\t\t\"%s\"\n",rule->header.toPort.c_str());
if(rule->header.bidirectional){
fprintf(stdout,"Direction:\t\t\t<>\n");
}else{
fprintf(stdout,"Direction:\t\t\t->\n");
}
fprintf(stdout,"Message:\t\t\t%s\n",rule->body.msg.c_str());
//loop through content related vectors
for(unsigned long i=0;i<rule->body.content.size();i++){
if(rule->body.negatedContent.at(i)==true){
fprintf(stdout,"NOT ");
}
//fprintf(stdout,"ContentOriginal:\t%s\n",rule->body.contentOriginal[i].c_str());
if(rule->body.containsHex.at(i)==true){
fprintf(stdout,"Content (hex converted):\t%s\n",rule->body.content.at(i).c_str());
}else{
fprintf(stdout,"Content:\t\t\t\"%s\"\n",rule->body.content.at(i).c_str());
}
switch(rule->body.contentModifierHTTP.at(i)){
case 0: modifierHttp=""; break;
case 1: modifierHttp="http_method"; break;
case 2: modifierHttp="http_uri"; break;
case 3: modifierHttp="http_raw_uri"; break;
case 4: modifierHttp="http_stat_msg"; break;
case 5: modifierHttp="http_stat_code"; break;
case 6: modifierHttp="http_header"; break;
case 7: modifierHttp="http_raw_header"; break;
case 8: modifierHttp="http_client_body"; break;
case 9: modifierHttp="http_cookie"; break;
case 10: modifierHttp="http_raw_cookie"; break;
default: fprintf(stderr,"IpfixIds: Wrong internal content modifier HTTP encoding. Aborting!\n"); exit(0);
}
fprintf(stdout,"ContentModifierHttp:\t\t%s\n",modifierHttp.c_str());
if(rule->body.contentNocase[i]==true){
fprintf(stdout,"Nocase:\t\t\t\ttrue\n");
}else{
fprintf(stdout,"Nocase:\t\t\t\tfalse\n");
}
}
//loop through pcre related vectors
for(unsigned long j=0;j<rule->body.pcre.size();j++){
if(rule->body.negatedPcre.at(j)==true){
fprintf(stdout,"NOT ");
}
fprintf(stdout,"pcre:\t\t\t\t%s\n",rule->body.pcre.at(j).c_str());
switch(rule->body.contentModifierHTTP.at(j+(rule->body.content.size()))){
case 0: modifierHttp=""; break;
case 1: modifierHttp="http_method"; break;
case 2: modifierHttp="http_uri"; break;
case 3: modifierHttp="http_raw_uri"; break;
case 4: modifierHttp="http_stat_msg"; break;
case 5: modifierHttp="http_stat_code"; break;
case 6: modifierHttp="http_header"; break;
case 7: modifierHttp="http_raw_header"; break;
case 8: modifierHttp="http_client_body"; break;
case 9: modifierHttp="http_cookie"; break;
case 10: modifierHttp="http_raw_cookie"; break;
default: fprintf(stderr,"IpfixIds: Wrong internal pcre content modifier HTTP encoding. Aborting!\n"); exit(0);
}
fprintf(stdout,"pcreModifierHttp:\t\t%s\n",modifierHttp.c_str());
if(rule->body.pcreNocase[j]==true){
fprintf(stdout,"NocasePcre:\t\t\ttrue\n");
}else{
fprintf(stdout,"NocasePcre:\t\t\tfalse\n");
}
}
fprintf(stdout,"sid:\t\t\t\t%s\n",rule->body.sid.c_str());
fprintf(stdout,"sid rev:\t\t\t%s\n",rule->body.rev.c_str());
fprintf(stdout,"\n");
}
/**
* returns a string of x Xs
*/
std::string xtimesx(int x){
std::string returnString="";
for(int i=0;i<x;i++){
returnString=returnString+"X";
}
return(returnString);
}
/**
* replaces escaped chars in given text
* according to the snort manual only 3 chars have to be escaped inside a content rule: ;,",\
*/
std::string replaceEscapedChars(std::string* text){
std::string returnString;
std::size_t startPosition;
returnString=*text;
//first replace escaped backslash(\\)
startPosition=returnString.find("\\");
while(startPosition!=std::string::npos){
returnString.replace(startPosition,2,"XX");
startPosition=returnString.find("\\");
}
//replace escaped quotes(\")
startPosition=returnString.find("\\\"");
while(startPosition!=std::string::npos){
returnString.replace(startPosition,2,"XX");
startPosition=returnString.find("\\\"");
}
//replace escaped semicolon(\;)
startPosition=returnString.find("\\;");
while(startPosition!=std::string::npos){
returnString.replace(startPosition,2,"XX");
startPosition=returnString.find("\\;");
}
return returnString;
}
/**
* This function replaces everything in quotes of the given string with Xs, this includes also escaped characters
* this can be used in keyword search to avoid finding keywords in escaped strings
*/
std::string replaceQuotedText(std::string* quotedText){
std::size_t startPosition;
std::size_t endPosition;
std::string quotedTextReplaced;
//replace all escaped chars
quotedTextReplaced=replaceEscapedChars(quotedText);
//replace everything else that is quoted
startPosition=std::string::npos;
startPosition=quotedTextReplaced.find("\"",0);
endPosition=quotedTextReplaced.find("\"",startPosition+1);
while(startPosition!=std::string::npos&&endPosition!=std::string::npos){
quotedTextReplaced.replace(startPosition,endPosition-startPosition+1,xtimesx(endPosition-startPosition+1));
startPosition=quotedTextReplaced.find("\"",0);
endPosition=quotedTextReplaced.find("\"",startPosition+1);
}
return quotedTextReplaced;
}
/**
*parses the rule msg from given line and writes it to given snortRule class
*/
void parseMsg(std::string* line, int* linecounter, snortRule* tempRule){
std::size_t startPosition=line->find("msg:",0)+4;
std::size_t endPosition=line->find(";",startPosition);
if(startPosition==(std::string::npos+4)||endPosition==std::string::npos){
parsingError(*linecounter,"msg");
exit(1);
}
tempRule->body.msg=line->substr(startPosition+1,(endPosition-startPosition)-2);
}
/**
*parses the rule header from given line and writes it to given snortRule class
*/
void parseHeader(std::string* line, int* linecounter, snortRule* tempRule){
std::string headerString;
std::string from;
std::string fromPort;
std::string to;
std::size_t start;
std::size_t end;
start=line->find("(");
if(start==std::string::npos){
parsingError(*linecounter, "header");
}
headerString=line->substr(0,start);
end=headerString.find(" ");
tempRule->header.action=headerString.substr(0,end);
headerString.erase(0,end+1);
//TODO: skip rule if it does not apply to tcp... not really necessary
end=headerString.find(" ");
tempRule->header.protocol=headerString.substr(0,end);
headerString.erase(0,end+1);
end=headerString.find("<>");
if(end==std::string::npos){
end=headerString.find("->");
if(end==std::string::npos){
parsingError(*linecounter,"header direction sign");
}
tempRule->header.bidirectional=false;
}else{
tempRule->header.bidirectional=true;
}
//the end-1 omits the trailing space in this string
from=headerString.substr(0,end-1);
headerString.erase(0,end+3);
to=headerString.substr(0,headerString.size()-1);
end=from.find(" ");
if(end==std::string::npos){
parsingError(*linecounter,"no space between from address and port");
}
tempRule->header.from=from.substr(0,end);
from.erase(0,end+1);
fromPort=from.substr(0,from.size());
//this only catches if the default variable is used, but thats life...
if(fromPort.find("$HTTP_PORTS")!=std::string::npos){
fprintf(stderr,"Error: Rule looks for packet coming from server ports ($HTTP_PORTS variable). Can not control server responses, please remove this rule. Line: %d\n",*linecounter);
if(continueOnError==false){
exit(1);
}
}
tempRule->header.fromPort=fromPort;
end=to.find(" ");
if(end==std::string::npos){
parsingError(*linecounter,"no space between to address and port");
}
tempRule->header.to=to.substr(0,end);
to.erase(0,end+1);
tempRule->header.toPort=to.substr(0,to.size());
}
/**
* parses rule content (also multiple contents) from given line and writes it to given tempRule class in the corresponding vector of contents,
* it also converts hex characters to ascii characters, if possible, if not it omits them in the output content
*/
void parseContent(std::string* line, int* linecounter, snortRule* tempRule){
std::size_t startPosition;
std::size_t endPosition;
std::size_t hexStartPosition;
std::size_t hexEndPosition=0;
std::string hexContent;
std::string contentOrig;
std::string contentHexFree;
std::string tempContent;
std::string byte;
//we have to copy the line because we are messing around with it
std::string lineCopy=*line;
//this string is the same as line copy, only quotet text is replaces by X. length is the same!
std::string lineCopySearch=replaceQuotedText(&lineCopy);
char tempChar;
std::size_t tempPosition;
int contentCounter=0;
//on the first check there should definitively be at least one content
startPosition=lineCopySearch.find("content:",bodyStartPosition)+8;
endPosition=lineCopySearch.find(";",startPosition);
if(startPosition==(std::string::npos+8)||endPosition==std::string::npos){
parsingError(*linecounter,"content");
exit(1);
}
//loop to detect multiple content keywords, same check as above is repeated, will be true first time for sure, but we dont want to call parsingError the other times
while(startPosition!=(std::string::npos+8)&&endPosition!=std::string::npos){
contentHexFree="";
//check if content is negated BWARE: than also modifiers are negated!!!
if(lineCopy.substr(startPosition,1)=="!"){
tempRule->body.negatedContent.push_back(true);
//cut away negation sign
lineCopy.erase(startPosition,1);
lineCopySearch.erase(startPosition,1);
//because we erase one character, the endPosition moves back on char
endPosition--;
}else{
tempRule->body.negatedContent.push_back(false);
}
//we dont have to check for uricontent here because we can take care the same way we do for content. we have to take special care in parseContentModifier
contentOrig=lineCopy.substr(startPosition,(endPosition-startPosition));
//cut away quotes
contentOrig=contentOrig.substr(1,(contentOrig.size()-2));
//for debug and functionality check purposes write original content
tempRule->body.contentOriginal.push_back(contentOrig);
//check if it contains hex
hexStartPosition=contentOrig.find("|");
//is checked again below, but necessery here too
if(hexStartPosition!=std::string::npos||contentOrig.find("|",hexStartPosition+1)!=std::string::npos){
tempRule->body.containsHex.push_back(1);
//if it contains hex than add hexfree content before hex content to contentHexFree
contentHexFree=contentHexFree+contentOrig.substr(0,hexStartPosition);
}else{
tempRule->body.containsHex.push_back(0);
//if it does not contain hex at all add it now to hex free content
contentHexFree=contentHexFree+contentOrig;
}
//find all hex codes and convert them to ascii
while(hexStartPosition!=std::string::npos){
hexEndPosition=contentOrig.find("|",hexStartPosition+1);
if(hexEndPosition==std::string::npos){
fprintf(stdout,"Debug: content no hex=\t\t%s\nalready converted content:\t%s\n",contentOrig.c_str(),contentHexFree.c_str());
parsingError(*linecounter,"hex content (no termination sign)");
exit(1);
}
//copying hex string and cutting off first pipe sign
hexContent=contentOrig.substr(hexStartPosition+1,(hexEndPosition-hexStartPosition)-1);
//remove spaces from hex string
tempPosition=hexContent.find(" ");
while(tempPosition!=std::string::npos){
hexContent.erase(tempPosition,1);
tempPosition=hexContent.find(" ",tempPosition);
}
std::string asciiString;
//transform hex to ascii loop, as it always consumes two chars we have to move over two chars after every loop
//todo ev. convert line break/line feed hex codes to OS specific signs, convert more than 128 ascii signs
for (uint16_t i=0;i<(hexContent.length());i=i+2){
char * pEnd;
byte = hexContent.substr(i,2);
if(byte=="0d"||byte=="0D"){
asciiString=asciiString+"\\r";
}else if(byte=="0a"||byte=="0A"){
asciiString=asciiString+"\\n";
}else{
tempChar=(char) (int)strtol(byte.c_str(), &pEnd, 16);
if(isprint(tempChar)){
asciiString.push_back(tempChar);
}else{//warn if not printable
fprintf(stderr,"WARNING: non-printable hex chars (except 0d and 0a) and hex > 7F are not supported and thus omitted. Hex: %s, rule sid: %s, line:%d\n",byte.c_str(), tempRule->body.sid.c_str(), *linecounter);
}
}
}
//adding converted string to content
contentHexFree=contentHexFree+asciiString;
//content now does not contain previous hex anymore, but may contain pipe sign if converted from hex
hexStartPosition=contentOrig.find("|",hexEndPosition+1);
//if more hex, than get content in between last and next hex string
if(hexStartPosition!=std::string::npos){
contentHexFree=contentHexFree+contentOrig.substr(hexEndPosition+1,hexStartPosition-hexEndPosition-1);
//if this was last hex (and here we had at least one hex string) add possible tailing hex free string to content
}else{
contentHexFree=contentHexFree+contentOrig.substr(hexEndPosition+1,contentOrig.size()-hexEndPosition+1);
}
}//while hex loop
//add the summed up content to the rule class
tempRule->body.content.push_back(contentHexFree);
//erase content keyword, so that loop can find next content keyword or break
lineCopy.erase(startPosition-8,8);
//to keep same length do the same for search string
lineCopySearch.erase(startPosition-8,8);
startPosition=lineCopySearch.find("content:",bodyStartPosition)+8;
endPosition=lineCopySearch.find(";",startPosition);
contentCounter++;
}//while content loop
}
/**
* parses content modifiers from given line and writes it to given tempRule class in the corresponding vector
* Only nocase and http_* content modifier are supported. rawbytes, depth, offset, distance, within, fast_pattern are ignored by the parser.
*/
void parseContentModifier(std::string* line, int* linecounter, snortRule* tempRule){
bool uricontent=false;
std::size_t startPosition;
std::size_t endPosition;
std::size_t contentEndPosition;
std::size_t httpModifierStartPosition;
std::size_t httpModifierEndPosition;
std::string temp;
std::string allModifiers;
//we have to copy the line because we are messing around with it
std::string lineCopy=*line;
//this string is the same as lineCopy, only quoted text is replaces by X. length is the same. this way, searches dont trigger falsely on content found in quotes
std::string lineCopySearch=replaceQuotedText(&lineCopy);
//on the first check there should definitively be at least one content
startPosition=lineCopySearch.find("content:",bodyStartPosition)+8;
endPosition=lineCopySearch.find("content:",startPosition);
//for last content in rule the end is marked by the closing bracket of the rule body
if(endPosition==std::string::npos){
//do we have a +1 error here because of semicolon AND parentheses? No, because rule requires sid and rev keywords, and they are placed after modifiers
endPosition=(lineCopySearch.find(";)",startPosition));
}
if(startPosition==(std::string::npos+8)||endPosition==std::string::npos){
parsingError(*linecounter,"content (modifier)");
exit(1);
}
//loop to detect multiple content keywords, same check as above is repeated, will be true first time for sure, but we dont want to call parsingError the other times
while(startPosition!=(std::string::npos+8)&&endPosition!=std::string::npos){
temp=lineCopy.substr(startPosition,endPosition-startPosition);
allModifiers=replaceEscapedChars(&temp);
contentEndPosition=allModifiers.find(";");
if(startPosition==(std::string::npos+8)||endPosition==std::string::npos){
parsingError(*linecounter,"content (modifier), content string end position");
exit(1);
}
//check if its the uricontent keyword:
if(lineCopy.substr(startPosition-11,3)=="uri"){
uricontent=true;
}
//erase content keyword and content pattern
allModifiers.erase(0,contentEndPosition+1);
//see if it contains the nocase modifier
if(allModifiers.find("nocase;")==std::string::npos){
tempRule->body.contentNocase.push_back(false);
}else{
tempRule->body.contentNocase.push_back(true);
}
if(uricontent){
tempRule->body.contentModifierHTTP.push_back(2);
}else{
//find http content modifier:
httpModifierStartPosition=allModifiers.find("http_");
if(httpModifierStartPosition==std::string::npos){
tempRule->body.contentModifierHTTP.push_back(0);
}else{
httpModifierEndPosition=allModifiers.find(";",httpModifierStartPosition);
if(httpModifierEndPosition==std::string::npos){
parsingError(*linecounter,"content (modifier), content httpModifier end position");
}
temp=allModifiers.substr(httpModifierStartPosition,(httpModifierEndPosition-httpModifierStartPosition));
if(temp=="http_method"){
tempRule->body.contentModifierHTTP.push_back(1);
}else if(temp=="http_uri"){
tempRule->body.contentModifierHTTP.push_back(2);
//replace whitespaces in content patterns for http uris
//printf("uri detected, replacing:\n");
//temp=tempRule->body.content[tempRule->body.contentModifierHTTP.size()-1];
//printf("uri detected, replacing:\n");
for(int i = 0; i < tempRule->body.content.at(tempRule->body.contentModifierHTTP.size()-1).length(); i++)
{
if(tempRule->body.content.at(tempRule->body.contentModifierHTTP.size()-1).at(i)== ' '){
tempRule->body.content.at(tempRule->body.contentModifierHTTP.size()-1).at(i) = '+';
}
}
//tempRule->body.content.at(tempRule->body.contentModifierHTTP.size()-1)=temp;
}else if(temp=="http_raw_uri"){
tempRule->body.contentModifierHTTP.push_back(3);
}else if(temp=="http_stat_msg"){
//fprintf(stderr,"SnortRuleparser: content modifier http_stat_msg not supported in this version\n"); //just uncomment lines to support it
tempRule->body.contentModifierHTTP.push_back(4);
}else if(temp=="http_stat_code"){
tempRule->body.contentModifierHTTP.push_back(5);
}else if(temp=="http_header"){//BEWARE: this is not supported in Vermont because no IPFIX IE for http header exists
tempRule->body.contentModifierHTTP.push_back(6);
}else if(temp=="http_raw_header"){//BEWARE: this is not supported in Vermont because no IPFIX IE for http header exists
tempRule->body.contentModifierHTTP.push_back(7);
}else if(temp=="http_client_body"){//BEWARE: this is not supported in Vermont because no IPFIX IE for http header exists
tempRule->body.contentModifierHTTP.push_back(8);
}else if(temp=="http_cookie"){//BEWARE: this is not supported in Vermont because no IPFIX IE for http header exists
tempRule->body.contentModifierHTTP.push_back(9);
}else if(temp=="http_raw_cookie"){//BEWARE: this is not supported in Vermont because no IPFIX IE for http header exists
tempRule->body.contentModifierHTTP.push_back(10);
}else{
parsingError(*linecounter,"unrecognized content modifier");
}
}
}//if uricontent
//erase content keyword and content string, so that next content can be found
lineCopy.erase(startPosition-8,+8);
lineCopySearch.erase(startPosition-8,+8);
startPosition=lineCopySearch.find("content:",bodyStartPosition)+8;
endPosition=lineCopySearch.find("content:",startPosition);
//for last content in rule, the end is marked by the closing bracket of the rule body
if(endPosition==std::string::npos){
endPosition=(lineCopy.find(";)",startPosition))+1;
}
}//while
}
/**
* check given uri for disallowed and unwise characters see rfc-2396
* print warning if true
*/
void checkUri(std::string uri, std::string sid){
//delimiters
if(uri.find("#")!=std::string::npos||uri.find(">")!=std::string::npos||uri.find("<")!=std::string::npos||uri.find("%")!=std::string::npos||uri.find("\"")!=std::string::npos){
//TODO: check if they are escaped
fprintf(stderr,"WARNING: The HTTP uri used for this rule may contain disallowed characters. sid: %s\n",sid.c_str());
}
//unwise
if(uri.find("{")!=std::string::npos||uri.find("}")!=std::string::npos||uri.find("|")!=std::string::npos||uri.find("[")!=std::string::npos||uri.find("]")!=std::string::npos||uri.find("`")!=std::string::npos||uri.find("\\")!=std::string::npos){
fprintf(stderr,"WARNING: The HTTP uri used for this rule may contain unwise characters. sid: %s\n",sid.c_str());
}
}
/**
* parses pcre patterns in given line and writes it to given tempRule class in the corresponding vectors
*/
void parsePcre(std::string* line, int* linecounter, snortRule* tempRule){
std::size_t startPosition;
std::size_t endPosition;
std::size_t iPosition;
//we have to copy the line because we are messing around with it
std::string lineCopy=*line;
//this string is the same as line copy, only quoted text is replaces by X. length is the same!
std::string lineCopySearch=replaceQuotedText(&lineCopy);
std::string pcreModifierString;
std::string pcreString;
std::string temp;
//on the first check there should definitively be at least one pcre
startPosition=lineCopySearch.find("pcre:",bodyStartPosition)+5;
endPosition=lineCopySearch.find(";",startPosition);
//if not throw an error
if(startPosition==(std::string::npos+5)||endPosition==std::string::npos){
parsingError(*linecounter,"pcre");
exit(1);
}
//loop to detect multiple pcre keywords, same check as above is repeated, will be true first time for sure, but we dont want to call parsingError the other times
while(startPosition!=(std::string::npos+5)&&endPosition!=std::string::npos){
if(lineCopy.substr(startPosition,1)=="!"){
tempRule->body.negatedPcre.push_back(true);
//erase negation sign
lineCopy.erase(startPosition,1);
lineCopySearch.erase(startPosition,1);
//adjust endPosition
endPosition--;
}else{
tempRule->body.negatedPcre.push_back(false);
}
//copying pcre string (+snort specific modifiers) and cutting off quotes
temp=lineCopy.substr(startPosition+1,endPosition-startPosition-2);
//avoid any escaped chars by simply looking for the last occurence of / in the (not anymore) quoted pcre string
endPosition=temp.find_last_of("/");
pcreString=temp.substr(1,endPosition-1);
tempRule->body.pcre.push_back(pcreString);
//getting pcre modifiers
pcreModifierString=temp.substr(endPosition+1,temp.length()-endPosition);
//detailed handling of single pcre modifiers
iPosition=pcreModifierString.find("i");
if(iPosition!=std::string::npos){
tempRule->body.pcreNocase.push_back(true);
pcreModifierString.erase(iPosition,1);
}else{
tempRule->body.pcreNocase.push_back(false);
}
//if no modifiers left, no http modifier, so useless:
if(pcreModifierString.size()==0){
fprintf(stderr,"Error with rule sid:%s on line %d, failed to parse pcre modifier: No http modifier for pcre, we need at least one\n",tempRule->body.sid.c_str(),*linecounter);
if(continueOnError==false){
exit(1);
}
}
if(pcreModifierString.find("s")!=std::string::npos||pcreModifierString.find("m")!=std::string::npos||pcreModifierString.find("x")!=std::string::npos
||pcreModifierString.find("A")!=std::string::npos||pcreModifierString.find("E")!=std::string::npos
||pcreModifierString.find("G")!=std::string::npos||pcreModifierString.find("R")!=std::string::npos
||pcreModifierString.find("B")!=std::string::npos||pcreModifierString.find("O")!=std::string::npos){
fprintf(stderr,"Error with rule sid:%s on line %d, failed to parse pcre modifier: The Snort specific (non HTTP) pcre modifiers s,m,x,A,E,G,R,B,O are not supported.\n",tempRule->body.sid.c_str(),*linecounter);
if(continueOnError==false){
exit(1);
}
}
for(std::string::size_type k = 0; k < pcreModifierString.size(); ++k) {
switch(pcreModifierString[k]){
case 'P'://client body
tempRule->body.contentModifierHTTP.push_back(8);
break;
case 'H'://http header 6
tempRule->body.contentModifierHTTP.push_back(6);
break;
case 'D'://raw_header 7
tempRule->body.contentModifierHTTP.push_back(7);
break;
case 'C'://cookie 9
tempRule->body.contentModifierHTTP.push_back(9);
break;
case 'K'://raw cookie 19
tempRule->body.contentModifierHTTP.push_back(10);
break;
case 'U'://uri
//TODO: it would make sense to check already here for unescaped unsupported or unwise chars, on the other hand snort does accept most of them anyway
tempRule->body.contentModifierHTTP.push_back(2);
break;
case 'I'://raw uri
//checkUriPCRE(pcreString);
tempRule->body.contentModifierHTTP.push_back(3);
break;
case 'M'://method
tempRule->body.contentModifierHTTP.push_back(1);
break;
case 'S'://response code
tempRule->body.contentModifierHTTP.push_back(5);
break;
case 'Y'://response message
tempRule->body.contentModifierHTTP.push_back(4);
break;
default:
fprintf(stderr,"Error with rule sid:%s on line %d, failed to parse pcre modifier: There was an uncaught, unsupported snort specific modifier. This should not have happened!\n",tempRule->body.sid.c_str(),*linecounter);
if(continueOnError==false){
exit(1);
}
}
}
//printf("%s\n",temp.c_str());
//printf("%s\n",pcreString.c_str());
//printf("%s\n",pcreModifierString.c_str());
//erase pcre keyword from line so that we can move on to next line
lineCopy.erase(startPosition-5,5);
lineCopySearch.erase(startPosition-5,5);
startPosition=lineCopySearch.find("pcre:",bodyStartPosition)+5;
endPosition=lineCopySearch.find(";",startPosition);
}
}
/**
* parses SID and SID rev. number from given line and writes it to given snortRule struct
*/
void parseSid(std::string* line, int* linecounter, snortRule* tempRule){
std::string lineCopy=replaceQuotedText(line);
std::size_t startPosition=lineCopy.find("sid:",bodyStartPosition)+4;
std::size_t endPosition=lineCopy.find(';',startPosition);
if(startPosition==3||endPosition==std::string::npos){
parsingError(*linecounter,"SID");
exit(1);
}
tempRule->body.sid=lineCopy.substr(startPosition,(endPosition-startPosition));
//parse rev following SID
startPosition=lineCopy.find("rev:",startPosition)+4;
endPosition=lineCopy.find(';',startPosition);
if(startPosition==3||endPosition==std::string::npos){
parsingError(*linecounter,"SID revision");
exit(1);
}
tempRule->body.rev=lineCopy.substr(startPosition,(endPosition-startPosition));
}
/*
*Function that is used to handle return data from sent requests
*/
size_t write_data(void *buffer, size_t size, size_t nmemb, void *userp){
//ev. print response which resides in buffer
if(printResponse){
}
return size*nmemb;
}
/**
* removes \r and \n at beginning and end of strings
*/
std::string removeCRLF(std::string str, std::string ruleSid){
if(str.size()==0){
fprintf(stderr,"Error, can not sanitize empty Header for rulesid:%s. Likely, this rule produced an empty pcre string, check pcre.\n",ruleSid.c_str());
if(continueOnError==false){
exit(0);
}
}
//remove all \r and \n at end, libcurl will add them anyway
while((str.at(str.size()-1)=='n'&&str.at(str.size()-2)=='\\')||(str.at(str.size()-1)=='r'&&str.at(str.size()-2)=='\\')){
str.pop_back();
str.pop_back();
}
//snort rules also search for \r\n at beginning of some fields, remove them too:
while((str.at(0)=='\\'&&str.at(1)=='r')||(str.at(0)=='\\'&&str.at(1)=='n')){
str.erase(0,2);
}
if(str==""){
fprintf(stderr,"WARNING: Empty String after removing initial and trailing newlines. sid: %s\n",str.c_str());
}
return str;
}
/**
* 2 steps:
* 1:remove excess \r\n at end and beginning. libcurl adds a \r\n anyway, so we have to remove them.
* 2:if colon OR colon+whitespace at end of header are found a value is added.
* WHY?: if a header without a value is set, curl assumes you want to remove the original header, so we have to set a value after colon or colon and space:
*/
std::string sanitizeHeader(std::string header, std::string ruleSid){
if(header.size()==0){
fprintf(stderr,"Error, can not sanitize empty Header for rulesid:%s. Likely, this rule produced an empty pcre string, check pcre.\n",ruleSid.c_str());
if(continueOnError==false){
exit(0);
}
}else{
header=removeCRLF(header,ruleSid);
//add dummystuff if missing
if(header.at(header.size()-1)==':'){
header=header+" DummyValue";
if(verbose){
printf("INFO: added dummy value to incomplete name: value header. sid:%s\n",ruleSid.c_str());
}
}else if(header.at(header.size()-1)==' '&&header.at(header.size()-2)==':'){
header=header+"DummyValue";
if(verbose){
printf("INFO: added dummy value to incomplete name: value header. sid:%s\n",ruleSid.c_str());
}
}else if(header.find(':')==std::string::npos){
header="DummyHeader: "+header;
if(verbose){
printf("INFO: added dummy value to incomplete name: value header. sid:%s\n",ruleSid.c_str());
}
}
}
if(header==""){
fprintf(stderr,"WARNING: Empty header after sanitazion. sid: %s\n",ruleSid.c_str());
}
return header;
}
/**
* this function replaces character classes that are not supported by the exrex and problematic chars by equivalent signs
*/
std::string sanitizePCRE(std::string pcre, std::string sid){
std::size_t index;
//replace \s with " ", so whitespace chars become just whitespace and not something like newlines
while(true){
index=pcre.find("\\s");
if(index==std::string::npos){
break;
}else{
pcre.replace(index,2," ");
index+=3;
if(verbose){
printf("INFO: replaced \\s with single whitespace before generation. sid:%s\n",sid.c_str());
}
}
}
//replace +? with +
while(true){
index=pcre.find("+?");
if(index==std::string::npos){
break;
}else{
pcre.replace(index,2,"+");
if(verbose){
printf("INFO: replaced +? with + in pcre before generation. sid:%s\n",sid.c_str());
}
}
}
//replace *? with *
while(true){
index=pcre.find("*?");
if(index==std::string::npos){
break;
}else{
pcre.replace(index,2,"*");
if(verbose){
printf("INFO: replaced *? with * in pcre before generation. sid:%s\n",sid.c_str());
}
}
}
//replace .+ with [a-z] so that it produces easy to use char and not some weird sh**
while(true){
index=pcre.find(".+");
if(index==std::string::npos){
break;
}else{
pcre.replace(index,2,"[a-z]}");
if(verbose){
printf("INFO: replaced .+ with [a-z] in pcre before generation. sid:%s\n",sid.c_str());
}
}
}
//replace .* with [a-z] so that it produces easy to use char and not some weird sh**
while(true){
index=pcre.find(".*");
if(index==std::string::npos){
break;
}else{
pcre.replace(index,2,"[a-z]");
if(verbose){
printf("INFO: replaced .* with [a-z] in pcre before generation. sid:%s\n",sid.c_str());
}
}
}
//replace .? with [a-z] so that it produces easy to use char and not some weird sh**
while(true){
index=pcre.find(".?");
if(index==std::string::npos){
break;
}else{
pcre.replace(index,2,"[a-z]");
if(verbose){
printf("INFO: replaced .? with [a-z] in pcre before generation. sid:%s\n",sid.c_str());
}
}
}
while(true){
index=pcre.find("[^&]");
if(index==std::string::npos){
break;
}else{
pcre.replace(index,4,"[a-z]");
if(verbose){
printf("INFO: replaced [^&] with [a-z] in pcre before generation. sid:%s\n",sid.c_str());
}
}
}
while(true){
index=pcre.find("[^\\]");
if(index==std::string::npos){
break;
}else{
pcre.replace(index,4,"[a-z]");
if(verbose){
printf("INFO: replaced [^\\] with [a-z] in pcre before generation. sid:%s\n",sid.c_str());
}
}
}
while(true){
index=pcre.find("[^\\n]");
if(index==std::string::npos){
break;
}else{
pcre.replace(index,5,"[a-z]");
if(verbose){
printf("INFO: replaced [^\\n] with [a-z] in pcre before generation. sid:%s\n",sid.c_str());
}
}
}
while(true){
index=pcre.find("[^\\r\\n]");
if(index==std::string::npos){
break;
}else{
pcre.replace(index,7,"[a-z]");
if(verbose){
printf("INFO: replaced [^\\r\\n] with [a-z] in pcre before generation. sid:%s\n",sid.c_str());
}
}
}
// while(true){
// index=pcre.find("[^\\0A\\0D]");
// if(index==std::string::npos){
// break;
// }else{
// pcre.replace(index,9,"[a-z]");
// if(verbose){
// printf("INFO: replaced [^\\0A\\0D] with [a-z] in pcre before generation. sid:%s\n",sid.c_str());
// }
// }
// }
// while(true){
// index=pcre.find("[^\\x26\\x3B]");
// if(index==std::string::npos){
// break;
// }else{
// pcre.replace(index,11,"[a-z]");
// if(verbose){
// printf("INFO: replaced [^\\x26\\x3B] with [a-z] in pcre before generation. sid:%s\n",sid.c_str());