-
Notifications
You must be signed in to change notification settings - Fork 15
/
fwsnort
executable file
·4944 lines (4281 loc) · 172 KB
/
fwsnort
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/perl -w
#
###############################################################################
#
# File: fwsnort
#
# URL: http://www.cipherdyne.org/fwsnort/
#
# Purpose: To translate snort rules into equivalent iptables rules.
# fwsnort is based on the original snort2iptables shell script
# written by William Stearns.
#
# Author: Michael Rash <mbr@cipherdyne.org>
#
# Credits: (see the CREDITS file)
#
# Version: 1.6.8
#
# Copyright (C) 2003-2018 Michael Rash (mbr@cipherdyne.org)
#
# License - GNU Public License version 2 (GPLv2):
#
# 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
#
# TODO:
# - Add the ability to remove rules from a real snort config in the same
# way we remove them from iptables rulesets in fwsnort (we remove rules
# from an iptables ruleset if the iptables policy will not allow such
# traffic through in the first place).
# - New option: --ipt-mark.
#
# Reference: Snort is a registered trademark of Sourcefire, Inc
#
# Snort Rule Options:
#
# msg: Prints a message in alerts and packet logs.
# logto: Log the packet to a user specified filename instead of the
# standard output file.
# ttl: Test the IP header's TTL field value.
# tos: Test the IP header's TOS field value.
# id: Test the IP header's fragment ID field for a specific
# value.
# ipoption: Watch the IP option fields for specific codes.
# fragbits: Test the fragmentation bits of the IP header.
# dsize: Test the packet's payload size against a value.
# flags Test the TCP flags for certain values.
# seq: Test the TCP sequence number field for a specific value.
# ack: Test the TCP acknowledgement field for a specific value.
# itype: Test the ICMP type field against a specific value.
# icode: Test the ICMP code field against a specific value.
# icmp_id: Test the ICMP ECHO ID field against a specific value.
# icmp_seq: Test the ICMP ECHO sequence number against a specific
# value.
# content: Search for a pattern in the packet's payload.
# content-list: Search for a set of patterns in the packet's payload.
# offset: Modifier for the content option, sets the offset to begin
# attempting a pattern match.
# depth: Modifier for the content option, sets the maximum search
# depth for a pattern match attempt.
# nocase: Match the preceding content string with case insensitivity.
# session Dumps the application layer information for a given
# session.
# rpc: Watch RPC services for specific application/procedure
# calls.
# resp: Active response (knock down connections, etc).
# react: Active response (block web sites).
# reference: External attack reference ids.
# sid: snort rule id.
# rev: Rule revision number.
# classtype: Rule classification identifier.
# priority: Rule severity identifier.
# uricontent: Search for a pattern in the URI portion of a packet
#
# tag: Advanced logging actions for rules.
# ip_proto: IP header's protocol value.
# sameip: Determines if source ip equals the destination ip.
# stateless: Valid regardless of stream state.
# regex: Wildcard pattern matching.
#
############################################################################
#
use IO::Socket;
use File::Copy;
use File::Path;
use Sys::Hostname;
use Data::Dumper;
use Cwd;
use Getopt::Long;
use strict;
### config file
my $CONFIG_DEFAULT = '/etc/fwsnort/fwsnort.conf';
my $fwsnort_conf = $CONFIG_DEFAULT;
### version number
my $version = '1.6.8';
my %ipt_hdr_opts = (
'src' => '-s',
'sport' => '--sport',
'dst' => '-d',
'dport' => '--dport',
'proto' => '-p',
);
my %snort_opts = (
### snort options that we can directly filter on
### in iptables rulesets (snort options are separate
### from the snort "header" which include protocol,
### source, destination, etc.)
'filter' => {
### application layer
'uricontent' => { ### use --strict to not translate this
'iptopt' => '-m string',
'regex' => qr/[\s;]uricontent:\s*\"(.*?)\"\s*;/
},
'content' => {
'iptopt' => '-m string',
'regex' => qr/[\s;]content:\s*\"(.*?)\"\s*;/
},
'fast_pattern' => {
'iptopt' => '', ### fast_pattern just governs ordering of
### content matches
'regex' => qr/[\s;]fast_pattern(?::\s*.*?\s*)?;/,
},
'pcre' => {
### only basic PCRE's that just have strings separated
### by ".*" or ".+" are supported.
'iptopt' => '-m string',
'regex' => qr/[\s;]pcre:\s*\"(.*?)\"\s*;/
},
'nocase' => {
'iptopt' => '--icase',
'regex' => qr/[\s;]nocase\s*;/,
},
'offset' => {
'iptopt' => '--from',
'regex' => qr/[\s;]offset:\s*(\d+)\s*;/
},
'depth' => {
'iptopt' => '--to',
'regex' => qr/[\s;]depth:\s*(\d+)\s*;/
},
### technically, the "distance" and "within" criteria
### are relative to the end of the previous pattern match,
### so iptables cannot emulate these directly; an approximation
### is made based on the on length of the previous pattern an
### any "depth" or "offset" criteria for the previous pattern.
### To disable signatures with "distance" and "within", just
### use the --strict option.
'distance' => {
'iptopt' => '--from',
'regex' => qr/[\s;]distance:\s*(\d+)\s*;/
},
'within' => {
'iptopt' => '--to',
'regex' => qr/[\s;]within:\s*(\d+)\s*;/
},
'replace' => { ### for Snort running in inline mode
'iptopt' => '--replace-string',
'regex' => qr/[\s;]replace:\s*\"(.*?)\"\s*;/
},
'resp' => {
'iptopt' => '-j REJECT',
'regex' => qr/[\s;]resp:\s*(.*?)\s*;/
},
### transport layer
'flags' => {
'iptopt' => '--tcp-flags',
'regex' => qr/[\s;]flags:\s*(.*?)\s*;/
},
'flow' => {
'iptopt' => '--tcp-flags',
'regex' => qr/[\s;]flow:\s*(.*?)\s*;/
},
### network layer
'itype' => {
'iptopt' => '--icmp-type', ### --icmp-type type/code
'regex' => qr/[\s;]itype:\s*(.*?)\s*;/
},
'icode' => {
'iptopt' => 'NONE',
'regex' => qr/[\s;]icode:\s*(.*?)\s*;/
},
'ttl' => {
'iptopt' => '-m ttl', ### requires CONFIG_IP_NF_MATCH_TTL
'regex' => qr/[\s;]ttl:\s*(.*?)\s*;/
},
'tos' => {
'iptopt' => '-m tos --tos', ### requires CONFIG_IP_NF_MATCH_TOS
'regex' => qr/[\s;]tos:\s*(\d+)\s*;/
},
'ipopts' => {
'iptopt' => '-m ipv4options', ### requires ipv4options extension
'regex' => qr/[\s;]ipopts:\s*(\w+)\s*;/
},
'ip_proto' => {
'iptopt' => '-p',
'regex' => qr/[\s;]ip_proto:\s*(.*?)\s*;/
},
'dsize' => { ### requires CONFIG_IP_NF_MATCH_LENGTH
'iptopt' => '-m length --length',
'regex' => qr/[\s;]dsize:\s*(.*?)\s*;/
},
},
### snort options that can be put into iptables
### ruleset, but only in log messages with --log-prefix
'logprefix' => {
'sid' => qr/[\s;]sid:\s*(\d+)\s*;/,
'msg' => qr/[\s;]msg:\s*\"(.*?)\"\s*;/, ### we create a space
'classtype' => qr/[\s;]classtype:\s*(.*?)\s*;/,
'reference' => qr/[\s;]reference:\s*(.*?)\s*;/,
'priority' => qr/[\s;]priority:\s*(\d+)\s*;/,
'rev' => qr/[\s;]rev:\s*(\d+)\s*;/,
},
### handle the metadata field
'info' => {
'metadata' => qr/[\s;]metadata\s*(.*?)\s*;/,
},
### snort options that cannot be included directly
### within iptables filter statements (yet :)
'unsupported' => {
'asn1' => qr/[\s;]asn1:\s*.*?\s*;/,
'fragbits' => qr/[\s;]fragbits:\s*.*?\s*;/,
'content-list' => qr/[\s;]content\-list:\s*\".*?\"\s*;/,
'rpc' => qr/[\s;]rpc:\s*.*?\s*;/,
'byte_test' => qr/[\s;]byte_test\s*.*?\s*;/,
'byte_jump' => qr/[\s;]byte_jump\s*.*?\s*;/,
'byte_extract' => qr/[\s;]byte_extract\s*.*?\s*;/,
'file_data' => qr/[\s;]file_data\s*;/,
'window' => qr/[\s;]window:\s*.*?\s*;/,
'flowbits' => qr/[\s;]flowbits:\s*.*?\s*;/,
'tag' => qr/[\s;]tag:\s*.*?\s*;/,
'ftpbounce' => qr/[\s;]ftpbounce\s*;/,
'base64_data' => qr/[\s;]base64_data\s*;/,
'base64_decode' => qr/[\s;]base64_decode:\s*.*?\s*;/,
# 'offset' => qr/[\s;]offset:\s*\d+\s*;/,
# 'depth' => qr/[\s;]depth:\s*\d+\s*;/,
### the following fields get logged by iptables but
### we cannot filter them directly except with the
### iptables u32 module. Functionality has been built
### into psad to generate alerts for most of these Snort
### options.
'id' => qr/[\s;]id:\s*(\d+)\s*;/,
'seq' => qr/[\s;]seq:\s*(\d+)\s*;/, ### --log-tcp-sequence
'ack' => qr/[\s;]ack:\s*.*?\s*;/, ### --log-tcp-sequence
'icmp_seq' => qr/[\s;]icmp_seq:\s*(\d+)\s*;/,
'icmp_id' => qr/[\s;]icmp_id:\s*(\d+)\s*;/,
'sameip' => qr/[\s;]sameip\s*;/,
'regex' => qr/[\s;]regex:\s*(.*?)\s*;/,
'isdataat' => qr/[\s;]isdataat:\s*(.*?)\s*;/,
'threshold' => qr/[\s;]threshold:\s*.*?\s*;/, ### FIXME --limit
'detection_filter' => qr/[\s;]detection_filter:\s*.*?\s*;/ ### FIXME --limit
},
### snort options that fwsnort will ignore
'ignore' => {
'rawbytes' => qr/[\s;]rawbytes\s*;/, ### iptables does a raw match anyway
'logto' => qr/[\s;]logto:\s*\S+\s*;/,
'session' => qr/[\s;]session\s*;/,
'tag' => qr/[\s;]tag:\s*.*?\s*;/,
'react' => qr/[\s;]react:\s*.*?\s*;/, ### FIXME -j REJECT
'http_uri' => qr/[\s;]http_uri\s*;/,
'http_raw_uri' => qr/[\s;]http_raw_uri\s*;/,
'http_method' => qr/[\s;]http_method\s*;/,
'http_stat_code' => qr/[\s;]http_stat_code\s*;/,
'http_stat_msg' => qr/[\s;]http_stat_msg\s*;/,
'http_client_body' => qr/[\s;]http_client_body\s*;/,
'http_cookie' => qr/[\s;]http_cookie\s*;/,
'urilen' => qr/[\s;]urilen:\s*.*?\s*;/,
},
### in --strict mode, signatures that include any of these
### options are not translated to iptables rules
'strict_list' => [
'uricontent',
'pcre',
'distance',
'within',
'http_uri',
'http_raw_uri',
'http_method',
'http_stat_code',
'http_stat_msg',
'http_client_body',
'http_cookie',
'urilen'
]
);
### rules update link
my $DEFAULT_RULES_URL = 'http://rules.emergingthreats.net/open/snort-2.9.0/emerging-all.rules';
my $rules_url = $DEFAULT_RULES_URL;
### config vars that may span multiple lines
my %multi_line_vars = (
'UPDATE_RULES_URL' => '',
'WHITELIST' => '',
'BLACKLIST' => '',
);
### array that contains the fwsnort iptables script (will be written
### to $config{'FWSNORT_SCRIPT'})
my @ipt_script_lines = ();
### array that contains the fwsnort policy in iptables-save format.
### This will also contain the running iptables policy, so the fwsnort
### policy is integrated in.
my @fwsnort_save_lines = ();
my @ipt_save_lines = ();
my $ipt_save_index = 0;
my @ipt_save_script_lines = ();
my $ipt_save_completed_line = '';
my $save_str = 'iptables-save';
my $ipt_str = 'iptables';
my $save_bin = '';
my $restore_bin = '';
my $ipt_bin = '';
### contains a cache of the iptables policy
my %ipt_policy = ();
my %ipt_default_policy_setting = ();
my %ipt_default_drop = ();
my %ipt_save_existing_chains = ();
### hashes for save format data
my %save_format_whitelist = ();
my %save_format_blacklist = ();
my %save_format_prereqs = ();
my %save_format_rules = ();
my %save_format_conntrack_jumps = ();
### regex to match ip addresses
my $ip_re = qr|(?:[0-2]?\d{1,2}\.){3}[0-2]?\d{1,2}|;
my %snort_dump_cache = ();
my %ipt_dump_cache = ();
### for iptables capabilities testing
my $NON_HOST = '127.0.0.2';
my $NON_IP6_HOST = '::2/128';
my $non_host = '';
my $IPT_SUCCESS = 1;
my $IPT_FAILURE = 0;
my $IPT_TEST_RULE_NUM = 1;
my $MATCH_EQUIV = 1;
my $MATCH_SUBSTR = 2;
### header lengths; note that IP and TCP lengths are defined
### in the fwsnort.conf file since they may each contain options,
### but until the --payload option is added to the string match
### extension there is no way to account for them except to
### define an average length.
my $MAC_HDR_LEN = 14;
my $UDP_HDR_LEN = 8;
my $ICMP_HDR_LEN = 8;
### config and commands hashes (constructed by import_config())
my %config = ();
my %cmds = ();
my @local_addrs = ();
my %include_types = ();
my %exclude_types = ();
my %include_sids = ();
my %exclude_sids = ();
my %restrict_interfaces = ();
### establish some default behavior
my $home_net = ''; ### normally comes from fwsnort.conf
my $ext_net = ''; ### normally comes from fwsnort.conf
my $ipt_exec = 0;
my $ipt_revert = 0;
my $ipt_drop = 0;
my $ipt_reject = 0;
my $ipt_max_buf_len = 1025;
my $ipt_cap_search_factor = 128;
my $help = 0;
my $stdout = 0;
my $lib_dir = '';
my $rules_file = '';
my $debug = 0;
my $is_root = 0;
my $dumper = 0;
my $dump_ipt = 0;
my $dump_snort = 0;
my $strict = 0;
my $ipt_script = '';
my $logfile = '';
my $rules_dir = '';
my $homedir = '';
my $abs_num = 0;
my $run_last = 0;
my $queue_rules_dir = '';
my $queue_pre_match_max = 0;
my $dump_conf = 0;
my $kernel_ver = '2.6'; ### default
my $string_match_alg = 'bm';
my $verbose = 0;
my $print_ver = 0;
my $cmdl_homedir = '';
my $update_rules = 0; ### used to download latest snort rules
my $default_icmp_type = 8; ### echo request
my $ipt_print_type = 0;
my $ipt_check_capabilities = 0;
my $ipt_rule_ctr = 1;
my $ipt_sync = 0;
my $ipt_flush = 0;
my $ipt_del_chains = 0;
my $ipt_list = 0;
my $ipt_file = '';
my $no_pcre = 0;
my $no_ipt_log = 0;
my $no_ipt_test = 0;
my $no_ipt_jumps = 0;
my $no_ipt_input = 0;
my $no_ipt_output = 0;
my $no_addr_check = 0;
my $no_ipt_forward = 0;
my $ignore_opt = 0;
my $include_sids = '';
my $exclude_sids = '';
my $add_deleted = 0;
my $rules_types = '';
my $exclude_types = '';
my $snort_type = '';
my $ulog_nlgroup = 1;
my $queue_mode = 0;
my $nfqueue_mode = 0;
my $nfqueue_num = 0;
my $ulog_mode = 0;
my $exclude_re = '';
my $include_re = '';
my $include_re_caseless = 0;
my $exclude_re_caseless = 0;
my $enable_ip6tables = 0;
my $ipt_var_str = 'IPTABLES';
my $no_ipt_conntrack = 0;
my $conntrack_state = 'ESTABLISHED';
my $have_conntrack = 0;
my $have_state = 0;
my $snort_conf_file = '';
my $ipt_restrict_intf = '';
my $no_ipt_comments = 0;
my $no_ipt_rule_nums = 0;
my $no_exclude_loopback = 0;
my $no_ipt_log_ip_opts = 0;
my $no_ipt_log_tcp_opts = 0;
my $ipt_log_tcp_seq = 0;
my $include_perl_triggers = 0;
my $duplicate_last_build = 0;
my $ipt_max_str_len = 1;
my $ipt_max_log_prefix_len = 1;
my $ipt_max_comment_len = 1;
my $no_fast_pattern_order = 0;
my $ipt_have_multiport_match = 0;
my $ipt_multiport_max = 2;
### to be added to the string match extension
my $ipt_has_string_payload_offset_opt = 0;
### default to processing these filter chains
my %process_chains = (
'INPUT' => 1,
'FORWARD' => 1,
'OUTPUT' => 1,
);
my $TEST_CHAIN = 'FWS_CAP_TEST';
my %chain_ctr = ();
### save a copy of the command line args
my @argv_cp = @ARGV;
### see if we are running as root
&is_root();
### handle the command line args
&handle_cmd_line();
&run_last_cmdline() if $run_last;
### import config, initialize various things, etc.
&fwsnort_init();
### if we are running with $chk_ipt_policy, then cache
### the current iptables policy
&cache_ipt_policy() if $ipt_sync;
### truncate old fwsnort log
&truncate_logfile();
### check to make sure iptables has various functionality available
### such as the LOG target, --hex-strings, the comment match, etc.
if ($no_ipt_test) {
&set_defaults_without_ipt_test();
} else {
&ipt_capabilities();
}
### cache the running iptables policy in iptables-save format
&cache_ipt_save_policy();
### print a header at the top of the iptables ruleset
### script
&ipt_hdr();
### now that we have the interfaces, add the iptables
### chains to the fwsnort shell script
&ipt_add_chains();
### add any WHITELIST rules to the main fwsnort chains
### with the RETURN target
&ipt_whitelist();
### add any BLACKLIST rules to the main fwsnort chains
### with the DROP or REJECT targets
&ipt_blacklist();
### add jump rules for established tcp connections to
### the fwsnort state tracking chains
&ipt_add_conntrack_jumps() unless $no_ipt_conntrack;
### display the config on STDOUT
&dump_conf() if $dump_conf;
### make sure <type>.rules file exists if --type was
### specified on the command line
&check_type() if $rules_types;
&logr("[+] Begin parsing cycle.");
### parse snort rules (signatures)
if ($include_sids) {
print "[+] Parsing Snort rules files...\n";
} else {
if ($ipt_sync) {
print "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=",
"-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n",
sprintf("%-30s%-10s%-10s%-10s%-10s", ' Snort Rules File',
'Success', 'Fail', 'Ipt_apply', 'Total'), "\n\n";
} else {
print "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=",
"-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n",
sprintf("%-30s%-10s%-10s%-10s", ' Snort Rules File',
'Success', 'Fail', 'Total'), "\n\n";
}
}
### main subroutine to parse snort rules and add them to the
### fwsnort.sh script.
&parse_snort_rules();
### append all translated rules to the iptables-save formatted array
&save_format_append_rules();
### jump packets (as appropriate) from the INPUT and
### FORWARD chains to our fwsnort chains
&ipt_jump_chain() unless $no_ipt_jumps;
push @ipt_script_lines, qq|\n\$ECHO "[+] Finished."|, '### EOF ###';
push @ipt_save_script_lines, $ipt_script_lines[$#ipt_script_lines];
print "\n[+] Logfile: $config{'LOG_FILE'}\n";
if ($ipt_rule_ctr > 1) {
### write the iptables script out to disk
&write_ipt_script();
if ($queue_mode or $nfqueue_mode) {
print "[+] Snort rule set directory for rules to be queued ",
"to userspace:\n $config{'QUEUE_RULES_DIR'}\n";
}
print "[+] $ipt_str script (individual commands): " .
"$config{'FWSNORT_SCRIPT'}\n";
} else {
die "[-] No Snort rules could be translated, exiting\n";
}
&write_save_file();
&print_final_message();
exit 0;
#===================== end main ======================
sub parse_snort_rules() {
my @rfiles = ();
my $cwd = cwd();
if ($rules_file) {
@rfiles = split /\,/, $rules_file;
} else {
for my $dir (split /\,/, $config{'RULES_DIR'}) {
opendir D, $dir or die "[*] Could not opendir $dir";
for my $file (readdir D) {
push @rfiles, "$dir/$file";
}
closedir D;
}
}
my $sabs_num = 0;
my $tot_ipt_apply = 0;
my $tot_unsup_ctr = 0;
FILE: for my $rfile (sort @rfiles) {
$rfile = $cwd . '/' . $rfile unless $rfile =~ m|^/|;
my $type = '';
my $filename = '';
if ($rfile =~ m|.*/(\S+\.rules)$|) {
$filename = $1;
}
if ($rfile =~ m|.*/(\S+)\.rules$|) {
$type = $1;
} else {
next FILE;
}
$ipt_print_type = 0;
if ($rules_types) {
next FILE unless defined $include_types{$type};
}
if ($exclude_types) {
next FILE if defined $exclude_types{$type};
}
if ($rfile =~ m|deleted\.rules|) {
next FILE unless $add_deleted;
}
($snort_type) = ($rfile =~ m|.*/(\S+)\.rules|);
printf("%-30s", "[+] $filename") unless $include_sids;
&logr("[+] Parsing $rfile");
open R, "< $rfile" or die "[*] Could not open: $rfile";
my @lines = <R>;
close R;
### contains Snort rules that will be used by Snort_inline
### if fwsnort is building a QUEUE policy; these rules have
### met the criteria that at least one "content" match is
### required.
my @queue_rules = ();
my $line_num = 0;
my $rule_num = 0;
my $parsed_ctr = 0;
my $unsup_ctr = 0;
my $ipt_apply_ctr = 0;
my $ipt_rules_ctr = 0;
RULE: for my $rule (@lines) {
chomp $rule;
my $rule_hdr;
my $rule_options;
$line_num++;
### pass == ACCEPT, log == ULOG
unless ($rule =~ /^\s*alert/ or $rule =~ /^\s*pass/
or $rule =~ /^\s*log/) {
next RULE;
}
### regex filters
if ($exclude_re) {
next RULE if $rule =~ $exclude_re;
}
if ($include_re) {
next RULE unless $rule =~ $include_re;
}
$rule_num++; ### keep track of the abs num of rules
$sabs_num++;
if ($rule =~ m|^(.*?)\s+\((.*)\)|) {
$rule_hdr = $1;
$rule_options = " $2 "; ### allows out-of-order options
} else {
&logr("[-] Unrecognized rule format at line: $line_num. " .
"Skipping.");
next RULE;
}
### skip all icmp "Undefined Code" rules; psad properly
### handles this, but not fwsnort (see the icmp-info.rules
### file).
if ($filename =~ /icmp/ and $rule_options =~ /undefined\s+code/i) {
$unsup_ctr++;
$tot_unsup_ctr++;
next RULE;
}
### parse header portion of Snort rule
my $hdr_hr = &parse_rule_hdr($rule_hdr, $line_num);
unless (keys %$hdr_hr) {
&logr("[-] Unrecognized rule header: \"$rule_hdr\" at " .
"line: $line_num, skipping.");
$unsup_ctr++;
$tot_unsup_ctr++;
next RULE;
}
### parse options portion of Snort rule
my ($parse_rv, $opts_hr, $patterns_ar) = &parse_rule_options(
$rule_options, &get_avg_hdr_len($hdr_hr), $line_num);
unless ($parse_rv) {
$unsup_ctr++;
$tot_unsup_ctr++;
next RULE;
}
if ($include_sids) {
print "[+] Found sid: $opts_hr->{'sid'} in $filename\n";
}
if ($queue_mode or $nfqueue_mode) {
### In general, it is not easy to modify the signatures that
### snort_inline would use; one would think that an optimzation
### would be to remove all "content" keywords since the kernel
### itself is doing this now, but consider the following:
### Suppose there are two original Snort signatures like so:
###
### msg: "SIG1"; content: "abc"; pcre: "(d|e)";
### msg: "SIG2"; content: "xyz"; pcre: "(e|f)";
###
### Now, suppose there is a packet with the following data:
###
### packet data: "xyz------------e------"
###
### Then the SIG1 matches when it shouldn't because the packet
### does not contain "abc" (assuming the "abc" string is
### removed from the signature that is actually deployed with
### snort_inline). There does not seem to be a good solution
### for this problem if pcre criteria are involved because the
### two pcre's would have to be interpreted to see if there is
### any data that could satisfy both at the same time.
### However, performing the duplicate string matching is far
### less expensive than not sending a large portion of network
### traffic to userspace for analysis by snort_inline in the
### first place. This is the real benefit of letting fwsnort
### build a smarter iptables queueing policy. This does come
### with a penalty against detection, since snort_inline is
### only receiving individual packets that match one of the
### content keywords in a signature; it does not get the
### entire stream. But, this may be worth it for large sites
### where performance is the primary concern. Also, there is
### some potential for removing a subset of the content
### matches if done in the right way; this is the reason the
### queue_get_rule() function is stubbed in below.
my $queue_rule = &queue_get_rule($rule_hdr, $rule_options);
push @queue_rules, $queue_rule if $queue_rule;
}
### construct the equivalent iptables rule and add it
### to $config{'FWSNORT_SCRIPT'}
my ($ipt_rv, $num_rules) = &ipt_build($hdr_hr,
$opts_hr, $patterns_ar, $rule);
if ($ipt_rv) {
$ipt_apply_ctr++;
$tot_ipt_apply++;
### may have the rule in several chains
$ipt_rules_ctr += $num_rules;
if ($include_sids) {
print " Successful translation.\n";
}
} else {
if ($include_sids) {
print " Unsuccessful translation.\n";
}
}
$parsed_ctr++; ### keep track of successfully parsed rules
$abs_num++;;
}
if (($queue_mode or $nfqueue_mode) and @queue_rules) {
open M, "> $config{'QUEUE_RULES_DIR'}/$filename" or die "[*] Could not ",
"open $config{'QUEUE_RULES_DIR'}/$filename: $!";
print M "#\n### This file generated with: fwsnort @argv_cp\n#\n\n";
print M "$_\n", for @queue_rules;
print M "\n### EOF ###\n";
close F;
}
if ($ipt_rules_ctr) {
$ipt_rules_ctr *= 2 if $ipt_drop;
$ipt_rules_ctr *= 2 if $ipt_reject;
push @ipt_script_lines,
qq|\$ECHO " Rules added: $ipt_rules_ctr"|;
}
unless ($include_sids) {
if ($ipt_sync) {
printf("%-10s%-10s%-10s%-10s\n", $parsed_ctr, $unsup_ctr,
$ipt_apply_ctr, $rule_num);
} else {
printf("%-10s%-10s%-10s\n", $parsed_ctr, $unsup_ctr,
$rule_num);
}
}
}
unless ($include_sids) {
if ($ipt_sync) {
printf("%30s", ' ');
print "=======================================\n";
printf("%30s%-10s%-10s%-10s%-10s\n", ' ',
$abs_num, $tot_unsup_ctr, $tot_ipt_apply, $sabs_num);
} else {
printf("%30s", ' ');
print "=============================\n";
printf("%30s%-10s%-10s%-10s\n", ' ',
$abs_num, $tot_unsup_ctr, $sabs_num);
}
print "\n";
if ($abs_num) { ### we parsed at least one rule
print "[+] Generated $ipt_str rules for $abs_num out of ",
"$sabs_num signatures: ",
sprintf("%.2f", $abs_num/$sabs_num*100), "%\n";
} else {
print "[+] No rules parsed.\n";
}
if ($ipt_sync) {
print "[+] Found $tot_ipt_apply applicable snort rules to your " .
"current $ipt_str\n policy.\n";
}
}
return;
}
sub parse_rule_options() {
my ($rule_options, $avg_hdr_len, $line_num) = @_;
my $sid = -1;
my %opts = ();
my @patterns = ();
### get the sid here for logging purposes
if ($rule_options =~ $snort_opts{'logprefix'}{'sid'}) {
$sid = $1;
} else {
return 0, \%opts, \@patterns;
}
if (%exclude_sids) {
return 0, \%opts, \@patterns if defined $exclude_sids{$sid};
}
if (%include_sids) {
if (defined $include_sids{$sid}) {
&logr("[+] matched sid:$sid: $rule_options");
} else {
return 0, \%opts, \@patterns;
}
}
unless ($queue_mode or $nfqueue_mode) {
### if we're queuing packets to userspace Snort, then we don't have to
### disqualify a signature based on an option that is not supported by
### iptables
my $found_unsupported = '';
for my $opt (keys %{$snort_opts{'unsupported'}}) {
### see if we match a regex belonging to an unsupported option
if ($rule_options =~ $snort_opts{'unsupported'}{$opt}) {
$found_unsupported .= "'$opt', ";
}
}
if ($found_unsupported) {
$found_unsupported =~ s/,\s+$//;
&logr("[-] SID: $sid Unsupported option(s): $found_unsupported " .
"at line: $line_num, skipping.");
if (%include_sids and defined $include_sids{$sid}) {
print "[-] SID: $sid contain the unsupported option(s): ",
"$found_unsupported at line: $line_num\n";
}
return 0, \%opts, \@patterns;
}
}
if ($rule_options =~ /ip_proto\s*:.*ip_proto\s*:/) {
&logr("[-] SID: $sid, unsupported multiple ip_proto fields at " .
"line: $line_num, skipping.");
return 0, \%opts, \@patterns;
}
for my $opt (keys %{$snort_opts{'filter'}}) {
### see if we match the option regex
if ($rule_options =~ $snort_opts{'filter'}{$opt}{'regex'}) {
$opts{$opt} = 1;
$opts{$opt} = $1 if defined $1; ### some keywords may not have an option
}
}
my $found_content = 0;
while ($rule_options =~ /(\w+):?\s*((?:.*?[^\x5c]?))\s*;/g) {
my $opt = $1;
my $val = 1;
$val = $2 if defined $2; ### some keywords may not have an argument
if ($opt eq 'content' or $opt eq 'uricontent') {
return 0, \%opts, \@patterns unless $val =~ /"$/;
$val =~ s/^\s*"//;
$val =~ s/"\s*$//;
return 0, \%opts, \@patterns unless $val =~ /\S/;
### convert the string into a form that is more compatible
### for iptables
my ($rv, $log_str, $ipt_pattern_hr)
= &convert_pattern_for_iptables($val);
if ($rv) {
$found_content = 1;
push @patterns, $ipt_pattern_hr;
} else {
&logr("[-] SID: $sid, $log_str");
return 0, \%opts, \@patterns;
}
} elsif ($opt eq 'pcre') {
$val =~ s|^\s*"/||;
$val =~ s|/\w{0,3}"$||;
### see if this pcre only has strings separated with ".*" or ".+"
### and if so translate to multple string matches
my ($pcre_rv, $pcre_strings_ar) = &parse_pcre($val);
if ($pcre_rv) {
for my $str (@$pcre_strings_ar) {
push @patterns, $str;
}
} else {
unless ($queue_mode or $nfqueue_mode) {
&logr("[-] SID: $sid, unsupported complex pcre: $val");
return 0, \%opts, \@patterns;
}
}
} elsif ($opt eq 'fast_pattern') {
if ($no_fast_pattern_order) {
### force it to be the first pattern so no reordering
### will happen
$patterns[0]->{'fast_pattern'} = 1;
} else {
$patterns[$#patterns]->{'fast_pattern'} = 1;
}
} elsif ($opt eq 'nocase') {
unless (defined $snort_opts{'ignore'}{'nocase'}) {
$patterns[$#patterns]->{'nocase'} = 1;
}
} else {
for my $key (qw(offset depth within distance)) {
if ($opt eq $key) {
my ($offsets_rv, $log_str)
= &define_offsets(\@patterns,
$avg_hdr_len, $key, $val);
unless ($offsets_rv) {
&logr("[-] SID: $sid, $log_str");
return 0, \%opts, \@patterns;
}
last;
}
}
}
}
if (($queue_mode or $nfqueue_mode) and not $found_content) {
my $queue_str = 'QUEUE';
$queue_str = 'NFQUEUE' if $nfqueue_mode;
&logr("[-] SID: $sid In --$queue_str mode signature must have " .
"'content' or 'uricontent' keyword " .
"at line: $line_num, skipping.");
if (%include_sids and defined $include_sids{$sid}) {
print "[-] SID: $sid does not contain 'content' ",
"or 'uricontent'\n";
}
return 0, \%opts, \@patterns;