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";
32 # Location where all config and settings files are stored.
33 our $settingsdir = "${General::swroot}/suricata";
35 # File where the used rulefiles are stored.
36 our $used_rulefiles_file = "$settingsdir/suricata-used-rulefiles.yaml";
38 # File where the addresses of the homenet are stored.
39 our $homenet_file = "$settingsdir/suricata-homenet.yaml";
41 # File where the addresses of the used DNS servers are stored.
42 our $dns_servers_file = "$settingsdir/suricata-dns-servers.yaml";
44 # File where the HTTP ports definition is stored.
45 our $http_ports_file = "$settingsdir/suricata-http-ports.yaml";
47 # File which contains the enabled sids.
48 our $enabled_sids_file = "$settingsdir/oinkmaster-enabled-sids.conf";
50 # File which contains the disabled sids.
51 our $disabled_sids_file = "$settingsdir/oinkmaster-disabled-sids.conf";
53 # File which contains wheater the rules should be changed.
54 our $modify_sids_file = "$settingsdir/oinkmaster-modify-sids.conf";
56 # File which stores the configured IPS settings.
57 our $ids_settings_file = "$settingsdir/settings";
59 # DEPRECATED - File which stores the configured rules-settings.
60 our $rules_settings_file = "$settingsdir/rules-settings";
62 # File which stores the used and configured ruleset providers.
63 our $providers_settings_file = "$settingsdir/providers-settings";
65 # File which stores the configured settings for whitelisted addresses.
66 our $ignored_file = "$settingsdir/ignored";
68 # DEPRECATED - Location and name of the tarball which contains the ruleset.
69 our $rulestarball = "/var/tmp/idsrules.tar.gz";
71 # Location where the downloaded rulesets are stored.
72 our $dl_rules_path = "/var/tmp";
74 # File to store any errors, which also will be read and displayed by the wui.
75 our $storederrorfile = "/tmp/ids_storederror";
77 # File to lock the WUI, while the autoupdate script runs.
78 our $ids_page_lock_file = "/tmp/ids_page_locked";
80 # Location where the rulefiles are stored.
81 our $rulespath = "/var/lib/suricata";
83 # Location of the classification file.
84 our $classification_file = "$rulespath/classification.config";
86 # Location of the sid to msg mappings file.
87 our $sid_msg_file = "$rulespath/sid-msg.map";
89 # Location to store local rules. This file will not be touched.
90 our $local_rules_file = "$rulespath/local.rules";
92 # File which contains the rules to whitelist addresses on suricata.
93 our $whitelist_file = "$rulespath/whitelist.rules";
95 # File which contains a list of all supported ruleset sources.
96 # (Sourcefire, Emergingthreads, etc..)
97 our $rulesetsourcesfile = "$settingsdir/ruleset-sources";
99 # The pidfile of the IDS.
100 our $idspidfile = "/var/run/suricata.pid";
102 # Location of suricatactrl.
103 my $suricatactrl = "/usr/local/bin/suricatactrl";
105 # Prefix for each downloaded ruleset.
106 my $dl_rulesfile_prefix = "idsrules";
108 # Temporary directory where the rulesets will be extracted.
109 my $tmp_directory = "/tmp/ids_tmp";
111 # Temporary directory where the extracted rules files will be stored.
112 my $tmp_rules_directory = "$tmp_directory/rules";
114 # Temporary directory where the extracted additional config files will be stored.
115 my $tmp_conf_directory = "$tmp_directory/conf";
117 # Array with allowed commands of suricatactrl.
118 my @suricatactrl_cmds = ( 'start', 'stop', 'restart', 'reload', 'fix-rules-dir', 'cron' );
120 # Array with supported cron intervals.
121 my @cron_intervals = ('off', 'daily', 'weekly' );
123 # Array which contains the HTTP ports, which statically will be declared as HTTP_PORTS in the
125 my @http_ports = ('80', '81');
127 # Hash which allows to convert the download type (dl_type) to a file suffix.
128 my %dl_type_to_suffix = (
129 "archive" => ".tar.gz",
134 ## Function to check and create all IDS related files, if the does not exist.
136 sub check_and_create_filelayout
() {
137 # Check if the files exist and if not, create them.
138 unless (-f
"$enabled_sids_file") { &create_empty_file
($enabled_sids_file); }
139 unless (-f
"$disabled_sids_file") { &create_empty_file
($disabled_sids_file); }
140 unless (-f
"$modify_sids_file") { &create_empty_file
($modify_sids_file); }
141 unless (-f
"$used_rulefiles_file") { &create_empty_file
($used_rulefiles_file); }
142 unless (-f
"$ids_settings_file") { &create_empty_file
($ids_settings_file); }
143 unless (-f
"$providers_settings_file") { &create_empty_file
($providers_settings_file); }
144 unless (-f
"$ignored_file") { &create_empty_file
($ignored_file); }
145 unless (-f
"$whitelist_file" ) { &create_empty_file
($whitelist_file); }
149 ## Function to get a list of all available ruleset providers.
151 ## They will be returned as a sorted array.
153 sub get_ruleset_providers
() {
156 # Loop through the hash of providers.
157 foreach my $provider ( keys %IDS::Ruleset
::Providers
) {
158 # Add the provider to the array.
159 push(@providers, $provider);
162 # Sort and return the array.
163 return sort(@providers);
167 ## Function to get a list of all enabled ruleset providers.
169 ## They will be returned as an array.
171 sub get_enabled_providers
() {
172 my %used_providers = ();
174 # Array to store the enabled providers.
175 my @enabled_providers = ();
177 # Read-in the providers config file.
178 &General
::readhasharray
("$providers_settings_file", \
%used_providers);
180 # Loop through the hash of used_providers.
181 foreach my $id (keys %used_providers) {
182 # Skip disabled providers.
183 next unless ($used_providers{$id}[3] eq "enabled");
185 # Grab the provider handle.
186 my $provider = "$used_providers{$id}[0]";
188 # Add the provider to the array of enabled providers.
189 push(@enabled_providers, $provider);
193 return @enabled_providers;
197 ## Function for checking if at least 300MB of free disk space are available
198 ## on the "/var" partition.
200 sub checkdiskspace
() {
201 # Call diskfree to gather the free disk space of /var.
202 my @df = &General
::system_output
("/bin/df", "-B", "M", "/var");
204 # Loop through the output.
205 foreach my $line (@df) {
206 # Ignore header line.
207 next if $line =~ m/^Filesystem/;
209 # Search for a line with the device information.
210 if ($line =~ m/dev/ ) {
211 # Split the line into single pieces.
212 my @values = split(' ', $line);
213 my ($filesystem, $blocks, $used, $available, $used_perenctage, $mounted_on) = @values;
215 # Check if the available disk space is more than 300MB.
216 if ($available < 300) {
217 # Log error to syslog.
218 &_log_to_syslog
("Not enough free disk space on /var. Only $available MB from 300 MB available.");
220 # Exit function and return "1" - False.
226 # Everything okay, return nothing.
231 ## This function is responsible for downloading the configured IDS rulesets or if no one is specified
232 ## all configured rulesets will be downloaded.
234 ## * At first it gathers all configured ruleset providers, initialize the downloader and sets an
235 ## upstream proxy if configured.
236 ## * After that, the given ruleset or in case all rulesets should be downloaded, it will determine wether it
237 ## is enabled or not.
238 ## * The next step will be to generate the final download url, by obtaining the URL for the desired
239 ## ruleset, add the settings for the upstream proxy.
240 ## * Finally the function will grab all the rules files or tarballs from the servers.
242 sub downloadruleset
($) {
245 # If no provider is given default to "all".
248 # Hash to store the providers and access id's, for which rules should be downloaded.
249 my %sheduled_providers = ();
251 # Get used provider settings.
252 my %used_providers = ();
253 &General
::readhasharray
("$providers_settings_file", \
%used_providers);
255 # Check if a ruleset has been configured.
256 unless(%used_providers) {
257 # Log that no ruleset has been configured and abort.
258 &_log_to_syslog
("No ruleset provider has been configured.");
264 # Read proxysettings.
265 my %proxysettings=();
266 &General
::readhash
("${General::swroot}/proxy/settings", \
%proxysettings);
268 # Load required perl module to handle the download.
271 # Init the download module.
272 my $downloader = LWP
::UserAgent
->new;
274 # Set timeout to 10 seconds.
275 $downloader->timeout(10);
277 # Check if an upstream proxy is configured.
278 if ($proxysettings{'UPSTREAM_PROXY'}) {
281 $proxy_url = "http://";
283 # Check if the proxy requires authentication.
284 if (($proxysettings{'UPSTREAM_USER'}) && ($proxysettings{'UPSTREAM_PASSWORD'})) {
285 $proxy_url .= "$proxysettings{'UPSTREAM_USER'}\:$proxysettings{'UPSTREAM_PASSWORD'}\@";
288 # Add proxy server address and port.
289 $proxy_url .= $proxysettings{'UPSTREAM_PROXY'};
291 # Setup proxy settings.
292 $downloader->proxy(['http', 'https'], $proxy_url);
295 # Loop through the hash of configured providers.
296 foreach my $id ( keys %used_providers ) {
297 # Skip providers which are not enabled.
298 next if ($used_providers{$id}[3] ne "enabled");
300 # Obtain the provider handle.
301 my $provider_handle = $used_providers{$id}[0];
303 # Handle update off all providers.
304 if (($provider eq "all") || ($provider_handle eq "$provider")) {
305 # Add provider handle and it's id to the hash of sheduled providers.
306 $sheduled_providers{$provider_handle} = $id;
310 # Loop through the hash of sheduled providers.
311 foreach my $provider ( keys %sheduled_providers) {
312 # Grab the download url for the provider.
313 my $url = $IDS::Ruleset
::Providers
{$provider}{'dl_url'};
315 # Check if the provider requires a subscription.
316 if ($IDS::Ruleset
::Providers
{$provider}{'requires_subscription'} eq "True") {
317 # Grab the previously stored access id for the provider from hash.
318 my $id = $sheduled_providers{$provider};
320 # Grab the subscription code.
321 my $subscription_code = $used_providers{$id}[1];
323 # Add the subscription code to the download url.
324 $url =~ s/\<subscription_code\>/$subscription_code/g;
328 # Abort if no url could be determined for the provider.
330 # Log error and abort.
331 &_log_to_syslog
("Unable to gather a download URL for the selected ruleset provider.");
335 # Variable to store the filesize of the remote object.
338 # The sourcfire (snort rules) does not allow to send "HEAD" requests, so skip this check
339 # for this webserver.
341 # Check if the ruleset source contains "snort.org".
342 unless ($url =~ /\.snort\.org/) {
343 # Pass the requrested url to the downloader.
344 my $request = HTTP
::Request
->new(HEAD
=> $url);
346 # Accept the html header.
347 $request->header('Accept' => 'text/html');
349 # Perform the request and fetch the html header.
350 my $response = $downloader->request($request);
352 # Check if there was any error.
353 unless ($response->is_success) {
355 my $error = $response->status_line();
358 &_log_to_syslog
("Unable to download the ruleset. \($error\)");
360 # Return "1" - false.
364 # Assign the fetched header object.
365 my $header = $response->headers();
367 # Grab the remote file size from the object and store it in the
369 $remote_filesize = $header->content_length;
372 # Load perl module to deal with temporary files.
375 # Generate temporary file name, located in "/var/tmp" and with a suffix of ".tmp".
376 my $tmp = File
::Temp
->new( SUFFIX
=> ".tmp", DIR
=> "/var/tmp/", UNLINK
=> 0 );
377 my $tmpfile = $tmp->filename();
379 # Pass the requested url to the downloader.
380 my $request = HTTP
::Request
->new(GET
=> $url);
382 # Perform the request and save the output into the tmpfile.
383 my $response = $downloader->request($request, $tmpfile);
385 # Check if there was any error.
386 unless ($response->is_success) {
388 my $error = $response->content;
391 &_log_to_syslog
("Unable to download the ruleset. \($error\)");
393 # Return "1" - false.
397 # Load perl stat module.
400 # Perform stat on the tmpfile.
401 my $stat = stat($tmpfile);
403 # Grab the local filesize of the downloaded tarball.
404 my $local_filesize = $stat->size;
406 # Check if both file sizes match.
407 if (($remote_filesize) && ($remote_filesize ne $local_filesize)) {
409 &_log_to_syslog
("Unable to completely download the ruleset. ");
410 &_log_to_syslog
("Only got $local_filesize Bytes instead of $remote_filesize Bytes. ");
412 # Delete temporary file.
415 # Return "1" - false.
419 # Genarate and assign file name and path to store the downloaded rules file.
420 my $dl_rulesfile = &_get_dl_rulesfile
($provider);
422 # Check if a file name could be obtained.
423 unless ($dl_rulesfile) {
425 &_log_to_syslog
("Unable to store the downloaded rules file. ");
427 # Delete downloaded temporary file.
430 # Return "1" - false.
433 # Load file copy module, which contains the move() function.
436 # Overwrite the may existing rulefile or tarball with the downloaded one.
437 move
("$tmpfile", "$dl_rulesfile");
439 # Delete temporary file.
442 # Set correct ownership for the tarball.
443 set_ownership
("$dl_rulesfile");
446 # If we got here, everything worked fine. Return nothing.
451 ## Function to extract a given ruleset.
453 sub extractruleset
($) {
456 # Load perl module to deal with archives.
459 # Load perl module to deal with files and path.
462 # Get full path and downloaded rulesfile for the given provider.
463 my $tarball = &_get_dl_rulesfile
($provider);
465 # Check if the file exists.
466 unless (-f
$tarball) {
467 &_log_to_syslog
("Could not extract ruleset file: $tarball");
473 # Check if the temporary directories exist, otherwise create them.
474 mkdir("$tmp_directory") unless (-d
"$tmp_directory");
475 mkdir("$tmp_rules_directory") unless (-d
"$tmp_rules_directory");
476 mkdir("$tmp_conf_directory") unless (-d
"$tmp_conf_directory");
478 # Initialize the tar module.
479 my $tar = Archive
::Tar
->new($tarball);
481 # Get the filelist inside the tarball.
482 my @packed_files = $tar->list_files;
484 # Loop through the filelist.
485 foreach my $packed_file (@packed_files) {
488 # Splitt the packed file into chunks.
489 my $file = fileparse
($packed_file);
491 # Handle msg-id.map file.
492 if ("$file" eq "sid-msg.map") {
493 # Set extract destination to temporary config_dir.
494 $destination = "$tmp_conf_directory/$provider\-sid-msg.map";
495 # Handle classification.conf
496 } elsif ("$file" eq "classification.config") {
497 # Set extract destination to temporary config_dir.
498 $destination = "$tmp_conf_directory/$provider\-classification.config";
499 # Handle rules files.
500 } elsif ($file =~ m/\.rules$/) {
503 # Splitt the filename into chunks.
504 my @filename = split("-", $file);
507 @filename = reverse(@filename);
509 # Get the amount of elements in the array.
510 my $elements = @filename;
512 # Remove last element of the hash.
513 # It contains the vendor name, which will be replaced.
514 if ($elements >= 3) {
515 # Remove last element from hash.
519 # Check if the last element of the filename does not
520 # contain the providers name.
521 if ($filename[-1] ne "$provider") {
522 # Add provider name as last element.
523 push(@filename, $provider);
526 # Reverse the array back.
527 @filename = reverse(@filename);
529 # Generate the name for the rulesfile.
530 $rulesfilename = join("-", @filename);
532 # Set extract destination to temporaray rules_dir.
533 $destination = "$tmp_rules_directory/$rulesfilename";
535 # Skip all other files.
539 # Extract the file to the temporary directory.
540 $tar->extract_file("$packed_file", "$destination");
545 ## A wrapper function to call the oinkmaster script, setup the rules structues and
546 ## call the functions to merge the additional config files. (classification, sid-msg, etc.).
549 # Load perl module for file copying.
552 # Check if the files in rulesdir have the correct permissions.
553 &_check_rulesdir_permissions
();
555 # Cleanup the rules directory before filling it with the new rulests.
556 &_cleanup_rulesdir
();
558 # Get all enabled providers.
559 my @enabled_providers = &get_enabled_providers
();
561 # Loop through the array of enabled providers.
562 foreach my $provider (@enabled_providers) {
563 # Omit the type (dl_type) of the stored ruleset.
564 my $type = $IDS::Ruleset
::Providers
{$provider}{'dl_type'};
566 # Handle the different ruleset types.
567 if ($type eq "archive") {
568 # Call the extractruleset function.
569 &extractruleset
($provider);
570 } elsif ($type eq "plain") {
571 # Generate filename and full path for the stored rulesfile.
572 my $dl_rulesfile = &_get_dl_rulesfile
($provider);
574 # Generate destination filename an full path.
575 my $destination = "$tmp_rules_directory/$provider\-ruleset.rules";
577 # Copy the file into the temporary rules directory.
578 copy
($dl_rulesfile, $destination);
585 # Load perl module to talk to the kernel syslog.
586 use Sys
::Syslog
qw(:DEFAULT setlogsock);
588 # Establish the connection to the syslog service.
589 openlog
('oinkmaster', 'cons,pid', 'user');
591 # Call oinkmaster to generate ruleset.
592 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";
594 # Log output of oinkmaster to syslog.
595 while(<OINKMASTER
>) {
596 # The syslog function works best with an array based input,
597 # so generate one before passing the message details to syslog.
598 my @syslog = ("INFO", "$_");
600 # Send the log message.
604 # Close the pipe to oinkmaster process.
607 # Close the log handle.
610 # Call function to merge the classification files.
611 &merge_classifications
(@enabled_providers);
613 # Call function to merge the sid to message mapping files.
614 &merge_sid_msg
(@enabled_providers);
616 # Cleanup temporary directory.
617 &cleanup_tmp_directory
();
621 ## Function to merge the classifications for a given amount of providers and write them
622 ## to the classifications file.
624 sub merge_classifications
(@
) {
627 # Hash to store all collected classifications.
628 my %classifications = ();
630 # Loop through the given array of providers.
631 foreach my $provider (@providers) {
632 # Generate full path to classification file.
633 my $classification_file = "$tmp_conf_directory/$provider\-classification.config";
635 # Skip provider if no classification file exists.
636 next unless (-f
"$classification_file");
638 # Open the classification file.
639 open(CLASSIFICATION
, $classification_file) or die "Could not open file $classification_file. $!\n";
641 # Loop through the file content.
642 while(<CLASSIFICATION
>) {
643 # Parse the file and grab the classification details.
644 if ($_ =~/.*config classification\: (.*)/) {
645 # Split the grabbed details.
646 my ($short_name, $short_desc, $priority) = split("\,", $1);
648 # Check if the grabbed classification is allready known and the priority value is greater
649 # than the stored one (which causes less priority in the IDS).
650 if (($classifications{$short_name}) && ($classifications{$short_name}[1] >= $priority)) {
651 #Change the priority value to the stricter one.
652 $classifications{$short_name} = [ "$classifications{$short_name}[0]", "$priority" ];
654 # Add the classification to the hash.
655 $classifications{$short_name} = [ "$short_desc", "$priority" ];
661 close(CLASSIFICATION
);
664 # Open classification file for writing.
665 open(FILE
, ">", "$classification_file") or die "Could not write to $classification_file. $!\n";
667 # Print notice about autogenerated file.
668 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n\n";
670 # Sort and loop through the hash of classifications.
671 foreach my $key (sort keys %classifications) {
672 # Assign some nice variable names for the items.
673 my $short_name = $key;
674 my $short_desc = $classifications{$key}[0];
675 my $priority = $classifications{$key}[1];
677 # Write the classification to the file.
678 print FILE
"config classification: $short_name,$short_desc,$priority\n";
686 ## Function to merge the "sid to message mapping" files of various given providers.
688 sub merge_sid_msg
(@
) {
691 # Hash which contains all the sid to message mappings.
694 # Loop through the array of given providers.
695 foreach my $provider (@providers) {
696 # Generate full path and filename.
697 my $sid_msg_file = "$tmp_conf_directory/$provider\-sid-msg.map";
699 # Skip provider if no sid to msg mapping file for this provider exists.
700 next unless (-f
$sid_msg_file);
703 open(MAPPING
, $sid_msg_file) or die "Could not open $sid_msg_file. $!\n";
705 # Loop through the file content.
710 # Skip lines which do not start with a number,
711 next unless ($_ =~ /^\d+/);
713 # Split line content and assign it to an array.
714 my @line = split(/ \|\| /, $_);
716 # Grab the first element (and remove it) from the line array.
717 # It contains the sid.
718 my $sid = shift(@line);
720 # Store the grabbed sid and the remain array as hash value.
721 # It still contains the messages, references etc.
722 $mappings{$sid} = [@line];
729 # Open mappings file for writing.
730 open(FILE
, ">", $sid_msg_file) or die "Could not write $sid_msg_file. $!\n";
732 # Write notice about autogenerated file.
733 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n\n";
735 # Loop through the hash of mappings.
736 foreach my $sid ( sort keys %mappings) {
737 # Grab data for the sid.
738 my @data = @
{$mappings{$sid}};
740 # Add the sid to the data array.
741 unshift(@data, $sid);
744 my $line = join(" \|\| ", @data);
746 print FILE
"$line\n";
755 ## Function to cleanup the temporary IDS directroy.
757 sub cleanup_tmp_directory
() {
758 # Load rmtree() function from file path perl module.
759 use File
::Path
'rmtree';
761 # Delete temporary directory and all containing files.
762 rmtree
([ "$tmp_directory" ]);
766 ## Function to do all the logging stuff if the downloading or updating of the ruleset fails.
771 # Remove any newline.
774 # Call private function to log the error message to syslog.
775 &_log_to_syslog
($error);
777 # Call private function to write/store the error message in the storederrorfile.
778 &_store_error_message
($error);
782 ## Function to log a given error message to the kernel syslog.
784 sub _log_to_syslog
($) {
787 # Load perl module to talk to the kernel syslog.
788 use Sys
::Syslog
qw(:DEFAULT setlogsock);
790 # The syslog function works best with an array based input,
791 # so generate one before passing the message details to syslog.
792 my @syslog = ("ERR", "<ERROR> $message");
794 # Establish the connection to the syslog service.
795 openlog
('oinkmaster', 'cons,pid', 'user');
797 # Send the log message.
800 # Close the log handle.
805 ## Private function to write a given error message to the storederror file.
807 sub _store_error_message
($) {
810 # Remove any newline.
813 # Open file for writing.
814 open (ERRORFILE
, ">$storederrorfile") or die "Could not write to $storederrorfile. $!\n";
816 # Write error to file.
817 print ERRORFILE
"$message\n";
822 # Set correct ownership for the file.
823 &set_ownership
("$storederrorfile");
827 ## Private function to get the path and filename for a downloaded ruleset by a given provider.
829 sub _get_dl_rulesfile
($) {
832 # Gather the download type for the given provider.
833 my $dl_type = $IDS::Ruleset
::Providers
{$provider}{'dl_type'};
835 # Obtain the file suffix for the download file type.
836 my $suffix = $dl_type_to_suffix{$dl_type};
838 # Check if a suffix has been found.
840 # Abort return - nothing.
844 # Generate the full filename and path for the stored rules file.
845 my $rulesfile = "$dl_rules_path/$dl_rulesfile_prefix-$provider$suffix";
847 # Return the generated filename.
852 ## Tiny function to delete the stored ruleset file or tarball for a given provider.
854 sub drop_dl_rulesfile
($) {
857 # Gather the full path and name of the stored rulesfile.
858 my $rulesfile = &_get_dl_rulesfile
($provider);
860 # Check if the given rulesfile exists.
862 # Delete the stored rulesfile.
863 unlink($rulesfile) or die "Could not delete $rulesfile. $!\n";
868 ## Function to check if the IDS is running.
870 sub ids_is_running
() {
872 # Open PID file for reading.
873 open(PIDFILE
, "$idspidfile") or die "Could not open $idspidfile. $!\n";
875 # Grab the process-id.
881 # Remove any newline.
884 # Check if a directory for the process-id exists in proc.
885 if(-d
"/proc/$pid") {
886 # The IDS daemon is running return the process id.
891 # Return nothing - IDS is not running.
896 ## Function to call suricatactrl binary with a given command.
898 sub call_suricatactrl
($) {
900 my ($option, $interval) = @_;
902 # Loop through the array of supported commands and check if
903 # the given one is part of it.
904 foreach my $cmd (@suricatactrl_cmds) {
905 # Skip current command unless the given one has been found.
906 next unless($cmd eq $option);
908 # Check if the given command is "cron".
909 if ($option eq "cron") {
910 # Check if an interval has been given.
912 # Check if the given interval is valid.
913 foreach my $element (@cron_intervals) {
914 # Skip current element until the given one has been found.
915 next unless($element eq $interval);
917 # Call the suricatactrl binary and pass the "cron" command
918 # with the requrested interval.
919 &General
::system("$suricatactrl", "$option", "$interval");
926 # If we got here, the given interval is not supported or none has been given. - Return nothing.
929 # Call the suricatactrl binary and pass the requrested
931 &General
::system("$suricatactrl", "$option");
938 # Command not found - return nothing.
943 ## Function to create a new empty file.
945 sub create_empty_file
($) {
948 # Check if the given file exists.
950 # Do nothing to prevent from overwriting existing files.
954 # Open the file for writing.
955 open(FILE
, ">$file") or die "Could not write to $file. $!\n";
965 ## Private function to check if the file permission of the rulespath are correct.
966 ## If not, call suricatactrl to fix them.
968 sub _check_rulesdir_permissions
() {
969 # Check if the rulepath main directory is writable.
970 unless (-W
$rulespath) {
971 # If not call suricatctrl to fix it.
972 &call_suricatactrl
("fix-rules-dir");
975 # Open snort rules directory and do a directory listing.
976 opendir(DIR
, $rulespath) or die $!;
977 # Loop through the direcory.
978 while (my $file = readdir(DIR
)) {
979 # We only want files.
980 next unless (-f
"$rulespath/$file");
982 # Check if the file is writable by the user.
983 if (-W
"$rulespath/$file") {
984 # Everything is okay - go on to the next file.
987 # There are wrong permissions, call suricatactrl to fix it.
988 &call_suricatactrl
("fix-rules-dir");
994 ## Private function to cleanup the directory which contains
995 ## the IDS rules, before extracting and modifing the new ruleset.
997 sub _cleanup_rulesdir
() {
998 # Open rules directory and do a directory listing.
999 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 # Skip rules file for whitelisted hosts.
1007 next if ("$rulespath/$file" eq $whitelist_file);
1009 # Skip rules file with local rules.
1010 next if ("$rulespath/$file" eq $local_rules_file);
1012 # Delete the current processed file, if not, exit this function
1013 # and return an error message.
1014 unlink("$rulespath/$file") or return "Could not delete $rulespath/$file. $!\n";
1022 ## Function to generate the file which contains the home net information.
1024 sub generate_home_net_file
() {
1027 # Read-in network settings.
1028 &General
::readhash
("${General::swroot}/ethernet/settings", \
%netsettings);
1030 # Get available network zones.
1031 my @network_zones = &Network
::get_available_network_zones
();
1033 # Temporary array to store network address and prefix of the configured
1037 # Loop through the array of available network zones.
1038 foreach my $zone (@network_zones) {
1039 # Check if the current processed zone is red.
1040 if($zone eq "red") {
1041 # Grab the IP-address of the red interface.
1042 my $red_address = &get_red_address
();
1044 # Check if an address has been obtained.
1046 # Generate full network string.
1047 my $red_network = join("/", $red_address, "32");
1049 # Add the red network to the array of networks.
1050 push(@networks, $red_network);
1053 # Check if the configured RED_TYPE is static.
1054 if ($netsettings{'RED_TYPE'} eq "STATIC") {
1055 # Get configured and enabled aliases.
1056 my @aliases = &get_aliases
();
1058 # Loop through the array.
1059 foreach my $alias (@aliases) {
1061 my $network = join("/", $alias, "32");
1063 # Add the generated network to the array of networks.
1064 push(@networks, $network);
1067 # Process remaining network zones.
1069 # Convert current zone name into upper case.
1072 # Generate key to access the required data from the netsettings hash.
1073 my $zone_netaddress = $zone . "_NETADDRESS";
1074 my $zone_netmask = $zone . "_NETMASK";
1076 # Obtain the settings from the netsettings hash.
1077 my $netaddress = $netsettings{$zone_netaddress};
1078 my $netmask = $netsettings{$zone_netmask};
1080 # Convert the subnetmask into prefix notation.
1081 my $prefix = &Network
::convert_netmask2prefix
($netmask);
1083 # Generate full network string.
1084 my $network = join("/", $netaddress,$prefix);
1086 # Check if the network is valid.
1087 if(&Network
::check_subnet
($network)) {
1088 # Add the generated network to the array of networks.
1089 push(@networks, $network);
1094 # Format home net declaration.
1095 my $line = "\"[" . join(',', @networks) . "]\"";
1097 # Open file to store the addresses of the home net.
1098 open(FILE
, ">$homenet_file") or die "Could not open $homenet_file. $!\n";
1100 # Print yaml header.
1101 print FILE
"%YAML 1.1\n";
1102 print FILE
"---\n\n";
1104 # Print notice about autogenerated file.
1105 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1107 # Print the generated and required HOME_NET declaration to the file.
1108 print FILE
"HOME_NET:\t$line\n";
1110 # Close file handle.
1115 # Function to generate and write the file which contains the configured and used DNS servers.
1117 sub generate_dns_servers_file
() {
1118 # Get the used DNS servers.
1119 my @nameservers = &General
::get_nameservers
();
1121 # Get network settings.
1123 &General
::readhash
("${General::swroot}/ethernet/settings", \
%netsettings);
1125 # Format dns servers declaration.
1128 # Check if the system has configured nameservers.
1130 # Add the GREEN address as DNS servers.
1131 push(@nameservers, $netsettings{'GREEN_ADDRESS'});
1133 # Check if a BLUE zone exists.
1134 if ($netsettings{'BLUE_ADDRESS'}) {
1135 # Add the BLUE address to the array of nameservers.
1136 push(@nameservers, $netsettings{'BLUE_ADDRESS'});
1139 # Generate the line which will be written to the DNS servers file.
1140 $line = join(",", @nameservers);
1142 # External net simply contains (any).
1143 $line = "\$EXTERNAL_NET";
1146 # Open file to store the used DNS server addresses.
1147 open(FILE
, ">$dns_servers_file") or die "Could not open $dns_servers_file. $!\n";
1149 # Print yaml header.
1150 print FILE
"%YAML 1.1\n";
1151 print FILE
"---\n\n";
1153 # Print notice about autogenerated file.
1154 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1156 # Print the generated DNS declaration to the file.
1157 print FILE
"DNS_SERVERS:\t\"[$line]\"\n";
1159 # Close file handle.
1164 # Function to generate and write the file which contains the HTTP_PORTS definition.
1166 sub generate_http_ports_file
() {
1169 # Read-in proxy settings
1170 &General
::readhash
("${General::swroot}/proxy/advanced/settings", \
%proxysettings);
1172 # Check if the proxy is enabled.
1173 if (( -e
"${General::swroot}/proxy/enable") || (-e
"${General::swroot}/proxy/enable_blue")) {
1174 # Add the proxy port to the array of HTTP ports.
1175 push(@http_ports, $proxysettings{'PROXY_PORT'});
1178 # Check if the transparent mode of the proxy is enabled.
1179 if ((-e
"${General::swroot}/proxy/transparent") || (-e
"${General::swroot}/proxy/transparent_blue")) {
1180 # Add the transparent proxy port to the array of HTTP ports.
1181 push(@http_ports, $proxysettings{'TRANSPARENT_PORT'});
1184 # Format HTTP_PORTS declaration.
1187 # Generate line which will be written to the http ports file.
1188 $line = join(",", @http_ports);
1190 # Open file to store the HTTP_PORTS.
1191 open(FILE
, ">$http_ports_file") or die "Could not open $http_ports_file. $!\n";
1193 # Print yaml header.
1194 print FILE
"%YAML 1.1\n";
1195 print FILE
"---\n\n";
1197 # Print notice about autogenerated file.
1198 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1200 # Print the generated HTTP_PORTS declaration to the file.
1201 print FILE
"HTTP_PORTS:\t\"[$line]\"\n";
1203 # Close file handle.
1208 ## Function to generate and write the file for used rulefiles.
1210 sub write_used_rulefiles_file
(@
) {
1213 # Open file for used rulefiles.
1214 open (FILE
, ">$used_rulefiles_file") or die "Could not write to $used_rulefiles_file. $!\n";
1216 # Write yaml header to the file.
1217 print FILE
"%YAML 1.1\n";
1218 print FILE
"---\n\n";
1220 # Write header to file.
1221 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1223 # Allways use the whitelist.
1224 print FILE
" - whitelist.rules\n";
1226 # Loop through the array of given files.
1227 foreach my $file (@files) {
1228 # Check if the given filename exists and write it to the file of used rulefiles.
1229 if(-f
"$rulespath/$file") {
1230 print FILE
" - $file\n";
1234 # Close file after writing.
1239 ## Function to generate and write the file for modify the ruleset.
1241 sub write_modify_sids_file
() {
1242 # Get configured settings.
1244 &General
::readhash
("$ids_settings_file", \
%idssettings);
1246 # Open modify sid's file for writing.
1247 open(FILE
, ">$modify_sids_file") or die "Could not write to $modify_sids_file. $!\n";
1249 # Write file header.
1250 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1252 # Check if the traffic only should be monitored.
1253 unless($idssettings{'MONITOR_TRAFFIC_ONLY'} eq 'on') {
1254 # Suricata is in IPS mode, which means that the rule actions have to be changed
1255 # from 'alert' to 'drop', however not all rules should be changed. Some rules
1256 # exist purely to set a flowbit which is used to convey other information, such
1257 # as a specific type of file being downloaded, to other rulewhich then check for
1258 # malware in that file. Rules which fall into the first category should stay as
1259 # alert since not all flows of that type contain malware.
1261 # These types of rulesfiles contain meta-data which gives the action that should
1262 # be used when in IPS mode. Do the following:
1264 # 1. Disable all rules and set the action to 'drop'
1265 # 2. Set the action back to 'alert' if the rule contains 'flowbits:noalert;'
1266 # This should give rules not in the policy a reasonable default if the user
1267 # manually enables them.
1268 # 3. Enable rules and set actions according to the meta-data strings.
1270 my $policy = 'balanced'; # Placeholder to allow policy to be changed.
1273 modifysid * "^#(?:alert|drop)(.+policy $policy-ips alert)" | "alert\${1}"
1274 modifysid * "^#(?:alert|drop)(.+policy $policy-ips drop)" | "drop\${1}"
1275 modifysid * "^(#?)(?:alert|drop)" | "\${1}drop"
1276 modifysid * "^(#?)drop(.+flowbits:noalert;)" | "\${1}alert\${2}"
1280 # Close file handle.
1285 ## Function to gather the version of suricata.
1287 sub get_suricata_version
($) {
1290 # Execute piped suricata command and return the version information.
1291 open(SURICATA
, "suricata -V |") or die "Couldn't execute program: $!";
1293 # Grab and store the output of the piped program.
1294 my $version_string = <SURICATA
>;
1300 chomp($version_string);
1302 # Grab the version from the version string.
1303 $version_string =~ /([0-9]+([.][0-9]+)+)/;
1305 # Splitt the version into single chunks.
1306 my ($major_ver, $minor_ver, $patchlevel) = split(/\./, $1);
1308 # Check and return the requested version sheme.
1309 if ($format eq "major") {
1310 # Return the full version.
1311 return "$major_ver";
1312 } elsif ($format eq "minor") {
1313 # Return the major and minor part.
1314 return "$major_ver.$minor_ver";
1316 # Return the full version string.
1317 return "$major_ver.$minor_ver.$patchlevel";
1322 ## Function to generate the rules file with whitelisted addresses.
1324 sub generate_ignore_file
() {
1327 # SID range 1000000-1999999 Reserved for Local Use
1328 # Put your custom rules in this range to avoid conflicts
1331 # Read-in ignoredfile.
1332 &General
::readhasharray
($IDS::ignored_file
, \
%ignored);
1334 # Open ignorefile for writing.
1335 open(FILE
, ">$IDS::whitelist_file") or die "Could not write to $IDS::whitelist_file. $!\n";
1337 # Config file header.
1338 print FILE
"# Autogenerated file.\n";
1339 print FILE
"# All user modifications will be overwritten.\n\n";
1341 # Add all user defined addresses to the whitelist.
1343 # Check if the hash contains any elements.
1344 if (keys (%ignored)) {
1345 # Loop through the entire hash and write the host/network
1346 # and remark to the ignore file.
1347 while ( (my $key) = each %ignored) {
1348 my $address = $ignored{$key}[0];
1349 my $remark = $ignored{$key}[1];
1350 my $status = $ignored{$key}[2];
1352 # Check if the status of the entry is "enabled".
1353 if ($status eq "enabled") {
1354 # Check if the address/network is valid.
1355 if ((&General
::validip
($address)) || (&General
::validipandmask
($address))) {
1356 # Write rule line to the file to pass any traffic from this IP
1357 print FILE
"pass ip $address any -> any any (msg:\"pass all traffic from/to $address\"\; sid:$sid\;)\n";
1370 ## Function to set correct ownership for single files and directories.
1373 sub set_ownership
($) {
1376 # User and group of the WUI.
1377 my $uname = "nobody";
1378 my $grname = "nobody";
1380 # The chown function implemented in perl requies the user and group as nummeric id's.
1381 my $uid = getpwnam($uname);
1382 my $gid = getgrnam($grname);
1384 # Check if the given target exists.
1386 # Stop the script and print error message.
1387 die "The $target does not exist. Cannot change the ownership!\n";
1390 # Check weather the target is a file or directory.
1392 # Change ownership ot the single file.
1393 chown($uid, $gid, "$target");
1394 } elsif (-d
$target) {
1395 # Do a directory listing.
1396 opendir(DIR
, $target) or die $!;
1397 # Loop through the direcory.
1398 while (my $file = readdir(DIR
)) {
1400 # We only want files.
1401 next unless (-f
"$target/$file");
1403 # Set correct ownership for the files.
1404 chown($uid, $gid, "$target/$file");
1409 # Change ownership of the directory.
1410 chown($uid, $gid, "$target");
1415 ## Function to read-in the aliases file and returns all configured and enabled aliases.
1418 # Location of the aliases file.
1419 my $aliases_file = "${General::swroot}/ethernet/aliases";
1421 # Array to store the aliases.
1424 # Check if the file is empty.
1425 if (-z
$aliases_file) {
1426 # Abort nothing to do.
1430 # Open the aliases file.
1431 open(ALIASES
, $aliases_file) or die "Could not open $aliases_file. $!\n";
1433 # Loop through the file content.
1434 while (my $line = <ALIASES
>) {
1438 # Splitt line content into single chunks.
1439 my ($address, $state, $remark) = split(/\,/, $line);
1441 # Check if the state of the current processed alias is "on".
1442 if ($state eq "on") {
1443 # Check if the address is valid.
1444 if(&Network
::check_ip_address
($address)) {
1445 # Add the alias to the array of aliases.
1446 push(@aliases, $address);
1451 # Close file handle.
1459 ## Function to grab the current assigned IP-address on red.
1461 sub get_red_address
() {
1462 # File, which contains the current IP-address of the red interface.
1463 my $file = "${General::swroot}/red/local-ipaddress";
1465 # Check if the file exists.
1467 # Open the given file.
1468 open(FILE
, "$file") or die "Could not open $file.";
1470 # Obtain the address from the first line of the file.
1471 my $address = <FILE
>;
1479 # Check if the grabbed address is valid.
1480 if (&General
::validip
($address)) {
1481 # Return the address.
1491 ## Function to get all used rulesfiles files.
1493 sub get_used_rulesfiles
() {
1494 # Array to store the used rulefiles.
1495 my @used_rulesfiles = ();
1497 # Check if the used rulesfile is empty.
1498 unless (-z
$used_rulefiles_file) {
1499 # Open the file or used rulefiles and read-in content.
1500 open(FILE
, $used_rulefiles_file) or die "Could not open $used_rulefiles_file. $!\n";
1503 # Assign the current line to a nice variable.
1510 next if ($line =~ /\#/);
1513 next if ($line =~ /^\s*$/);
1515 # Gather the rulefile.
1516 if ($line =~ /.*- (.*)/) {
1519 # Add the rulefile to the array of used rulesfiles.
1520 push(@used_rulesfiles, $rulefile);
1528 # Return the array of used rulesfiles.
1529 return @used_rulesfiles;
1533 ## Function to write the lock file for locking the WUI, while
1534 ## the autoupdate script runs.
1536 sub lock_ids_page
() {
1537 # Call subfunction to create the file.
1538 &create_empty_file
($ids_page_lock_file);
1542 ## Function to release the lock of the WUI, again.
1544 sub unlock_ids_page
() {
1546 unlink($ids_page_lock_file);