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 for checking if at least 300MB of free disk space are available
168 ## on the "/var" partition.
170 sub checkdiskspace
() {
171 # Call diskfree to gather the free disk space of /var.
172 my @df = &General
::system_output
("/bin/df", "-B", "M", "/var");
174 # Loop through the output.
175 foreach my $line (@df) {
176 # Ignore header line.
177 next if $line =~ m/^Filesystem/;
179 # Search for a line with the device information.
180 if ($line =~ m/dev/ ) {
181 # Split the line into single pieces.
182 my @values = split(' ', $line);
183 my ($filesystem, $blocks, $used, $available, $used_perenctage, $mounted_on) = @values;
185 # Check if the available disk space is more than 300MB.
186 if ($available < 300) {
187 # Log error to syslog.
188 &_log_to_syslog
("Not enough free disk space on /var. Only $available MB from 300 MB available.");
190 # Exit function and return "1" - False.
196 # Everything okay, return nothing.
201 ## This function is responsible for downloading the configured IDS rulesets or if no one is specified
202 ## all configured rulesets will be downloaded.
204 ## * At first it gathers all configured ruleset providers, initialize the downloader and sets an
205 ## upstream proxy if configured.
206 ## * After that, the given ruleset or in case all rulesets should be downloaded, it will determine wether it
207 ## is enabled or not.
208 ## * The next step will be to generate the final download url, by obtaining the URL for the desired
209 ## ruleset, add the settings for the upstream proxy.
210 ## * Finally the function will grab all the rules files or tarballs from the servers.
212 sub downloadruleset
($) {
215 # If no provider is given default to "all".
218 # Hash to store the providers and access id's, for which rules should be downloaded.
219 my %sheduled_providers = ();
221 # Get used provider settings.
222 my %used_providers = ();
223 &General
::readhasharray
("$providers_settings_file", \
%used_providers);
225 # Check if a ruleset has been configured.
226 unless(%used_providers) {
227 # Log that no ruleset has been configured and abort.
228 &_log_to_syslog
("No ruleset provider has been configured.");
234 # Read proxysettings.
235 my %proxysettings=();
236 &General
::readhash
("${General::swroot}/proxy/settings", \
%proxysettings);
238 # Load required perl module to handle the download.
241 # Init the download module.
242 my $downloader = LWP
::UserAgent
->new;
244 # Set timeout to 10 seconds.
245 $downloader->timeout(10);
247 # Check if an upstream proxy is configured.
248 if ($proxysettings{'UPSTREAM_PROXY'}) {
251 $proxy_url = "http://";
253 # Check if the proxy requires authentication.
254 if (($proxysettings{'UPSTREAM_USER'}) && ($proxysettings{'UPSTREAM_PASSWORD'})) {
255 $proxy_url .= "$proxysettings{'UPSTREAM_USER'}\:$proxysettings{'UPSTREAM_PASSWORD'}\@";
258 # Add proxy server address and port.
259 $proxy_url .= $proxysettings{'UPSTREAM_PROXY'};
261 # Setup proxy settings.
262 $downloader->proxy(['http', 'https'], $proxy_url);
265 # Loop through the hash of configured providers.
266 foreach my $id ( keys %used_providers ) {
267 # Skip providers which are not enabled.
268 next if ($used_providers{$id}[3] ne "enabled");
270 # Obtain the provider handle.
271 my $provider_handle = $used_providers{$id}[0];
273 # Handle update off all providers.
274 if (($provider eq "all") || ($provider_handle eq "$provider")) {
275 # Add provider handle and it's id to the hash of sheduled providers.
276 $sheduled_providers{$provider_handle} = $id;
280 # Loop through the hash of sheduled providers.
281 foreach my $provider ( keys %sheduled_providers) {
282 # Grab the download url for the provider.
283 my $url = $IDS::Ruleset
::Providers
{$provider}{'dl_url'};
285 # Check if the provider requires a subscription.
286 if ($IDS::Ruleset
::Providers
{$provider}{'requires_subscription'} eq "True") {
287 # Grab the previously stored access id for the provider from hash.
288 my $id = $sheduled_providers{$provider};
290 # Grab the subscription code.
291 my $subscription_code = $used_providers{$id}[1];
293 # Add the subscription code to the download url.
294 $url =~ s/\<subscription_code\>/$subscription_code/g;
298 # Abort if no url could be determined for the provider.
300 # Log error and abort.
301 &_log_to_syslog
("Unable to gather a download URL for the selected ruleset provider.");
305 # Variable to store the filesize of the remote object.
308 # The sourcfire (snort rules) does not allow to send "HEAD" requests, so skip this check
309 # for this webserver.
311 # Check if the ruleset source contains "snort.org".
312 unless ($url =~ /\.snort\.org/) {
313 # Pass the requrested url to the downloader.
314 my $request = HTTP
::Request
->new(HEAD
=> $url);
316 # Accept the html header.
317 $request->header('Accept' => 'text/html');
319 # Perform the request and fetch the html header.
320 my $response = $downloader->request($request);
322 # Check if there was any error.
323 unless ($response->is_success) {
325 my $error = $response->status_line();
328 &_log_to_syslog
("Unable to download the ruleset. \($error\)");
330 # Return "1" - false.
334 # Assign the fetched header object.
335 my $header = $response->headers();
337 # Grab the remote file size from the object and store it in the
339 $remote_filesize = $header->content_length;
342 # Load perl module to deal with temporary files.
345 # Generate temporary file name, located in "/var/tmp" and with a suffix of ".tmp".
346 my $tmp = File
::Temp
->new( SUFFIX
=> ".tmp", DIR
=> "/var/tmp/", UNLINK
=> 0 );
347 my $tmpfile = $tmp->filename();
349 # Pass the requested url to the downloader.
350 my $request = HTTP
::Request
->new(GET
=> $url);
352 # Perform the request and save the output into the tmpfile.
353 my $response = $downloader->request($request, $tmpfile);
355 # Check if there was any error.
356 unless ($response->is_success) {
358 my $error = $response->content;
361 &_log_to_syslog
("Unable to download the ruleset. \($error\)");
363 # Return "1" - false.
367 # Load perl stat module.
370 # Perform stat on the tmpfile.
371 my $stat = stat($tmpfile);
373 # Grab the local filesize of the downloaded tarball.
374 my $local_filesize = $stat->size;
376 # Check if both file sizes match.
377 if (($remote_filesize) && ($remote_filesize ne $local_filesize)) {
379 &_log_to_syslog
("Unable to completely download the ruleset. ");
380 &_log_to_syslog
("Only got $local_filesize Bytes instead of $remote_filesize Bytes. ");
382 # Delete temporary file.
385 # Return "1" - false.
389 # Genarate and assign file name and path to store the downloaded rules file.
390 my $dl_rulesfile = &_get_dl_rulesfile
($provider);
392 # Check if a file name could be obtained.
393 unless ($dl_rulesfile) {
395 &_log_to_syslog
("Unable to store the downloaded rules file. ");
397 # Delete downloaded temporary file.
400 # Return "1" - false.
403 # Load file copy module, which contains the move() function.
406 # Overwrite the may existing rulefile or tarball with the downloaded one.
407 move
("$tmpfile", "$dl_rulesfile");
409 # Delete temporary file.
412 # Set correct ownership for the tarball.
413 set_ownership
("$dl_rulesfile");
416 # If we got here, everything worked fine. Return nothing.
421 ## Function to extract a given ruleset.
423 sub extractruleset
($) {
426 # Load perl module to deal with archives.
429 # Load perl module to deal with files and path.
432 # Get full path and downloaded rulesfile for the given provider.
433 my $tarball = &_get_dl_rulesfile
($provider);
435 # Check if the file exists.
436 unless (-f
$tarball) {
437 &_log_to_syslog
("Could not extract ruleset file: $tarball");
443 # Check if the temporary directories exist, otherwise create them.
444 mkdir("$tmp_directory") unless (-d
"$tmp_directory");
445 mkdir("$tmp_rules_directory") unless (-d
"$tmp_rules_directory");
446 mkdir("$tmp_conf_directory") unless (-d
"$tmp_conf_directory");
448 # Initialize the tar module.
449 my $tar = Archive
::Tar
->new($tarball);
451 # Get the filelist inside the tarball.
452 my @packed_files = $tar->list_files;
454 # Loop through the filelist.
455 foreach my $packed_file (@packed_files) {
458 # Splitt the packed file into chunks.
459 my $file = fileparse
($packed_file);
461 # Handle msg-id.map file.
462 if ("$file" eq "sid-msg.map") {
463 # Set extract destination to temporary config_dir.
464 $destination = "$tmp_conf_directory/$provider\-sid-msg.map";
465 # Handle classification.conf
466 } elsif ("$file" eq "classification.config") {
467 # Set extract destination to temporary config_dir.
468 $destination = "$tmp_conf_directory/$provider\-classification.config";
469 # Handle rules files.
470 } elsif ($file =~ m/\.rules$/) {
473 # Splitt the filename into chunks.
474 my @filename = split("-", $file);
477 @filename = reverse(@filename);
479 # Get the amount of elements in the array.
480 my $elements = @filename;
482 # Remove last element of the hash.
483 # It contains the vendor name, which will be replaced.
484 if ($elements >= 3) {
485 # Remove last element from hash.
489 # Check if the last element of the filename does not
490 # contain the providers name.
491 if ($filename[-1] ne "$provider") {
492 # Add provider name as last element.
493 push(@filename, $provider);
496 # Reverse the array back.
497 @filename = reverse(@filename);
499 # Generate the name for the rulesfile.
500 $rulesfilename = join("-", @filename);
502 # Set extract destination to temporaray rules_dir.
503 $destination = "$tmp_rules_directory/$rulesfilename";
505 # Skip all other files.
509 # Extract the file to the temporary directory.
510 $tar->extract_file("$packed_file", "$destination");
515 ## A wrapper function to call the oinkmaster script, setup the rules structues and
516 ## call the functions to merge the additional config files. (classification, sid-msg, etc.).
519 # Load perl module for file copying.
522 # Hash to store the used providers.
523 my %used_providers = ();
525 # Array to store the enabled providers.
526 my @enabled_providers = ();
528 # Check if the files in rulesdir have the correct permissions.
529 &_check_rulesdir_permissions
();
531 # Cleanup the rules directory before filling it with the new rulests.
532 &_cleanup_rulesdir
();
534 # Read-in the providers config file.
535 &General
::readhasharray
("$providers_settings_file", \
%used_providers);
537 # Loop through the hash of used_providers.
538 foreach my $id (keys %used_providers) {
539 # Skip disabled providers.
540 next unless ($used_providers{$id}[3] eq "enabled");
542 # Grab the provider handle.
543 my $provider = "$used_providers{$id}[0]";
545 # Add the provider handle to the array of enabled providers.
546 push(@enabled_providers, $provider);
548 # Omit the type (dl_type) of the stored ruleset.
549 my $type = $IDS::Ruleset
::Providers
{$provider}{'dl_type'};
551 # Handle the different ruleset types.
552 if ($type eq "archive") {
553 # Call the extractruleset function.
554 &extractruleset
($provider);
555 } elsif ($type eq "plain") {
556 # Generate filename and full path for the stored rulesfile.
557 my $dl_rulesfile = &_get_dl_rulesfile
($provider);
559 # Generate destination filename an full path.
560 my $destination = "$tmp_rules_directory/$provider\-ruleset.rules";
562 # Copy the file into the temporary rules directory.
563 copy
($dl_rulesfile, $destination);
570 # Load perl module to talk to the kernel syslog.
571 use Sys
::Syslog
qw(:DEFAULT setlogsock);
573 # Establish the connection to the syslog service.
574 openlog
('oinkmaster', 'cons,pid', 'user');
576 # Call oinkmaster to generate ruleset.
577 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";
579 # Log output of oinkmaster to syslog.
580 while(<OINKMASTER
>) {
581 # The syslog function works best with an array based input,
582 # so generate one before passing the message details to syslog.
583 my @syslog = ("INFO", "$_");
585 # Send the log message.
589 # Close the pipe to oinkmaster process.
592 # Close the log handle.
597 print Dumper \
@enabled_providers;
599 # Call function to merge the classification files.
600 &merge_classifications
(@enabled_providers);
602 # Call function to merge the sid to message mapping files.
603 &merge_sid_msg
(@enabled_providers);
605 # Cleanup temporary directory.
606 &cleanup_tmp_directory
();
610 ## Function to merge the classifications for a given amount of providers and write them
611 ## to the classifications file.
613 sub merge_classifications
(@
) {
616 # Hash to store all collected classifications.
617 my %classifications = ();
619 # Loop through the given array of providers.
620 foreach my $provider (@providers) {
621 # Generate full path to classification file.
622 my $classification_file = "$tmp_conf_directory/$provider\-classification.config";
624 # Skip provider if no classification file exists.
625 next unless (-f
"$classification_file");
627 # Open the classification file.
628 open(CLASSIFICATION
, $classification_file) or die "Could not open file $classification_file. $!\n";
630 # Loop through the file content.
631 while(<CLASSIFICATION
>) {
632 # Parse the file and grab the classification details.
633 if ($_ =~/.*config classification\: (.*)/) {
634 # Split the grabbed details.
635 my ($short_name, $short_desc, $priority) = split("\,", $1);
637 # Check if the grabbed classification is allready known and the priority value is greater
638 # than the stored one (which causes less priority in the IDS).
639 if (($classifications{$short_name}) && ($classifications{$short_name}[1] >= $priority)) {
640 #Change the priority value to the stricter one.
641 $classifications{$short_name} = [ "$classifications{$short_name}[0]", "$priority" ];
643 # Add the classification to the hash.
644 $classifications{$short_name} = [ "$short_desc", "$priority" ];
650 close(CLASSIFICATION
);
653 # Open classification file for writing.
654 open(FILE
, ">", "$classification_file") or die "Could not write to $classification_file. $!\n";
656 # Print notice about autogenerated file.
657 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n\n";
659 # Sort and loop through the hash of classifications.
660 foreach my $key (sort keys %classifications) {
661 # Assign some nice variable names for the items.
662 my $short_name = $key;
663 my $short_desc = $classifications{$key}[0];
664 my $priority = $classifications{$key}[1];
666 # Write the classification to the file.
667 print FILE
"config classification: $short_name,$short_desc,$priority\n";
675 ## Function to merge the "sid to message mapping" files of various given providers.
677 sub merge_sid_msg
(@
) {
680 # Hash which contains all the sid to message mappings.
683 # Loop through the array of given providers.
684 foreach my $provider (@providers) {
685 # Generate full path and filename.
686 my $sid_msg_file = "$tmp_conf_directory/$provider\-sid-msg.map";
688 # Skip provider if no sid to msg mapping file for this provider exists.
689 next unless (-f
$sid_msg_file);
692 open(MAPPING
, $sid_msg_file) or die "Could not open $sid_msg_file. $!\n";
694 # Loop through the file content.
699 # Skip lines which do not start with a number,
700 next unless ($_ =~ /^\d+/);
702 # Split line content and assign it to an array.
703 my @line = split(/ \|\| /, $_);
705 # Grab the first element (and remove it) from the line array.
706 # It contains the sid.
707 my $sid = shift(@line);
709 # Store the grabbed sid and the remain array as hash value.
710 # It still contains the messages, references etc.
711 $mappings{$sid} = [@line];
718 # Open mappings file for writing.
719 open(FILE
, ">", $sid_msg_file) or die "Could not write $sid_msg_file. $!\n";
721 # Write notice about autogenerated file.
722 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n\n";
724 # Loop through the hash of mappings.
725 foreach my $sid ( sort keys %mappings) {
726 # Grab data for the sid.
727 my @data = @
{$mappings{$sid}};
729 # Add the sid to the data array.
730 unshift(@data, $sid);
733 my $line = join(" \|\| ", @data);
735 print FILE
"$line\n";
744 ## Function to cleanup the temporary IDS directroy.
746 sub cleanup_tmp_directory
() {
747 # Load rmtree() function from file path perl module.
748 use File
::Path
'rmtree';
750 # Delete temporary directory and all containing files.
751 rmtree
([ "$tmp_directory" ]);
755 ## Function to do all the logging stuff if the downloading or updating of the ruleset fails.
760 # Remove any newline.
763 # Call private function to log the error message to syslog.
764 &_log_to_syslog
($error);
766 # Call private function to write/store the error message in the storederrorfile.
767 &_store_error_message
($error);
771 ## Function to log a given error message to the kernel syslog.
773 sub _log_to_syslog
($) {
776 # Load perl module to talk to the kernel syslog.
777 use Sys
::Syslog
qw(:DEFAULT setlogsock);
779 # The syslog function works best with an array based input,
780 # so generate one before passing the message details to syslog.
781 my @syslog = ("ERR", "<ERROR> $message");
783 # Establish the connection to the syslog service.
784 openlog
('oinkmaster', 'cons,pid', 'user');
786 # Send the log message.
789 # Close the log handle.
794 ## Private function to write a given error message to the storederror file.
796 sub _store_error_message
($) {
799 # Remove any newline.
802 # Open file for writing.
803 open (ERRORFILE
, ">$storederrorfile") or die "Could not write to $storederrorfile. $!\n";
805 # Write error to file.
806 print ERRORFILE
"$message\n";
811 # Set correct ownership for the file.
812 &set_ownership
("$storederrorfile");
816 ## Private function to get the path and filename for a downloaded ruleset by a given provider.
818 sub _get_dl_rulesfile
($) {
821 # Gather the download type for the given provider.
822 my $dl_type = $IDS::Ruleset
::Providers
{$provider}{'dl_type'};
824 # Obtain the file suffix for the download file type.
825 my $suffix = $dl_type_to_suffix{$dl_type};
827 # Check if a suffix has been found.
829 # Abort return - nothing.
833 # Generate the full filename and path for the stored rules file.
834 my $rulesfile = "$dl_rules_path/$dl_rulesfile_prefix-$provider$suffix";
836 # Return the generated filename.
841 ## Function to check if the IDS is running.
843 sub ids_is_running
() {
845 # Open PID file for reading.
846 open(PIDFILE
, "$idspidfile") or die "Could not open $idspidfile. $!\n";
848 # Grab the process-id.
854 # Remove any newline.
857 # Check if a directory for the process-id exists in proc.
858 if(-d
"/proc/$pid") {
859 # The IDS daemon is running return the process id.
864 # Return nothing - IDS is not running.
869 ## Function to call suricatactrl binary with a given command.
871 sub call_suricatactrl
($) {
873 my ($option, $interval) = @_;
875 # Loop through the array of supported commands and check if
876 # the given one is part of it.
877 foreach my $cmd (@suricatactrl_cmds) {
878 # Skip current command unless the given one has been found.
879 next unless($cmd eq $option);
881 # Check if the given command is "cron".
882 if ($option eq "cron") {
883 # Check if an interval has been given.
885 # Check if the given interval is valid.
886 foreach my $element (@cron_intervals) {
887 # Skip current element until the given one has been found.
888 next unless($element eq $interval);
890 # Call the suricatactrl binary and pass the "cron" command
891 # with the requrested interval.
892 &General
::system("$suricatactrl", "$option", "$interval");
899 # If we got here, the given interval is not supported or none has been given. - Return nothing.
902 # Call the suricatactrl binary and pass the requrested
904 &General
::system("$suricatactrl", "$option");
911 # Command not found - return nothing.
916 ## Function to create a new empty file.
918 sub create_empty_file
($) {
921 # Check if the given file exists.
923 # Do nothing to prevent from overwriting existing files.
927 # Open the file for writing.
928 open(FILE
, ">$file") or die "Could not write to $file. $!\n";
938 ## Private function to check if the file permission of the rulespath are correct.
939 ## If not, call suricatactrl to fix them.
941 sub _check_rulesdir_permissions
() {
942 # Check if the rulepath main directory is writable.
943 unless (-W
$rulespath) {
944 # If not call suricatctrl to fix it.
945 &call_suricatactrl
("fix-rules-dir");
948 # Open snort rules directory and do a directory listing.
949 opendir(DIR
, $rulespath) or die $!;
950 # Loop through the direcory.
951 while (my $file = readdir(DIR
)) {
952 # We only want files.
953 next unless (-f
"$rulespath/$file");
955 # Check if the file is writable by the user.
956 if (-W
"$rulespath/$file") {
957 # Everything is okay - go on to the next file.
960 # There are wrong permissions, call suricatactrl to fix it.
961 &call_suricatactrl
("fix-rules-dir");
967 ## Private function to cleanup the directory which contains
968 ## the IDS rules, before extracting and modifing the new ruleset.
970 sub _cleanup_rulesdir
() {
971 # Open rules directory and do a directory listing.
972 opendir(DIR
, $rulespath) or die $!;
974 # Loop through the direcory.
975 while (my $file = readdir(DIR
)) {
976 # We only want files.
977 next unless (-f
"$rulespath/$file");
979 # Skip rules file for whitelisted hosts.
980 next if ("$rulespath/$file" eq $whitelist_file);
982 # Skip rules file with local rules.
983 next if ("$rulespath/$file" eq $local_rules_file);
985 # Delete the current processed file, if not, exit this function
986 # and return an error message.
987 unlink("$rulespath/$file") or return "Could not delete $rulespath/$file. $!\n";
995 ## Function to generate the file which contains the home net information.
997 sub generate_home_net_file
() {
1000 # Read-in network settings.
1001 &General
::readhash
("${General::swroot}/ethernet/settings", \
%netsettings);
1003 # Get available network zones.
1004 my @network_zones = &Network
::get_available_network_zones
();
1006 # Temporary array to store network address and prefix of the configured
1010 # Loop through the array of available network zones.
1011 foreach my $zone (@network_zones) {
1012 # Check if the current processed zone is red.
1013 if($zone eq "red") {
1014 # Grab the IP-address of the red interface.
1015 my $red_address = &get_red_address
();
1017 # Check if an address has been obtained.
1019 # Generate full network string.
1020 my $red_network = join("/", $red_address, "32");
1022 # Add the red network to the array of networks.
1023 push(@networks, $red_network);
1026 # Check if the configured RED_TYPE is static.
1027 if ($netsettings{'RED_TYPE'} eq "STATIC") {
1028 # Get configured and enabled aliases.
1029 my @aliases = &get_aliases
();
1031 # Loop through the array.
1032 foreach my $alias (@aliases) {
1034 my $network = join("/", $alias, "32");
1036 # Add the generated network to the array of networks.
1037 push(@networks, $network);
1040 # Process remaining network zones.
1042 # Convert current zone name into upper case.
1045 # Generate key to access the required data from the netsettings hash.
1046 my $zone_netaddress = $zone . "_NETADDRESS";
1047 my $zone_netmask = $zone . "_NETMASK";
1049 # Obtain the settings from the netsettings hash.
1050 my $netaddress = $netsettings{$zone_netaddress};
1051 my $netmask = $netsettings{$zone_netmask};
1053 # Convert the subnetmask into prefix notation.
1054 my $prefix = &Network
::convert_netmask2prefix
($netmask);
1056 # Generate full network string.
1057 my $network = join("/", $netaddress,$prefix);
1059 # Check if the network is valid.
1060 if(&Network
::check_subnet
($network)) {
1061 # Add the generated network to the array of networks.
1062 push(@networks, $network);
1067 # Format home net declaration.
1068 my $line = "\"[" . join(',', @networks) . "]\"";
1070 # Open file to store the addresses of the home net.
1071 open(FILE
, ">$homenet_file") or die "Could not open $homenet_file. $!\n";
1073 # Print yaml header.
1074 print FILE
"%YAML 1.1\n";
1075 print FILE
"---\n\n";
1077 # Print notice about autogenerated file.
1078 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1080 # Print the generated and required HOME_NET declaration to the file.
1081 print FILE
"HOME_NET:\t$line\n";
1083 # Close file handle.
1088 # Function to generate and write the file which contains the configured and used DNS servers.
1090 sub generate_dns_servers_file
() {
1091 # Get the used DNS servers.
1092 my @nameservers = &General
::get_nameservers
();
1094 # Get network settings.
1096 &General
::readhash
("${General::swroot}/ethernet/settings", \
%netsettings);
1098 # Format dns servers declaration.
1101 # Check if the system has configured nameservers.
1103 # Add the GREEN address as DNS servers.
1104 push(@nameservers, $netsettings{'GREEN_ADDRESS'});
1106 # Check if a BLUE zone exists.
1107 if ($netsettings{'BLUE_ADDRESS'}) {
1108 # Add the BLUE address to the array of nameservers.
1109 push(@nameservers, $netsettings{'BLUE_ADDRESS'});
1112 # Generate the line which will be written to the DNS servers file.
1113 $line = join(",", @nameservers);
1115 # External net simply contains (any).
1116 $line = "\$EXTERNAL_NET";
1119 # Open file to store the used DNS server addresses.
1120 open(FILE
, ">$dns_servers_file") or die "Could not open $dns_servers_file. $!\n";
1122 # Print yaml header.
1123 print FILE
"%YAML 1.1\n";
1124 print FILE
"---\n\n";
1126 # Print notice about autogenerated file.
1127 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1129 # Print the generated DNS declaration to the file.
1130 print FILE
"DNS_SERVERS:\t\"[$line]\"\n";
1132 # Close file handle.
1137 # Function to generate and write the file which contains the HTTP_PORTS definition.
1139 sub generate_http_ports_file
() {
1142 # Read-in proxy settings
1143 &General
::readhash
("${General::swroot}/proxy/advanced/settings", \
%proxysettings);
1145 # Check if the proxy is enabled.
1146 if (( -e
"${General::swroot}/proxy/enable") || (-e
"${General::swroot}/proxy/enable_blue")) {
1147 # Add the proxy port to the array of HTTP ports.
1148 push(@http_ports, $proxysettings{'PROXY_PORT'});
1151 # Check if the transparent mode of the proxy is enabled.
1152 if ((-e
"${General::swroot}/proxy/transparent") || (-e
"${General::swroot}/proxy/transparent_blue")) {
1153 # Add the transparent proxy port to the array of HTTP ports.
1154 push(@http_ports, $proxysettings{'TRANSPARENT_PORT'});
1157 # Format HTTP_PORTS declaration.
1160 # Generate line which will be written to the http ports file.
1161 $line = join(",", @http_ports);
1163 # Open file to store the HTTP_PORTS.
1164 open(FILE
, ">$http_ports_file") or die "Could not open $http_ports_file. $!\n";
1166 # Print yaml header.
1167 print FILE
"%YAML 1.1\n";
1168 print FILE
"---\n\n";
1170 # Print notice about autogenerated file.
1171 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1173 # Print the generated HTTP_PORTS declaration to the file.
1174 print FILE
"HTTP_PORTS:\t\"[$line]\"\n";
1176 # Close file handle.
1181 ## Function to generate and write the file for used rulefiles.
1183 sub write_used_rulefiles_file
(@
) {
1186 # Open file for used rulefiles.
1187 open (FILE
, ">$used_rulefiles_file") or die "Could not write to $used_rulefiles_file. $!\n";
1189 # Write yaml header to the file.
1190 print FILE
"%YAML 1.1\n";
1191 print FILE
"---\n\n";
1193 # Write header to file.
1194 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1196 # Allways use the whitelist.
1197 print FILE
" - whitelist.rules\n";
1199 # Loop through the array of given files.
1200 foreach my $file (@files) {
1201 # Check if the given filename exists and write it to the file of used rulefiles.
1202 if(-f
"$rulespath/$file") {
1203 print FILE
" - $file\n";
1207 # Close file after writing.
1212 ## Function to generate and write the file for modify the ruleset.
1214 sub write_modify_sids_file
() {
1215 # Get configured settings.
1217 &General
::readhash
("$ids_settings_file", \
%idssettings);
1219 # Open modify sid's file for writing.
1220 open(FILE
, ">$modify_sids_file") or die "Could not write to $modify_sids_file. $!\n";
1222 # Write file header.
1223 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1225 # Check if the traffic only should be monitored.
1226 unless($idssettings{'MONITOR_TRAFFIC_ONLY'} eq 'on') {
1227 # Suricata is in IPS mode, which means that the rule actions have to be changed
1228 # from 'alert' to 'drop', however not all rules should be changed. Some rules
1229 # exist purely to set a flowbit which is used to convey other information, such
1230 # as a specific type of file being downloaded, to other rulewhich then check for
1231 # malware in that file. Rules which fall into the first category should stay as
1232 # alert since not all flows of that type contain malware.
1234 # These types of rulesfiles contain meta-data which gives the action that should
1235 # be used when in IPS mode. Do the following:
1237 # 1. Disable all rules and set the action to 'drop'
1238 # 2. Set the action back to 'alert' if the rule contains 'flowbits:noalert;'
1239 # This should give rules not in the policy a reasonable default if the user
1240 # manually enables them.
1241 # 3. Enable rules and set actions according to the meta-data strings.
1243 my $policy = 'balanced'; # Placeholder to allow policy to be changed.
1246 modifysid * "^#(?:alert|drop)(.+policy $policy-ips alert)" | "alert\${1}"
1247 modifysid * "^#(?:alert|drop)(.+policy $policy-ips drop)" | "drop\${1}"
1248 modifysid * "^(#?)(?:alert|drop)" | "\${1}drop"
1249 modifysid * "^(#?)drop(.+flowbits:noalert;)" | "\${1}alert\${2}"
1253 # Close file handle.
1258 ## Function to gather the version of suricata.
1260 sub get_suricata_version
($) {
1263 # Execute piped suricata command and return the version information.
1264 open(SURICATA
, "suricata -V |") or die "Couldn't execute program: $!";
1266 # Grab and store the output of the piped program.
1267 my $version_string = <SURICATA
>;
1273 chomp($version_string);
1275 # Grab the version from the version string.
1276 $version_string =~ /([0-9]+([.][0-9]+)+)/;
1278 # Splitt the version into single chunks.
1279 my ($major_ver, $minor_ver, $patchlevel) = split(/\./, $1);
1281 # Check and return the requested version sheme.
1282 if ($format eq "major") {
1283 # Return the full version.
1284 return "$major_ver";
1285 } elsif ($format eq "minor") {
1286 # Return the major and minor part.
1287 return "$major_ver.$minor_ver";
1289 # Return the full version string.
1290 return "$major_ver.$minor_ver.$patchlevel";
1295 ## Function to generate the rules file with whitelisted addresses.
1297 sub generate_ignore_file
() {
1300 # SID range 1000000-1999999 Reserved for Local Use
1301 # Put your custom rules in this range to avoid conflicts
1304 # Read-in ignoredfile.
1305 &General
::readhasharray
($IDS::ignored_file
, \
%ignored);
1307 # Open ignorefile for writing.
1308 open(FILE
, ">$IDS::whitelist_file") or die "Could not write to $IDS::whitelist_file. $!\n";
1310 # Config file header.
1311 print FILE
"# Autogenerated file.\n";
1312 print FILE
"# All user modifications will be overwritten.\n\n";
1314 # Add all user defined addresses to the whitelist.
1316 # Check if the hash contains any elements.
1317 if (keys (%ignored)) {
1318 # Loop through the entire hash and write the host/network
1319 # and remark to the ignore file.
1320 while ( (my $key) = each %ignored) {
1321 my $address = $ignored{$key}[0];
1322 my $remark = $ignored{$key}[1];
1323 my $status = $ignored{$key}[2];
1325 # Check if the status of the entry is "enabled".
1326 if ($status eq "enabled") {
1327 # Check if the address/network is valid.
1328 if ((&General
::validip
($address)) || (&General
::validipandmask
($address))) {
1329 # Write rule line to the file to pass any traffic from this IP
1330 print FILE
"pass ip $address any -> any any (msg:\"pass all traffic from/to $address\"\; sid:$sid\;)\n";
1343 ## Function to set correct ownership for single files and directories.
1346 sub set_ownership
($) {
1349 # User and group of the WUI.
1350 my $uname = "nobody";
1351 my $grname = "nobody";
1353 # The chown function implemented in perl requies the user and group as nummeric id's.
1354 my $uid = getpwnam($uname);
1355 my $gid = getgrnam($grname);
1357 # Check if the given target exists.
1359 # Stop the script and print error message.
1360 die "The $target does not exist. Cannot change the ownership!\n";
1363 # Check weather the target is a file or directory.
1365 # Change ownership ot the single file.
1366 chown($uid, $gid, "$target");
1367 } elsif (-d
$target) {
1368 # Do a directory listing.
1369 opendir(DIR
, $target) or die $!;
1370 # Loop through the direcory.
1371 while (my $file = readdir(DIR
)) {
1373 # We only want files.
1374 next unless (-f
"$target/$file");
1376 # Set correct ownership for the files.
1377 chown($uid, $gid, "$target/$file");
1382 # Change ownership of the directory.
1383 chown($uid, $gid, "$target");
1388 ## Function to read-in the aliases file and returns all configured and enabled aliases.
1391 # Location of the aliases file.
1392 my $aliases_file = "${General::swroot}/ethernet/aliases";
1394 # Array to store the aliases.
1397 # Check if the file is empty.
1398 if (-z
$aliases_file) {
1399 # Abort nothing to do.
1403 # Open the aliases file.
1404 open(ALIASES
, $aliases_file) or die "Could not open $aliases_file. $!\n";
1406 # Loop through the file content.
1407 while (my $line = <ALIASES
>) {
1411 # Splitt line content into single chunks.
1412 my ($address, $state, $remark) = split(/\,/, $line);
1414 # Check if the state of the current processed alias is "on".
1415 if ($state eq "on") {
1416 # Check if the address is valid.
1417 if(&Network
::check_ip_address
($address)) {
1418 # Add the alias to the array of aliases.
1419 push(@aliases, $address);
1424 # Close file handle.
1432 ## Function to grab the current assigned IP-address on red.
1434 sub get_red_address
() {
1435 # File, which contains the current IP-address of the red interface.
1436 my $file = "${General::swroot}/red/local-ipaddress";
1438 # Check if the file exists.
1440 # Open the given file.
1441 open(FILE
, "$file") or die "Could not open $file.";
1443 # Obtain the address from the first line of the file.
1444 my $address = <FILE
>;
1452 # Check if the grabbed address is valid.
1453 if (&General
::validip
($address)) {
1454 # Return the address.
1464 ## Function to write the lock file for locking the WUI, while
1465 ## the autoupdate script runs.
1467 sub lock_ids_page
() {
1468 # Call subfunction to create the file.
1469 &create_empty_file
($ids_page_lock_file);
1473 ## Function to release the lock of the WUI, again.
1475 sub unlock_ids_page
() {
1477 unlink($ids_page_lock_file);