-
Notifications
You must be signed in to change notification settings - Fork 133
/
pulledpork.pl
executable file
·2459 lines (2246 loc) · 87 KB
/
pulledpork.pl
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 perl
## pulledpork v(whatever it says below!)
# Copyright (C) 2009-2021 JJ Cummings, Michael Shirk and the PulledPork Team!
# 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 2
# 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.
use strict;
use warnings;
use File::Copy;
use LWP::UserAgent;
use HTTP::Request::Common;
use HTTP::Status qw (is_success);
#use Crypt::SSLeay;
use Sys::Syslog;
use Digest::MD5;
use File::Path;
use File::Find;
use File::Basename;
use Getopt::Long qw(:config no_ignore_case bundling);
use Archive::Tar;
use POSIX qw(:errno_h);
use Cwd;
use Carp;
use Data::Dumper;
### Vars here
# we are gonna need these!
my ($oinkcode, $temp_path, $rule_file, $Syslogging);
my $VERSION = "0.8.0";
my $HUMOR = "The only positive thing to come out of 2020...well this and take-out liquor!";
my $ua = LWP::UserAgent->new;
#Read in proxy settings from the environment
$ua->env_proxy;
#Add PulledPork version to the user agent
$ua->agent("PulledPork v$VERSION");
# for certificate validation, check for the operating system
# and set the path to the certificate store if required.
my $oSystem = "$^O";
my $CAFile = "OS Default";
if ($oSystem =~ /freebsd/i) {
#Check to ensure the cert file exists
if (-e "/etc/ssl/cert.pem") {
$CAFile = "/etc/ssl/cert.pem";
if (-r $CAFile) {
$ua->ssl_opts(SSL_ca_file => $CAFile);
}
else {
carp "ERROR: $CAFile is not readable by "
. (getpwuid($<))[0] . "\n";
syslogit('err|local0',
"FATAL: ERROR: $CAFile is not readable by "
. (getpwuid($<))[0] . "\n")
if $Syslogging;
exit(1);
}
#Check for the other location for the cert file
}
elsif (-e "/usr/local/etc/ssl/cert.pem") {
$CAFile = "/usr/local/etc/ssl/cert.pem";
if (-r $CAFile) {
$ua->ssl_opts(SSL_ca_file => $CAFile);
}
else {
carp "ERROR: $CAFile is not readable by "
. (getpwuid($<))[0] . "\n";
syslogit('err|local0',
"FATAL: ERROR: $CAFile is not readable by "
. (getpwuid($<))[0] . "\n")
if $Syslogging;
exit(1);
}
}
else {
carp
"ERROR: cert file does not exist (/etc/ssl/cert.pem or /usr/local/etc/ssl/cert.pem) Ensure that the ca_root_nss port/pkg is installed, or use -w to skip SSL verification\n";
syslogit('err|local0',
"FATAL: cert file does not exist. Ensure that the ca_root_nss port/pkg is installed, or use -w to skip SSL verification\n"
) if $Syslogging;
exit(1);
}
}
my ($Hash, $ALogger, $Config_file, $Sorules, $Auto);
my ($Output, $Distro, $Snort, $sid_changelog, $ignore_files);
my ($Snort_config, $Snort_path, $Textonly, $grabonly, $ips_policy,);
my ($pid_path, $SigName, $NoDownload, $sid_msg_map, @base_url);
my ($local_rules, $arch, @records, $enonly);
my ($rstate, $keep_rulefiles, $rule_file_path, $prefix, $block_list);
my ($Process, $hmatch, $bmatch, $sid_msg_version, $skip_verify,
$proxy_workaround);
my $Sostubs = 1;
my $Snortv3 = 0;
# verbose and quiet control print()
# default values if not set otherwise in getopt
# $Verbose = 0 is normal output (default behaviour)
# $Verbose = 1 is loud output
# $Verbose = 2 is troubleshooting output
# $Quiet = 0 leaves verbosity as default or otherwise set
# $Quiet = 1 suppresses all but FAIL messages, eg, anything preceding an exit
my $Verbose = 0;
my $Quiet = 0;
undef($Hash);
undef($ALogger);
my %rules_hash = ();
my %blocklist = ();
my %oldrules_hash = ();
my %sid_msg_map = ();
my %sidmod = ();
my $categories = ();
undef %rules_hash;
undef %oldrules_hash;
undef %sid_msg_map;
## initialize some vars
my $rule_digest = "";
my $md5 = "";
# Vars the subroutine to fetch config values
my ($Config_key);
my %Config_info = ();
### Subroutines here
## routine to grab our config from the defined config file
sub parse_config_file {
my ($FileConf, $Config_val) = @_;
my ($config_line, $Name, $Value);
if (!open(CONFIG, "$FileConf")) {
carp "ERROR: Config file not found : $FileConf\n";
syslogit('err|local0', "FATAL: Config file not found: $FileConf")
if $Syslogging;
exit(1);
}
open(CONFIG, "$FileConf");
while (<CONFIG>) {
$config_line = $_;
chomp($config_line);
$config_line = trim($config_line);
if (($config_line !~ /^#/) && ($config_line ne "")) {
($Name, $Value) = split(/=/, $config_line);
if ($Value =~ /,/ && $Name eq "rule_url") {
push(@{ $$Config_val{$Name} }, split(/,/, $Value));
}
elsif ($Name eq "rule_url") {
push(@{ $$Config_val{$Name} }, split(/,/, $Value))
if $Value;
}
else {
$$Config_val{$Name} = $Value;
}
}
}
close(CONFIG);
}
## Help routine.. display help to stdout then exit
sub Help {
my $msg = shift;
if ($msg) { print "\nERROR: $msg\n"; }
print <<__EOT;
Usage: $0 [-dEgklnRTPVvv? -help] -c <config filename> -o <rule output path>
-O <oinkcode> -s <so_rule output directory> -D <Distro> -S <SnortVer>
-p <path to your snort binary> -C <path to your snort.conf> -t <sostub output path>
-h <changelog path> -H <signal_name> -I (security|connectivity|balanced) -i <path to disablesid.conf>
-b <path to dropsid.conf> -e <path to enablesid.conf> -M <path to modifysid.conf>
Options:
-help/? Print this help info.
-b Where the dropsid config file lives.
-C Path to your snort.conf
-c Where the pulledpork config file lives.
-d Do not verify signature of rules tarball, i.e. downloading fron non VRT or ET locations.
-D What Distro are you running on, for the so_rules
For latest supported options see http://www.snort.org/snort-rules/shared-object-rules
Valid Distro Types:
Alpine-3-10
Centos-6, Centos-7, Centos-8
Debian-8, Debian-9, Debian-10
FC-27, FC-30
FreeBSD-11, FreeBSD-12
OpenBSD-6-2, OpenBSD-6-4, OpenBSD-6-5
OpenSUSE-15-0, OpenSUS-15-1, OpenSUSE-42-3
RHEL-6, RHEL-7, RHEL-8
Slackware-14-2
Ubuntu-14-4, Ubuntu-16-4, Ubuntu-17-10, Ubuntu-18-4
-e Where the enablesid config file lives.
-E Write ONLY the enabled rules to the output files.
-g grabonly (download tarball rule file(s) and do NOT process)
-h path to the sid_changelog if you want to keep one?
-H Send signal_name to the pids listed in the config file (SIGHUP or SIGUSR2)
-I Specify a base ruleset( -I security,connectivity,or balanced, see README.RULESET)
-i Where the disablesid config file lives.
-k Keep the rules in separate files (using same file names as found when reading)
-K Where (what directory) do you want me to put the separate rules files?
-l Log Important Info to Syslog (Errors, Successful run etc, all items logged as WARN or higher)
-L Where do you want me to read your local.rules for inclusion in sid-msg.map
-m where do you want me to put the sid-msg.map file?
-M where the modifysid config file lives.
-n Do everything other than download of new files (disablesid, etc)
-o Where do you want me to put generic rules file?
-O Define the oinkcode on the command line (necessary for some users)
-p Path to your Snort binary
-P Process rules even if no new rules were downloaded
-R When processing enablesid, return the rules to their ORIGINAL state
-S What version of snort are you using (2.8.6 or 2.9.0) are valid values
-s Where do you want me to put the so_rules?
-T Process text based rules files only, i.e. DO NOT process so_rules
-u Where do you want me to pull the rules tarball from
** E.g., ET, Snort.org. See pulledpork config rule_url option for value ideas
-V Print Version and exit
-v Verbose mode, you know.. for troubleshooting and such nonsense.
-vv EXTRA Verbose mode, you know.. for in-depth troubleshooting and other such nonsense.
-w Skip the SSL verification (if there are issues pulling down rule files)
-W Where you want to work around the issue where some implementations of LWP do not work with pulledpork's proxy configuration.
__EOT
exit(0);
}
## OMG We MUST HAVE FLYING PIGS!
sub pulledpork {
print <<__EOT;
https://github.com/shirkdog/pulledpork
_____ ____
`----,\\ )
`--==\\\\ / PulledPork v$VERSION - $HUMOR
`--==\\\\/
.-~~~~-.Y|\\\\_ Copyright (C) 2009-2021 JJ Cummings, Michael Shirk
\@_/ / 66\\_ and the PulledPork Team!
| \\ \\ _(\")
\\ /-| ||'--' Rules give me wings!
\\_\\ \\_\\\\
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
__EOT
}
## subroutine to cleanup the temp rubbish!!!
sub temp_cleanup {
my $remove = rmtree($temp_path . "tha_rules");
if ($Verbose && !$Quiet) {
print "Cleanup....\n";
print
"\tremoved $remove temporary snort files or directories from $temp_path"
. "tha_rules!\n";
}
}
# subroutine to extract the files to a temp path so that we can do what we need to do..
sub rule_extract {
my ($rule_file, $temp_path, $Distro, $arch, $Snort,
$Sorules, $ignore, $prefix, $Snortv3)
= @_;
#special case to bypass file operations when -nPT are specified
my $BypassTar = 0;
if (!$BypassTar) {
print "Prepping rules from $rule_file for work....\n" if !$Quiet;
print "\textracting contents of $temp_path$rule_file...\n"
if ($Verbose && !$Quiet);
}
mkpath($temp_path . "tha_rules");
mkpath($temp_path . "tha_rules/so_rules");
my $tar = Archive::Tar->new();
if (!$BypassTar) {
$tar->read($temp_path . $rule_file);
$tar->setcwd(cwd());
}
local $Archive::Tar::CHOWN = 0;
my @ignores = split(/,/, $ignore) if (defined $ignore);
foreach (@ignores) {
if ($_ =~ /\.rules/) {
print "\tIgnoring plaintext rules: $_\n" if ($Verbose && !$Quiet);
$tar->remove("rules/$_");
}
elsif ($_ =~ /\.preproc/) {
print "\tIgnoring preprocessor rules: $_\n"
if ($Verbose && !$Quiet);
my $preprocfile = $_;
$preprocfile =~ s/\.preproc/\.rules/;
$tar->remove("preproc_rules/$preprocfile");
}
elsif ($_ =~ /\.so/) {
print "\tIgnoring shared object rules: $_\n"
if ($Verbose && !$Quiet);
$tar->remove("so_rules/precompiled/$Distro/$arch/$Snort/$_");
}
else {
print "\tIgnoring all rule types in $_ category!\n"
if ($Verbose && !$Quiet);
$tar->remove("rules/$_.rules");
$tar->remove("preproc_rules/$_.rules");
$tar->remove("so_rules/precompiled/$Distro/$arch/$Snort/$_");
}
}
my $sofile_pat_base = "^so_rules\/precompiled\/";
if ($Snortv3 == 0) {
$sofile_pat_base = $sofile_pat_base . "($Distro)\/($arch)\/($Snort)\/";
}
else {
$sofile_pat_base = $sofile_pat_base . "($Distro)-($arch)\/";
}
my $sofile_pat = $sofile_pat_base . ".*\.so";
my @files = $tar->get_files();
foreach (@files) {
my $filename = $_->name;
my $singlefile = $filename;
if ($filename =~ /^(community-)?rules\/.*\.rules$/) {
$singlefile =~ s/^(community-)?rules\///;
$tar->extract_file($filename,
$temp_path . "/tha_rules/$prefix" . $singlefile);
print "\tExtracted: /tha_rules/$prefix$singlefile\n"
if ($Verbose && !$Quiet);
}
elsif ($filename =~ /^preproc_rules\/.*\.rules$/) {
$singlefile =~ s/^preproc_rules\///;
$tar->extract_file($filename,
$temp_path . "/tha_rules/$prefix" . $singlefile);
print "\tExtracted: /tha_rules/$prefix$singlefile\n"
if ($Verbose && !$Quiet);
}
elsif ($Sorules
&& $filename
=~ m/$sofile_pat/
&& -d $Sorules
&& !$Textonly)
{
$singlefile
=~ s/$sofile_pat_base//;
$tar->extract_file($filename, $Sorules . $singlefile);
print "\tExtracted: $Sorules$singlefile\n"
if ($Verbose && !$Quiet);
}
}
print "\tDone!\n" if (!$Verbose && !$Quiet);
}
## subroutine to actually check the md5 values, if they match we move onto file manipulation routines
sub compare_md5 {
my (
$oinkcode, $rule_file, $temp_path, $Hash,
$base_url, $md5, $rule_digest, $Distro,
$arch, $Snort, $Sorules, $ignore_files,
$prefix, $Process, $hmatch, $fref
) = @_;
if ($rule_digest =~ $md5 && !$Hash) {
if ($Verbose && !$Quiet) {
print "\tThe MD5 for $rule_file matched $md5\n\n";
}
if (!$Verbose && !$Quiet) { print "\tThey Match\n\tDone!\n"; }
return (1);
}
elsif ($rule_digest !~ $md5 && !$Hash) {
if ($Verbose && !$Quiet) {
print
"\tThe MD5 for $rule_file did not match the latest digest... so I am gonna fetch the latest rules file!\n";
}
if (!$Verbose && !$Quiet) { print "\tNo Match\n\tDone\n"; }
rulefetch($oinkcode, $rule_file, $temp_path, $base_url);
$rule_digest = md5sum($rule_file, $temp_path);
$fref->{EXTRACT} = 1 if !$grabonly;
return (
compare_md5(
$oinkcode, $rule_file, $temp_path, $Hash,
$base_url, $md5, $rule_digest, $Distro,
$arch, $Snort, $Sorules, $ignore_files,
$prefix, $Process, $hmatch, $fref
)
);
}
elsif ($Hash) {
if ($Verbose && !$Quiet) {
print
"\tOk, not verifying the digest.. lame, but that's what you specified!\n";
print
"\tSo if the rules tarball doesn't extract properly and this script croaks.. it's your fault!\n";
print "\tNo Verify Set\n\tDone!\n";
}
$fref->{EXTRACT} = 1 if !$grabonly;
return (1);
}
else {
return ($hmatch);
}
}
sub _get_ua_request {
my ($ua, $method, $url, $file) = @_;
my $request = HTTP::Request->new($method => $url);
my $response = $ua->request($request, $file);
if ($response->is_success) {
return $response->code;
}
# TODO: 4XX catching
my $msg = sprintf("Error downloading %s: %s [ %d ]",
$url, $response->status_line, $response->code);
syslogit('err|local0', $msg) if $Syslogging;
die $msg, $/;
}
## mimic LWP::Simple getstore routine - Thx pkthound!
sub getstore {
my ($url, $file) = @_;
my $method = "GET";
#Workaround proxy issues, depends on version of LWP
#May need to be addressed in the future
if ($ua->proxy("https") && $url =~ /^https:/ && !$proxy_workaround) {
$method = "CONNECT";
}
else {
$method = "GET";
}
# on the first run, the file may not exist, so check.
if (-e $file) {
# Check to ensure the user has write access to the file
if (-r $file && -w _) {
return _get_ua_request($ua, $method, $url, $file);
}
else {
carp "ERROR: $file is not writable by "
. (getpwuid($<))[0] . "\n";
syslogit('err|local0',
"FATAL: $file is not writable by " . (getpwuid($<))[0] . "\n")
if $Syslogging;
exit(1);
}
}
else {
return _get_ua_request($ua, $method, $url, $file);
}
}
## time to grab the real 0xb33f
sub rulefetch {
my ($oinkcode, $rule_file, $temp_path, $base_url) = @_;
print "Rules tarball download of $rule_file....\n"
if (!$Quiet
&& $rule_file !~ /IPBLOCKLIST/
&& $oinkcode !~ /RULEFILE/);
print "Rule file download of $rule_file....\n"
if (!$Quiet
&& $rule_file !~ /IPBLOCKLIST/
&& $oinkcode =~ /RULEFILE/);
print "IP Blocklist download of $base_url....\n"
if (!$Quiet
&& $rule_file =~ /IPBLOCKLIST/
&& $oinkcode !~ /RULEFILE/);
$base_url = slash(0, $base_url);
my ($getrules_rule);
if ($Verbose && !$Quiet) {
print "\tFetching rules file: $rule_file\n"
if ($rule_file !~ /IPBLOCKLIST/ && $oinkcode !~ /RULEFILE/);
if ($Hash && $rule_file !~ /IPBLOCKLIST/ && $oinkcode !~ /RULEFILE/) {
print "But not verifying MD5\n";
}
}
if ($base_url =~ /[^labs]\.snort\.org/i) {
$getrules_rule
= getstore(
"https://www.snort.org/rules/$rule_file\?oinkcode=$oinkcode",
$temp_path . $rule_file);
}
elsif ($rule_file =~ /IPBLOCKLIST/ && !$NoDownload) {
my $rand = rand(1000);
$getrules_rule
= getstore($base_url, $temp_path . "$rand-block_list.rules");
read_iplist(\%blocklist, $temp_path . "$rand-block_list.rules");
unlink($temp_path . "$rand-block_list.rules");
}
elsif ($oinkcode =~ /RULEFILE/ && !$NoDownload) {
my $rand = rand(1000);
mkpath($temp_path . "/tha_rules");
$getrules_rule = getstore($base_url . "/" . $rule_file,
$temp_path . "/tha_rules/" . $rule_file);
}
else {
$getrules_rule
= getstore($base_url . "/" . $rule_file, $temp_path . $rule_file);
}
if ($getrules_rule == 403) {
print
"\tA 403 error occurred, please wait for the 15 minute timeout\n\tto expire before trying again or specify the -n runtime switch\n",
"\tYou may also wish to verify your oinkcode, tarball name, and other configuration options\n";
syslogit('emerg|local0', "FATAL: 403 error occured") if $Syslogging;
exit(1); # For you shirkdog
}
elsif ($getrules_rule == 404) {
print
"\tA 404 error occurred, please verify your filenames and urls for your tarball!\n";
syslogit('emerg|local0', "FATAL: 404 error occured") if $Syslogging;
exit(1); # For you shirkdog
}
elsif ($getrules_rule == 500) {
print
"\tA 500 error occurred, please verify that you have recently updated your root certificates!\n";
syslogit('emerg|local0', "FATAL: 500 error occured") if $Syslogging;
exit(1); # Certs bitches!
}
unless (is_success($getrules_rule)) {
syslogit('emerg|local0',
"FATAL: Error $getrules_rule when fetching $rule_file")
if $Syslogging;
croak "\tError $getrules_rule when fetching " . $rule_file;
}
if ($Verbose && !$Quiet && $rule_file !~ /IPBLOCKLIST/) {
print("\tstoring file at: $temp_path$rule_file\n\n");
}
if (!$Verbose && !$Quiet) { "\tDone!\n"; }
}
## subroutine to deterine the md5 digest of the current rules file
sub md5sum {
my ($rule_file, $temp_path) = @_;
open(MD5FILE, "$temp_path$rule_file")
or croak $!;
binmode(MD5FILE);
$rule_digest = Digest::MD5->new->addfile(*MD5FILE)->hexdigest;
close(MD5FILE);
if ($@) {
print $@;
return "";
}
if ($Verbose && !$Quiet) {
print "\tcurrent local rules file digest: $rule_digest\n";
}
return $rule_digest;
}
## subroutine to fetch the latest md5 digest signature file from snort.org
sub md5file {
my ($oinkcode, $rule_file, $temp_path, $base_url) = @_;
my ($getrules_md5, $md5) = "";
$base_url = slash(0, $base_url);
print "Checking latest MD5 for $rule_file....\n" if !$Quiet;
print "\tFetching md5sum for: " . $rule_file . ".md5\n"
if ($Verbose && !$Quiet);
if ($base_url =~ /[^labs]\.snort\.org/i) {
$getrules_md5 = getstore(
"https://www.snort.org/rules/$rule_file.md5\?oinkcode=$oinkcode",
$temp_path . $rule_file . ".md5"
);
}
elsif ($base_url
=~ /(secureworks|emergingthreats\.net|emergingthreatspro\.com|snort\.org.+community)/i
)
{
$getrules_md5 = getstore(
"$base_url/$rule_file" . ".md5",
$temp_path . $rule_file . ".md5"
);
}
if ($getrules_md5 == 403) {
print
"\tA 403 error occurred, please wait for the 15 minute timeout\n\tto expire before trying again or specify the -n runtime switch\n",
"\tYou may also wish to verify your oinkcode, tarball name, and other configuration options\n";
}
elsif ($getrules_md5 == 429) {
print
"\tA 429 error occurred, please wait for the 15 minute timeout\n\tto expire before trying again or specify the -n runtime switch\n",
"\tYou may also wish to verify your oinkcode, tarball name, and other configuration options\n";
}
elsif ($getrules_md5 == 404) {
print
"\tA 404 error occurred, please verify your filenames and urls for your tarball!\n";
}
open(FILE, "$temp_path$rule_file.md5")
or warn $!;
$md5 = <FILE>;
chomp($md5);
close(FILE);
$md5 =~ /\w{32}/
; ## Lets just grab the hash out of the string.. don't care about the rest!
$md5 = $&;
if ($Verbose && !$Quiet) {
print "\tmost recent rules file digest: $md5\n";
}
return $md5;
}
## This sub allows for ip-reputation list de-duplication and processing:
sub read_iplist {
my ($href, $path) = @_;
print "\t" if ($Verbose && !$Quiet);
print "Reading IP List...\n" if !$Quiet;
open(FH, '<', $path) || croak "Couldn't read $path - $!\n";
while (<FH>) {
chomp();
# we only want valid IP addresses, otherwise shiz melts!
next
unless $_
=~ /(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/;
$_ = trim($_);
$_ =~ s/,*//;
$href->{$_} = 1;
}
close(FH);
}
## This replaces the copy_rules routine and allows for in-memory processing
# of disablesid, enablesid, dropsid and other sid functions.. here we place
# all of the rules values into a hash as {$gid}{$sid}=$rule
sub read_rules {
my ($hashref, $path, $extra_rules) = @_;
my ($file, $sid, $gid, @elements);
print "\t" if ($Verbose && !$Quiet);
print "Reading rules...\n" if !$Quiet;
my $reading_old_rules = $path eq ($rule_file_path || '');
my @local_rules = split(/,/, $extra_rules);
foreach (@local_rules)
{ #First let's read our local rules and assign a gid of 0
$extra_rules = slash(0, $_);
$file = basename($extra_rules);
if ($extra_rules && -f $extra_rules) {
open(DATA, "$extra_rules")
|| croak "Couldn't read $extra_rules - $!\n";
my @extra_raw = <DATA>;
close(DATA);
my $trk = 0;
my $record;
foreach my $row (@extra_raw) {
$row = trim($row);
chomp($row);
if ($row =~ /^\s*#*\s*(alert|drop|pass)/i || $trk == 1) {
if (($row !~ /^#/) && ($row ne "")) {
if ($row =~ /\\$/) { # handle multiline rules here
$row =~ s/\\$//;
$record .= $row;
$trk = 1;
}
elsif ($row !~ /\\$/ && $trk == 1)
{ # last line of multiline rule here
$record .= $row;
if ($record =~ /\ssid:\s*\d+\s*;/i) {
$sid = $&;
$sid =~ s/\ssid:\s*//;
$sid =~ s/\s*;//;
$$hashref{0}{ trim($sid) }{'rule'} = $record;
}
$trk = 0;
undef $record;
}
else {
if ($row =~ /\ssid:\s*\d+\s*;/i) {
$sid = $&;
$sid =~ s/\ssid:\s*//;
$sid =~ s/\s*;//;
$$hashref{0}{ trim($sid) }{'rule'} = $row;
}
$trk = 0;
}
if ($trk == 0) {
$sid = trim($sid);
my $rule = $$hashref{0}{$sid}{'rule'};
if ($rule =~ /^\s*\#+/) {
$$hashref{0}{$sid}{'state'} = 0;
}
elsif ($rule =~ /^\s*(alert|pass|drop)/) {
$$hashref{0}{$sid}{'state'} = 1;
}
$file =~ s/\.rules//;
$$hashref{0}{$sid}{'category'} = $file;
$categories->{$file}{0}{$sid} = 1;
}
}
}
}
undef @extra_raw;
}
}
if (-d $path) {
opendir(DIR, "$path");
while (defined($file = readdir DIR)) {
my $fullpath = $path.$file;
if (grep /^$fullpath$/, @local_rules) {
next;
}
else {
open(DATA, "$fullpath");
@elements = <DATA>;
close(DATA);
}
foreach my $rule (@elements) {
chomp($rule);
$rule = trim($rule);
if ($rule =~ /^\s*#*\s*(alert|drop|pass)/i) {
if ($rule =~ /\ssid:\s*\d+\s*;/i) {
$sid = $&;
$sid =~ s/\ssid:\s*//;
$sid =~ s/\s*;//;
if ($rule =~ /\sgid:\s*\d+/i) {
$gid = $&;
$gid =~ s/\sgid:\s*//;
}
else { $gid = 1; }
if ($rule =~ /flowbits:\s*((un)?set(x)?|toggle)/i) {
# There is a much cleaner way to do this, I just don't have the time to do it right now!
my ($header, $options)
= split(/^[^"]* \(/, $rule);
my @optarray = split(/(?<!\\);(\t|\s)*/, $options)
if $options;
foreach my $option (reverse(@optarray)) {
my ($kw, $arg) = split(/:/, $option)
if $option;
next
unless ($kw && $arg && $kw eq "flowbits");
my ($flowact, $flowbit) = split(/,/, $arg);
next
unless $flowact
=~ /^\s*((un)?set(x)?|toggle)/i;
$$hashref{ trim($gid) }{ trim($sid) }
{ trim($flowbit) } = 1;
}
}
if ($rule =~ /^\s*\#+/) {
$$hashref{ trim($gid) }{ trim($sid) }{'state'}
= 0;
}
elsif ($rule =~ /^\s*(alert|pass|drop)/) {
$$hashref{ trim($gid) }{ trim($sid) }{'state'}
= 1;
}
$file =~ s/\.rules//;
$file = "VRT-SO-$file"
if ($gid == 3 && $file !~ /VRT-SO/);
$$hashref{ trim($gid) }{ trim($sid) }{'rule'} = $rule;
$$hashref{ trim($gid) }{ trim($sid) }{'category'}
= $file;
next if $reading_old_rules;
$categories->{$file}{ trim($gid) }{ trim($sid) } = 1;
}
}
}
}
close(DIR);
}
elsif (-f $path) {
open(DATA, "$path") || croak "Couldn't read $path - $!";
@elements = <DATA>;
close(DATA);
foreach my $rule (@elements) {
if ($rule =~ /^\s*#*\s*(alert|drop|pass)/i) {
if ($rule =~ /\ssid:\s*\d+/) {
$sid = $&;
$sid =~ s/\ssid:\s*//;
if ($rule =~ /\sgid:\s*\d+/i) {
$gid = $&;
$gid =~ s/\sgid:\s*//;
}
else { $gid = 1; }
if ($rule =~ /flowbits:\s*((un)?set(x)?|toggle)/) {
my ($header, $options) = split(/^[^"]* \(/, $rule);
# There is a much cleaner way to do this, I just don't have the time to do it right now!
my @optarray = split(/(?<!\\);(\t|\s)*/, $options)
if $options;
foreach my $option (reverse(@optarray)) {
my ($kw, $arg) = split(/:/, $option) if $option;
next unless ($kw && $arg && $kw eq "flowbits");
my ($flowact, $flowbit) = split(/,/, $arg);
next
unless $flowact
=~ /^\s*((un)?set(x)?|toggle)/i;
$$hashref{ trim($gid) }{ trim($sid) }
{ trim($flowbit) } = 1;
}
}
$$hashref{ trim($gid) }{ trim($sid) }{'rule'} = $rule;
}
}
}
}
undef @elements;
}
## sub to generate stub files using the snort --dump-dynamic-rules option
sub gen_stubs {
my ($Snort_path, $Snort_config, $Sostubs, $Snortv3, $Sorules) = @_;
print "Generating Stub Rules....\n" if !$Quiet;
unless (-B $Snort_path) {
Help("$Snort_path is not a valid binary file");
}
if (-d $Sostubs && -B $Snort_path && -f $Snort_config) {
my $cmd = "";
if ($Snortv3) {
$cmd = "$Snort_path -c $Snort_config --plugin-path $Sorules --dump-dynamic-rules > $Sostubs/allso.rules";
}
else {
$cmd = "$Snort_path -c $Snort_config --dump-dynamic-rules=$Sostubs"
}
if ($Verbose && !$Quiet) {
print(
"\tGenerating shared object stubs via: $cmd\n"
);
}
if (!$Snortv3) {
open(FH, "$cmd 2>&1|");
} else {
open(FH, "|-", "$cmd");
}
while (<FH>) {
print "\t$_" if $_ =~ /Dumping/i && ($Verbose && !$Quiet);
next unless $_ =~ /(err|warn|fail)/i;
syslogit('warning|local0', "FATAL: An error occured: $_")
if $Syslogging;
print "\tAn error occurred: $_\n";
# Yes, this is lame error reporting to stdout ...
}
close(FH);
}
else {
print(
"Something failed in the gen_stubs sub, please verify your shared object config!\n"
);
if ($Verbose && !$Quiet) {
unless (-d $Sostubs) {
Help(
"The path that you specified: $Sostubs does not exist! Please verify your configuration.\n"
);
}
unless (-f $Snort_path) {
Help(
"The file that you specified: $Snort_path does not exist! Please verify your configuration.\n"
);
}
unless (-f $Snort_config) {
Help(
"The file that you specified: $Snort_config does not exist! Please verify your configuration.\n"
);
}
}
}
print "\tDone\n" if !$Quiet;
}
sub vrt_policy {
my ($ids_policy, $rule) = @_;
my ($gid, $sid);
if ($rule =~ /policy\s$ids_policy/i && $rule !~ /flowbits\s*:\s*noalert/i)
{
$rule =~ s/^#*\s*//;
}
elsif ($rule !~ /^\s*#/) {
$rule = "# $rule";
}
return $rule;
}
sub policy_set {
my ($ids_policy, $hashref) = @_;
if ($hashref) {
if ($ids_policy ne "Disabled" && $ids_policy ne "") {
print "Activating $ids_policy rulesets....\n" if !$Quiet;
foreach my $k (sort keys %$hashref) {
foreach my $k2 (keys %{ $$hashref{$k} }) {
$$hashref{$k}{$k2}{'rule'}
= vrt_policy($ids_policy, $$hashref{$k}{$k2}{'rule'});
}
}
print "\tDone\n" if !$Quiet;
}
}
}
## this allows the user to use regular expressions to modify rule contents
sub modify_sid {
my ($href, $file) = @_;
my @arry;
print "Modifying Sids....\n" if !$Quiet;
open(FH, "<$file") || carp "Unable to open $file\n";
while (<FH>) {
next if (($_ =~ /^\s*#/) || ($_ eq " "));
if ($_ =~ /([(\d+)?\d+|,|\*]*)\s+"(.+)"\s+"(.*)"/) {
my ($ruleids, $from, $to) = ($1, $2, $3);
@arry = split(/,/, $ruleids) if $ruleids !~ /\*/;
@arry = "*" if $ruleids =~ /\*/;
foreach my $ruleid (@arry) {
$ruleid = trim($ruleid);
my @rule_comp;
@rule_comp = split(/-/, $ruleid, 2);
my $sid = pop @rule_comp;
my $gid = pop @rule_comp;
if (not defined $gid) {
$gid = 1;
}
if ($sid ne "*" && safe_defined($href, $gid, $sid, 'rule')) {
print "\tModifying GID:$gid,SID:$sid from:$from to:$to\n"
if ($Verbose && !$Quiet);
$$href{$gid}{$sid}{'rule'} =~ s/$from/$to/;
}
elsif ($sid eq "*") {
print
"\tModifying ALL SIDS for GID:$gid from:$from to:$to\n"
if ($Verbose && !$Quiet);
foreach my $k (sort keys %{ $$href{$gid} }) {
$$href{$gid}{$k}{'rule'} =~ s/$from/$to/;
}
}
}
undef @arry;
}
# Handle use case where we want to modify multiple sids based on
# comment in rule (think multiple rules with same or similar comment)
if ($_ =~ /^regex:'([^']+)'\s+"(.+)"\s+"(.*)"/) {
my ($regex, $from, $to) = ($1, $2, $3);
# Go through each rule in gid:1 and look for matching rules
foreach my $sid (sort keys(%{ $$href{1} })) {
next unless ($$href{1}{$sid}{'rule'} =~ /$regex/);
print "\tModifying SID:$sid from:$from to:$to\n"
if ($Verbose && !$Quiet);
$$href{1}{$sid}{'rule'} =~ s/$from/$to/;
}
}
}
print "\tDone!\n" if !$Quiet;
close(FH);
}
## this relaces the enablesid, disablesid and dropsid functions..
# speed ftw!
sub modify_state {
my ($function, $SID_conf, $hashref, $rstate) = @_;
my (@sid_mod, $sidlist);
print "Processing $SID_conf....\n" if !$Quiet;
print "\tSetting rules specified in $SID_conf to their default state!\n"
if (!$Quiet && $function eq 'enable' && $rstate);
if (-f $SID_conf) {
open(DATA, "$SID_conf") or carp "unable to open $SID_conf $!";
while (<DATA>) {
next unless ($_ !~ /^\s*#/ && $_ ne "");
$sidlist = (split '#', $_)[0];
chomp($sidlist);
$sidlist = trim($sidlist);
if (!@sid_mod) {
@sid_mod = split(/,/, $sidlist);
}
elsif (@sid_mod) {
push(@sid_mod, split(/,/, $sidlist));
}
}
close(DATA);
if ($hashref) {
my $sidcount = 0;
my $skipcount = 0;
foreach (@sid_mod) {
# ranges
if ($_ =~ /^(\d+):\d+-\1:\d+/) {