]> git.ipfire.org Git - people/pmueller/ipfire-2.x.git/blob - config/cfgroot/ids-functions.pl
ids-functions.pl: Drop oinkmaster related functions and declarations.
[people/pmueller/ipfire-2.x.git] / config / cfgroot / ids-functions.pl
1 #!/usr/bin/perl -w
2 ############################################################################
3 # #
4 # This file is part of the IPFire Firewall. #
5 # #
6 # IPFire is free software; you can redistribute it and/or modify #
7 # it under the terms of the GNU General Public License as published by #
8 # the Free Software Foundation; either version 2 of the License, or #
9 # (at your option) any later version. #
10 # #
11 # IPFire is distributed in the hope that it will be useful, #
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of #
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
14 # GNU General Public License for more details. #
15 # #
16 # You should have received a copy of the GNU General Public License #
17 # along with IPFire; if not, write to the Free Software #
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #
19 # #
20 # Copyright (C) 2018-2019 IPFire Team <info@ipfire.org> #
21 # #
22 ############################################################################
23
24 use strict;
25
26 package IDS;
27
28 require '/var/ipfire/general-functions.pl';
29 require "${General::swroot}/network-functions.pl";
30 require "${General::swroot}/suricata/ruleset-sources";
31
32 # Load perl module to deal with Archives.
33 use Archive::Tar;
34
35 # Load perl module to deal with files and path.
36 use File::Basename;
37
38 # Load module to move files.
39 use File::Copy;
40
41 # Load module to recursely remove files and a folder.
42 use File::Path qw(rmtree);
43
44 # Load module to get file stats.
45 use File::stat;
46
47 # Load module to deal with temporary files.
48 use File::Temp;
49
50 # Load module to deal with the date formats used by the HTTP protocol.
51 use HTTP::Date;
52
53 # Load the libwwwperl User Agent module.
54 use LWP::UserAgent;
55
56 # Load function from posix module to format time strings.
57 use POSIX qw (strftime);
58
59 # Load module to talk to the kernel log daemon.
60 use Sys::Syslog qw(:DEFAULT setlogsock);
61
62 # Location where all config and settings files are stored.
63 our $settingsdir = "${General::swroot}/suricata";
64
65 # File where the main file for providers ruleset inclusion exists.
66 our $suricata_used_providers_file = "$settingsdir/suricata-used-providers.yaml";
67
68 # File for static ruleset inclusions.
69 our $suricata_default_rulefiles_file = "$settingsdir/suricata-default-rules.yaml";
70
71 # File where the addresses of the homenet are stored.
72 our $homenet_file = "$settingsdir/suricata-homenet.yaml";
73
74 # File where the addresses of the used DNS servers are stored.
75 our $dns_servers_file = "$settingsdir/suricata-dns-servers.yaml";
76
77 # File where the HTTP ports definition is stored.
78 our $http_ports_file = "$settingsdir/suricata-http-ports.yaml";
79
80 # File which stores the configured IPS settings.
81 our $ids_settings_file = "$settingsdir/settings";
82
83 # File which stores the used and configured ruleset providers.
84 our $providers_settings_file = "$settingsdir/providers-settings";
85
86 # File which stores the configured settings for whitelisted addresses.
87 our $ignored_file = "$settingsdir/ignored";
88
89 # Location where the downloaded rulesets are stored.
90 our $dl_rules_path = "/var/tmp";
91
92 # File to store any errors, which also will be read and displayed by the wui.
93 our $storederrorfile = "/tmp/ids_storederror";
94
95 # File to lock the WUI, while the autoupdate script runs.
96 our $ids_page_lock_file = "/tmp/ids_page_locked";
97
98 # Location where the rulefiles are stored.
99 our $rulespath = "/var/lib/suricata";
100
101 # Location where the default rulefils are stored.
102 our $default_rulespath = "/usr/share/suricata/rules";
103
104 # Location where the addition config files are stored.
105 our $configspath = "/usr/share/suricata";
106
107 # Location of the classification file.
108 our $classification_file = "$configspath/classification.config";
109
110 # Location of the sid to msg mappings file.
111 our $sid_msg_file = "$rulespath/sid-msg.map";
112
113 # Location to store local rules. This file will not be touched.
114 our $local_rules_file = "$rulespath/local.rules";
115
116 # File which contains the rules to whitelist addresses on suricata.
117 our $whitelist_file = "$rulespath/whitelist.rules";
118
119 # File which contains a list of all supported ruleset sources.
120 # (Sourcefire, Emergingthreads, etc..)
121 our $rulesetsourcesfile = "$settingsdir/ruleset-sources";
122
123 # The pidfile of the IDS.
124 our $idspidfile = "/var/run/suricata.pid";
125
126 # Location of suricatactrl.
127 my $suricatactrl = "/usr/local/bin/suricatactrl";
128
129 # Prefix for each downloaded ruleset.
130 my $dl_rulesfile_prefix = "idsrules";
131
132 # Temporary directory where the rulesets will be extracted.
133 my $tmp_directory = "/tmp/ids_tmp";
134
135 # Temporary directory where the extracted rules files will be stored.
136 my $tmp_rules_directory = "$tmp_directory/rules";
137
138 # Temporary directory where the extracted additional config files will be stored.
139 my $tmp_conf_directory = "$tmp_directory/conf";
140
141 # Array with allowed commands of suricatactrl.
142 my @suricatactrl_cmds = ( 'start', 'stop', 'restart', 'reload', 'fix-rules-dir', 'cron' );
143
144 # Array with supported cron intervals.
145 my @cron_intervals = ('off', 'daily', 'weekly' );
146
147 # Array which contains the HTTP ports, which statically will be declared as HTTP_PORTS in the
148 # http_ports_file.
149 my @http_ports = ('80', '81');
150
151 # Array which contains a list of rulefiles which always will be included if they exist.
152 my @static_included_rulefiles = ('local.rules', 'whitelist.rules');
153
154 # Array which contains a list of allways enabled application layer protocols.
155 my @static_enabled_app_layer_protos = ('app-layer', 'decoder', 'files', 'stream');
156
157 # Hash which allows to convert the download type (dl_type) to a file suffix.
158 my %dl_type_to_suffix = (
159 "archive" => ".tar.gz",
160 "plain" => ".rules",
161 );
162
163 # Hash to translate an application layer protocol to the application name.
164 my %tr_app_layer_proto = (
165 "ikev2" => "ipsec",
166 "krb5" => "kerberos",
167 );
168
169 #
170 ## Function to check and create all IDS related files, if the does not exist.
171 #
172 sub check_and_create_filelayout() {
173 # Check if the files exist and if not, create them.
174 unless (-f "$suricata_used_providers_file") { &create_empty_file($suricata_used_providers_file); }
175 unless (-f "$suricata_default_rulefiles_file") { &create_empty_file($suricata_default_rulefiles_file); }
176 unless (-f "$ids_settings_file") { &create_empty_file($ids_settings_file); }
177 unless (-f "$providers_settings_file") { &create_empty_file($providers_settings_file); }
178 unless (-f "$whitelist_file" ) { &create_empty_file($whitelist_file); }
179 }
180
181 #
182 ## Function to get a list of all available ruleset providers.
183 ##
184 ## They will be returned as a sorted array.
185 #
186 sub get_ruleset_providers() {
187 my @providers;
188
189 # Loop through the hash of providers.
190 foreach my $provider ( keys %IDS::Ruleset::Providers ) {
191 # Add the provider to the array.
192 push(@providers, $provider);
193 }
194
195 # Sort and return the array.
196 return sort(@providers);
197 }
198
199 #
200 ## Function to get a list of all enabled ruleset providers.
201 ##
202 ## They will be returned as an array.
203 #
204 sub get_enabled_providers () {
205 my %used_providers = ();
206
207 # Array to store the enabled providers.
208 my @enabled_providers = ();
209
210 # Read-in the providers config file.
211 &General::readhasharray("$providers_settings_file", \%used_providers);
212
213 # Loop through the hash of used_providers.
214 foreach my $id (keys %used_providers) {
215 # Skip disabled providers.
216 next unless ($used_providers{$id}[3] eq "enabled");
217
218 # Grab the provider handle.
219 my $provider = "$used_providers{$id}[0]";
220
221 # Add the provider to the array of enabled providers.
222 push(@enabled_providers, $provider);
223 }
224
225 # Return the array.
226 return @enabled_providers;
227 }
228
229 #
230 ## Function to get a hash of provider handles and their configured modes (IDS/IPS).
231 #
232 sub get_providers_mode () {
233 my %used_providers = ();
234
235 # Hash to store the providers and their configured modes.
236 my %providers_mode = ();
237
238 # Read-in the providers config file.
239 &General::readhasharray("$providers_settings_file", \%used_providers);
240
241 # Loop through the hash of used_providers.
242 foreach my $id (keys %used_providers) {
243 # Skip disabled providers.
244 next unless ($used_providers{$id}[3] eq "enabled");
245
246 # Grab the provider handle.
247 my $provider = "$used_providers{$id}[0]";
248
249 # Grab the provider mode.
250 my $mode = "$used_providers{$id}[4]";
251
252 # Fall back to IDS if no mode could be obtained.
253 unless($mode) {
254 $mode = "IDS";
255 }
256
257 # Add details to provider_modes hash.
258 $providers_mode{$provider} = $mode;
259 }
260
261 # Return the hash.
262 return %providers_mode;
263 }
264
265 #
266 ## Function for checking if at least 300MB of free disk space are available
267 ## on the "/var" partition.
268 #
269 sub checkdiskspace () {
270 # Call diskfree to gather the free disk space of /var.
271 my @df = &General::system_output("/bin/df", "-B", "M", "/var");
272
273 # Loop through the output.
274 foreach my $line (@df) {
275 # Ignore header line.
276 next if $line =~ m/^Filesystem/;
277
278 # Search for a line with the device information.
279 if ($line =~ m/dev/ ) {
280 # Split the line into single pieces.
281 my @values = split(' ', $line);
282 my ($filesystem, $blocks, $used, $available, $used_perenctage, $mounted_on) = @values;
283
284 # Check if the available disk space is more than 300MB.
285 if ($available < 300) {
286 # Exit function and return the available disk space.
287 return $available;
288 }
289 }
290 }
291
292 # Everything okay, return nothing.
293 return;
294 }
295
296 #
297 ## This function is responsible for downloading the ruleset for a given provider.
298 ##
299 ## * At first it initialize the downloader and sets an upstream proxy if configured.
300 ## * The next step will be to generate the final download url, by obtaining the URL for the desired
301 ## ruleset and add the settings for the upstream proxy.
302 ## * Finally the function will grab the rule file or tarball from the server.
303 ## It tries to reduce the amount of download by using the "If-Modified-Since" HTTP header.
304 #
305 ## Return codes:
306 ##
307 ## * "no url" - If no download URL could be gathered for the provider.
308 ## * "not modified" - In case the already stored rules file is up to date.
309 ## * "incomplete download" - When the remote file size differs from the downloaded file size.
310 ## * "$error" - The error message generated from the LWP::User Agent module.
311 #
312 sub downloadruleset ($) {
313 my ($provider) = @_;
314
315 # The amount of download attempts before giving up and
316 # logging an error.
317 my $max_dl_attempts = 3;
318
319 # Read proxysettings.
320 my %proxysettings=();
321 &General::readhash("${General::swroot}/proxy/settings", \%proxysettings);
322
323 # Init the download module.
324 #
325 # Request SSL hostname verification and specify path
326 # to the CA file.
327 my $downloader = LWP::UserAgent->new(
328 ssl_opts => {
329 SSL_ca_file => '/etc/ssl/cert.pem',
330 verify_hostname => 1,
331 }
332 );
333
334 # Set timeout to 10 seconds.
335 $downloader->timeout(10);
336
337 # Check if an upstream proxy is configured.
338 if ($proxysettings{'UPSTREAM_PROXY'}) {
339 my $proxy_url;
340
341 $proxy_url = "http://";
342
343 # Check if the proxy requires authentication.
344 if (($proxysettings{'UPSTREAM_USER'}) && ($proxysettings{'UPSTREAM_PASSWORD'})) {
345 $proxy_url .= "$proxysettings{'UPSTREAM_USER'}\:$proxysettings{'UPSTREAM_PASSWORD'}\@";
346 }
347
348 # Add proxy server address and port.
349 $proxy_url .= $proxysettings{'UPSTREAM_PROXY'};
350
351 # Setup proxy settings.
352 $downloader->proxy(['http', 'https'], $proxy_url);
353 }
354
355 # Grab the download url for the provider.
356 my $url = $IDS::Ruleset::Providers{$provider}{'dl_url'};
357
358 # Check if the provider requires a subscription.
359 if ($IDS::Ruleset::Providers{$provider}{'requires_subscription'} eq "True") {
360 # Grab the subscription code.
361 my $subscription_code = &get_subscription_code($provider);
362
363 # Add the subscription code to the download url.
364 $url =~ s/\<subscription_code\>/$subscription_code/g;
365
366 }
367
368 # Abort and return "no url", if no url could be determined for the provider.
369 return "no url" unless ($url);
370
371 # Pass the requested URL to the downloader.
372 my $request = HTTP::Request->new(GET => $url);
373
374 # Generate temporary file name, located in "/var/tmp" and with a suffix of ".tmp".
375 # The downloaded file will be stored there until some sanity checks are performed.
376 my $tmp = File::Temp->new( SUFFIX => ".tmp", DIR => "/var/tmp/", UNLINK => 0 );
377 my $tmpfile = $tmp->filename();
378
379 # Call function to get the final path and filename for the downloaded file.
380 my $dl_rulesfile = &_get_dl_rulesfile($provider);
381
382 # Check if the rulesfile already exits, because it has been downloaded in the past.
383 #
384 # In this case we are requesting the server if the remote file has been changed or not.
385 # This will be done by sending the modification time in a special HTTP header.
386 if (-f $dl_rulesfile) {
387 # Call stat on the file.
388 my $stat = stat($dl_rulesfile);
389
390 # Omit the mtime of the existing file.
391 my $mtime = $stat->mtime;
392
393 # Convert the timestamp into right format.
394 my $http_date = time2str($mtime);
395
396 # Add the If-Modified-Since header to the request to ask the server if the
397 # file has been modified.
398 $request->header( 'If-Modified-Since' => "$http_date" );
399 }
400
401 my $dl_attempt = 1;
402 my $response;
403
404 # Download and retry on failure.
405 while ($dl_attempt <= $max_dl_attempts) {
406 # Perform the request and save the output into the tmpfile.
407 $response = $downloader->request($request, $tmpfile);
408
409 # Check if the download was successfull.
410 if($response->is_success) {
411 # Break loop.
412 last;
413
414 # Check if the server responds with 304 (Not Modified).
415 } elsif ($response->code == 304) {
416 # Return "not modified".
417 return "not modified";
418
419 # Check if we ran out of download re-tries.
420 } elsif ($dl_attempt eq $max_dl_attempts) {
421 # Obtain error.
422 my $error = $response->content;
423
424 # Return the error message from response..
425 return "$error";
426 }
427
428 # Remove temporary file, if one exists.
429 unlink("$tmpfile") if (-e "$tmpfile");
430
431 # Increase download attempt counter.
432 $dl_attempt++;
433 }
434
435 # Obtain the connection headers.
436 my $headers = $response->headers;
437
438 # Get the timestamp from header, when the file has been modified the
439 # last time.
440 my $last_modified = $headers->last_modified;
441
442 # Get the remote size of the downloaded file.
443 my $remote_filesize = $headers->content_length;
444
445 # Perform stat on the tmpfile.
446 my $stat = stat($tmpfile);
447
448 # Grab the local filesize of the downloaded tarball.
449 my $local_filesize = $stat->size;
450
451 # Check if both file sizes match.
452 if (($remote_filesize) && ($remote_filesize ne $local_filesize)) {
453 # Delete temporary file.
454 unlink("$tmpfile");
455
456 # Return "1" - false.
457 return "incomplete download";
458 }
459
460 # Overwrite the may existing rulefile or tarball with the downloaded one.
461 move("$tmpfile", "$dl_rulesfile");
462
463 # Check if we got a last-modified value from the server.
464 if ($last_modified) {
465 # Assign the last-modified timestamp as mtime to the
466 # rules file.
467 utime(time(), "$last_modified", "$dl_rulesfile");
468 }
469
470 # Delete temporary file.
471 unlink("$tmpfile");
472
473 # Set correct ownership for the tarball.
474 set_ownership("$dl_rulesfile");
475
476 # If we got here, everything worked fine. Return nothing.
477 return;
478 }
479
480 #
481 ## Function to extract a given ruleset.
482 ##
483 ## In case the ruleset provider offers a plain file, it simply will
484 ## be copied.
485 #
486 sub extractruleset ($) {
487 my ($provider) = @_;
488
489 # Disable chown functionality when uncompressing files.
490 $Archive::Tar::CHOWN = "0";
491
492 # Get full path and downloaded rulesfile for the given provider.
493 my $tarball = &_get_dl_rulesfile($provider);
494
495 # Check if the file exists.
496 unless (-f $tarball) {
497 &_log_to_syslog("Could not find ruleset file: $tarball");
498
499 # Return nothing.
500 return;
501 }
502
503 # Check if the temporary directories exist, otherwise create them.
504 mkdir("$tmp_directory") unless (-d "$tmp_directory");
505 mkdir("$tmp_rules_directory") unless (-d "$tmp_rules_directory");
506 mkdir("$tmp_conf_directory") unless (-d "$tmp_conf_directory");
507
508 # Omit the type (dl_type) of the stored ruleset.
509 my $type = $IDS::Ruleset::Providers{$provider}{'dl_type'};
510
511 # Handle the different ruleset types.
512 if ($type eq "plain") {
513 # Generate destination filename an full path.
514 my $destination = "$tmp_rules_directory/$provider\-ruleset.rules";
515
516 # Copy the file into the temporary rules directory.
517 copy($tarball, $destination);
518
519 } elsif ( $type eq "archive") {
520 # Initialize the tar module.
521 my $tar = Archive::Tar->new($tarball);
522
523 # Get the filelist inside the tarball.
524 my @packed_files = $tar->list_files;
525
526 # Loop through the filelist.
527 foreach my $packed_file (@packed_files) {
528 my $destination;
529
530 # Splitt the packed file into chunks.
531 my $file = fileparse($packed_file);
532
533 # Handle msg-id.map file.
534 if ("$file" eq "sid-msg.map") {
535 # Set extract destination to temporary config_dir.
536 $destination = "$tmp_conf_directory/$provider\-sid-msg.map";
537
538 # Handle classification.conf
539 } elsif ("$file" eq "classification.config") {
540 # Set extract destination to temporary config_dir.
541 $destination = "$tmp_conf_directory/$provider\-classification.config";
542
543 # Handle rules files.
544 } elsif ($file =~ m/\.rules$/) {
545 # Skip rule files which are not located in the rules directory or archive root.
546 next unless(($packed_file =~ /^rules\//) || ($packed_file !~ /\//));
547
548 # Skip deleted.rules.
549 #
550 # Mostly they have been taken out for correctness or performance reasons and therfore
551 # it is not a great idea to enable any of them.
552 next if($file =~ m/deleted.rules$/);
553
554 my $rulesfilename;
555
556 # Splitt the filename into chunks.
557 my @filename = split("-", $file);
558
559 # Reverse the array.
560 @filename = reverse(@filename);
561
562 # Get the amount of elements in the array.
563 my $elements = @filename;
564
565 # Remove last element of the hash.
566 # It contains the vendor name, which will be replaced.
567 if ($elements >= 3) {
568 # Remove last element from hash.
569 pop(@filename);
570 }
571
572 # Check if the last element of the filename does not
573 # contain the providers name.
574 if ($filename[-1] ne "$provider") {
575 # Add provider name as last element.
576 push(@filename, $provider);
577 }
578
579 # Reverse the array back.
580 @filename = reverse(@filename);
581
582 # Generate the name for the rulesfile.
583 $rulesfilename = join("-", @filename);
584
585 # Set extract destination to temporaray rules_dir.
586 $destination = "$tmp_rules_directory/$rulesfilename";
587 } else {
588 # Skip all other files.
589 next;
590 }
591
592 # Check if the destination file exists.
593 unless(-e "$destination") {
594 # Extract the file to the temporary directory.
595 $tar->extract_file("$packed_file", "$destination");
596 } else {
597 # Generate temporary file name, located in the temporary rules directory and a suffix of ".tmp".
598 my $tmp = File::Temp->new( SUFFIX => ".tmp", DIR => "$tmp_rules_directory", UNLINK => 0 );
599 my $tmpfile = $tmp->filename();
600
601 # Extract the file to the new temporary file name.
602 $tar->extract_file("$packed_file", "$tmpfile");
603
604 # Open the the existing file.
605 open(DESTFILE, ">>", "$destination") or die "Could not open $destination. $!\n";
606 open(TMPFILE, "<", "$tmpfile") or die "Could not open $tmpfile. $!\n";
607
608 # Loop through the content of the temporary file.
609 while (<TMPFILE>) {
610 # Append the content line by line to the destination file.
611 print DESTFILE "$_";
612 }
613
614 # Close the file handles.
615 close(TMPFILE);
616 close(DESTFILE);
617
618 # Remove the temporary file.
619 unlink("$tmpfile");
620 }
621 }
622 }
623 }
624
625 #
626 ## A wrapper function to call the oinkmaster script, setup the rules structues and
627 ## call the functions to merge the additional config files. (classification, sid-msg, etc.).
628 #
629 sub oinkmaster () {
630 # Check if the files in rulesdir have the correct permissions.
631 &_check_rulesdir_permissions();
632
633 # Cleanup the rules directory before filling it with the new rulests.
634 &_cleanup_rulesdir();
635
636 # Get all enabled providers.
637 my @enabled_providers = &get_enabled_providers();
638
639 # Loop through the array of enabled providers.
640 foreach my $provider (@enabled_providers) {
641 # Call the extractruleset function.
642 &extractruleset($provider);
643 }
644
645 # Call function to process the ruleset and do all modifications.
646 &process_ruleset(@enabled_providers);
647
648 # Call function to merge the classification files.
649 &merge_classifications(@enabled_providers);
650
651 # Call function to merge the sid to message mapping files.
652 &merge_sid_msg(@enabled_providers);
653
654 # Cleanup temporary directory.
655 &cleanup_tmp_directory();
656 }
657
658 #
659 ## Function to alter the ruleset.
660 #
661 sub process_ruleset(@) {
662 my (@providers) = @_;
663
664 # Hash to store the configured provider modes.
665 my %providers_mode = &get_providers_mode();
666
667 # Array to store the extracted rulefile from the temporary rules directory.
668 my @extracted_rulefiles;
669
670 # Get names of the extracted raw rulefiles.
671 opendir(DIR, $tmp_rules_directory) or die "Could not read from $tmp_rules_directory. $!\n";
672 while (my $file = readdir(DIR)) {
673 # Ignore single and double dotted files.
674 next if $file =~ /^\.\.?$/;
675
676 # Add file to the array of extracted files.
677 push(@extracted_rulefiles, $file);
678 }
679
680 # Close directory handle.
681 closedir(DIR);
682
683 # Loop through the array of providers.
684 foreach my $provider (@providers) {
685 # Hash to store the obtained SIDs and REV of each provider.
686 my %rules = ();
687
688 # Hash which holds modifications to apply to the rules.
689 my %modifications = ();
690
691 # Loop through the array of extraced rulefiles.
692 foreach my $file (@extracted_rulefiles) {
693 # Skip file if it does not belong to the current processed provider.
694 next unless ($file =~ m/^$provider/);
695
696 # Open the rulefile.
697 open(FILE, "$tmp_rules_directory/$file") or die "Could not read $tmp_rules_directory/$file. $!\n";
698
699 # Loop through the file content.
700 while (my $line = <FILE>) {
701 # Skip blank lines.
702 next if ($line =~ /^\s*$/);
703
704 # Call function to get the sid and rev of the rule.
705 my ($sid, $rev) = &_get_sid_and_rev($line);
706
707 # Skip rule if a sid with a higher rev already has added to the rules hash.
708 next if ($rev le $rules{$sid});
709
710 # Add the new or rule with higher rev to the hash of rules.
711 $rules{$sid} = $rev;
712 }
713
714 # Close file handle.
715 close(FILE);
716 }
717
718 # Get filename which contains the ruleset modifications for this provider.
719 my $modification_file = &get_provider_ruleset_modifications_file($provider);
720
721 # Read file which holds the modifications of the ruleset for the current provider.
722 &General::readhash($modification_file, \%modifications) if (-f $modification_file);
723
724 # Loop again through the array of extracted rulesfiles.
725 foreach my $file (@extracted_rulefiles) {
726 # Skip the file if it does not belong to the current provider.
727 next unless ($file =~ m/^$provider/);
728
729 # Open the rulefile for writing.
730 open(RULEFILE, ">", "$rulespath/$file") or die "Could not write to file $rulespath/$file. $!\n";
731
732 # Open the rulefile for reading.
733 open(TMP_RULEFILE, "$tmp_rules_directory/$file") or die "Could not read $tmp_rules_directory/$file. $!\n";
734
735 # Loop through the raw temporary rulefile.
736 while (my $line = <TMP_RULEFILE>) {
737 # Get the sid and rev of the rule.
738 my ($sid, $rev) = &_get_sid_and_rev($line);
739
740 # Check if the current rule is obsoleted by a newer one.
741 #
742 # In this case the rev number in the rules hash is higher than the current one.
743 next if ($rev lt $rules{$sid});
744
745 # Check if the rule should be enabled or disabled.
746 if ($modifications{$sid} eq "enabled") {
747 # Drop the # at the start of the line.
748 $line =~ s/^\#//;
749 } elsif ($modifications{$sid} eq "disabled") {
750 # Add a # at the start of the line to disable the rule.
751 $line = "#$line" unless ($line =~ /^#/);
752 }
753
754 # Check if the Provider is set so IPS mode.
755 if ($providers_mode{$provider} eq "IPS") {
756 # Replacements for sourcefire rules.
757 $line =~ s/^#\s*(?:alert|drop)(.+policy balanced-ips alert)/alert${1}/;
758 $line =~ s/^#\s*(?:alert|drop)(.+policy balanced-ips drop)/drop${1}/;
759
760 # Replacements for generic rules.
761 $line =~ s/^(#?)\s*(?:alert|drop)/${1}drop/;
762 $line =~ s/^(#?)\s*drop(.+flowbits:noalert;)/${1}alert${2}/;
763 }
764
765 # Write line / rule to the target rule file.
766 print RULEFILE "$line";
767 }
768
769 # Close filehandles.
770 close(RULEFILE);
771 close(TMP_RULEFILE);
772 }
773 }
774 }
775
776 #
777 ## Function to merge the classifications for a given amount of providers and write them
778 ## to the classifications file.
779 #
780 sub merge_classifications(@) {
781 my @providers = @_;
782
783 # Hash to store all collected classifications.
784 my %classifications = ();
785
786 # Loop through the given array of providers.
787 foreach my $provider (@providers) {
788 # Generate full path to classification file.
789 my $classification_file = "$tmp_conf_directory/$provider\-classification.config";
790
791 # Skip provider if no classification file exists.
792 next unless (-f "$classification_file");
793
794 # Open the classification file.
795 open(CLASSIFICATION, $classification_file) or die "Could not open file $classification_file. $!\n";
796
797 # Loop through the file content.
798 while(<CLASSIFICATION>) {
799 # Parse the file and grab the classification details.
800 if ($_ =~/.*config classification\: (.*)/) {
801 # Split the grabbed details.
802 my ($short_name, $short_desc, $priority) = split("\,", $1);
803
804 # Check if the grabbed classification is allready known and the priority value is greater
805 # than the stored one (which causes less priority in the IDS).
806 if (($classifications{$short_name}) && ($classifications{$short_name}[1] >= $priority)) {
807 #Change the priority value to the stricter one.
808 $classifications{$short_name} = [ "$classifications{$short_name}[0]", "$priority" ];
809 } else {
810 # Add the classification to the hash.
811 $classifications{$short_name} = [ "$short_desc", "$priority" ];
812 }
813 }
814 }
815
816 # Close the file.
817 close(CLASSIFICATION);
818 }
819
820 # Open classification file for writing.
821 open(FILE, ">", "$classification_file") or die "Could not write to $classification_file. $!\n";
822
823 # Print notice about autogenerated file.
824 print FILE "#Autogenerated file. Any custom changes will be overwritten!\n\n";
825
826 # Sort and loop through the hash of classifications.
827 foreach my $key (sort keys %classifications) {
828 # Assign some nice variable names for the items.
829 my $short_name = $key;
830 my $short_desc = $classifications{$key}[0];
831 my $priority = $classifications{$key}[1];
832
833 # Write the classification to the file.
834 print FILE "config classification: $short_name,$short_desc,$priority\n";
835 }
836
837 # Close file handle.
838 close(FILE);
839 }
840
841 #
842 ## Function to merge the "sid to message mapping" files of various given providers.
843 #
844 sub merge_sid_msg (@) {
845 my @providers = @_;
846
847 # Hash which contains all the sid to message mappings.
848 my %mappings = ();
849
850 # Loop through the array of given providers.
851 foreach my $provider (@providers) {
852 # Generate full path and filename.
853 my $sid_msg_file = "$tmp_conf_directory/$provider\-sid-msg.map";
854
855 # Skip provider if no sid to msg mapping file for this provider exists.
856 next unless (-f $sid_msg_file);
857
858 # Open the file.
859 open(MAPPING, $sid_msg_file) or die "Could not open $sid_msg_file. $!\n";
860
861 # Loop through the file content.
862 while (<MAPPING>) {
863 # Remove newlines.
864 chomp($_);
865
866 # Skip lines which do not start with a number,
867 next unless ($_ =~ /^\d+/);
868
869 # Split line content and assign it to an array.
870 my @line = split(/ \|\| /, $_);
871
872 # Grab the first element (and remove it) from the line array.
873 # It contains the sid.
874 my $sid = shift(@line);
875
876 # Store the grabbed sid and the remain array as hash value.
877 # It still contains the messages, references etc.
878 $mappings{$sid} = [@line];
879 }
880
881 # Close file handle.
882 close(MAPPING);
883 }
884
885 # Open mappings file for writing.
886 open(FILE, ">", $sid_msg_file) or die "Could not write $sid_msg_file. $!\n";
887
888 # Write notice about autogenerated file.
889 print FILE "#Autogenerated file. Any custom changes will be overwritten!\n\n";
890
891 # Loop through the hash of mappings.
892 foreach my $sid ( sort keys %mappings) {
893 # Grab data for the sid.
894 my @data = @{$mappings{$sid}};
895
896 # Add the sid to the data array.
897 unshift(@data, $sid);
898
899 # Generate line.
900 my $line = join(" \|\| ", @data);
901
902 print FILE "$line\n";
903
904 }
905
906 # Close file handle.
907 close(FILE);
908 }
909
910 #
911 ## A very tiny function to move an extracted ruleset from the temporary directory into
912 ## the rules directory.
913 #
914 sub move_tmp_ruleset() {
915 # Do a directory listing of the temporary directory.
916 opendir DH, $tmp_rules_directory;
917
918 # Loop over all files.
919 while(my $file = readdir DH) {
920 # Move them to the rules directory.
921 move "$tmp_rules_directory/$file" , "$rulespath/$file";
922 }
923
924 # Close directory handle.
925 closedir DH;
926 }
927
928 #
929 ## Function to cleanup the temporary IDS directroy.
930 #
931 sub cleanup_tmp_directory () {
932
933 # Delete temporary directory and all containing files.
934 rmtree([ "$tmp_directory" ]);
935 }
936
937 #
938 ## Function to do all the logging stuff if the downloading or updating of the ruleset fails.
939 #
940 sub log_error ($) {
941 my ($error) = @_;
942
943 # Remove any newline.
944 chomp($error);
945
946 # Call private function to log the error message to syslog.
947 &_log_to_syslog($error);
948
949 # Call private function to write/store the error message in the storederrorfile.
950 &_store_error_message($error);
951 }
952
953 #
954 ## Function to log a given error message to the kernel syslog.
955 #
956 sub _log_to_syslog ($) {
957 my ($message) = @_;
958
959 # The syslog function works best with an array based input,
960 # so generate one before passing the message details to syslog.
961 my @syslog = ("ERR", "<ERROR> $message");
962
963 # Establish the connection to the syslog service.
964 openlog('oinkmaster', 'cons,pid', 'user');
965
966 # Send the log message.
967 syslog(@syslog);
968
969 # Close the log handle.
970 closelog();
971 }
972
973 #
974 ## Private function to write a given error message to the storederror file.
975 #
976 sub _store_error_message ($) {
977 my ($message) = @_;
978
979 # Remove any newline.
980 chomp($message);
981
982 # Open file for writing.
983 open (ERRORFILE, ">$storederrorfile") or die "Could not write to $storederrorfile. $!\n";
984
985 # Write error to file.
986 print ERRORFILE "$message\n";
987
988 # Close file.
989 close (ERRORFILE);
990
991 # Set correct ownership for the file.
992 &set_ownership("$storederrorfile");
993 }
994
995 #
996 ## Private function to get the path and filename for a downloaded ruleset by a given provider.
997 #
998 sub _get_dl_rulesfile($) {
999 my ($provider) = @_;
1000
1001 # Gather the download type for the given provider.
1002 my $dl_type = $IDS::Ruleset::Providers{$provider}{'dl_type'};
1003
1004 # Obtain the file suffix for the download file type.
1005 my $suffix = $dl_type_to_suffix{$dl_type};
1006
1007 # Check if a suffix has been found.
1008 unless ($suffix) {
1009 # Abort return - nothing.
1010 return;
1011 }
1012
1013 # Generate the full filename and path for the stored rules file.
1014 my $rulesfile = "$dl_rules_path/$dl_rulesfile_prefix-$provider$suffix";
1015
1016 # Return the generated filename.
1017 return $rulesfile;
1018 }
1019
1020 #
1021 ## Private function to obtain the sid and rev of a rule.
1022 #
1023 ## Returns an array with the sid as first and the rev as second value.
1024 #
1025 sub _get_sid_and_rev ($) {
1026 my ($line) = @_;
1027
1028 my @ret;
1029
1030 # Use regex to obtain the sid and rev.
1031 if ($line =~ m/.*sid:\s*(.*?);.*rev:\s*(.*?);/) {
1032 # Add the sid and rev to the array.
1033 push(@ret, $1);
1034 push(@ret, $2);
1035 }
1036
1037 # Return the array.
1038 return @ret;
1039 }
1040
1041 #
1042 ## Tiny function to delete the stored ruleset file or tarball for a given provider.
1043 #
1044 sub drop_dl_rulesfile ($) {
1045 my ($provider) = @_;
1046
1047 # Gather the full path and name of the stored rulesfile.
1048 my $rulesfile = &_get_dl_rulesfile($provider);
1049
1050 # Check if the given rulesfile exists.
1051 if (-f $rulesfile) {
1052 # Delete the stored rulesfile.
1053 unlink($rulesfile) or die "Could not delete $rulesfile. $!\n";
1054 }
1055 }
1056
1057 #
1058 ## Function to read-in the given enabled or disables sids file.
1059 #
1060 sub read_enabled_disabled_sids_file($) {
1061 my ($file) = @_;
1062
1063 # Temporary hash to store the sids and their state. It will be
1064 # returned at the end of this function.
1065 my %temphash;
1066
1067 # Open the given filename.
1068 open(FILE, "$file") or die "Could not open $file. $!\n";
1069
1070 # Loop through the file.
1071 while(<FILE>) {
1072 # Remove newlines.
1073 chomp $_;
1074
1075 # Skip blank lines.
1076 next if ($_ =~ /^\s*$/);
1077
1078 # Skip coments.
1079 next if ($_ =~ /^\#/);
1080
1081 # Splitt line into sid and state part.
1082 my ($state, $sid) = split(" ", $_);
1083
1084 # Skip line if the sid is not numeric.
1085 next unless ($sid =~ /\d+/ );
1086
1087 # Check if the sid was enabled.
1088 if ($state eq "enablesid") {
1089 # Add the sid and its state as enabled to the temporary hash.
1090 $temphash{$sid} = "enabled";
1091 # Check if the sid was disabled.
1092 } elsif ($state eq "disablesid") {
1093 # Add the sid and its state as disabled to the temporary hash.
1094 $temphash{$sid} = "disabled";
1095 # Invalid state - skip the current sid and state.
1096 } else {
1097 next;
1098 }
1099 }
1100
1101 # Close filehandle.
1102 close(FILE);
1103
1104 # Return the hash.
1105 return %temphash;
1106 }
1107
1108 #
1109 ## Function to check if the IDS is running.
1110 #
1111 sub ids_is_running () {
1112 if(-f $idspidfile) {
1113 # Open PID file for reading.
1114 open(PIDFILE, "$idspidfile") or die "Could not open $idspidfile. $!\n";
1115
1116 # Grab the process-id.
1117 my $pid = <PIDFILE>;
1118
1119 # Close filehandle.
1120 close(PIDFILE);
1121
1122 # Remove any newline.
1123 chomp($pid);
1124
1125 # Check if a directory for the process-id exists in proc.
1126 if(-d "/proc/$pid") {
1127 # The IDS daemon is running return the process id.
1128 return $pid;
1129 }
1130 }
1131
1132 # Return nothing - IDS is not running.
1133 return;
1134 }
1135
1136 #
1137 ## Function to call suricatactrl binary with a given command.
1138 #
1139 sub call_suricatactrl ($) {
1140 # Get called option.
1141 my ($option, $interval) = @_;
1142
1143 # Loop through the array of supported commands and check if
1144 # the given one is part of it.
1145 foreach my $cmd (@suricatactrl_cmds) {
1146 # Skip current command unless the given one has been found.
1147 next unless($cmd eq $option);
1148
1149 # Check if the given command is "cron".
1150 if ($option eq "cron") {
1151 # Check if an interval has been given.
1152 if ($interval) {
1153 # Check if the given interval is valid.
1154 foreach my $element (@cron_intervals) {
1155 # Skip current element until the given one has been found.
1156 next unless($element eq $interval);
1157
1158 # Call the suricatactrl binary and pass the "cron" command
1159 # with the requrested interval.
1160 &General::system("$suricatactrl", "$option", "$interval");
1161
1162 # Return "1" - True.
1163 return 1;
1164 }
1165 }
1166
1167 # If we got here, the given interval is not supported or none has been given. - Return nothing.
1168 return;
1169 } else {
1170 # Call the suricatactrl binary and pass the requrested
1171 # option to it.
1172 &General::system("$suricatactrl", "$option");
1173
1174 # Return "1" - True.
1175 return 1;
1176 }
1177 }
1178
1179 # Command not found - return nothing.
1180 return;
1181 }
1182
1183 #
1184 ## Function to create a new empty file.
1185 #
1186 sub create_empty_file($) {
1187 my ($file) = @_;
1188
1189 # Check if the given file exists.
1190 if(-e $file) {
1191 # Do nothing to prevent from overwriting existing files.
1192 return;
1193 }
1194
1195 # Open the file for writing.
1196 open(FILE, ">$file") or die "Could not write to $file. $!\n";
1197
1198 # Close file handle.
1199 close(FILE);
1200
1201 # Return true.
1202 return 1;
1203 }
1204
1205 #
1206 ## Private function to check if the file permission of the rulespath are correct.
1207 ## If not, call suricatactrl to fix them.
1208 #
1209 sub _check_rulesdir_permissions() {
1210 # Check if the rulepath main directory is writable.
1211 unless (-W $rulespath) {
1212 # If not call suricatctrl to fix it.
1213 &call_suricatactrl("fix-rules-dir");
1214 }
1215
1216 # Open snort rules directory and do a directory listing.
1217 opendir(DIR, $rulespath) or die $!;
1218 # Loop through the direcory.
1219 while (my $file = readdir(DIR)) {
1220 # We only want files.
1221 next unless (-f "$rulespath/$file");
1222
1223 # Check if the file is writable by the user.
1224 if (-W "$rulespath/$file") {
1225 # Everything is okay - go on to the next file.
1226 next;
1227 } else {
1228 # There are wrong permissions, call suricatactrl to fix it.
1229 &call_suricatactrl("fix-rules-dir");
1230 }
1231 }
1232 }
1233
1234 #
1235 ## Private function to cleanup the directory which contains
1236 ## the IDS rules, before extracting and modifing the new ruleset.
1237 #
1238 sub _cleanup_rulesdir() {
1239 # Open rules directory and do a directory listing.
1240 opendir(DIR, $rulespath) or die $!;
1241
1242 # Loop through the direcory.
1243 while (my $file = readdir(DIR)) {
1244 # We only want files.
1245 next unless (-f "$rulespath/$file");
1246
1247 # Skip rules file for whitelisted hosts.
1248 next if ("$rulespath/$file" eq $whitelist_file);
1249
1250 # Skip rules file with local rules.
1251 next if ("$rulespath/$file" eq $local_rules_file);
1252
1253 # Delete the current processed file, if not, exit this function
1254 # and return an error message.
1255 unlink("$rulespath/$file") or return "Could not delete $rulespath/$file. $!\n";
1256 }
1257
1258 # Return nothing;
1259 return;
1260 }
1261
1262 #
1263 ## Function to generate the file which contains the home net information.
1264 #
1265 sub generate_home_net_file() {
1266 my %netsettings;
1267
1268 # Read-in network settings.
1269 &General::readhash("${General::swroot}/ethernet/settings", \%netsettings);
1270
1271 # Get available network zones.
1272 my @network_zones = &Network::get_available_network_zones();
1273
1274 # Temporary array to store network address and prefix of the configured
1275 # networks.
1276 my @networks;
1277
1278 # Loop through the array of available network zones.
1279 foreach my $zone (@network_zones) {
1280 # Check if the current processed zone is red.
1281 if($zone eq "red") {
1282 # Grab the IP-address of the red interface.
1283 my $red_address = &get_red_address();
1284
1285 # Check if an address has been obtained.
1286 if ($red_address) {
1287 # Generate full network string.
1288 my $red_network = join("/", $red_address, "32");
1289
1290 # Add the red network to the array of networks.
1291 push(@networks, $red_network);
1292 }
1293
1294 # Check if the configured RED_TYPE is static.
1295 if ($netsettings{'RED_TYPE'} eq "STATIC") {
1296 # Get configured and enabled aliases.
1297 my @aliases = &get_aliases();
1298
1299 # Loop through the array.
1300 foreach my $alias (@aliases) {
1301 # Add "/32" prefix.
1302 my $network = join("/", $alias, "32");
1303
1304 # Add the generated network to the array of networks.
1305 push(@networks, $network);
1306 }
1307 }
1308 # Process remaining network zones.
1309 } else {
1310 # Convert current zone name into upper case.
1311 $zone = uc($zone);
1312
1313 # Generate key to access the required data from the netsettings hash.
1314 my $zone_netaddress = $zone . "_NETADDRESS";
1315 my $zone_netmask = $zone . "_NETMASK";
1316
1317 # Obtain the settings from the netsettings hash.
1318 my $netaddress = $netsettings{$zone_netaddress};
1319 my $netmask = $netsettings{$zone_netmask};
1320
1321 # Convert the subnetmask into prefix notation.
1322 my $prefix = &Network::convert_netmask2prefix($netmask);
1323
1324 # Generate full network string.
1325 my $network = join("/", $netaddress,$prefix);
1326
1327 # Check if the network is valid.
1328 if(&Network::check_subnet($network)) {
1329 # Add the generated network to the array of networks.
1330 push(@networks, $network);
1331 }
1332 }
1333 }
1334
1335 # Format home net declaration.
1336 my $line = "\"[" . join(',', @networks) . "]\"";
1337
1338 # Open file to store the addresses of the home net.
1339 open(FILE, ">$homenet_file") or die "Could not open $homenet_file. $!\n";
1340
1341 # Print yaml header.
1342 print FILE "%YAML 1.1\n";
1343 print FILE "---\n\n";
1344
1345 # Print notice about autogenerated file.
1346 print FILE "#Autogenerated file. Any custom changes will be overwritten!\n";
1347
1348 # Print the generated and required HOME_NET declaration to the file.
1349 print FILE "HOME_NET:\t$line\n";
1350
1351 # Close file handle.
1352 close(FILE);
1353 }
1354
1355 #
1356 # Function to generate and write the file which contains the configured and used DNS servers.
1357 #
1358 sub generate_dns_servers_file() {
1359 # Get the used DNS servers.
1360 my @nameservers = &General::get_nameservers();
1361
1362 # Get network settings.
1363 my %netsettings;
1364 &General::readhash("${General::swroot}/ethernet/settings", \%netsettings);
1365
1366 # Format dns servers declaration.
1367 my $line = "";
1368
1369 # Check if the system has configured nameservers.
1370 if (@nameservers) {
1371 # Add the GREEN address as DNS servers.
1372 push(@nameservers, $netsettings{'GREEN_ADDRESS'});
1373
1374 # Check if a BLUE zone exists.
1375 if ($netsettings{'BLUE_ADDRESS'}) {
1376 # Add the BLUE address to the array of nameservers.
1377 push(@nameservers, $netsettings{'BLUE_ADDRESS'});
1378 }
1379
1380 # Generate the line which will be written to the DNS servers file.
1381 $line = join(",", @nameservers);
1382 } else {
1383 # External net simply contains (any).
1384 $line = "\$EXTERNAL_NET";
1385 }
1386
1387 # Open file to store the used DNS server addresses.
1388 open(FILE, ">$dns_servers_file") or die "Could not open $dns_servers_file. $!\n";
1389
1390 # Print yaml header.
1391 print FILE "%YAML 1.1\n";
1392 print FILE "---\n\n";
1393
1394 # Print notice about autogenerated file.
1395 print FILE "#Autogenerated file. Any custom changes will be overwritten!\n";
1396
1397 # Print the generated DNS declaration to the file.
1398 print FILE "DNS_SERVERS:\t\"[$line]\"\n";
1399
1400 # Close file handle.
1401 close(FILE);
1402 }
1403
1404 #
1405 # Function to generate and write the file which contains the HTTP_PORTS definition.
1406 #
1407 sub generate_http_ports_file() {
1408 my %proxysettings;
1409
1410 # Read-in proxy settings
1411 &General::readhash("${General::swroot}/proxy/advanced/settings", \%proxysettings);
1412
1413 # Check if the proxy is enabled.
1414 if (( -e "${General::swroot}/proxy/enable") || (-e "${General::swroot}/proxy/enable_blue")) {
1415 # Add the proxy port to the array of HTTP ports.
1416 push(@http_ports, $proxysettings{'PROXY_PORT'});
1417 }
1418
1419 # Check if the transparent mode of the proxy is enabled.
1420 if ((-e "${General::swroot}/proxy/transparent") || (-e "${General::swroot}/proxy/transparent_blue")) {
1421 # Add the transparent proxy port to the array of HTTP ports.
1422 push(@http_ports, $proxysettings{'TRANSPARENT_PORT'});
1423 }
1424
1425 # Format HTTP_PORTS declaration.
1426 my $line = "";
1427
1428 # Generate line which will be written to the http ports file.
1429 $line = join(",", @http_ports);
1430
1431 # Open file to store the HTTP_PORTS.
1432 open(FILE, ">$http_ports_file") or die "Could not open $http_ports_file. $!\n";
1433
1434 # Print yaml header.
1435 print FILE "%YAML 1.1\n";
1436 print FILE "---\n\n";
1437
1438 # Print notice about autogenerated file.
1439 print FILE "#Autogenerated file. Any custom changes will be overwritten!\n";
1440
1441 # Print the generated HTTP_PORTS declaration to the file.
1442 print FILE "HTTP_PORTS:\t\"[$line]\"\n";
1443
1444 # Close file handle.
1445 close(FILE);
1446 }
1447
1448 #
1449 ## Function to generate and write the file for used rulefiles file for a given provider.
1450 ##
1451 ## The function requires as first argument a provider handle, and as second an array with files.
1452 #
1453 sub write_used_provider_rulefiles_file($@) {
1454 my ($provider, @files) = @_;
1455
1456 # Get the path and file for the provider specific used rulefiles file.
1457 my $used_provider_rulesfile_file = &get_used_provider_rulesfile_file($provider);
1458
1459 # Open file for used rulefiles.
1460 open (FILE, ">", "$used_provider_rulesfile_file") or die "Could not write to $used_provider_rulesfile_file. $!\n";
1461
1462 # Write yaml header to the file.
1463 print FILE "%YAML 1.1\n";
1464 print FILE "---\n\n";
1465
1466 # Write header to file.
1467 print FILE "#Autogenerated file. Any custom changes will be overwritten!\n";
1468
1469 # Loop through the array of given files.
1470 foreach my $file (@files) {
1471 # Check if the given filename exists and write it to the file of used rulefiles.
1472 if(-f "$rulespath/$file") {
1473 print FILE " - $file\n";
1474 }
1475 }
1476
1477 # Close file after writing.
1478 close(FILE);
1479 }
1480
1481 #
1482 ## Function to write the main file for provider rulesfiles inclusions.
1483 ##
1484 ## This function requires an array of provider handles.
1485 #
1486 sub write_main_used_rulefiles_file (@) {
1487 my (@providers) = @_;
1488
1489 # Call function to write the static rulefiles file.
1490 &_write_default_rulefiles_file();
1491
1492 # Open file for used rulefils inclusion.
1493 open (FILE, ">", "$suricata_used_providers_file") or die "Could not write to $suricata_used_providers_file. $!\n";
1494
1495 # Write yaml header to the file.
1496 print FILE "%YAML 1.1\n";
1497 print FILE "---\n\n";
1498
1499 # Write header to file.
1500 print FILE "#Autogenerated file. Any custom changes will be overwritten!\n";
1501
1502 # Loop through the list of given providers.
1503 foreach my $provider (@providers) {
1504 # Call function to get the providers used rulefiles file.
1505 my $filename = &get_used_provider_rulesfile_file($provider);
1506
1507 # Check if the file exists and write it into the used rulefiles file.
1508 if (-f $filename) {
1509 # Print the provider to the file.
1510 print FILE "include\: $filename\n";
1511 }
1512 }
1513
1514 # Close the filehandle after writing.
1515 close(FILE);
1516 }
1517
1518 sub _write_default_rulefiles_file () {
1519 # Get enabled application layer protocols.
1520 my @enabled_app_layer_protos = &get_suricata_enabled_app_layer_protos();
1521
1522 # Open file.
1523 open (FILE, ">", $suricata_default_rulefiles_file) or die "Could not write to $suricata_default_rulefiles_file. $!\n";
1524
1525 # Write yaml header to the file.
1526 print FILE "%YAML 1.1\n";
1527 print FILE "---\n\n";
1528
1529 # Write notice about autogenerated file.
1530 print FILE "#Autogenerated file. Any custom changes will be overwritten!\n";
1531
1532 # Loop through the array of static included rulesfiles.
1533 foreach my $file (@static_included_rulefiles) {
1534 # Check if the file exists.
1535 if (-f "$rulespath/$file") {
1536 # Write the rulesfile name to the file.
1537 print FILE " - $rulespath/$file\n";
1538 }
1539 }
1540
1541 print FILE "\n#Default rules for used application layer protocols.\n";
1542 foreach my $enabled_app_layer_proto (@enabled_app_layer_protos) {
1543 # Check if the current processed app layer proto needs to be translated
1544 # into an application name.
1545 if (exists($tr_app_layer_proto{$enabled_app_layer_proto})) {
1546 # Obtain the translated application name for this protocol.
1547 $enabled_app_layer_proto = $tr_app_layer_proto{$enabled_app_layer_proto};
1548 }
1549
1550 # Generate filename.
1551 my $rulesfile = "$default_rulespath/$enabled_app_layer_proto\.rules";
1552
1553 # Check if such a file exists.
1554 if (-f "$rulesfile") {
1555 # Write the rulesfile name to the file.
1556 print FILE " - $rulesfile\n";
1557 }
1558
1559 # Generate filename with "events" in filename.
1560 $rulesfile = "$default_rulespath/$enabled_app_layer_proto\-events.rules";
1561
1562 # Check if this file exists.
1563 if (-f "$rulesfile" ) {
1564 # Write the rulesfile name to the file.
1565 print FILE " - $rulesfile\n";
1566 }
1567 }
1568
1569 # Close the file handle
1570 close(FILE);
1571 }
1572
1573 #
1574 ## Tiny function to generate the full path and name for the used_provider_rulesfile file of a given provider.
1575 #
1576 sub get_used_provider_rulesfile_file ($) {
1577 my ($provider) = @_;
1578
1579 my $filename = "$settingsdir/suricata\-$provider\-used\-rulefiles.yaml";
1580
1581 # Return the gernerated file.
1582 return $filename;
1583 }
1584
1585 #
1586 ## Tiny function to generate the full path and name for the file which stores the modifications of a ruleset.
1587 #
1588 sub get_provider_ruleset_modifications_file($) {
1589 my ($provider) = @_;
1590
1591 my $filename = "$settingsdir/$provider\-modifications";
1592
1593 # Return the filename.
1594 return $filename;
1595 }
1596
1597 #
1598 ## Function to get the subscription code of a configured provider.
1599 #
1600 sub get_subscription_code($) {
1601 my ($provider) = @_;
1602
1603 my %configured_providers = ();
1604
1605 # Read-in providers settings file.
1606 &General::readhasharray($providers_settings_file, \%configured_providers);
1607
1608 # Loop through the hash of configured providers.
1609 foreach my $id (keys %configured_providers) {
1610 # Assign nice human-readable values to the data fields.
1611 my $provider_handle = $configured_providers{$id}[0];
1612 my $subscription_code = $configured_providers{$id}[1];
1613
1614 # Check if the current processed provider is the requested one.
1615 if ($provider_handle eq $provider) {
1616 # Return the obtained subscription code.
1617 return $subscription_code;
1618 }
1619 }
1620
1621 # No subscription code found - return nothing.
1622 return;
1623 }
1624
1625 #
1626 ## Function to get the ruleset date for a given provider.
1627 ##
1628 ## The function simply return the creation date in a human read-able format
1629 ## of the stored providers rulesfile.
1630 #
1631 sub get_ruleset_date($) {
1632 my ($provider) = @_;
1633 my $date;
1634 my $mtime;
1635
1636 # Get the stored rulesfile for this provider.
1637 my $stored_rulesfile = &_get_dl_rulesfile($provider);
1638
1639 # Check if we got a file.
1640 if (-f $stored_rulesfile) {
1641 # Call stat on the rulestarball.
1642 my $stat = stat("$stored_rulesfile");
1643
1644 # Get timestamp the file creation.
1645 $mtime = $stat->mtime;
1646 }
1647
1648 # Check if the timestamp has not been grabbed.
1649 unless ($mtime) {
1650 # Return N/A for Not available.
1651 return "N/A";
1652 }
1653
1654 # Convert into human read-able format.
1655 $date = strftime('%Y-%m-%d %H:%M:%S', localtime($mtime));
1656
1657 # Return the date.
1658 return $date;
1659 }
1660
1661 #
1662 ## Function to gather the version of suricata.
1663 #
1664 sub get_suricata_version($) {
1665 my ($format) = @_;
1666
1667 # Execute piped suricata command and return the version information.
1668 open(SURICATA, "suricata -V |") or die "Couldn't execute program: $!";
1669
1670 # Grab and store the output of the piped program.
1671 my $version_string = <SURICATA>;
1672
1673 # Close pipe.
1674 close(SURICATA);
1675
1676 # Remove newlines.
1677 chomp($version_string);
1678
1679 # Grab the version from the version string.
1680 $version_string =~ /([0-9]+([.][0-9]+)+)/;
1681
1682 # Splitt the version into single chunks.
1683 my ($major_ver, $minor_ver, $patchlevel) = split(/\./, $1);
1684
1685 # Check and return the requested version sheme.
1686 if ($format eq "major") {
1687 # Return the full version.
1688 return "$major_ver";
1689 } elsif ($format eq "minor") {
1690 # Return the major and minor part.
1691 return "$major_ver.$minor_ver";
1692 } else {
1693 # Return the full version string.
1694 return "$major_ver.$minor_ver.$patchlevel";
1695 }
1696 }
1697
1698 #
1699 ## Function to get the enabled application layer protocols.
1700 #
1701 sub get_suricata_enabled_app_layer_protos() {
1702 # Array to store and return the enabled app layer protos.
1703 my @enabled_app_layer_protos = ();
1704
1705 # Execute piped suricata command and return the list of
1706 # enabled application layer protocols.
1707 open(SURICATA, "suricata --list-app-layer-protos |") or die "Could not execute program: $!";
1708
1709 # Grab and store the list of enabled application layer protocols.
1710 my @output = <SURICATA>;
1711
1712 # Close pipe.
1713 close(SURICATA);
1714
1715 # Merge allways enabled static application layers protocols array.
1716 @enabled_app_layer_protos = @static_enabled_app_layer_protos;
1717
1718 # Loop through the array which contains the output of suricata.
1719 foreach my $line (@output) {
1720 # Skip header line which starts with "===".
1721 next if ($line =~ /^\s*=/);
1722
1723 # Skip info or warning lines.
1724 next if ($line =~ /\s*--/);
1725
1726 # Remove newlines.
1727 chomp($line);
1728
1729 # Add enabled app layer proto to the array.
1730 push(@enabled_app_layer_protos, $line);
1731 }
1732
1733 # Sort the array.
1734 @enabled_app_layer_protos = sort(@enabled_app_layer_protos);
1735
1736 # Return the array.
1737 return @enabled_app_layer_protos;
1738 }
1739
1740 #
1741 ## Function to generate the rules file with whitelisted addresses.
1742 #
1743 sub generate_ignore_file() {
1744 my %ignored = ();
1745
1746 # SID range 1000000-1999999 Reserved for Local Use
1747 # Put your custom rules in this range to avoid conflicts
1748 my $sid = 1500000;
1749
1750 # Read-in ignoredfile.
1751 &General::readhasharray($IDS::ignored_file, \%ignored);
1752
1753 # Open ignorefile for writing.
1754 open(FILE, ">$IDS::whitelist_file") or die "Could not write to $IDS::whitelist_file. $!\n";
1755
1756 # Config file header.
1757 print FILE "# Autogenerated file.\n";
1758 print FILE "# All user modifications will be overwritten.\n\n";
1759
1760 # Add all user defined addresses to the whitelist.
1761 #
1762 # Check if the hash contains any elements.
1763 if (keys (%ignored)) {
1764 # Loop through the entire hash and write the host/network
1765 # and remark to the ignore file.
1766 while ( (my $key) = each %ignored) {
1767 my $address = $ignored{$key}[0];
1768 my $remark = $ignored{$key}[1];
1769 my $status = $ignored{$key}[2];
1770
1771 # Check if the status of the entry is "enabled".
1772 if ($status eq "enabled") {
1773 # Check if the address/network is valid.
1774 if ((&General::validip($address)) || (&General::validipandmask($address))) {
1775 # Write rule line to the file to pass any traffic from this IP
1776 print FILE "pass ip $address any -> any any (msg:\"pass all traffic from/to $address\"\; bypass; sid:$sid\;)\n";
1777
1778 # Increment sid.
1779 $sid++;
1780 }
1781 }
1782 }
1783 }
1784
1785 close(FILE);
1786 }
1787
1788 #
1789 ## Function to set correct ownership for single files and directories.
1790 #
1791
1792 sub set_ownership($) {
1793 my ($target) = @_;
1794
1795 # User and group of the WUI.
1796 my $uname = "nobody";
1797 my $grname = "nobody";
1798
1799 # The chown function implemented in perl requies the user and group as nummeric id's.
1800 my $uid = getpwnam($uname);
1801 my $gid = getgrnam($grname);
1802
1803 # Check if the given target exists.
1804 unless ($target) {
1805 # Stop the script and print error message.
1806 die "The $target does not exist. Cannot change the ownership!\n";
1807 }
1808
1809 # Check weather the target is a file or directory.
1810 if (-f $target) {
1811 # Change ownership ot the single file.
1812 chown($uid, $gid, "$target");
1813 } elsif (-d $target) {
1814 # Do a directory listing.
1815 opendir(DIR, $target) or die $!;
1816 # Loop through the direcory.
1817 while (my $file = readdir(DIR)) {
1818
1819 # We only want files.
1820 next unless (-f "$target/$file");
1821
1822 # Set correct ownership for the files.
1823 chown($uid, $gid, "$target/$file");
1824 }
1825
1826 closedir(DIR);
1827
1828 # Change ownership of the directory.
1829 chown($uid, $gid, "$target");
1830 }
1831 }
1832
1833 #
1834 ## Function to read-in the aliases file and returns all configured and enabled aliases.
1835 #
1836 sub get_aliases() {
1837 # Location of the aliases file.
1838 my $aliases_file = "${General::swroot}/ethernet/aliases";
1839
1840 # Array to store the aliases.
1841 my @aliases;
1842
1843 # Check if the file is empty.
1844 if (-z $aliases_file) {
1845 # Abort nothing to do.
1846 return;
1847 }
1848
1849 # Open the aliases file.
1850 open(ALIASES, $aliases_file) or die "Could not open $aliases_file. $!\n";
1851
1852 # Loop through the file content.
1853 while (my $line = <ALIASES>) {
1854 # Remove newlines.
1855 chomp($line);
1856
1857 # Splitt line content into single chunks.
1858 my ($address, $state, $remark) = split(/\,/, $line);
1859
1860 # Check if the state of the current processed alias is "on".
1861 if ($state eq "on") {
1862 # Check if the address is valid.
1863 if(&Network::check_ip_address($address)) {
1864 # Add the alias to the array of aliases.
1865 push(@aliases, $address);
1866 }
1867 }
1868 }
1869
1870 # Close file handle.
1871 close(ALIASES);
1872
1873 # Return the array.
1874 return @aliases;
1875 }
1876
1877 #
1878 ## Function to grab the current assigned IP-address on red.
1879 #
1880 sub get_red_address() {
1881 # File, which contains the current IP-address of the red interface.
1882 my $file = "${General::swroot}/red/local-ipaddress";
1883
1884 # Check if the file exists.
1885 if (-e $file) {
1886 # Open the given file.
1887 open(FILE, "$file") or die "Could not open $file.";
1888
1889 # Obtain the address from the first line of the file.
1890 my $address = <FILE>;
1891
1892 # Close filehandle
1893 close(FILE);
1894
1895 # Remove newlines.
1896 chomp $address;
1897
1898 # Check if the grabbed address is valid.
1899 if (&General::validip($address)) {
1900 # Return the address.
1901 return $address;
1902 }
1903 }
1904
1905 # Return nothing.
1906 return;
1907 }
1908
1909 #
1910 ## Function to get the used rules files of a given provider.
1911 #
1912 sub read_used_provider_rulesfiles($) {
1913 my ($provider) = @_;
1914
1915 # Array to store the used rulefiles.
1916 my @used_rulesfiles = ();
1917
1918 # Get the used rulesefile file for the provider.
1919 my $rulesfile_file = &get_used_provider_rulesfile_file($provider);
1920
1921 # Check if the a used rulesfile exists for this provider.
1922 if (-f $rulesfile_file) {
1923 # Open the file or used rulefiles and read-in content.
1924 open(FILE, $rulesfile_file) or die "Could not open $rulesfile_file. $!\n";
1925
1926 while (<FILE>) {
1927 # Assign the current line to a nice variable.
1928 my $line = $_;
1929
1930 # Remove newlines.
1931 chomp($line);
1932
1933 # Skip comments.
1934 next if ($line =~ /\#/);
1935
1936 # Skip blank lines.
1937 next if ($line =~ /^\s*$/);
1938
1939 # Gather the rulefile.
1940 if ($line =~ /.*- (.*)/) {
1941 my $rulefile = $1;
1942
1943 # Add the rulefile to the array of used rulesfiles.
1944 push(@used_rulesfiles, $rulefile);
1945 }
1946 }
1947
1948 # Close the file.
1949 close(FILE);
1950 }
1951
1952 # Return the array of used rulesfiles.
1953 return @used_rulesfiles;
1954 }
1955
1956 #
1957 ## Function to write the lock file for locking the WUI, while
1958 ## the autoupdate script runs.
1959 #
1960 sub lock_ids_page() {
1961 # Call subfunction to create the file.
1962 &create_empty_file($ids_page_lock_file);
1963 }
1964
1965 #
1966 ## Function to release the lock of the WUI, again.
1967 #
1968 sub unlock_ids_page() {
1969 # Delete lock file.
1970 unlink($ids_page_lock_file);
1971 }
1972
1973 1;