-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathsnort2fortigate.py
executable file
·1796 lines (1576 loc) · 58.3 KB
/
snort2fortigate.py
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
#!/usr/bin/env python3
# This script is being provided by the copyright holders under the following
# license. By obtaining, using and/or copying this work, you (the licensee)
# agree that you have read, understood, and will comply with the following terms
# and conditions
#
# Permission to copy, modify, and distribute this software and its documentation
# with or without modification, for any purpose and without fee or royalty is
# hereby granted, provided that you include the following on ALL copies of the
# software and documentation or portions thereof, including modifications:
#
# 1. The full text of this NOTICE in a location viewable to users of the
# redistributed or derivative work.
# 2. Notice of any changes or modifications to the files, including the date
# changes were made.
#
# THIS SOFTWARE AND DOCUMENTATION IS PROVIDED "AS IS," AND COPYRIGHT HOLDERS
# MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT
# LIMITED TO, WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
# PURPOSE OR THAT THE USE OF THE SOFTWARE OR DOCUMENTATION WILL NOT INFRINGE ANY
# THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS.
#
# COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL OR
# CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE OR DOCUMENTATION.
#
# Title to copyright in this software and any associated documentation will at
# all times remain with copyright holders.
#
# Copyright 2019 Fortinet, Inc. All Rights Reserved.
import sys
import re
import argparse
import logging
import json
from io import StringIO #Python 3
# Declare the globals
version = '3.1.1'
print_err_warning = False
debug_log = False
input_file = None
output_file = 'fortirules.txt'
snort_count = 0
disabled_snort_count = 0
fgt_rule_count = 0
rule_maxlen = 1024
log_stream = StringIO()
json_stream = StringIO()
max_sig_name_len = 50
# Keeping state for Snort3 syntax
content_seen_flag = False # has encountered content: or pcre: in this rule
sticky_buffer_flag = False # sticky buffer encountered
alert_file_flag = False # alert file is found in rule header
# Keeping state for Snort2 syntax
open_context_flag = False
added_context_flag = False
context_modifier_flag = False
bi_direction_flag = False
force_snort_2 = False
# Distinguish Snort2/3 at the end for edge case where a rule begins with file_data
# and swaps to another context. Default parsed as Snort3 rule but cannot tell
# until we see whether we end in a context option (S2) or a content option (S3)
# set to last seen key (content/pcre/file_data/http_uri/http_raw_...etc)
last_seen_option = ''
context_flags = None
regs = None
service_priority = None
keywordhandler = None
#Declare all the constants related to common Snort keywords
#map all the different keywords related to context for easy conversion later
context_header = {'http_cookie':'H', 'http_raw_cookie':'H', 'http_header':'H', 'http_raw_header':'H', 'sip_header':'H', 'http_user_agent': 'H'}
context_banner = {'http_stat_code':'R', 'http_stat_msg':'R', 'sip_method':'R', 'sip_stat_code':'R', 'http_raw_status':'R'}
context_body = {'sip_body':'B', 'http_client_body':'B', 'http_raw_body':'B'}
context_uri = {'http_method':'U', 'http_uri':'U', 'http_raw_uri':'U', 'http_raw_request':'U'}
context_packet = {'pkt_data':'P'}
context_file = {'file_data':'F'}
context_raw_packet = {'raw_data':'O', 'rawbytes':'O'}
keyword_dict = {} #this dictionary will store all the context related keyword
for i in (context_header, context_banner, context_body, context_uri, context_packet, \
context_file, context_raw_packet):
keyword_dict.update(i)
#keyword that we can omit without any impact on the signature detection
key_drop = {'msg', 'reference', 'rev', 'classtype', 'priority', 'sid', 'gid',
'fast_pattern', 'http_encode', 'service', 'rem'}
unsupported_fatal = {'md5', 'sha256', 'sha512', 'so', 'soid'}
direct_trans = {
'icmp_id': 'icmp_id',
'icmp_seq': 'icmp_seq',
'id': 'ip_id',
'sameip': 'same_ip',
'ack': 'ack',
'seq': 'seq',
'ipopts': 'ip_option',
'dsize': 'data_size',
'icode': 'icmp.code',
'itype': 'icmp.type',
'window': 'window_size',
'tos': 'ip_tos',
'flags': 'tcp_flags'
}
content_modifier = {'depth', 'offset', 'distance', 'within', 'nocase'}
content_pattern = {'content', 'pcre', 'uricontent'}
class Registers:
#This class holds the mapping for Snort variables to registers
def __init__(self):
self.reg = []
def set_reg(self, var, value):
if len(self.reg) == 8:
logging.error("Too many registers set. Signature failed to convert.")
return False
else:
self.reg.append((var, value))
return len(self.reg) - 1
def get_var_frm_reg(self, i):
return self.reg[i]
def get_reg_frm_var(self, var):
for i, val in enumerate(self.reg):
if val[0] == var:
return i
return -1
def clear_regs(self):
self.reg = []
class ContextFlags:
#This class holds context flags for encountering Snort modifiers
#and sticky buffers and returns the appropriate IPS pattern
#context. (body [B], file [F], header [H], uri [U], packet [P],
#banner [R], packet_origin [O] )
#context_cursor holds boolean for encountering cursors file_data
#or pkt_data which require special handling to distinguish in
#Snort2 vs Snort3. True only if cursor is in a Snort2 rule
def __init__(self):
self.context = None
self.context_cursor = False
def set_flag(self, flag):
if flag in ['B', 'F', 'H', 'P', 'U', 'R', 'O']:
self.context = flag
def reset(self):
self.context = None
self.context_cursor = False
def get_flag(self):
return self.context
def set_cursor(self):
self.context_cursor = True
def unset_cursor(self):
self.context_cursor = False
def is_context_cursor(self):
return self.context_cursor
def get_context_rule(self):
if self.context == 'B':
return ' --context body;'
elif self.context == 'F':
return ' --context file;'
elif self.context == 'H':
return ' --context header;'
elif self.context == 'U':
return ' --context uri;'
elif self.context == 'R':
return ' --context banner;'
elif self.context == 'O':
return ' --context packet_origin;'
else:
return ' --context packet;'
class ServicePriority:
#This class holds --service option to add that is priority, when
#encountering a context option that should refer to a specific service
#overriding the service options added from the default ports in the
#header.
#eg. encountering sip_body, we should set --service sip;
#If there is priority set, the service option is added in __single_option_check
supported_services = {
'http': ' --service http;',
'sip': ' --service sip;',
'modbus': ' --service modbus;',
'ssl': ' --service ssl;',
'tls': ' --service ssl;',
'ftp': ' --service ftp;',
'telnet': ' --service telnet;',
'smtp': ' --service smtp;',
'ssh': ' --service ssh;',
'dcerpc': ' --service dcerpc;',
'netbios': ' --service nbss;',
'nntp': ' --service nntp;',
'sunrpc': ' --service rpc;',
'dns': ' --service dns;',
'imap': ' --service imap;',
'pop3': ' --service pop3;',
'snmp': ' --service snmp;',
'ldap': ' --service ldap;',
'radius': ' --service radius;',
'rtsp': ' --service rtsp;'
}
def __init__(self):
self.reset_service()
def set_service(self, service):
self.service = self.supported_services.get(service)
def set_high_service(self, service):
self.high_service = self.supported_services.get(service)
def get_service(self):
# Either returns the --service <service_name>; or None if not set
if self.high_service is None:
return self.service
return self.high_service
def reset_service(self):
self.service = None
self.high_service = None
class FunctionSwitch:
#To avoid rebuilding the dictionary for the function calls each time a keyword is examined,
#this class will create a map per instance to optimize the code.
def __init__(self):
self.__map = { # all other keywords that are not pcre: or content:or its suboptions
'flowbits': _handle_flowbits,
'flow': _handle_flow,
'byte_jump': _handle_byte_jump,
'byte_test': _handle_byte_test,
'byte_extract': _handle_byte_extract,
'ip_proto': _handle_ip_proto,
'ssl_version': _handle_ssl_version,
'bufferlen': _handle_bufferlen,
'urilen': _handle_urilen,
'detection_filter': _handle_detection_filter,
'icmp_id': _handle_direct_trans,
'icmp_seq': _handle_direct_trans,
'id': _handle_direct_trans,
'sameip': _handle_direct_trans,
'ack': _handle_direct_trans,
'seq': _handle_direct_trans,
'ipopts': _handle_direct_trans,
'dsize': _handle_min_max_convert,
'icode': _handle_min_max_convert,
'itype': _handle_min_max_convert,
'window': _handle_direct_trans,
'isdataat': _handle_isdataat,
'flags': _handle_direct_trans,
'tos': _handle_direct_trans,
'ttl': _handle_ttl,
'service': _handle_service,
'metadata': _handle_metadata
}
#From key, call appropriate function to handle from switch.
def get_handler(self, key):
return self.__map.get(key)
def keyword_handler(key, value):
#Snort option keys are organized in the following groups:
#key_drop: metadata related or keywords that we drop WITHOUT warning
#context_<name>: groups keys that translate into some --context <name>;
#content_modifier: Snort content modifiers (if it's a separate keyword
# entering this function, this is Snort2)
#content_pattern: the 'content' and 'pcre' keys that are handled
# separately outside of the switch statement
#direct_trans: subset of switch that can be handled with a 1:1
# translation substituting the option name (_handle_direct_trans)
#unsupported_fatal: skip the signature if encountering this option
#
#returns from handler functions called are:
#- the converted rule if it is successful
#- False (literal False, '', or None) if it is not successful
# - is None if we are just omitting but continuing with rest of
# rule
#
#Return (validity_boolean,converted_rule)
global open_context_flag
global last_seen_option
rule = ''
valid = False
##########################################
# Begin parsing keyword:
__keyword_handler = keywordhandler.get_handler(key)
if key in content_pattern:
last_seen_option = key
if key == 'pcre':
handled_opt = _handle_pcre(value)
elif key == 'content':
handled_opt = _handle_content(value)
else:
handled_opt = _handle_uri_content(value)
if handled_opt:
rule += handled_opt
valid = True
elif handled_opt is None:
valid = True
elif __keyword_handler != None:
rule += __check_and_add_context_packet()
open_context_flag = False
if key.lower() in direct_trans.keys():
handled_opt = __keyword_handler(direct_trans[key.lower()], value)
else:
handled_opt = __keyword_handler(value.lower())
if handled_opt:
rule += handled_opt
valid = True
elif handled_opt is None:
valid = True
elif key in key_drop:
valid = True
pass
elif key in keyword_dict.keys():
last_seen_option = key
handled_opt = _handle_context(key, keyword_dict[key])
if handled_opt:
rule += handled_opt
valid = True
elif handled_opt is None: # This occurs with Snort3 sticky buffers, None returned
valid = True
service_priority.set_service(key.split('_')[0])
elif key in content_modifier:
handled_opt = _handle_content_modifier(key, value.lower())
if handled_opt:
rule += handled_opt
valid = True
elif handled_opt is None:
valid = True
elif key in unsupported_fatal:
logging.error('Unsupported Snort option "%s" found. Skipping rule.' % key)
else:
# unsupported keywords.
logging.warning('Unsupported Snort option "%s" found. Omitting' % key)
valid = True
return (valid, rule)
def _handle_content_modifier(key, value):
#Content modifiers: nocase, offset, depth, distance, within.
#Supports registers from byte_extract.
logging.debug('inside _handle_content_modifier')
global context_modifier_flag
value = value.strip()
rule = ''
if value and re.match('^\-?\d+$', value) is None:
# convert to a register , must be previously extracted w/ byte_extract
reg_val = regs.get_reg_frm_var(value)
if reg_val == -1:
logging.warning('Register not found for extracted content modifier variable %s. Omitting modifier.' % value)
return None
else:
value = '$%s' % reg_val
if open_context_flag:
if key == 'nocase':
rule = ' --no_case;'
elif key == 'depth':
rule = ' --within %s,context;' % value
if not sticky_buffer_flag:
context_modifier_flag = True
elif key == 'distance':
rule = ' --distance %s;' % value
elif key == 'offset':
rule = ' --distance %s,context;' % value
if not sticky_buffer_flag:
context_modifier_flag = True
elif key == 'within':
rule = ' --within %s;' % value
return rule
def _handle_context(key, context):
#Handle receiving a context related keyword
#Snort 2 and 3 syntax results in different state
logging.debug('inside _handle_context with context %s' % context)
global sticky_buffer_flag
global added_context_flag
cursor_keys = ['file_data', 'pkt_data']
if context_flags.is_context_cursor():
# is currently in a S2 cursor move
if key in cursor_keys:
# got another cursor set, eg. from file_data; to pkt_data
context_flags.set_flag(context)
else:
# remove cursor flag and set back to being Snort 2 to parse rest of rule properly
context_flags.unset_cursor()
sticky_buffer_flag = False
context_flags.set_flag(context)
return context_flags.get_context_rule()
if content_seen_flag == False:
# Snort3 Rule
sticky_buffer_flag = True
context_flags.set_flag(context)
elif sticky_buffer_flag == True:
context_flags.set_flag(context)
else:
# Snort2 Rule
if open_context_flag:
if not added_context_flag:
# parsed content: earlier, need to add context now
context_flags.set_flag(context)
added_context_flag = True
return context_flags.get_context_rule()
else:
# this is probably pkt_data or something that goes first
# despite the other content modifiers going after in Snort 2
context_flags.set_flag(context)
context_flags.set_cursor()
# treat this section of rule as Snort 3 since it comes before content
sticky_buffer_flag = True
return None
else:
if force_snort_2:
# REPARSING AS SNORT 2 when beginning with file_data/pkt_data
context_flags.set_flag(context)
context_flags.set_cursor()
# treat this section of rule as Snort 3 since it comes before content
sticky_buffer_flag = True
return None
# don't know what this context is doing here
logging.warning("Syntax error at Snort option %s. Skipping" % key)
return None
return None
def __normalize_pattern(p):
p = p.replace('\\|', '|7C|')
p = p.replace('\\\\', '|5C|')
return p
def __check_and_add_context_packet():
#Snort2: having written --pattern or --pcre without context yet
#while having distance/within with ,context; requiring a
#--context packet; at the end.
pattern = ''
if open_context_flag:
if context_modifier_flag and not added_context_flag:
pattern += ' --context packet;'
return pattern
def _handle_content(value):
#When receiving content value, it can be Snort2 or Snort3 style
#Snort2: content:"/Home/"; depth:6; would only give pattern and
#require handling content modifier 'depth' in keyword_handler as
#its own key.
#Snort3: content:"/Home/",depth 6; provides the modifiers as
#suboptions and can be added immediately. Context is also known
#for Snort3 rules to be added based on global flags.
logging.debug('inside _handle_content')
global content_seen_flag
global open_context_flag
global added_context_flag
content_seen_flag = True
pattern = __check_and_add_context_packet()
open_context_flag = True
added_context = False
pattern += ' --pattern ' + __normalize_pattern(value.strip())
if pattern[-1] != '"': # options after end of pattern string
s3_opts = pattern.rsplit('",', 1)
if len(s3_opts) > 1:
# Snort3 content suboptions found
# currently parses distance/within/offset/depth/nocase
pattern = s3_opts[0] + '";'
added_context = True
for s in s3_opts[1].split(','):
subkey = s.strip().split(' ')
if subkey[0] in ['nocase', 'offset', 'depth', 'distance', 'within']:
if len(subkey) < 2:
subkey_val = ''
else:
subkey_val = subkey[1]
content_mod = _handle_content_modifier(subkey[0], subkey_val)
if content_mod:
pattern += content_mod
else: # unknown? skip (eg. fast_pattern)
continue
if not added_context:
pattern += ';'
if sticky_buffer_flag:
# Snort3: already know context, add it in:
pattern += context_flags.get_context_rule()
else:
added_context_flag = False
return pattern
def _handle_flow(value):
#Converts option flow -> --flow dir;
#Snort flow syntax: [(established|not_established|stateless)]
# [,(to_client|to_server| from_client| from_server)]
# [,(no_stream|only stream)]
# [,(no_frag|only_frag)]
#FGT engine does not differentiate between established/not/stateless
#FGT engine does not support no_stream/only_stream/no_frag/only_frag
logging.debug('inside _handle_flow')
global bi_direction_flag
if bi_direction_flag:
return None
opts = value.replace(' ', '').split(',')
pattern = ''
from_server = ['to_client', 'from_server']
from_client = ['to_server', 'from_client']
established = ['established', 'not_established', 'stateless']
for o in opts:
if o in from_server:
pattern = "".join((pattern, ' --flow from_server;'))
elif o in from_client:
pattern = "".join((pattern, ' --flow from_client;'))
elif o in established:
if len(opts) == 1:
logging.warning('"flow" cannot convert "%s". Option not supported. Omitting option.' % o)
return None
continue
else:
logging.warning('"flow" cannot convert "%s". Option not supported. Omitting option.' % o)
return None
return pattern
def _handle_flowbits(value):
#Converts option flowbits -> --tag test,set
#flowbits:<cmd>,<tag_name(s)>,<group_name>;
#FGT keyword does not accept group_name option
logging.debug('inside _handle_flowbits')
tag_keys = {
'set': 'set',
'unset': 'clear',
'isnotset': 'test,!',
'isset': 'test',
'noalert': 'quiet',
'toggle': 'toggle'
}
opts = value.replace(' ', '').split(',')
pattern = ''
cmd = tag_keys.get(opts[0])
if cmd is None:
logging.error('"flowbits" cannot convert "%s". cmd is not supported. Omitting option.' % cmd)
return False
if len(opts) == 3:
logging.warning('"flowbits" cannot convert "%s". Group names are not supported. Omitting option.' % opts[2])
if len(opts) == 1:
pattern += ' --tag %s;' % cmd
return pattern
tags = [opts[1]]
if "&" in opts[1]:
tags = opts[1].split("&")
for t in tags:
pattern += ' --tag %s,%s;' % (cmd, t)
return pattern
def _handle_pcre(value):
#PCRE option in Snort2 can have Snort specific modifiers:
#'R': Match relative to the end of the last pattern match.
# (Similar to distance:0;)
# -> --distance 0;
#'I', 'U': URI buffer (ignore decoded or unnormalized)
# -> --context uri;
#'C', 'D', 'H', 'K', 'M': cookie/http_raw_header/http_header/
# /raw cookie/http_method, all of which is just..
# -> -- context header;
#'S', 'Y': http_stat_code/http_stat_msg
# -> --context banner;
#'P': http_client_body
# -> --context body;
#'B': rawbytes --> --context packet; (possibly packet,origin)
#
#
#Meanwhile, Snort3 removes this in favour of sticky buffers.
#Similar to content option.
#Check sticky_buffer_flag and add context if it already is known.
logging.debug('inside _handle_pcre')
global content_seen_flag
global open_context_flag
global added_context_flag
content_seen_flag = True # Since Snort3 uses buffers for PCRE too
rule = __check_and_add_context_packet()
open_context_flag = True
mod_uri = ['I', 'U']
mod_header = ['C', 'D', 'H', 'K', 'M']
mod_banner = ['S', 'Y']
mod_packet = ['B']
mod_body = ['P']
mod_distance = ['R'] # I think this still exists in Snort 3
mod_unsupported = ['O']
rule_mod = ''
pcre = re.compile(r'!?\"(?P<exp>\/.*\/)(?P<mod>[\w]*)\"')
m = pcre.match(value)
if not m:
logging.error('Syntax error in PCRE option: %s. Skipping rule.' % value)
return False
else:
expr = m.group('exp')
mods = m.group('mod')
expr.replace('"', '\x22')
expr.replace("'", '\x27')
# Handle PCRE modifiers, removing each Snort specific modifier found
mod_list = list(mods)
mod_i = 0
del_mod = False
while len(mod_list) > 0:
mod = mod_list[mod_i]
if mod in mod_uri:
rule_mod += ' --context uri;'
# update list to delete this modifier since we are done with it.
# Same context ones are deleted at the same time to not duplicate.
mod_list = [x for x in mod_list if x not in mod_uri]
added_context_flag = True
del_mod = True
elif mod in mod_header:
rule_mod = "".join((rule_mod, ' --context header;'))
mod_list = [x for x in mod_list if x not in mod_header]
added_context_flag = True
del_mod = True
elif mod in mod_body:
rule_mod = "".join((rule_mod, ' --context body;'))
mod_list = [x for x in mod_list if x not in mod_body]
added_context_flag = True
del_mod = True
elif mod in mod_banner:
rule_mod = "".join((rule_mod, ' --context banner;'))
mod_list = [x for x in mod_list if x not in mod_banner]
added_context_flag = True
del_mod = True
elif mod in mod_packet:
rule_mod = "".join((rule_mod, ' --context packet;'))
mod_list = [x for x in mod_list if x not in mod_packet]
added_context_flag = True
del_mod = True
elif mod in mod_distance:
rule_mod = "".join((rule_mod, ' --distance 0;'))
mod_list = [x for x in mod_list if x not in mod_distance]
del_mod = True
elif mod in mod_unsupported:
logging.warning("Snort PCRE option %s not supported." % mod)
mod_list = [x for x in mod_list if x not in mod_unsupported]
del_mod = True
if del_mod:
if len(mod_list) <= mod_i:
# Have removed all Snort specific modifiers
break
else:
# Move iterator to next position in mod_list since nothing was deleted
if len(mod_list) > mod_i + 1:
mod_i += 1
else:
# Have removed all Snort specific modifiers
break
del_mod = False
# If multiple different contexts are added from above.. remove
if len(rule_mod.split('--context')) > 2:
logging.warning(
'Cannot support multiple Snort HTTP modifiers in PCRE expression "%s%s". Omitting context' % (
expr, mods))
rule_mod = ''
# Remaining in mod_list is either a regular Perl/PCRE modifier
# or an invalid one. We are keeping it in the PCRE expression "/<exp>/<mod>"
expr += ''.join(mod_list)
# Snort3:
if sticky_buffer_flag:
# Just in case someone writes a sig with the PCRE modifier anyways
# even in a Snort3 sig, don't duplicate it.
if '--context' not in rule_mod:
rule_mod += context_flags.get_context_rule()
rule += ' --pcre "' + expr + '";' + rule_mod
return rule
def _handle_byte_jump(value):
#Converts byte_jump option to --byte_jump
#Syntax: byte_jump: <bytes>, <offset> [,modifiers]
#Do not support keywords: dce, bitmask, from_end, post_offset
logging.debug('inside _handle_byte_jump')
frm_beg_flag = False
opts = [x.strip() for x in value.split(',')]
mult_num = ''
add_opts = []
pattern = ' --byte_jump %s,%s' % (opts[0], opts[1])
if len(opts) > 2:
for o in opts[2:]:
if o == 'from_beginning':
frm_beg_flag = True
elif 'multiplier' in o:
mult_num = o.split(' ')[1]
elif (o in ['dce', 'from_end']) or ('bitmask' in o) or ('post_offset' in o):
logging.error('"byte_jump" cannot convert "%s". Modifier not supported.' % o)
return False
else:
add_opts.append(o)
if mult_num != '':
pattern += ',%s' % mult_num
if len(add_opts) > 0:
pattern += ',%s' % ','.join(add_opts)
pattern += ';'
if frm_beg_flag:
pattern = pattern.replace('relative', '')
pattern = pattern.replace(',,', ',')
pattern = pattern.replace(',;', ';')
return pattern
def __get_val(value):
#Converts string variable from byte_test to int or retrieves
#register from variable name. returns tuple (value, data_type)
if '0x' == value[:2]:
val = int(value, 16)
val_type = 'hex'
elif re.match('^\-?\d+$', value):
val = int(value)
val_type = 'int'
else:
val = regs.get_reg_frm_var(value)
if val == -1:
return False
val = '$%s' % val
val_type = 'reg'
return (val, val_type)
def __arith(value, op):
#Performs arithmetic operations on the extracted values
#from byte_test. Also performs overflow check. returns
#False if overflow occurs.
#value = (value, type). type can be int/hex/register
#op = +/-. May add more in the future.
if value[1] == 'reg':
return value[0] + op + '1'
# currently only support + and -
if op == '+':
ret_val = value[0] + 1
elif op == '-':
ret_val = value[0] - 1
# checks overflow
if ret_val > 4294967295:
return False
if value[1] == 'hex':
return hex(ret_val)
return ret_val
def _handle_byte_test(value):
#Converts byte_test to -> --byte_test
#Syntax: byte_test <bytes>,<op>,<value>,<offset>[,modifiers]
#1. Do not support operators: !&, !^
#2. Snort allows byte test of 1-10 bytes. FGT only allows 1,2,4
#3. Do not support keywords: bitmask, dce
logging.debug('inside _handle_byte_test')
opts = [x.strip() for x in value.split(',')]
op = opts[1]
# handle bytes:
if opts[0] not in ['1', '2', '4']:
logging.error('"byte_test" cannot convert "%s". Option only allow testing against 1,2,4 bytes.' % value)
return False
pattern = ' --byte_test %s' % opts[0]
# handles values
val = __get_val(opts[2])
if not val:
logging.error('"byte_test" cannot convert "%s". Cannot map register to variable.' % value)
return False
else:
ret_val = val[0]
# handles operator
if '!' in op:
if '!=' == op:
pattern += ',!,'
elif '>' in op:
pattern += ',<,'
if '!>' == op:
ret_val = __arith(val, '+')
if not ret_val:
logging.error('"byte_test" cannot convert "%s". Operator not supported.' % value)
return False
elif '<' in op:
pattern += ',>,'
if '!<' == op:
ret_val = __arith(val, '-')
if not ret_val:
logging.error('"byte_test" cannot convert "%s". Operator not supported.' % value)
return False
else:
logging.error('"byte_test" cannot convert "%s". Operator not supported.' % value)
return False
elif '>=' == op:
ret_val = __arith(val, '-')
if not ret_val:
logging.error('"byte_test" cannot convert "%s". Operator not supported.' % value)
return False
pattern += ',>,'
elif '<=' == op:
ret_val = __arith(val, '+')
if not ret_val:
logging.error('"byte_test" cannot convert "%s". Operator not supported.' % value)
return False
pattern += ',<,'
else:
pattern += ',%s,' % op
# add offset
pattern += '%s,' % ret_val
pattern += opts[3]
# parse options
if len(opts) > 4:
for o in opts[4:]:
if o == 'dce' or 'bitmask' in o:
logging.error('"byte_test" cannot convert "%s". Modifier not supported.' % o)
return False
pattern += ',%s' % o
pattern += ';'
return pattern
def _handle_byte_extract(value):
#Converts byte_extract option to --extract
#byte_extract: <bytes>, <offset>, <name>, [options]
#Do not support keywords: dce, bitmask, multiplier
# align
logging.debug('inside _handle_byte_extract')
opts = [x.strip() for x in value.split(',')]
pattern = ' --extract %s,%s,' % (opts[0], opts[1])
reg = regs.set_reg(opts[2], 0)
pattern += '$%s' % reg
mult_num = ''
add_opts = []
if len(opts) > 3:
for o in opts[3:]:
if 'multiplier' in o:
mult_num = o.split(' ')[1]
elif o == 'dce' or 'bitmask' in o or 'align' in o:
logging.error('"byte_extract" cannot convert "%s". Modifier not supported.' % o)
return False
else:
add_opts.append(o)
if mult_num != '':
pattern += ',%s' % mult_num
if len(add_opts) > 0:
pattern += ',%s' % ','.join(add_opts)
pattern += ';'
return pattern
def _handle_ip_proto(value):
#Convert ip_proto -> --protocol <protocol>;
#If ip_proto contains operator, use ip[offset] instead.
logging.debug('inside _handle_ip_proto')
ip_protocols = {
'icmp': 1, 'igmp': 2, 'ggp': 3, 'ipip': 4, 'st': 5, 'tcp': 6, 'cbt': 7, 'egp': 8, 'igp': 9, 'bbnrcc': 10,
'nvp': 11, 'pup': 12, 'argus': 13, 'emcon': 14, 'xnet': 15, 'chaos': 16, 'udp': 17, 'mux': 18, 'dcnmeas': 19,
'hmp': 20, 'prm': 21, 'idp': 22, 'trunk1': 23, 'trunk2': 24, 'leaf1': 25, 'leaf2': 26, 'rdp': 27, 'irtp': 28,
'tp': 29, 'netblt': 30, 'mfpnsp': 31, 'meritinp': 32, 'sep': 33, '3pc': 34, 'idpr': 35, 'xtp': 36, 'ddp': 37,
'cmtp': 38, 'tppp': 39, 'il': 40, 'ip6': 41, 'sdrp': 42, 'routing': 43, 'fragment': 44, 'rsvp': 46, 'gre': 47,
'mhrp': 48, 'ena': 49, 'esp': 50, 'ah': 51, 'inlsp': 52, 'swipe': 53, 'narp': 54, 'mobile': 55, 'tlsp': 56,
'skip': 57, 'icmp6': 58, 'none': 59, 'dstopts': 60, 'anyhost': 61, 'cftp': 62, 'anynet': 63, 'expak': 64,
'kryptolan': 65, 'rvd': 66, 'ippc': 67, 'distfs': 68, 'satmon': 69, 'visa': 70, 'ipcv': 71, 'cpnx': 72,
'cphb': 73,
'wsn': 74, 'pvp': 75, 'brsatmon': 76, 'sunnd': 77, 'wbmon': 78, 'wbexpak': 79, 'eon': 80, 'vmtp': 81,
'svmtp': 82,
'vines': 83, 'ttp': 84, 'nsfigp': 85, 'dgp': 86, 'tcf': 87, 'eigrp': 88, 'ospf': 89, 'spriterpc': 90,
'larp': 91,
'mtp': 92, 'ax25': 93, 'ipipencap': 94, 'micp': 95, 'sccsp': 96, 'etherip': 97, 'encap': 98, 'anyenc': 99,
'gmtp': 100, 'ifmp': 101, 'pnni': 102, 'pim': 103, 'aris': 104, 'scps': 105, 'qnx': 106, 'an': 107,
'ipcomp': 108,
'snp': 109, 'compaqpeer': 110, 'ipxip': 111, 'vrrp': 112, 'pgm': 113, 'any0hop': 114, 'l2tp': 115, 'ddx': 116,
'iatp': 117,
'stp': 118, 'srp': 119, 'uti': 120, 'smp': 121, 'sm': 122, 'ptp': 123, 'isis': 124, 'fire': 125, 'crtp': 126,
'crudp': 127, 'sscopmce': 128, 'iplt': 129, 'sps': 130, 'pipe': 131, 'sctp': 132, 'fc': 133, 'rsvpign': 134
}
pattern = ''
value = value.replace(' ', '')
if '!' not in value and '<' not in value and '>' not in value:
if not value.isdigit():
value = ip_protocols.get(value)
if value is None:
logging.warning('"ip_proto" cannot convert "%s". Protocol cannot be converted. Omitting option.' % value)
return None
pattern += ' --protocol %s;' % value
elif '<>' in value or '<=>' in value:
pattern += _handle_min_max_convert('ip[9]', value)
else:
op = value[0]
proto_num = value[1:]
if not proto_num.isdigit():
proto_num = ip_protocols.get(proto_num)
if proto_num is None:
logging.warning('"ip_proto" cannot convert "%s". Protocol cannot be converted. Omitting option.' % value)
return None
pattern += ' --ip[9] %s%s;' % (op, proto_num)
return pattern
def _handle_ssl_version(value):
#Convert ssl_version -> --parsed_type <ssl_version>.
#One rule can have multiple --parsed_type options.
logging.debug('inside _handle_ssl_version')
service_priority.set_service('ssl')
pattern = ''
ssl_ver = {'tls1.0':'TLS_V1', 'tls1.1':'TLS_V2', 'tls1.2':'TLS_V3', 'sslv2':'SSL_V2', 'sslv3':'SSL_V3'}
opts = value.replace(' ', '').split(',')
for o in opts:
o = o.strip()
try:
pattern = "".join((' --parsed_type ', ssl_ver.get(o), ';'))
except:
logging.warning('"ssl_version" cannot convert "%s". SSL Version unknown. Omitting option.' % o)
continue
if pattern == '':
return None
return pattern
def _handle_uri_content(value):
#Handle Snort 2 'uricontent' (removed in favour of sticky buffers in
#Snort 3). uricontent is like content:"hdjsd"; http_uri; and modifiers
#like offset and distance can still be applied
#eg. uricontent:"hdjsd"; offset:4;
logging.debug('inside _handle_uri_content')
global content_seen_flag
global open_context_flag
global added_context_flag
content_seen_flag = True
pattern = __check_and_add_context_packet()
open_context_flag = True
added_context_flag = True
pattern += ' --pattern ' + __normalize_pattern(value.strip()) + '; --context uri;'
return pattern
def _handle_bufferlen(value):
#We only handle the case where bufferlen is part of a sticky buffer.
#Currently only supports bufferlen for uri, ie. the equivalent of
#urilen.
logging.debug('inside _handle_bufferlen')
uri_bufferlen = ''
if sticky_buffer_flag: