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 # File for static ruleset inclusions.
39 our $suricata_static_rulefiles_file = "$settingsdir/suricata-static-included-rulefiles.yaml";
41 # DEPRECATED - File where the used rulefiles are stored.
42 our $used_rulefiles_file = "$settingsdir/suricata-used-rulefiles.yaml";
44 # File where the addresses of the homenet are stored.
45 our $homenet_file = "$settingsdir/suricata-homenet.yaml";
47 # File where the addresses of the used DNS servers are stored.
48 our $dns_servers_file = "$settingsdir/suricata-dns-servers.yaml";
50 # File where the HTTP ports definition is stored.
51 our $http_ports_file = "$settingsdir/suricata-http-ports.yaml";
53 # DEPRECATED - File which contains the enabled sids.
54 our $enabled_sids_file = "$settingsdir/oinkmaster-enabled-sids.conf";
56 # DEPRECATED - File which contains the disabled sids.
57 our $disabled_sids_file = "$settingsdir/oinkmaster-disabled-sids.conf";
59 # File which contains includes for provider specific rule modifications.
60 our $oinkmaster_provider_includes_file = "$settingsdir/oinkmaster-provider-includes.conf";
62 # File which contains wheater the rules should be changed.
63 our $modify_sids_file = "$settingsdir/oinkmaster-modify-sids.conf";
65 # File which stores the configured IPS settings.
66 our $ids_settings_file = "$settingsdir/settings";
68 # DEPRECATED - File which stores the configured rules-settings.
69 our $rules_settings_file = "$settingsdir/rules-settings";
71 # File which stores the used and configured ruleset providers.
72 our $providers_settings_file = "$settingsdir/providers-settings";
74 # File which stores the configured settings for whitelisted addresses.
75 our $ignored_file = "$settingsdir/ignored";
77 # DEPRECATED - Location and name of the tarball which contains the ruleset.
78 our $rulestarball = "/var/tmp/idsrules.tar.gz";
80 # Location where the downloaded rulesets are stored.
81 our $dl_rules_path = "/var/tmp";
83 # File to store any errors, which also will be read and displayed by the wui.
84 our $storederrorfile = "/tmp/ids_storederror";
86 # File to lock the WUI, while the autoupdate script runs.
87 our $ids_page_lock_file = "/tmp/ids_page_locked";
89 # Location where the rulefiles are stored.
90 our $rulespath = "/var/lib/suricata";
92 # Location of the classification file.
93 our $classification_file = "$rulespath/classification.config";
95 # Location of the sid to msg mappings file.
96 our $sid_msg_file = "$rulespath/sid-msg.map";
98 # Location to store local rules. This file will not be touched.
99 our $local_rules_file = "$rulespath/local.rules";
101 # File which contains the rules to whitelist addresses on suricata.
102 our $whitelist_file = "$rulespath/whitelist.rules";
104 # File which contains a list of all supported ruleset sources.
105 # (Sourcefire, Emergingthreads, etc..)
106 our $rulesetsourcesfile = "$settingsdir/ruleset-sources";
108 # The pidfile of the IDS.
109 our $idspidfile = "/var/run/suricata.pid";
111 # Location of suricatactrl.
112 my $suricatactrl = "/usr/local/bin/suricatactrl";
114 # Prefix for each downloaded ruleset.
115 my $dl_rulesfile_prefix = "idsrules";
117 # Temporary directory where the rulesets will be extracted.
118 my $tmp_directory = "/tmp/ids_tmp";
120 # Temporary directory where the extracted rules files will be stored.
121 my $tmp_rules_directory = "$tmp_directory/rules";
123 # Temporary directory where the extracted additional config files will be stored.
124 my $tmp_conf_directory = "$tmp_directory/conf";
126 # Array with allowed commands of suricatactrl.
127 my @suricatactrl_cmds = ( 'start', 'stop', 'restart', 'reload', 'fix-rules-dir', 'cron' );
129 # Array with supported cron intervals.
130 my @cron_intervals = ('off', 'daily', 'weekly' );
132 # Array which contains the HTTP ports, which statically will be declared as HTTP_PORTS in the
134 my @http_ports = ('80', '81');
136 # Array which contains a list of rulefiles which always will be included if they exist.
137 my @static_included_rulefiles = ('local.rules', 'whitelist.rules' );
139 # Hash which allows to convert the download type (dl_type) to a file suffix.
140 my %dl_type_to_suffix = (
141 "archive" => ".tar.gz",
146 ## Function to check and create all IDS related files, if the does not exist.
148 sub check_and_create_filelayout
() {
149 # Check if the files exist and if not, create them.
150 unless (-f
"$oinkmaster_provider_includes_file") { &create_empty_file
($oinkmaster_provider_includes_file); }
151 unless (-f
"$modify_sids_file") { &create_empty_file
($modify_sids_file); }
152 unless (-f
"$suricata_used_providers_file") { &create_empty_file
($suricata_used_providers_file); }
153 unless (-f
"$ids_settings_file") { &create_empty_file
($ids_settings_file); }
154 unless (-f
"$providers_settings_file") { &create_empty_file
($providers_settings_file); }
155 unless (-f
"$ignored_file") { &create_empty_file
($ignored_file); }
156 unless (-f
"$whitelist_file" ) { &create_empty_file
($whitelist_file); }
160 ## Function to get a list of all available ruleset providers.
162 ## They will be returned as a sorted array.
164 sub get_ruleset_providers
() {
167 # Loop through the hash of providers.
168 foreach my $provider ( keys %IDS::Ruleset
::Providers
) {
169 # Add the provider to the array.
170 push(@providers, $provider);
173 # Sort and return the array.
174 return sort(@providers);
178 ## Function to get a list of all enabled ruleset providers.
180 ## They will be returned as an array.
182 sub get_enabled_providers
() {
183 my %used_providers = ();
185 # Array to store the enabled providers.
186 my @enabled_providers = ();
188 # Read-in the providers config file.
189 &General
::readhasharray
("$providers_settings_file", \
%used_providers);
191 # Loop through the hash of used_providers.
192 foreach my $id (keys %used_providers) {
193 # Skip disabled providers.
194 next unless ($used_providers{$id}[3] eq "enabled");
196 # Grab the provider handle.
197 my $provider = "$used_providers{$id}[0]";
199 # Add the provider to the array of enabled providers.
200 push(@enabled_providers, $provider);
204 return @enabled_providers;
208 ## Function for checking if at least 300MB of free disk space are available
209 ## on the "/var" partition.
211 sub checkdiskspace
() {
212 # Call diskfree to gather the free disk space of /var.
213 my @df = &General
::system_output
("/bin/df", "-B", "M", "/var");
215 # Loop through the output.
216 foreach my $line (@df) {
217 # Ignore header line.
218 next if $line =~ m/^Filesystem/;
220 # Search for a line with the device information.
221 if ($line =~ m/dev/ ) {
222 # Split the line into single pieces.
223 my @values = split(' ', $line);
224 my ($filesystem, $blocks, $used, $available, $used_perenctage, $mounted_on) = @values;
226 # Check if the available disk space is more than 300MB.
227 if ($available < 300) {
228 # Log error to syslog.
229 &_log_to_syslog
("Not enough free disk space on /var. Only $available MB from 300 MB available.");
231 # Exit function and return "1" - False.
237 # Everything okay, return nothing.
242 ## This function is responsible for downloading the configured IDS rulesets or if no one is specified
243 ## all configured rulesets will be downloaded.
245 ## * At first it gathers all configured ruleset providers, initialize the downloader and sets an
246 ## upstream proxy if configured.
247 ## * After that, the given ruleset or in case all rulesets should be downloaded, it will determine wether it
248 ## is enabled or not.
249 ## * The next step will be to generate the final download url, by obtaining the URL for the desired
250 ## ruleset, add the settings for the upstream proxy.
251 ## * Finally the function will grab all the rules files or tarballs from the servers.
253 sub downloadruleset
($) {
256 # If no provider is given default to "all".
259 # Hash to store the providers and access id's, for which rules should be downloaded.
260 my %sheduled_providers = ();
262 # Get used provider settings.
263 my %used_providers = ();
264 &General
::readhasharray
("$providers_settings_file", \
%used_providers);
266 # Check if a ruleset has been configured.
267 unless(%used_providers) {
268 # Log that no ruleset has been configured and abort.
269 &_log_to_syslog
("No ruleset provider has been configured.");
275 # Read proxysettings.
276 my %proxysettings=();
277 &General
::readhash
("${General::swroot}/proxy/settings", \
%proxysettings);
279 # Load required perl module to handle the download.
282 # Init the download module.
283 my $downloader = LWP
::UserAgent
->new;
285 # Set timeout to 10 seconds.
286 $downloader->timeout(10);
288 # Check if an upstream proxy is configured.
289 if ($proxysettings{'UPSTREAM_PROXY'}) {
292 $proxy_url = "http://";
294 # Check if the proxy requires authentication.
295 if (($proxysettings{'UPSTREAM_USER'}) && ($proxysettings{'UPSTREAM_PASSWORD'})) {
296 $proxy_url .= "$proxysettings{'UPSTREAM_USER'}\:$proxysettings{'UPSTREAM_PASSWORD'}\@";
299 # Add proxy server address and port.
300 $proxy_url .= $proxysettings{'UPSTREAM_PROXY'};
302 # Setup proxy settings.
303 $downloader->proxy(['http', 'https'], $proxy_url);
306 # Loop through the hash of configured providers.
307 foreach my $id ( keys %used_providers ) {
308 # Skip providers which are not enabled.
309 next if ($used_providers{$id}[3] ne "enabled");
311 # Obtain the provider handle.
312 my $provider_handle = $used_providers{$id}[0];
314 # Handle update off all providers.
315 if (($provider eq "all") || ($provider_handle eq "$provider")) {
316 # Add provider handle and it's id to the hash of sheduled providers.
317 $sheduled_providers{$provider_handle} = $id;
321 # Loop through the hash of sheduled providers.
322 foreach my $provider ( keys %sheduled_providers) {
323 # Grab the download url for the provider.
324 my $url = $IDS::Ruleset
::Providers
{$provider}{'dl_url'};
326 # Check if the provider requires a subscription.
327 if ($IDS::Ruleset
::Providers
{$provider}{'requires_subscription'} eq "True") {
328 # Grab the previously stored access id for the provider from hash.
329 my $id = $sheduled_providers{$provider};
331 # Grab the subscription code.
332 my $subscription_code = $used_providers{$id}[1];
334 # Add the subscription code to the download url.
335 $url =~ s/\<subscription_code\>/$subscription_code/g;
339 # Abort if no url could be determined for the provider.
341 # Log error and abort.
342 &_log_to_syslog
("Unable to gather a download URL for the selected ruleset provider.");
346 # Variable to store the filesize of the remote object.
349 # The sourcfire (snort rules) does not allow to send "HEAD" requests, so skip this check
350 # for this webserver.
352 # Check if the ruleset source contains "snort.org".
353 unless ($url =~ /\.snort\.org/) {
354 # Pass the requrested url to the downloader.
355 my $request = HTTP
::Request
->new(HEAD
=> $url);
357 # Accept the html header.
358 $request->header('Accept' => 'text/html');
360 # Perform the request and fetch the html header.
361 my $response = $downloader->request($request);
363 # Check if there was any error.
364 unless ($response->is_success) {
366 my $error = $response->status_line();
369 &_log_to_syslog
("Unable to download the ruleset. \($error\)");
371 # Return "1" - false.
375 # Assign the fetched header object.
376 my $header = $response->headers();
378 # Grab the remote file size from the object and store it in the
380 $remote_filesize = $header->content_length;
383 # Load perl module to deal with temporary files.
386 # Generate temporary file name, located in "/var/tmp" and with a suffix of ".tmp".
387 my $tmp = File
::Temp
->new( SUFFIX
=> ".tmp", DIR
=> "/var/tmp/", UNLINK
=> 0 );
388 my $tmpfile = $tmp->filename();
390 # Pass the requested url to the downloader.
391 my $request = HTTP
::Request
->new(GET
=> $url);
393 # Perform the request and save the output into the tmpfile.
394 my $response = $downloader->request($request, $tmpfile);
396 # Check if there was any error.
397 unless ($response->is_success) {
399 my $error = $response->content;
402 &_log_to_syslog
("Unable to download the ruleset. \($error\)");
404 # Return "1" - false.
408 # Load perl stat module.
411 # Perform stat on the tmpfile.
412 my $stat = stat($tmpfile);
414 # Grab the local filesize of the downloaded tarball.
415 my $local_filesize = $stat->size;
417 # Check if both file sizes match.
418 if (($remote_filesize) && ($remote_filesize ne $local_filesize)) {
420 &_log_to_syslog
("Unable to completely download the ruleset. ");
421 &_log_to_syslog
("Only got $local_filesize Bytes instead of $remote_filesize Bytes. ");
423 # Delete temporary file.
426 # Return "1" - false.
430 # Genarate and assign file name and path to store the downloaded rules file.
431 my $dl_rulesfile = &_get_dl_rulesfile
($provider);
433 # Check if a file name could be obtained.
434 unless ($dl_rulesfile) {
436 &_log_to_syslog
("Unable to store the downloaded rules file. ");
438 # Delete downloaded temporary file.
441 # Return "1" - false.
444 # Load file copy module, which contains the move() function.
447 # Overwrite the may existing rulefile or tarball with the downloaded one.
448 move
("$tmpfile", "$dl_rulesfile");
450 # Delete temporary file.
453 # Set correct ownership for the tarball.
454 set_ownership
("$dl_rulesfile");
457 # If we got here, everything worked fine. Return nothing.
462 ## Function to extract a given ruleset.
464 sub extractruleset
($) {
467 # Load perl module to deal with archives.
470 # Load perl module to deal with files and path.
473 # Get full path and downloaded rulesfile for the given provider.
474 my $tarball = &_get_dl_rulesfile
($provider);
476 # Check if the file exists.
477 unless (-f
$tarball) {
478 &_log_to_syslog
("Could not extract ruleset file: $tarball");
484 # Check if the temporary directories exist, otherwise create them.
485 mkdir("$tmp_directory") unless (-d
"$tmp_directory");
486 mkdir("$tmp_rules_directory") unless (-d
"$tmp_rules_directory");
487 mkdir("$tmp_conf_directory") unless (-d
"$tmp_conf_directory");
489 # Initialize the tar module.
490 my $tar = Archive
::Tar
->new($tarball);
492 # Get the filelist inside the tarball.
493 my @packed_files = $tar->list_files;
495 # Loop through the filelist.
496 foreach my $packed_file (@packed_files) {
499 # Splitt the packed file into chunks.
500 my $file = fileparse
($packed_file);
502 # Handle msg-id.map file.
503 if ("$file" eq "sid-msg.map") {
504 # Set extract destination to temporary config_dir.
505 $destination = "$tmp_conf_directory/$provider\-sid-msg.map";
506 # Handle classification.conf
507 } elsif ("$file" eq "classification.config") {
508 # Set extract destination to temporary config_dir.
509 $destination = "$tmp_conf_directory/$provider\-classification.config";
510 # Handle rules files.
511 } elsif ($file =~ m/\.rules$/) {
514 # Splitt the filename into chunks.
515 my @filename = split("-", $file);
518 @filename = reverse(@filename);
520 # Get the amount of elements in the array.
521 my $elements = @filename;
523 # Remove last element of the hash.
524 # It contains the vendor name, which will be replaced.
525 if ($elements >= 3) {
526 # Remove last element from hash.
530 # Check if the last element of the filename does not
531 # contain the providers name.
532 if ($filename[-1] ne "$provider") {
533 # Add provider name as last element.
534 push(@filename, $provider);
537 # Reverse the array back.
538 @filename = reverse(@filename);
540 # Generate the name for the rulesfile.
541 $rulesfilename = join("-", @filename);
543 # Set extract destination to temporaray rules_dir.
544 $destination = "$tmp_rules_directory/$rulesfilename";
546 # Skip all other files.
550 # Extract the file to the temporary directory.
551 $tar->extract_file("$packed_file", "$destination");
556 ## A wrapper function to call the oinkmaster script, setup the rules structues and
557 ## call the functions to merge the additional config files. (classification, sid-msg, etc.).
560 # Load perl module for file copying.
563 # Check if the files in rulesdir have the correct permissions.
564 &_check_rulesdir_permissions
();
566 # Cleanup the rules directory before filling it with the new rulests.
567 &_cleanup_rulesdir
();
569 # Get all enabled providers.
570 my @enabled_providers = &get_enabled_providers
();
572 # Loop through the array of enabled providers.
573 foreach my $provider (@enabled_providers) {
574 # Omit the type (dl_type) of the stored ruleset.
575 my $type = $IDS::Ruleset
::Providers
{$provider}{'dl_type'};
577 # Handle the different ruleset types.
578 if ($type eq "archive") {
579 # Call the extractruleset function.
580 &extractruleset
($provider);
581 } elsif ($type eq "plain") {
582 # Generate filename and full path for the stored rulesfile.
583 my $dl_rulesfile = &_get_dl_rulesfile
($provider);
585 # Generate destination filename an full path.
586 my $destination = "$tmp_rules_directory/$provider\-ruleset.rules";
588 # Copy the file into the temporary rules directory.
589 copy
($dl_rulesfile, $destination);
596 # Load perl module to talk to the kernel syslog.
597 use Sys
::Syslog
qw(:DEFAULT setlogsock);
599 # Establish the connection to the syslog service.
600 openlog
('oinkmaster', 'cons,pid', 'user');
602 # Call oinkmaster to generate ruleset.
603 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";
605 # Log output of oinkmaster to syslog.
606 while(<OINKMASTER
>) {
607 # The syslog function works best with an array based input,
608 # so generate one before passing the message details to syslog.
609 my @syslog = ("INFO", "$_");
611 # Send the log message.
615 # Close the pipe to oinkmaster process.
618 # Close the log handle.
621 # Call function to merge the classification files.
622 &merge_classifications
(@enabled_providers);
624 # Call function to merge the sid to message mapping files.
625 &merge_sid_msg
(@enabled_providers);
627 # Cleanup temporary directory.
628 &cleanup_tmp_directory
();
632 ## Function to merge the classifications for a given amount of providers and write them
633 ## to the classifications file.
635 sub merge_classifications
(@
) {
638 # Hash to store all collected classifications.
639 my %classifications = ();
641 # Loop through the given array of providers.
642 foreach my $provider (@providers) {
643 # Generate full path to classification file.
644 my $classification_file = "$tmp_conf_directory/$provider\-classification.config";
646 # Skip provider if no classification file exists.
647 next unless (-f
"$classification_file");
649 # Open the classification file.
650 open(CLASSIFICATION
, $classification_file) or die "Could not open file $classification_file. $!\n";
652 # Loop through the file content.
653 while(<CLASSIFICATION
>) {
654 # Parse the file and grab the classification details.
655 if ($_ =~/.*config classification\: (.*)/) {
656 # Split the grabbed details.
657 my ($short_name, $short_desc, $priority) = split("\,", $1);
659 # Check if the grabbed classification is allready known and the priority value is greater
660 # than the stored one (which causes less priority in the IDS).
661 if (($classifications{$short_name}) && ($classifications{$short_name}[1] >= $priority)) {
662 #Change the priority value to the stricter one.
663 $classifications{$short_name} = [ "$classifications{$short_name}[0]", "$priority" ];
665 # Add the classification to the hash.
666 $classifications{$short_name} = [ "$short_desc", "$priority" ];
672 close(CLASSIFICATION
);
675 # Open classification file for writing.
676 open(FILE
, ">", "$classification_file") or die "Could not write to $classification_file. $!\n";
678 # Print notice about autogenerated file.
679 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n\n";
681 # Sort and loop through the hash of classifications.
682 foreach my $key (sort keys %classifications) {
683 # Assign some nice variable names for the items.
684 my $short_name = $key;
685 my $short_desc = $classifications{$key}[0];
686 my $priority = $classifications{$key}[1];
688 # Write the classification to the file.
689 print FILE
"config classification: $short_name,$short_desc,$priority\n";
697 ## Function to merge the "sid to message mapping" files of various given providers.
699 sub merge_sid_msg
(@
) {
702 # Hash which contains all the sid to message mappings.
705 # Loop through the array of given providers.
706 foreach my $provider (@providers) {
707 # Generate full path and filename.
708 my $sid_msg_file = "$tmp_conf_directory/$provider\-sid-msg.map";
710 # Skip provider if no sid to msg mapping file for this provider exists.
711 next unless (-f
$sid_msg_file);
714 open(MAPPING
, $sid_msg_file) or die "Could not open $sid_msg_file. $!\n";
716 # Loop through the file content.
721 # Skip lines which do not start with a number,
722 next unless ($_ =~ /^\d+/);
724 # Split line content and assign it to an array.
725 my @line = split(/ \|\| /, $_);
727 # Grab the first element (and remove it) from the line array.
728 # It contains the sid.
729 my $sid = shift(@line);
731 # Store the grabbed sid and the remain array as hash value.
732 # It still contains the messages, references etc.
733 $mappings{$sid} = [@line];
740 # Open mappings file for writing.
741 open(FILE
, ">", $sid_msg_file) or die "Could not write $sid_msg_file. $!\n";
743 # Write notice about autogenerated file.
744 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n\n";
746 # Loop through the hash of mappings.
747 foreach my $sid ( sort keys %mappings) {
748 # Grab data for the sid.
749 my @data = @
{$mappings{$sid}};
751 # Add the sid to the data array.
752 unshift(@data, $sid);
755 my $line = join(" \|\| ", @data);
757 print FILE
"$line\n";
766 ## A very tiny function to move an extracted ruleset from the temporary directory into
767 ## the rules directory.
769 sub move_tmp_ruleset
() {
773 # Do a directory listing of the temporary directory.
774 opendir DH
, $tmp_rules_directory;
776 # Loop over all files.
777 while(my $file = readdir DH
) {
778 # Move them to the rules directory.
779 move
"$tmp_rules_directory/$file" , "$rulespath/$file";
782 # Close directory handle.
787 ## Function to cleanup the temporary IDS directroy.
789 sub cleanup_tmp_directory
() {
790 # Load rmtree() function from file path perl module.
791 use File
::Path
'rmtree';
793 # Delete temporary directory and all containing files.
794 rmtree
([ "$tmp_directory" ]);
798 ## Function to do all the logging stuff if the downloading or updating of the ruleset fails.
803 # Remove any newline.
806 # Call private function to log the error message to syslog.
807 &_log_to_syslog
($error);
809 # Call private function to write/store the error message in the storederrorfile.
810 &_store_error_message
($error);
814 ## Function to log a given error message to the kernel syslog.
816 sub _log_to_syslog
($) {
819 # Load perl module to talk to the kernel syslog.
820 use Sys
::Syslog
qw(:DEFAULT setlogsock);
822 # The syslog function works best with an array based input,
823 # so generate one before passing the message details to syslog.
824 my @syslog = ("ERR", "<ERROR> $message");
826 # Establish the connection to the syslog service.
827 openlog
('oinkmaster', 'cons,pid', 'user');
829 # Send the log message.
832 # Close the log handle.
837 ## Private function to write a given error message to the storederror file.
839 sub _store_error_message
($) {
842 # Remove any newline.
845 # Open file for writing.
846 open (ERRORFILE
, ">$storederrorfile") or die "Could not write to $storederrorfile. $!\n";
848 # Write error to file.
849 print ERRORFILE
"$message\n";
854 # Set correct ownership for the file.
855 &set_ownership
("$storederrorfile");
859 ## Private function to get the path and filename for a downloaded ruleset by a given provider.
861 sub _get_dl_rulesfile
($) {
864 # Gather the download type for the given provider.
865 my $dl_type = $IDS::Ruleset
::Providers
{$provider}{'dl_type'};
867 # Obtain the file suffix for the download file type.
868 my $suffix = $dl_type_to_suffix{$dl_type};
870 # Check if a suffix has been found.
872 # Abort return - nothing.
876 # Generate the full filename and path for the stored rules file.
877 my $rulesfile = "$dl_rules_path/$dl_rulesfile_prefix-$provider$suffix";
879 # Return the generated filename.
884 ## Tiny function to delete the stored ruleset file or tarball for a given provider.
886 sub drop_dl_rulesfile
($) {
889 # Gather the full path and name of the stored rulesfile.
890 my $rulesfile = &_get_dl_rulesfile
($provider);
892 # Check if the given rulesfile exists.
894 # Delete the stored rulesfile.
895 unlink($rulesfile) or die "Could not delete $rulesfile. $!\n";
900 ## Tiny function to get/generate the full path and filename for the providers oinkmaster
901 ## modified sids file.
903 sub get_oinkmaster_provider_modified_sids_file
($) {
906 # Generate the filename.
907 my $filename = "$settingsdir/oinkmaster-$provider-modified-sids.conf";
909 # Return the filename.
914 ## Function to check if the IDS is running.
916 sub ids_is_running
() {
918 # Open PID file for reading.
919 open(PIDFILE
, "$idspidfile") or die "Could not open $idspidfile. $!\n";
921 # Grab the process-id.
927 # Remove any newline.
930 # Check if a directory for the process-id exists in proc.
931 if(-d
"/proc/$pid") {
932 # The IDS daemon is running return the process id.
937 # Return nothing - IDS is not running.
942 ## Function to call suricatactrl binary with a given command.
944 sub call_suricatactrl
($) {
946 my ($option, $interval) = @_;
948 # Loop through the array of supported commands and check if
949 # the given one is part of it.
950 foreach my $cmd (@suricatactrl_cmds) {
951 # Skip current command unless the given one has been found.
952 next unless($cmd eq $option);
954 # Check if the given command is "cron".
955 if ($option eq "cron") {
956 # Check if an interval has been given.
958 # Check if the given interval is valid.
959 foreach my $element (@cron_intervals) {
960 # Skip current element until the given one has been found.
961 next unless($element eq $interval);
963 # Call the suricatactrl binary and pass the "cron" command
964 # with the requrested interval.
965 &General
::system("$suricatactrl", "$option", "$interval");
972 # If we got here, the given interval is not supported or none has been given. - Return nothing.
975 # Call the suricatactrl binary and pass the requrested
977 &General
::system("$suricatactrl", "$option");
984 # Command not found - return nothing.
989 ## Function to create a new empty file.
991 sub create_empty_file
($) {
994 # Check if the given file exists.
996 # Do nothing to prevent from overwriting existing files.
1000 # Open the file for writing.
1001 open(FILE
, ">$file") or die "Could not write to $file. $!\n";
1003 # Close file handle.
1011 ## Private function to check if the file permission of the rulespath are correct.
1012 ## If not, call suricatactrl to fix them.
1014 sub _check_rulesdir_permissions
() {
1015 # Check if the rulepath main directory is writable.
1016 unless (-W
$rulespath) {
1017 # If not call suricatctrl to fix it.
1018 &call_suricatactrl
("fix-rules-dir");
1021 # Open snort rules directory and do a directory listing.
1022 opendir(DIR
, $rulespath) or die $!;
1023 # Loop through the direcory.
1024 while (my $file = readdir(DIR
)) {
1025 # We only want files.
1026 next unless (-f
"$rulespath/$file");
1028 # Check if the file is writable by the user.
1029 if (-W
"$rulespath/$file") {
1030 # Everything is okay - go on to the next file.
1033 # There are wrong permissions, call suricatactrl to fix it.
1034 &call_suricatactrl
("fix-rules-dir");
1040 ## Private function to cleanup the directory which contains
1041 ## the IDS rules, before extracting and modifing the new ruleset.
1043 sub _cleanup_rulesdir
() {
1044 # Open rules directory and do a directory listing.
1045 opendir(DIR
, $rulespath) or die $!;
1047 # Loop through the direcory.
1048 while (my $file = readdir(DIR
)) {
1049 # We only want files.
1050 next unless (-f
"$rulespath/$file");
1052 # Skip rules file for whitelisted hosts.
1053 next if ("$rulespath/$file" eq $whitelist_file);
1055 # Skip rules file with local rules.
1056 next if ("$rulespath/$file" eq $local_rules_file);
1058 # Delete the current processed file, if not, exit this function
1059 # and return an error message.
1060 unlink("$rulespath/$file") or return "Could not delete $rulespath/$file. $!\n";
1068 ## Function to generate the file which contains the home net information.
1070 sub generate_home_net_file
() {
1073 # Read-in network settings.
1074 &General
::readhash
("${General::swroot}/ethernet/settings", \
%netsettings);
1076 # Get available network zones.
1077 my @network_zones = &Network
::get_available_network_zones
();
1079 # Temporary array to store network address and prefix of the configured
1083 # Loop through the array of available network zones.
1084 foreach my $zone (@network_zones) {
1085 # Check if the current processed zone is red.
1086 if($zone eq "red") {
1087 # Grab the IP-address of the red interface.
1088 my $red_address = &get_red_address
();
1090 # Check if an address has been obtained.
1092 # Generate full network string.
1093 my $red_network = join("/", $red_address, "32");
1095 # Add the red network to the array of networks.
1096 push(@networks, $red_network);
1099 # Check if the configured RED_TYPE is static.
1100 if ($netsettings{'RED_TYPE'} eq "STATIC") {
1101 # Get configured and enabled aliases.
1102 my @aliases = &get_aliases
();
1104 # Loop through the array.
1105 foreach my $alias (@aliases) {
1107 my $network = join("/", $alias, "32");
1109 # Add the generated network to the array of networks.
1110 push(@networks, $network);
1113 # Process remaining network zones.
1115 # Convert current zone name into upper case.
1118 # Generate key to access the required data from the netsettings hash.
1119 my $zone_netaddress = $zone . "_NETADDRESS";
1120 my $zone_netmask = $zone . "_NETMASK";
1122 # Obtain the settings from the netsettings hash.
1123 my $netaddress = $netsettings{$zone_netaddress};
1124 my $netmask = $netsettings{$zone_netmask};
1126 # Convert the subnetmask into prefix notation.
1127 my $prefix = &Network
::convert_netmask2prefix
($netmask);
1129 # Generate full network string.
1130 my $network = join("/", $netaddress,$prefix);
1132 # Check if the network is valid.
1133 if(&Network
::check_subnet
($network)) {
1134 # Add the generated network to the array of networks.
1135 push(@networks, $network);
1140 # Format home net declaration.
1141 my $line = "\"[" . join(',', @networks) . "]\"";
1143 # Open file to store the addresses of the home net.
1144 open(FILE
, ">$homenet_file") or die "Could not open $homenet_file. $!\n";
1146 # Print yaml header.
1147 print FILE
"%YAML 1.1\n";
1148 print FILE
"---\n\n";
1150 # Print notice about autogenerated file.
1151 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1153 # Print the generated and required HOME_NET declaration to the file.
1154 print FILE
"HOME_NET:\t$line\n";
1156 # Close file handle.
1161 # Function to generate and write the file which contains the configured and used DNS servers.
1163 sub generate_dns_servers_file
() {
1164 # Get the used DNS servers.
1165 my @nameservers = &General
::get_nameservers
();
1167 # Get network settings.
1169 &General
::readhash
("${General::swroot}/ethernet/settings", \
%netsettings);
1171 # Format dns servers declaration.
1174 # Check if the system has configured nameservers.
1176 # Add the GREEN address as DNS servers.
1177 push(@nameservers, $netsettings{'GREEN_ADDRESS'});
1179 # Check if a BLUE zone exists.
1180 if ($netsettings{'BLUE_ADDRESS'}) {
1181 # Add the BLUE address to the array of nameservers.
1182 push(@nameservers, $netsettings{'BLUE_ADDRESS'});
1185 # Generate the line which will be written to the DNS servers file.
1186 $line = join(",", @nameservers);
1188 # External net simply contains (any).
1189 $line = "\$EXTERNAL_NET";
1192 # Open file to store the used DNS server addresses.
1193 open(FILE
, ">$dns_servers_file") or die "Could not open $dns_servers_file. $!\n";
1195 # Print yaml header.
1196 print FILE
"%YAML 1.1\n";
1197 print FILE
"---\n\n";
1199 # Print notice about autogenerated file.
1200 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1202 # Print the generated DNS declaration to the file.
1203 print FILE
"DNS_SERVERS:\t\"[$line]\"\n";
1205 # Close file handle.
1210 # Function to generate and write the file which contains the HTTP_PORTS definition.
1212 sub generate_http_ports_file
() {
1215 # Read-in proxy settings
1216 &General
::readhash
("${General::swroot}/proxy/advanced/settings", \
%proxysettings);
1218 # Check if the proxy is enabled.
1219 if (( -e
"${General::swroot}/proxy/enable") || (-e
"${General::swroot}/proxy/enable_blue")) {
1220 # Add the proxy port to the array of HTTP ports.
1221 push(@http_ports, $proxysettings{'PROXY_PORT'});
1224 # Check if the transparent mode of the proxy is enabled.
1225 if ((-e
"${General::swroot}/proxy/transparent") || (-e
"${General::swroot}/proxy/transparent_blue")) {
1226 # Add the transparent proxy port to the array of HTTP ports.
1227 push(@http_ports, $proxysettings{'TRANSPARENT_PORT'});
1230 # Format HTTP_PORTS declaration.
1233 # Generate line which will be written to the http ports file.
1234 $line = join(",", @http_ports);
1236 # Open file to store the HTTP_PORTS.
1237 open(FILE
, ">$http_ports_file") or die "Could not open $http_ports_file. $!\n";
1239 # Print yaml header.
1240 print FILE
"%YAML 1.1\n";
1241 print FILE
"---\n\n";
1243 # Print notice about autogenerated file.
1244 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1246 # Print the generated HTTP_PORTS declaration to the file.
1247 print FILE
"HTTP_PORTS:\t\"[$line]\"\n";
1249 # Close file handle.
1254 ## Function to generate and write the file for used rulefiles file for a given provider.
1256 ## The function requires as first argument a provider handle, and as second an array with files.
1258 sub write_used_provider_rulefiles_file
($@
) {
1259 my ($provider, @files) = @_;
1261 # Get the path and file for the provider specific used rulefiles file.
1262 my $used_provider_rulesfile_file = &get_used_provider_rulesfile_file
($provider);
1264 # Open file for used rulefiles.
1265 open (FILE
, ">$used_provider_rulesfile_file") or die "Could not write to $used_provider_rulesfile_file. $!\n";
1267 # Write yaml header to the file.
1268 print FILE
"%YAML 1.1\n";
1269 print FILE
"---\n\n";
1271 # Write header to file.
1272 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1274 # Loop through the array of given files.
1275 foreach my $file (@files) {
1276 # Check if the given filename exists and write it to the file of used rulefiles.
1277 if(-f
"$rulespath/$file") {
1278 print FILE
" - $file\n";
1282 # Close file after writing.
1287 ## Function to write the main file for provider rulesfiles inclusions.
1289 ## This function requires an array of provider handles.
1291 sub write_main_used_rulefiles_file
(@
) {
1292 my (@providers) = @_;
1294 # Call function to write the static rulefiles file.
1295 &_write_static_rulefiles_file
();
1297 # Open file for used rulefils inclusion.
1298 open (FILE
, ">", "$suricata_used_providers_file") or die "Could not write to $suricata_used_providers_file. $!\n";
1300 # Write yaml header to the file.
1301 print FILE
"%YAML 1.1\n";
1302 print FILE
"---\n\n";
1304 # Write header to file.
1305 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1307 # Loop through the list of given providers.
1308 foreach my $provider (@providers) {
1309 # Call function to get the providers used rulefiles file.
1310 my $filename = &get_used_provider_rulesfile_file
($provider);
1312 # Print the provider to the file.
1313 print FILE
"include\: $filename\n";
1316 # Always include the file which hold the static includes.
1317 print FILE
"include\: $suricata_static_rulefiles_file\n";
1319 # Close the filehandle after writing.
1323 sub _write_static_rulefiles_file
() {
1325 open (FILE
, ">", $suricata_static_rulefiles_file) or die "Could not write to $suricata_static_rulefiles_file. $!\n";
1327 # Write yaml header to the file.
1328 print FILE
"%YAML 1.1\n";
1329 print FILE
"---\n\n";
1331 # Write notice about autogenerated file.
1332 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1334 # Loop through the array of static included rulesfiles.
1335 foreach my $file (@static_included_rulefiles) {
1336 # Check if the file exists.
1337 if (-f
"$rulespath/$file") {
1338 # Write the rulesfile name to the file.
1339 print FILE
" - $file\n";
1343 # Close the file handle
1348 ## Tiny function to generate the full path and name for the used_provider_rulesfile file of a given provider.
1350 sub get_used_provider_rulesfile_file
($) {
1351 my ($provider) = @_;
1353 my $filename = "$settingsdir/suricata\-$provider\-used\-rulefiles.yaml";
1355 # Return the gernerated file.
1360 ## Function to generate and write the file for modify the ruleset.
1362 sub write_modify_sids_file
() {
1363 # Get configured settings.
1365 &General
::readhash
("$ids_settings_file", \
%idssettings);
1367 # Open modify sid's file for writing.
1368 open(FILE
, ">$modify_sids_file") or die "Could not write to $modify_sids_file. $!\n";
1370 # Write file header.
1371 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1373 # Check if the traffic only should be monitored.
1374 unless($idssettings{'MONITOR_TRAFFIC_ONLY'} eq 'on') {
1375 # Suricata is in IPS mode, which means that the rule actions have to be changed
1376 # from 'alert' to 'drop', however not all rules should be changed. Some rules
1377 # exist purely to set a flowbit which is used to convey other information, such
1378 # as a specific type of file being downloaded, to other rulewhich then check for
1379 # malware in that file. Rules which fall into the first category should stay as
1380 # alert since not all flows of that type contain malware.
1382 # These types of rulesfiles contain meta-data which gives the action that should
1383 # be used when in IPS mode. Do the following:
1385 # 1. Disable all rules and set the action to 'drop'
1386 # 2. Set the action back to 'alert' if the rule contains 'flowbits:noalert;'
1387 # This should give rules not in the policy a reasonable default if the user
1388 # manually enables them.
1389 # 3. Enable rules and set actions according to the meta-data strings.
1391 my $policy = 'balanced'; # Placeholder to allow policy to be changed.
1394 modifysid * "^#(?:alert|drop)(.+policy $policy-ips alert)" | "alert\${1}"
1395 modifysid * "^#(?:alert|drop)(.+policy $policy-ips drop)" | "drop\${1}"
1396 modifysid * "^(#?)(?:alert|drop)" | "\${1}drop"
1397 modifysid * "^(#?)drop(.+flowbits:noalert;)" | "\${1}alert\${2}"
1401 # Close file handle.
1406 ## Function to get the ruleset date for a given provider.
1408 ## The function simply return the creation date in a human read-able format
1409 ## of the stored providers rulesfile.
1411 sub get_ruleset_date
($) {
1412 my ($provider) = @_;
1414 # Load neccessary perl modules for file stat and to format the timestamp.
1416 use POSIX
qw( strftime );
1418 # Get the stored rulesfile for this provider.
1419 my $stored_rulesfile = &_get_dl_rulesfile
($provider);
1421 # Call stat on the rulestarball.
1422 my $stat = stat("$stored_rulesfile");
1424 # Get timestamp the file creation.
1425 my $mtime = $stat->mtime;
1427 # Convert into human read-able format.
1428 my $date = strftime
('%Y-%m-%d %H:%M:%S', localtime($mtime));
1435 ## Function to gather the version of suricata.
1437 sub get_suricata_version
($) {
1440 # Execute piped suricata command and return the version information.
1441 open(SURICATA
, "suricata -V |") or die "Couldn't execute program: $!";
1443 # Grab and store the output of the piped program.
1444 my $version_string = <SURICATA
>;
1450 chomp($version_string);
1452 # Grab the version from the version string.
1453 $version_string =~ /([0-9]+([.][0-9]+)+)/;
1455 # Splitt the version into single chunks.
1456 my ($major_ver, $minor_ver, $patchlevel) = split(/\./, $1);
1458 # Check and return the requested version sheme.
1459 if ($format eq "major") {
1460 # Return the full version.
1461 return "$major_ver";
1462 } elsif ($format eq "minor") {
1463 # Return the major and minor part.
1464 return "$major_ver.$minor_ver";
1466 # Return the full version string.
1467 return "$major_ver.$minor_ver.$patchlevel";
1472 ## Function to generate the rules file with whitelisted addresses.
1474 sub generate_ignore_file
() {
1477 # SID range 1000000-1999999 Reserved for Local Use
1478 # Put your custom rules in this range to avoid conflicts
1481 # Read-in ignoredfile.
1482 &General
::readhasharray
($IDS::ignored_file
, \
%ignored);
1484 # Open ignorefile for writing.
1485 open(FILE
, ">$IDS::whitelist_file") or die "Could not write to $IDS::whitelist_file. $!\n";
1487 # Config file header.
1488 print FILE
"# Autogenerated file.\n";
1489 print FILE
"# All user modifications will be overwritten.\n\n";
1491 # Add all user defined addresses to the whitelist.
1493 # Check if the hash contains any elements.
1494 if (keys (%ignored)) {
1495 # Loop through the entire hash and write the host/network
1496 # and remark to the ignore file.
1497 while ( (my $key) = each %ignored) {
1498 my $address = $ignored{$key}[0];
1499 my $remark = $ignored{$key}[1];
1500 my $status = $ignored{$key}[2];
1502 # Check if the status of the entry is "enabled".
1503 if ($status eq "enabled") {
1504 # Check if the address/network is valid.
1505 if ((&General
::validip
($address)) || (&General
::validipandmask
($address))) {
1506 # Write rule line to the file to pass any traffic from this IP
1507 print FILE
"pass ip $address any -> any any (msg:\"pass all traffic from/to $address\"\; sid:$sid\;)\n";
1520 ## Function to set correct ownership for single files and directories.
1523 sub set_ownership
($) {
1526 # User and group of the WUI.
1527 my $uname = "nobody";
1528 my $grname = "nobody";
1530 # The chown function implemented in perl requies the user and group as nummeric id's.
1531 my $uid = getpwnam($uname);
1532 my $gid = getgrnam($grname);
1534 # Check if the given target exists.
1536 # Stop the script and print error message.
1537 die "The $target does not exist. Cannot change the ownership!\n";
1540 # Check weather the target is a file or directory.
1542 # Change ownership ot the single file.
1543 chown($uid, $gid, "$target");
1544 } elsif (-d
$target) {
1545 # Do a directory listing.
1546 opendir(DIR
, $target) or die $!;
1547 # Loop through the direcory.
1548 while (my $file = readdir(DIR
)) {
1550 # We only want files.
1551 next unless (-f
"$target/$file");
1553 # Set correct ownership for the files.
1554 chown($uid, $gid, "$target/$file");
1559 # Change ownership of the directory.
1560 chown($uid, $gid, "$target");
1565 ## Function to read-in the aliases file and returns all configured and enabled aliases.
1568 # Location of the aliases file.
1569 my $aliases_file = "${General::swroot}/ethernet/aliases";
1571 # Array to store the aliases.
1574 # Check if the file is empty.
1575 if (-z
$aliases_file) {
1576 # Abort nothing to do.
1580 # Open the aliases file.
1581 open(ALIASES
, $aliases_file) or die "Could not open $aliases_file. $!\n";
1583 # Loop through the file content.
1584 while (my $line = <ALIASES
>) {
1588 # Splitt line content into single chunks.
1589 my ($address, $state, $remark) = split(/\,/, $line);
1591 # Check if the state of the current processed alias is "on".
1592 if ($state eq "on") {
1593 # Check if the address is valid.
1594 if(&Network
::check_ip_address
($address)) {
1595 # Add the alias to the array of aliases.
1596 push(@aliases, $address);
1601 # Close file handle.
1609 ## Function to grab the current assigned IP-address on red.
1611 sub get_red_address
() {
1612 # File, which contains the current IP-address of the red interface.
1613 my $file = "${General::swroot}/red/local-ipaddress";
1615 # Check if the file exists.
1617 # Open the given file.
1618 open(FILE
, "$file") or die "Could not open $file.";
1620 # Obtain the address from the first line of the file.
1621 my $address = <FILE
>;
1629 # Check if the grabbed address is valid.
1630 if (&General
::validip
($address)) {
1631 # Return the address.
1641 ## Function to get the used rules files of a given provider.
1643 sub read_used_provider_rulesfiles
($) {
1644 my ($provider) = @_;
1646 # Array to store the used rulefiles.
1647 my @used_rulesfiles = ();
1649 # Get the used rulesefile file for the provider.
1650 my $rulesfile_file = &get_used_provider_rulesfile_file
($provider);
1652 # Check if the used rulesfile is empty.
1653 unless (-z
$rulesfile_file) {
1654 # Open the file or used rulefiles and read-in content.
1655 open(FILE
, $rulesfile_file) or die "Could not open $rulesfile_file. $!\n";
1658 # Assign the current line to a nice variable.
1665 next if ($line =~ /\#/);
1668 next if ($line =~ /^\s*$/);
1670 # Gather the rulefile.
1671 if ($line =~ /.*- (.*)/) {
1674 # Add the rulefile to the array of used rulesfiles.
1675 push(@used_rulesfiles, $rulefile);
1683 # Return the array of used rulesfiles.
1684 return @used_rulesfiles;
1688 ## Function to write the lock file for locking the WUI, while
1689 ## the autoupdate script runs.
1691 sub lock_ids_page
() {
1692 # Call subfunction to create the file.
1693 &create_empty_file
($ids_page_lock_file);
1697 ## Function to release the lock of the WUI, again.
1699 sub unlock_ids_page
() {
1701 unlink($ids_page_lock_file);