2 ############################################################################
4 # This file is part of the IPFire Firewall. #
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. #
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. #
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 #
20 # Copyright (C) 2018-2019 IPFire Team <info@ipfire.org> #
22 ############################################################################
28 require '/var/ipfire/general-functions.pl';
29 require "${General::swroot}/network-functions.pl";
30 require "${General::swroot}/suricata/ruleset-sources-new";
32 # Location where all config and settings files are stored.
33 our $settingsdir = "${General::swroot}/suricata";
35 # File where the main file for providers ruleset inclusion exists.
36 our $suricata_used_providers_file = "$settingsdir/suricata-used-providers.yaml";
38 # DEPRECATED - File where the used rulefiles are stored.
39 our $used_rulefiles_file = "$settingsdir/suricata-used-rulefiles.yaml";
41 # File where the addresses of the homenet are stored.
42 our $homenet_file = "$settingsdir/suricata-homenet.yaml";
44 # File where the addresses of the used DNS servers are stored.
45 our $dns_servers_file = "$settingsdir/suricata-dns-servers.yaml";
47 # File where the HTTP ports definition is stored.
48 our $http_ports_file = "$settingsdir/suricata-http-ports.yaml";
50 # File which contains the enabled sids.
51 our $enabled_sids_file = "$settingsdir/oinkmaster-enabled-sids.conf";
53 # File which contains the disabled sids.
54 our $disabled_sids_file = "$settingsdir/oinkmaster-disabled-sids.conf";
56 # File which contains wheater the rules should be changed.
57 our $modify_sids_file = "$settingsdir/oinkmaster-modify-sids.conf";
59 # File which stores the configured IPS settings.
60 our $ids_settings_file = "$settingsdir/settings";
62 # DEPRECATED - File which stores the configured rules-settings.
63 our $rules_settings_file = "$settingsdir/rules-settings";
65 # File which stores the used and configured ruleset providers.
66 our $providers_settings_file = "$settingsdir/providers-settings";
68 # File which stores the configured settings for whitelisted addresses.
69 our $ignored_file = "$settingsdir/ignored";
71 # DEPRECATED - Location and name of the tarball which contains the ruleset.
72 our $rulestarball = "/var/tmp/idsrules.tar.gz";
74 # Location where the downloaded rulesets are stored.
75 our $dl_rules_path = "/var/tmp";
77 # File to store any errors, which also will be read and displayed by the wui.
78 our $storederrorfile = "/tmp/ids_storederror";
80 # File to lock the WUI, while the autoupdate script runs.
81 our $ids_page_lock_file = "/tmp/ids_page_locked";
83 # Location where the rulefiles are stored.
84 our $rulespath = "/var/lib/suricata";
86 # Location of the classification file.
87 our $classification_file = "$rulespath/classification.config";
89 # Location of the sid to msg mappings file.
90 our $sid_msg_file = "$rulespath/sid-msg.map";
92 # Location to store local rules. This file will not be touched.
93 our $local_rules_file = "$rulespath/local.rules";
95 # File which contains the rules to whitelist addresses on suricata.
96 our $whitelist_file = "$rulespath/whitelist.rules";
98 # File which contains a list of all supported ruleset sources.
99 # (Sourcefire, Emergingthreads, etc..)
100 our $rulesetsourcesfile = "$settingsdir/ruleset-sources";
102 # The pidfile of the IDS.
103 our $idspidfile = "/var/run/suricata.pid";
105 # Location of suricatactrl.
106 my $suricatactrl = "/usr/local/bin/suricatactrl";
108 # Prefix for each downloaded ruleset.
109 my $dl_rulesfile_prefix = "idsrules";
111 # Temporary directory where the rulesets will be extracted.
112 my $tmp_directory = "/tmp/ids_tmp";
114 # Temporary directory where the extracted rules files will be stored.
115 my $tmp_rules_directory = "$tmp_directory/rules";
117 # Temporary directory where the extracted additional config files will be stored.
118 my $tmp_conf_directory = "$tmp_directory/conf";
120 # Array with allowed commands of suricatactrl.
121 my @suricatactrl_cmds = ( 'start', 'stop', 'restart', 'reload', 'fix-rules-dir', 'cron' );
123 # Array with supported cron intervals.
124 my @cron_intervals = ('off', 'daily', 'weekly' );
126 # Array which contains the HTTP ports, which statically will be declared as HTTP_PORTS in the
128 my @http_ports = ('80', '81');
130 # Hash which allows to convert the download type (dl_type) to a file suffix.
131 my %dl_type_to_suffix = (
132 "archive" => ".tar.gz",
137 ## Function to check and create all IDS related files, if the does not exist.
139 sub check_and_create_filelayout
() {
140 # Check if the files exist and if not, create them.
141 unless (-f
"$enabled_sids_file") { &create_empty_file
($enabled_sids_file); }
142 unless (-f
"$disabled_sids_file") { &create_empty_file
($disabled_sids_file); }
143 unless (-f
"$modify_sids_file") { &create_empty_file
($modify_sids_file); }
144 unless (-f
"$suricata_used_providers_file") { &create_empty_file
($suricata_used_providers_file); }
145 unless (-f
"$ids_settings_file") { &create_empty_file
($ids_settings_file); }
146 unless (-f
"$providers_settings_file") { &create_empty_file
($providers_settings_file); }
147 unless (-f
"$ignored_file") { &create_empty_file
($ignored_file); }
148 unless (-f
"$whitelist_file" ) { &create_empty_file
($whitelist_file); }
152 ## Function to get a list of all available ruleset providers.
154 ## They will be returned as a sorted array.
156 sub get_ruleset_providers
() {
159 # Loop through the hash of providers.
160 foreach my $provider ( keys %IDS::Ruleset
::Providers
) {
161 # Add the provider to the array.
162 push(@providers, $provider);
165 # Sort and return the array.
166 return sort(@providers);
170 ## Function to get a list of all enabled ruleset providers.
172 ## They will be returned as an array.
174 sub get_enabled_providers
() {
175 my %used_providers = ();
177 # Array to store the enabled providers.
178 my @enabled_providers = ();
180 # Read-in the providers config file.
181 &General
::readhasharray
("$providers_settings_file", \
%used_providers);
183 # Loop through the hash of used_providers.
184 foreach my $id (keys %used_providers) {
185 # Skip disabled providers.
186 next unless ($used_providers{$id}[3] eq "enabled");
188 # Grab the provider handle.
189 my $provider = "$used_providers{$id}[0]";
191 # Add the provider to the array of enabled providers.
192 push(@enabled_providers, $provider);
196 return @enabled_providers;
200 ## Function for checking if at least 300MB of free disk space are available
201 ## on the "/var" partition.
203 sub checkdiskspace
() {
204 # Call diskfree to gather the free disk space of /var.
205 my @df = &General
::system_output
("/bin/df", "-B", "M", "/var");
207 # Loop through the output.
208 foreach my $line (@df) {
209 # Ignore header line.
210 next if $line =~ m/^Filesystem/;
212 # Search for a line with the device information.
213 if ($line =~ m/dev/ ) {
214 # Split the line into single pieces.
215 my @values = split(' ', $line);
216 my ($filesystem, $blocks, $used, $available, $used_perenctage, $mounted_on) = @values;
218 # Check if the available disk space is more than 300MB.
219 if ($available < 300) {
220 # Log error to syslog.
221 &_log_to_syslog
("Not enough free disk space on /var. Only $available MB from 300 MB available.");
223 # Exit function and return "1" - False.
229 # Everything okay, return nothing.
234 ## This function is responsible for downloading the configured IDS rulesets or if no one is specified
235 ## all configured rulesets will be downloaded.
237 ## * At first it gathers all configured ruleset providers, initialize the downloader and sets an
238 ## upstream proxy if configured.
239 ## * After that, the given ruleset or in case all rulesets should be downloaded, it will determine wether it
240 ## is enabled or not.
241 ## * The next step will be to generate the final download url, by obtaining the URL for the desired
242 ## ruleset, add the settings for the upstream proxy.
243 ## * Finally the function will grab all the rules files or tarballs from the servers.
245 sub downloadruleset
($) {
248 # If no provider is given default to "all".
251 # Hash to store the providers and access id's, for which rules should be downloaded.
252 my %sheduled_providers = ();
254 # Get used provider settings.
255 my %used_providers = ();
256 &General
::readhasharray
("$providers_settings_file", \
%used_providers);
258 # Check if a ruleset has been configured.
259 unless(%used_providers) {
260 # Log that no ruleset has been configured and abort.
261 &_log_to_syslog
("No ruleset provider has been configured.");
267 # Read proxysettings.
268 my %proxysettings=();
269 &General
::readhash
("${General::swroot}/proxy/settings", \
%proxysettings);
271 # Load required perl module to handle the download.
274 # Init the download module.
275 my $downloader = LWP
::UserAgent
->new;
277 # Set timeout to 10 seconds.
278 $downloader->timeout(10);
280 # Check if an upstream proxy is configured.
281 if ($proxysettings{'UPSTREAM_PROXY'}) {
284 $proxy_url = "http://";
286 # Check if the proxy requires authentication.
287 if (($proxysettings{'UPSTREAM_USER'}) && ($proxysettings{'UPSTREAM_PASSWORD'})) {
288 $proxy_url .= "$proxysettings{'UPSTREAM_USER'}\:$proxysettings{'UPSTREAM_PASSWORD'}\@";
291 # Add proxy server address and port.
292 $proxy_url .= $proxysettings{'UPSTREAM_PROXY'};
294 # Setup proxy settings.
295 $downloader->proxy(['http', 'https'], $proxy_url);
298 # Loop through the hash of configured providers.
299 foreach my $id ( keys %used_providers ) {
300 # Skip providers which are not enabled.
301 next if ($used_providers{$id}[3] ne "enabled");
303 # Obtain the provider handle.
304 my $provider_handle = $used_providers{$id}[0];
306 # Handle update off all providers.
307 if (($provider eq "all") || ($provider_handle eq "$provider")) {
308 # Add provider handle and it's id to the hash of sheduled providers.
309 $sheduled_providers{$provider_handle} = $id;
313 # Loop through the hash of sheduled providers.
314 foreach my $provider ( keys %sheduled_providers) {
315 # Grab the download url for the provider.
316 my $url = $IDS::Ruleset
::Providers
{$provider}{'dl_url'};
318 # Check if the provider requires a subscription.
319 if ($IDS::Ruleset
::Providers
{$provider}{'requires_subscription'} eq "True") {
320 # Grab the previously stored access id for the provider from hash.
321 my $id = $sheduled_providers{$provider};
323 # Grab the subscription code.
324 my $subscription_code = $used_providers{$id}[1];
326 # Add the subscription code to the download url.
327 $url =~ s/\<subscription_code\>/$subscription_code/g;
331 # Abort if no url could be determined for the provider.
333 # Log error and abort.
334 &_log_to_syslog
("Unable to gather a download URL for the selected ruleset provider.");
338 # Variable to store the filesize of the remote object.
341 # The sourcfire (snort rules) does not allow to send "HEAD" requests, so skip this check
342 # for this webserver.
344 # Check if the ruleset source contains "snort.org".
345 unless ($url =~ /\.snort\.org/) {
346 # Pass the requrested url to the downloader.
347 my $request = HTTP
::Request
->new(HEAD
=> $url);
349 # Accept the html header.
350 $request->header('Accept' => 'text/html');
352 # Perform the request and fetch the html header.
353 my $response = $downloader->request($request);
355 # Check if there was any error.
356 unless ($response->is_success) {
358 my $error = $response->status_line();
361 &_log_to_syslog
("Unable to download the ruleset. \($error\)");
363 # Return "1" - false.
367 # Assign the fetched header object.
368 my $header = $response->headers();
370 # Grab the remote file size from the object and store it in the
372 $remote_filesize = $header->content_length;
375 # Load perl module to deal with temporary files.
378 # Generate temporary file name, located in "/var/tmp" and with a suffix of ".tmp".
379 my $tmp = File
::Temp
->new( SUFFIX
=> ".tmp", DIR
=> "/var/tmp/", UNLINK
=> 0 );
380 my $tmpfile = $tmp->filename();
382 # Pass the requested url to the downloader.
383 my $request = HTTP
::Request
->new(GET
=> $url);
385 # Perform the request and save the output into the tmpfile.
386 my $response = $downloader->request($request, $tmpfile);
388 # Check if there was any error.
389 unless ($response->is_success) {
391 my $error = $response->content;
394 &_log_to_syslog
("Unable to download the ruleset. \($error\)");
396 # Return "1" - false.
400 # Load perl stat module.
403 # Perform stat on the tmpfile.
404 my $stat = stat($tmpfile);
406 # Grab the local filesize of the downloaded tarball.
407 my $local_filesize = $stat->size;
409 # Check if both file sizes match.
410 if (($remote_filesize) && ($remote_filesize ne $local_filesize)) {
412 &_log_to_syslog
("Unable to completely download the ruleset. ");
413 &_log_to_syslog
("Only got $local_filesize Bytes instead of $remote_filesize Bytes. ");
415 # Delete temporary file.
418 # Return "1" - false.
422 # Genarate and assign file name and path to store the downloaded rules file.
423 my $dl_rulesfile = &_get_dl_rulesfile
($provider);
425 # Check if a file name could be obtained.
426 unless ($dl_rulesfile) {
428 &_log_to_syslog
("Unable to store the downloaded rules file. ");
430 # Delete downloaded temporary file.
433 # Return "1" - false.
436 # Load file copy module, which contains the move() function.
439 # Overwrite the may existing rulefile or tarball with the downloaded one.
440 move
("$tmpfile", "$dl_rulesfile");
442 # Delete temporary file.
445 # Set correct ownership for the tarball.
446 set_ownership
("$dl_rulesfile");
449 # If we got here, everything worked fine. Return nothing.
454 ## Function to extract a given ruleset.
456 sub extractruleset
($) {
459 # Load perl module to deal with archives.
462 # Load perl module to deal with files and path.
465 # Get full path and downloaded rulesfile for the given provider.
466 my $tarball = &_get_dl_rulesfile
($provider);
468 # Check if the file exists.
469 unless (-f
$tarball) {
470 &_log_to_syslog
("Could not extract ruleset file: $tarball");
476 # Check if the temporary directories exist, otherwise create them.
477 mkdir("$tmp_directory") unless (-d
"$tmp_directory");
478 mkdir("$tmp_rules_directory") unless (-d
"$tmp_rules_directory");
479 mkdir("$tmp_conf_directory") unless (-d
"$tmp_conf_directory");
481 # Initialize the tar module.
482 my $tar = Archive
::Tar
->new($tarball);
484 # Get the filelist inside the tarball.
485 my @packed_files = $tar->list_files;
487 # Loop through the filelist.
488 foreach my $packed_file (@packed_files) {
491 # Splitt the packed file into chunks.
492 my $file = fileparse
($packed_file);
494 # Handle msg-id.map file.
495 if ("$file" eq "sid-msg.map") {
496 # Set extract destination to temporary config_dir.
497 $destination = "$tmp_conf_directory/$provider\-sid-msg.map";
498 # Handle classification.conf
499 } elsif ("$file" eq "classification.config") {
500 # Set extract destination to temporary config_dir.
501 $destination = "$tmp_conf_directory/$provider\-classification.config";
502 # Handle rules files.
503 } elsif ($file =~ m/\.rules$/) {
506 # Splitt the filename into chunks.
507 my @filename = split("-", $file);
510 @filename = reverse(@filename);
512 # Get the amount of elements in the array.
513 my $elements = @filename;
515 # Remove last element of the hash.
516 # It contains the vendor name, which will be replaced.
517 if ($elements >= 3) {
518 # Remove last element from hash.
522 # Check if the last element of the filename does not
523 # contain the providers name.
524 if ($filename[-1] ne "$provider") {
525 # Add provider name as last element.
526 push(@filename, $provider);
529 # Reverse the array back.
530 @filename = reverse(@filename);
532 # Generate the name for the rulesfile.
533 $rulesfilename = join("-", @filename);
535 # Set extract destination to temporaray rules_dir.
536 $destination = "$tmp_rules_directory/$rulesfilename";
538 # Skip all other files.
542 # Extract the file to the temporary directory.
543 $tar->extract_file("$packed_file", "$destination");
548 ## A wrapper function to call the oinkmaster script, setup the rules structues and
549 ## call the functions to merge the additional config files. (classification, sid-msg, etc.).
552 # Load perl module for file copying.
555 # Check if the files in rulesdir have the correct permissions.
556 &_check_rulesdir_permissions
();
558 # Cleanup the rules directory before filling it with the new rulests.
559 &_cleanup_rulesdir
();
561 # Get all enabled providers.
562 my @enabled_providers = &get_enabled_providers
();
564 # Loop through the array of enabled providers.
565 foreach my $provider (@enabled_providers) {
566 # Omit the type (dl_type) of the stored ruleset.
567 my $type = $IDS::Ruleset
::Providers
{$provider}{'dl_type'};
569 # Handle the different ruleset types.
570 if ($type eq "archive") {
571 # Call the extractruleset function.
572 &extractruleset
($provider);
573 } elsif ($type eq "plain") {
574 # Generate filename and full path for the stored rulesfile.
575 my $dl_rulesfile = &_get_dl_rulesfile
($provider);
577 # Generate destination filename an full path.
578 my $destination = "$tmp_rules_directory/$provider\-ruleset.rules";
580 # Copy the file into the temporary rules directory.
581 copy
($dl_rulesfile, $destination);
588 # Load perl module to talk to the kernel syslog.
589 use Sys
::Syslog
qw(:DEFAULT setlogsock);
591 # Establish the connection to the syslog service.
592 openlog
('oinkmaster', 'cons,pid', 'user');
594 # Call oinkmaster to generate ruleset.
595 open(OINKMASTER
, "/usr/local/bin/oinkmaster.pl -s -u dir://$tmp_rules_directory -C $settingsdir/oinkmaster.conf -o $rulespath 2>&1 |") or die "Could not execute oinkmaster $!\n";
597 # Log output of oinkmaster to syslog.
598 while(<OINKMASTER
>) {
599 # The syslog function works best with an array based input,
600 # so generate one before passing the message details to syslog.
601 my @syslog = ("INFO", "$_");
603 # Send the log message.
607 # Close the pipe to oinkmaster process.
610 # Close the log handle.
613 # Call function to merge the classification files.
614 &merge_classifications
(@enabled_providers);
616 # Call function to merge the sid to message mapping files.
617 &merge_sid_msg
(@enabled_providers);
619 # Cleanup temporary directory.
620 &cleanup_tmp_directory
();
624 ## Function to merge the classifications for a given amount of providers and write them
625 ## to the classifications file.
627 sub merge_classifications
(@
) {
630 # Hash to store all collected classifications.
631 my %classifications = ();
633 # Loop through the given array of providers.
634 foreach my $provider (@providers) {
635 # Generate full path to classification file.
636 my $classification_file = "$tmp_conf_directory/$provider\-classification.config";
638 # Skip provider if no classification file exists.
639 next unless (-f
"$classification_file");
641 # Open the classification file.
642 open(CLASSIFICATION
, $classification_file) or die "Could not open file $classification_file. $!\n";
644 # Loop through the file content.
645 while(<CLASSIFICATION
>) {
646 # Parse the file and grab the classification details.
647 if ($_ =~/.*config classification\: (.*)/) {
648 # Split the grabbed details.
649 my ($short_name, $short_desc, $priority) = split("\,", $1);
651 # Check if the grabbed classification is allready known and the priority value is greater
652 # than the stored one (which causes less priority in the IDS).
653 if (($classifications{$short_name}) && ($classifications{$short_name}[1] >= $priority)) {
654 #Change the priority value to the stricter one.
655 $classifications{$short_name} = [ "$classifications{$short_name}[0]", "$priority" ];
657 # Add the classification to the hash.
658 $classifications{$short_name} = [ "$short_desc", "$priority" ];
664 close(CLASSIFICATION
);
667 # Open classification file for writing.
668 open(FILE
, ">", "$classification_file") or die "Could not write to $classification_file. $!\n";
670 # Print notice about autogenerated file.
671 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n\n";
673 # Sort and loop through the hash of classifications.
674 foreach my $key (sort keys %classifications) {
675 # Assign some nice variable names for the items.
676 my $short_name = $key;
677 my $short_desc = $classifications{$key}[0];
678 my $priority = $classifications{$key}[1];
680 # Write the classification to the file.
681 print FILE
"config classification: $short_name,$short_desc,$priority\n";
689 ## Function to merge the "sid to message mapping" files of various given providers.
691 sub merge_sid_msg
(@
) {
694 # Hash which contains all the sid to message mappings.
697 # Loop through the array of given providers.
698 foreach my $provider (@providers) {
699 # Generate full path and filename.
700 my $sid_msg_file = "$tmp_conf_directory/$provider\-sid-msg.map";
702 # Skip provider if no sid to msg mapping file for this provider exists.
703 next unless (-f
$sid_msg_file);
706 open(MAPPING
, $sid_msg_file) or die "Could not open $sid_msg_file. $!\n";
708 # Loop through the file content.
713 # Skip lines which do not start with a number,
714 next unless ($_ =~ /^\d+/);
716 # Split line content and assign it to an array.
717 my @line = split(/ \|\| /, $_);
719 # Grab the first element (and remove it) from the line array.
720 # It contains the sid.
721 my $sid = shift(@line);
723 # Store the grabbed sid and the remain array as hash value.
724 # It still contains the messages, references etc.
725 $mappings{$sid} = [@line];
732 # Open mappings file for writing.
733 open(FILE
, ">", $sid_msg_file) or die "Could not write $sid_msg_file. $!\n";
735 # Write notice about autogenerated file.
736 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n\n";
738 # Loop through the hash of mappings.
739 foreach my $sid ( sort keys %mappings) {
740 # Grab data for the sid.
741 my @data = @
{$mappings{$sid}};
743 # Add the sid to the data array.
744 unshift(@data, $sid);
747 my $line = join(" \|\| ", @data);
749 print FILE
"$line\n";
758 ## A very tiny function to move an extracted ruleset from the temporary directory into
759 ## the rules directory.
761 sub move_tmp_ruleset
() {
765 # Do a directory listing of the temporary directory.
766 opendir DH
, $tmp_rules_directory;
768 # Loop over all files.
769 while(my $file = readdir DH
) {
770 # Move them to the rules directory.
771 move
"$tmp_rules_directory/$file" , "$rulespath/$file";
774 # Close directory handle.
779 ## Function to cleanup the temporary IDS directroy.
781 sub cleanup_tmp_directory
() {
782 # Load rmtree() function from file path perl module.
783 use File
::Path
'rmtree';
785 # Delete temporary directory and all containing files.
786 rmtree
([ "$tmp_directory" ]);
790 ## Function to do all the logging stuff if the downloading or updating of the ruleset fails.
795 # Remove any newline.
798 # Call private function to log the error message to syslog.
799 &_log_to_syslog
($error);
801 # Call private function to write/store the error message in the storederrorfile.
802 &_store_error_message
($error);
806 ## Function to log a given error message to the kernel syslog.
808 sub _log_to_syslog
($) {
811 # Load perl module to talk to the kernel syslog.
812 use Sys
::Syslog
qw(:DEFAULT setlogsock);
814 # The syslog function works best with an array based input,
815 # so generate one before passing the message details to syslog.
816 my @syslog = ("ERR", "<ERROR> $message");
818 # Establish the connection to the syslog service.
819 openlog
('oinkmaster', 'cons,pid', 'user');
821 # Send the log message.
824 # Close the log handle.
829 ## Private function to write a given error message to the storederror file.
831 sub _store_error_message
($) {
834 # Remove any newline.
837 # Open file for writing.
838 open (ERRORFILE
, ">$storederrorfile") or die "Could not write to $storederrorfile. $!\n";
840 # Write error to file.
841 print ERRORFILE
"$message\n";
846 # Set correct ownership for the file.
847 &set_ownership
("$storederrorfile");
851 ## Private function to get the path and filename for a downloaded ruleset by a given provider.
853 sub _get_dl_rulesfile
($) {
856 # Gather the download type for the given provider.
857 my $dl_type = $IDS::Ruleset
::Providers
{$provider}{'dl_type'};
859 # Obtain the file suffix for the download file type.
860 my $suffix = $dl_type_to_suffix{$dl_type};
862 # Check if a suffix has been found.
864 # Abort return - nothing.
868 # Generate the full filename and path for the stored rules file.
869 my $rulesfile = "$dl_rules_path/$dl_rulesfile_prefix-$provider$suffix";
871 # Return the generated filename.
876 ## Tiny function to delete the stored ruleset file or tarball for a given provider.
878 sub drop_dl_rulesfile
($) {
881 # Gather the full path and name of the stored rulesfile.
882 my $rulesfile = &_get_dl_rulesfile
($provider);
884 # Check if the given rulesfile exists.
886 # Delete the stored rulesfile.
887 unlink($rulesfile) or die "Could not delete $rulesfile. $!\n";
892 ## Function to check if the IDS is running.
894 sub ids_is_running
() {
896 # Open PID file for reading.
897 open(PIDFILE
, "$idspidfile") or die "Could not open $idspidfile. $!\n";
899 # Grab the process-id.
905 # Remove any newline.
908 # Check if a directory for the process-id exists in proc.
909 if(-d
"/proc/$pid") {
910 # The IDS daemon is running return the process id.
915 # Return nothing - IDS is not running.
920 ## Function to call suricatactrl binary with a given command.
922 sub call_suricatactrl
($) {
924 my ($option, $interval) = @_;
926 # Loop through the array of supported commands and check if
927 # the given one is part of it.
928 foreach my $cmd (@suricatactrl_cmds) {
929 # Skip current command unless the given one has been found.
930 next unless($cmd eq $option);
932 # Check if the given command is "cron".
933 if ($option eq "cron") {
934 # Check if an interval has been given.
936 # Check if the given interval is valid.
937 foreach my $element (@cron_intervals) {
938 # Skip current element until the given one has been found.
939 next unless($element eq $interval);
941 # Call the suricatactrl binary and pass the "cron" command
942 # with the requrested interval.
943 &General
::system("$suricatactrl", "$option", "$interval");
950 # If we got here, the given interval is not supported or none has been given. - Return nothing.
953 # Call the suricatactrl binary and pass the requrested
955 &General
::system("$suricatactrl", "$option");
962 # Command not found - return nothing.
967 ## Function to create a new empty file.
969 sub create_empty_file
($) {
972 # Check if the given file exists.
974 # Do nothing to prevent from overwriting existing files.
978 # Open the file for writing.
979 open(FILE
, ">$file") or die "Could not write to $file. $!\n";
989 ## Private function to check if the file permission of the rulespath are correct.
990 ## If not, call suricatactrl to fix them.
992 sub _check_rulesdir_permissions
() {
993 # Check if the rulepath main directory is writable.
994 unless (-W
$rulespath) {
995 # If not call suricatctrl to fix it.
996 &call_suricatactrl
("fix-rules-dir");
999 # Open snort rules directory and do a directory listing.
1000 opendir(DIR
, $rulespath) or die $!;
1001 # Loop through the direcory.
1002 while (my $file = readdir(DIR
)) {
1003 # We only want files.
1004 next unless (-f
"$rulespath/$file");
1006 # Check if the file is writable by the user.
1007 if (-W
"$rulespath/$file") {
1008 # Everything is okay - go on to the next file.
1011 # There are wrong permissions, call suricatactrl to fix it.
1012 &call_suricatactrl
("fix-rules-dir");
1018 ## Private function to cleanup the directory which contains
1019 ## the IDS rules, before extracting and modifing the new ruleset.
1021 sub _cleanup_rulesdir
() {
1022 # Open rules directory and do a directory listing.
1023 opendir(DIR
, $rulespath) or die $!;
1025 # Loop through the direcory.
1026 while (my $file = readdir(DIR
)) {
1027 # We only want files.
1028 next unless (-f
"$rulespath/$file");
1030 # Skip rules file for whitelisted hosts.
1031 next if ("$rulespath/$file" eq $whitelist_file);
1033 # Skip rules file with local rules.
1034 next if ("$rulespath/$file" eq $local_rules_file);
1036 # Delete the current processed file, if not, exit this function
1037 # and return an error message.
1038 unlink("$rulespath/$file") or return "Could not delete $rulespath/$file. $!\n";
1046 ## Function to generate the file which contains the home net information.
1048 sub generate_home_net_file
() {
1051 # Read-in network settings.
1052 &General
::readhash
("${General::swroot}/ethernet/settings", \
%netsettings);
1054 # Get available network zones.
1055 my @network_zones = &Network
::get_available_network_zones
();
1057 # Temporary array to store network address and prefix of the configured
1061 # Loop through the array of available network zones.
1062 foreach my $zone (@network_zones) {
1063 # Check if the current processed zone is red.
1064 if($zone eq "red") {
1065 # Grab the IP-address of the red interface.
1066 my $red_address = &get_red_address
();
1068 # Check if an address has been obtained.
1070 # Generate full network string.
1071 my $red_network = join("/", $red_address, "32");
1073 # Add the red network to the array of networks.
1074 push(@networks, $red_network);
1077 # Check if the configured RED_TYPE is static.
1078 if ($netsettings{'RED_TYPE'} eq "STATIC") {
1079 # Get configured and enabled aliases.
1080 my @aliases = &get_aliases
();
1082 # Loop through the array.
1083 foreach my $alias (@aliases) {
1085 my $network = join("/", $alias, "32");
1087 # Add the generated network to the array of networks.
1088 push(@networks, $network);
1091 # Process remaining network zones.
1093 # Convert current zone name into upper case.
1096 # Generate key to access the required data from the netsettings hash.
1097 my $zone_netaddress = $zone . "_NETADDRESS";
1098 my $zone_netmask = $zone . "_NETMASK";
1100 # Obtain the settings from the netsettings hash.
1101 my $netaddress = $netsettings{$zone_netaddress};
1102 my $netmask = $netsettings{$zone_netmask};
1104 # Convert the subnetmask into prefix notation.
1105 my $prefix = &Network
::convert_netmask2prefix
($netmask);
1107 # Generate full network string.
1108 my $network = join("/", $netaddress,$prefix);
1110 # Check if the network is valid.
1111 if(&Network
::check_subnet
($network)) {
1112 # Add the generated network to the array of networks.
1113 push(@networks, $network);
1118 # Format home net declaration.
1119 my $line = "\"[" . join(',', @networks) . "]\"";
1121 # Open file to store the addresses of the home net.
1122 open(FILE
, ">$homenet_file") or die "Could not open $homenet_file. $!\n";
1124 # Print yaml header.
1125 print FILE
"%YAML 1.1\n";
1126 print FILE
"---\n\n";
1128 # Print notice about autogenerated file.
1129 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1131 # Print the generated and required HOME_NET declaration to the file.
1132 print FILE
"HOME_NET:\t$line\n";
1134 # Close file handle.
1139 # Function to generate and write the file which contains the configured and used DNS servers.
1141 sub generate_dns_servers_file
() {
1142 # Get the used DNS servers.
1143 my @nameservers = &General
::get_nameservers
();
1145 # Get network settings.
1147 &General
::readhash
("${General::swroot}/ethernet/settings", \
%netsettings);
1149 # Format dns servers declaration.
1152 # Check if the system has configured nameservers.
1154 # Add the GREEN address as DNS servers.
1155 push(@nameservers, $netsettings{'GREEN_ADDRESS'});
1157 # Check if a BLUE zone exists.
1158 if ($netsettings{'BLUE_ADDRESS'}) {
1159 # Add the BLUE address to the array of nameservers.
1160 push(@nameservers, $netsettings{'BLUE_ADDRESS'});
1163 # Generate the line which will be written to the DNS servers file.
1164 $line = join(",", @nameservers);
1166 # External net simply contains (any).
1167 $line = "\$EXTERNAL_NET";
1170 # Open file to store the used DNS server addresses.
1171 open(FILE
, ">$dns_servers_file") or die "Could not open $dns_servers_file. $!\n";
1173 # Print yaml header.
1174 print FILE
"%YAML 1.1\n";
1175 print FILE
"---\n\n";
1177 # Print notice about autogenerated file.
1178 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1180 # Print the generated DNS declaration to the file.
1181 print FILE
"DNS_SERVERS:\t\"[$line]\"\n";
1183 # Close file handle.
1188 # Function to generate and write the file which contains the HTTP_PORTS definition.
1190 sub generate_http_ports_file
() {
1193 # Read-in proxy settings
1194 &General
::readhash
("${General::swroot}/proxy/advanced/settings", \
%proxysettings);
1196 # Check if the proxy is enabled.
1197 if (( -e
"${General::swroot}/proxy/enable") || (-e
"${General::swroot}/proxy/enable_blue")) {
1198 # Add the proxy port to the array of HTTP ports.
1199 push(@http_ports, $proxysettings{'PROXY_PORT'});
1202 # Check if the transparent mode of the proxy is enabled.
1203 if ((-e
"${General::swroot}/proxy/transparent") || (-e
"${General::swroot}/proxy/transparent_blue")) {
1204 # Add the transparent proxy port to the array of HTTP ports.
1205 push(@http_ports, $proxysettings{'TRANSPARENT_PORT'});
1208 # Format HTTP_PORTS declaration.
1211 # Generate line which will be written to the http ports file.
1212 $line = join(",", @http_ports);
1214 # Open file to store the HTTP_PORTS.
1215 open(FILE
, ">$http_ports_file") or die "Could not open $http_ports_file. $!\n";
1217 # Print yaml header.
1218 print FILE
"%YAML 1.1\n";
1219 print FILE
"---\n\n";
1221 # Print notice about autogenerated file.
1222 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1224 # Print the generated HTTP_PORTS declaration to the file.
1225 print FILE
"HTTP_PORTS:\t\"[$line]\"\n";
1227 # Close file handle.
1232 ## Function to generate and write the file for used rulefiles file for a given provider.
1234 ## The function requires as first argument a provider handle, and as second an array with files.
1236 sub write_used_provider_rulefiles_file
($@
) {
1237 my ($provider, @files) = @_;
1239 # Get the path and file for the provider specific used rulefiles file.
1240 my $used_provider_rulesfile_file = &get_used_provider_rulesfile_file
($provider);
1242 # Open file for used rulefiles.
1243 open (FILE
, ">$used_provider_rulesfile_file") or die "Could not write to $used_provider_rulesfile_file. $!\n";
1245 # Write yaml header to the file.
1246 print FILE
"%YAML 1.1\n";
1247 print FILE
"---\n\n";
1249 # Write header to file.
1250 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1252 # Loop through the array of given files.
1253 foreach my $file (@files) {
1254 # Check if the given filename exists and write it to the file of used rulefiles.
1255 if(-f
"$rulespath/$file") {
1256 print FILE
" - $file\n";
1260 # Close file after writing.
1265 ## Function to write the main file for provider rulesfiles inclusions.
1267 ## This function requires an array of provider handles.
1269 sub write_main_used_rulefiles_file
(@
) {
1270 my (@providers) = @_;
1272 # Open file for used rulefils inclusion.
1273 open (FILE
, ">", "$suricata_used_providers_file") or die "Could not write to $suricata_used_providers_file. $!\n";
1275 # Write yaml header to the file.
1276 print FILE
"%YAML 1.1\n";
1277 print FILE
"---\n\n";
1279 # Write header to file.
1280 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1282 # Loop through the list of given providers.
1283 foreach my $provider (@providers) {
1284 # Call function to get the providers used rulefiles file.
1285 my $filename = &get_used_provider_rulesfile_file
($provider);
1287 # Print the provider to the file.
1288 print FILE
"include\: $filename\n";
1291 # XXX - whitelist.rules is not allowed directly, needs to be in a yaml file which has to be included.
1292 # Always use the whitelist file.
1293 #print FILE "\n - whitelist.rules\n";
1295 # Close the filehandle after writing.
1300 ## Tiny function to generate the full path and name for the used_provider_rulesfile file of a given provider.
1302 sub get_used_provider_rulesfile_file
($) {
1303 my ($provider) = @_;
1305 my $filename = "$settingsdir/suricata\-$provider\-used\-rulefiles.yaml";
1307 # Return the gernerated file.
1312 ## Function to generate and write the file for modify the ruleset.
1314 sub write_modify_sids_file
() {
1315 # Get configured settings.
1317 &General
::readhash
("$ids_settings_file", \
%idssettings);
1319 # Open modify sid's file for writing.
1320 open(FILE
, ">$modify_sids_file") or die "Could not write to $modify_sids_file. $!\n";
1322 # Write file header.
1323 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1325 # Check if the traffic only should be monitored.
1326 unless($idssettings{'MONITOR_TRAFFIC_ONLY'} eq 'on') {
1327 # Suricata is in IPS mode, which means that the rule actions have to be changed
1328 # from 'alert' to 'drop', however not all rules should be changed. Some rules
1329 # exist purely to set a flowbit which is used to convey other information, such
1330 # as a specific type of file being downloaded, to other rulewhich then check for
1331 # malware in that file. Rules which fall into the first category should stay as
1332 # alert since not all flows of that type contain malware.
1334 # These types of rulesfiles contain meta-data which gives the action that should
1335 # be used when in IPS mode. Do the following:
1337 # 1. Disable all rules and set the action to 'drop'
1338 # 2. Set the action back to 'alert' if the rule contains 'flowbits:noalert;'
1339 # This should give rules not in the policy a reasonable default if the user
1340 # manually enables them.
1341 # 3. Enable rules and set actions according to the meta-data strings.
1343 my $policy = 'balanced'; # Placeholder to allow policy to be changed.
1346 modifysid * "^#(?:alert|drop)(.+policy $policy-ips alert)" | "alert\${1}"
1347 modifysid * "^#(?:alert|drop)(.+policy $policy-ips drop)" | "drop\${1}"
1348 modifysid * "^(#?)(?:alert|drop)" | "\${1}drop"
1349 modifysid * "^(#?)drop(.+flowbits:noalert;)" | "\${1}alert\${2}"
1353 # Close file handle.
1358 ## Function to get the ruleset date for a given provider.
1360 ## The function simply return the creation date in a human read-able format
1361 ## of the stored providers rulesfile.
1363 sub get_ruleset_date
($) {
1364 my ($provider) = @_;
1366 # Load neccessary perl modules for file stat and to format the timestamp.
1368 use POSIX
qw( strftime );
1370 # Get the stored rulesfile for this provider.
1371 my $stored_rulesfile = &_get_dl_rulesfile
($provider);
1373 # Call stat on the rulestarball.
1374 my $stat = stat("$stored_rulesfile");
1376 # Get timestamp the file creation.
1377 my $mtime = $stat->mtime;
1379 # Convert into human read-able format.
1380 my $date = strftime
('%Y-%m-%d %H:%M:%S', localtime($mtime));
1387 ## Function to gather the version of suricata.
1389 sub get_suricata_version
($) {
1392 # Execute piped suricata command and return the version information.
1393 open(SURICATA
, "suricata -V |") or die "Couldn't execute program: $!";
1395 # Grab and store the output of the piped program.
1396 my $version_string = <SURICATA
>;
1402 chomp($version_string);
1404 # Grab the version from the version string.
1405 $version_string =~ /([0-9]+([.][0-9]+)+)/;
1407 # Splitt the version into single chunks.
1408 my ($major_ver, $minor_ver, $patchlevel) = split(/\./, $1);
1410 # Check and return the requested version sheme.
1411 if ($format eq "major") {
1412 # Return the full version.
1413 return "$major_ver";
1414 } elsif ($format eq "minor") {
1415 # Return the major and minor part.
1416 return "$major_ver.$minor_ver";
1418 # Return the full version string.
1419 return "$major_ver.$minor_ver.$patchlevel";
1424 ## Function to generate the rules file with whitelisted addresses.
1426 sub generate_ignore_file
() {
1429 # SID range 1000000-1999999 Reserved for Local Use
1430 # Put your custom rules in this range to avoid conflicts
1433 # Read-in ignoredfile.
1434 &General
::readhasharray
($IDS::ignored_file
, \
%ignored);
1436 # Open ignorefile for writing.
1437 open(FILE
, ">$IDS::whitelist_file") or die "Could not write to $IDS::whitelist_file. $!\n";
1439 # Config file header.
1440 print FILE
"# Autogenerated file.\n";
1441 print FILE
"# All user modifications will be overwritten.\n\n";
1443 # Add all user defined addresses to the whitelist.
1445 # Check if the hash contains any elements.
1446 if (keys (%ignored)) {
1447 # Loop through the entire hash and write the host/network
1448 # and remark to the ignore file.
1449 while ( (my $key) = each %ignored) {
1450 my $address = $ignored{$key}[0];
1451 my $remark = $ignored{$key}[1];
1452 my $status = $ignored{$key}[2];
1454 # Check if the status of the entry is "enabled".
1455 if ($status eq "enabled") {
1456 # Check if the address/network is valid.
1457 if ((&General
::validip
($address)) || (&General
::validipandmask
($address))) {
1458 # Write rule line to the file to pass any traffic from this IP
1459 print FILE
"pass ip $address any -> any any (msg:\"pass all traffic from/to $address\"\; sid:$sid\;)\n";
1472 ## Function to set correct ownership for single files and directories.
1475 sub set_ownership
($) {
1478 # User and group of the WUI.
1479 my $uname = "nobody";
1480 my $grname = "nobody";
1482 # The chown function implemented in perl requies the user and group as nummeric id's.
1483 my $uid = getpwnam($uname);
1484 my $gid = getgrnam($grname);
1486 # Check if the given target exists.
1488 # Stop the script and print error message.
1489 die "The $target does not exist. Cannot change the ownership!\n";
1492 # Check weather the target is a file or directory.
1494 # Change ownership ot the single file.
1495 chown($uid, $gid, "$target");
1496 } elsif (-d
$target) {
1497 # Do a directory listing.
1498 opendir(DIR
, $target) or die $!;
1499 # Loop through the direcory.
1500 while (my $file = readdir(DIR
)) {
1502 # We only want files.
1503 next unless (-f
"$target/$file");
1505 # Set correct ownership for the files.
1506 chown($uid, $gid, "$target/$file");
1511 # Change ownership of the directory.
1512 chown($uid, $gid, "$target");
1517 ## Function to read-in the aliases file and returns all configured and enabled aliases.
1520 # Location of the aliases file.
1521 my $aliases_file = "${General::swroot}/ethernet/aliases";
1523 # Array to store the aliases.
1526 # Check if the file is empty.
1527 if (-z
$aliases_file) {
1528 # Abort nothing to do.
1532 # Open the aliases file.
1533 open(ALIASES
, $aliases_file) or die "Could not open $aliases_file. $!\n";
1535 # Loop through the file content.
1536 while (my $line = <ALIASES
>) {
1540 # Splitt line content into single chunks.
1541 my ($address, $state, $remark) = split(/\,/, $line);
1543 # Check if the state of the current processed alias is "on".
1544 if ($state eq "on") {
1545 # Check if the address is valid.
1546 if(&Network
::check_ip_address
($address)) {
1547 # Add the alias to the array of aliases.
1548 push(@aliases, $address);
1553 # Close file handle.
1561 ## Function to grab the current assigned IP-address on red.
1563 sub get_red_address
() {
1564 # File, which contains the current IP-address of the red interface.
1565 my $file = "${General::swroot}/red/local-ipaddress";
1567 # Check if the file exists.
1569 # Open the given file.
1570 open(FILE
, "$file") or die "Could not open $file.";
1572 # Obtain the address from the first line of the file.
1573 my $address = <FILE
>;
1581 # Check if the grabbed address is valid.
1582 if (&General
::validip
($address)) {
1583 # Return the address.
1593 ## Function to get the used rules files of a given provider.
1595 sub read_used_provider_rulesfiles
($) {
1596 my ($provider) = @_;
1598 # Array to store the used rulefiles.
1599 my @used_rulesfiles = ();
1601 # Get the used rulesefile file for the provider.
1602 my $rulesfile_file = &get_used_provider_rulesfile_file
($provider);
1604 # Check if the used rulesfile is empty.
1605 unless (-z
$rulesfile_file) {
1606 # Open the file or used rulefiles and read-in content.
1607 open(FILE
, $rulesfile_file) or die "Could not open $rulesfile_file. $!\n";
1610 # Assign the current line to a nice variable.
1617 next if ($line =~ /\#/);
1620 next if ($line =~ /^\s*$/);
1622 # Gather the rulefile.
1623 if ($line =~ /.*- (.*)/) {
1626 # Add the rulefile to the array of used rulesfiles.
1627 push(@used_rulesfiles, $rulefile);
1635 # Return the array of used rulesfiles.
1636 return @used_rulesfiles;
1640 ## Function to write the lock file for locking the WUI, while
1641 ## the autoupdate script runs.
1643 sub lock_ids_page
() {
1644 # Call subfunction to create the file.
1645 &create_empty_file
($ids_page_lock_file);
1649 ## Function to release the lock of the WUI, again.
1651 sub unlock_ids_page
() {
1653 unlink($ids_page_lock_file);