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 # Load perl module to deal with Archives.
33 use Archive
::Peek
::Libarchive
;
35 # Load perl module to deal with files and path.
38 # Load module to move files.
41 # Load module to recursely remove files and a folder.
42 use File
::Path
qw(rmtree);
44 # Load module to get file stats.
47 # Load module to deal with temporary files.
50 # Load module to deal with the date formats used by the HTTP protocol.
53 # Load the libwwwperl User Agent module.
56 # Load function from posix module to format time strings.
57 use POSIX qw
(strftime
);
59 # Load module to talk to the kernel log daemon.
60 use Sys
::Syslog
qw(:DEFAULT setlogsock);
62 # Location where all config and settings files are stored.
63 our $settingsdir = "${General::swroot}/suricata";
65 # File where the main file for providers ruleset inclusion exists.
66 our $suricata_used_rulesfiles_file = "$settingsdir/suricata-used-rulesfiles.yaml";
68 # File where the addresses of the homenet are stored.
69 our $homenet_file = "$settingsdir/suricata-homenet.yaml";
71 # File where the addresses of the used DNS servers are stored.
72 our $dns_servers_file = "$settingsdir/suricata-dns-servers.yaml";
74 # File where the HTTP ports definition is stored.
75 our $http_ports_file = "$settingsdir/suricata-http-ports.yaml";
77 # File which stores the configured IPS settings.
78 our $ids_settings_file = "$settingsdir/settings";
80 # File which stores the used and configured ruleset providers.
81 our $providers_settings_file = "$settingsdir/providers-settings";
83 # File which stores the configured settings for whitelisted addresses.
84 our $ignored_file = "$settingsdir/ignored";
86 # File which stores HTTP Etags for providers which supports them
87 # for cache management.
88 our $etags_file = "$settingsdir/etags";
90 # Location where the downloaded rulesets are stored.
91 our $dl_rules_path = "/var/cache/suricata";
93 # File to store any errors, which also will be read and displayed by the wui.
94 our $storederrorfile = "/tmp/ids_storederror";
96 # File to lock the WUI, while the autoupdate script runs.
97 our $ids_page_lock_file = "/tmp/ids_page_locked";
99 # Location where the rulefiles are stored.
100 our $rulespath = "/var/lib/suricata";
102 # Location where the default rulefils are stored.
103 our $default_rulespath = "/usr/share/suricata/rules";
105 # Location where the addition config files are stored.
106 our $configspath = "/usr/share/suricata";
108 # Location of the classification file.
109 our $classification_file = "$configspath/classification.config";
111 # Location of the sid to msg mappings file.
112 our $sid_msg_file = "$rulespath/sid-msg.map";
114 # Location to store local rules. This file will not be touched.
115 our $local_rules_file = "$rulespath/local.rules";
117 # File which contains the rules to whitelist addresses on suricata.
118 our $whitelist_file = "$rulespath/whitelist.rules";
120 # File which contains a list of all supported ruleset sources.
121 # (Sourcefire, Emergingthreads, etc..)
122 our $rulesetsourcesfile = "$settingsdir/ruleset-sources";
124 # The pidfile of the IDS.
125 our $idspidfile = "/var/run/suricata.pid";
127 # Location of suricatactrl.
128 my $suricatactrl = "/usr/local/bin/suricatactrl";
130 # Prefix for each downloaded ruleset.
131 my $dl_rulesfile_prefix = "idsrules";
133 # Temporary directory to download the rules files.
134 my $tmp_dl_directory = "/var/tmp";
136 # Temporary directory where the rulesets will be extracted.
137 my $tmp_directory = "/tmp/ids_tmp";
139 # Temporary directory where the extracted rules files will be stored.
140 my $tmp_rules_directory = "$tmp_directory/rules";
142 # Temporary directory where the extracted additional config files will be stored.
143 my $tmp_conf_directory = "$tmp_directory/conf";
145 # Array with allowed commands of suricatactrl.
146 my @suricatactrl_cmds = ( 'start', 'stop', 'restart', 'reload', 'fix-rules-dir' );
148 # Array which contains the HTTP ports, which statically will be declared as HTTP_PORTS in the
150 my @http_ports = ('80', '81');
152 # Array which contains a list of rulefiles which always will be included if they exist.
153 my @static_included_rulefiles = ('local.rules', 'whitelist.rules');
155 # Array which contains a list of allways enabled application layer protocols.
156 my @static_enabled_app_layer_protos = ('app-layer', 'decoder', 'files', 'stream');
158 # Hash which allows to convert the download type (dl_type) to a file suffix.
159 my %dl_type_to_suffix = (
160 "archive" => ".tar.gz",
164 # Hash to translate an application layer protocol to the application name.
165 my %tr_app_layer_proto = (
167 "krb5" => "kerberos",
171 ## Function to check and create all IDS related files, if the does not exist.
173 sub check_and_create_filelayout
() {
174 # Check if the files exist and if not, create them.
175 unless (-f
"$suricata_used_rulesfiles_file") { &create_empty_file
($suricata_used_rulesfiles_file); }
176 unless (-f
"$ids_settings_file") { &create_empty_file
($ids_settings_file); }
177 unless (-f
"$providers_settings_file") { &create_empty_file
($providers_settings_file); }
178 unless (-f
"$whitelist_file" ) { &create_empty_file
($whitelist_file); }
182 ## Function to get a list of all available ruleset providers.
184 ## They will be returned as a sorted array.
186 sub get_ruleset_providers
() {
189 # Loop through the hash of providers.
190 foreach my $provider ( keys %IDS::Ruleset
::Providers
) {
191 # Add the provider to the array.
192 push(@providers, $provider);
195 # Sort and return the array.
196 return sort(@providers);
200 ## Function to get a list of all enabled ruleset providers.
202 ## They will be returned as an array.
204 sub get_enabled_providers
() {
205 my %used_providers = ();
207 # Array to store the enabled providers.
208 my @enabled_providers = ();
210 # Read-in the providers config file.
211 &General
::readhasharray
("$providers_settings_file", \
%used_providers);
213 # Loop through the hash of used_providers.
214 foreach my $id (keys %used_providers) {
215 # Skip disabled providers.
216 next unless ($used_providers{$id}[3] eq "enabled");
218 # Grab the provider handle.
219 my $provider = "$used_providers{$id}[0]";
221 # Add the provider to the array of enabled providers.
222 push(@enabled_providers, $provider);
226 return @enabled_providers;
230 ## Function to get a hash of provider handles and their configured modes (IDS/IPS).
232 sub get_providers_mode
() {
233 my %used_providers = ();
235 # Hash to store the providers and their configured modes.
236 my %providers_mode = ();
238 # Read-in the providers config file.
239 &General
::readhasharray
("$providers_settings_file", \
%used_providers);
241 # Loop through the hash of used_providers.
242 foreach my $id (keys %used_providers) {
243 # Skip disabled providers.
244 next unless ($used_providers{$id}[3] eq "enabled");
246 # Grab the provider handle.
247 my $provider = "$used_providers{$id}[0]";
249 # Grab the provider mode.
250 my $mode = "$used_providers{$id}[4]";
252 # Fall back to IDS if no mode could be obtained.
257 # Add details to provider_modes hash.
258 $providers_mode{$provider} = $mode;
262 return %providers_mode;
266 ## Function for checking if at least 300MB of free disk space are available
267 ## on the "/var" partition.
269 sub checkdiskspace
() {
270 # Call diskfree to gather the free disk space of /var.
271 my @df = &General
::system_output
("/bin/df", "-B", "M", "/var");
273 # Loop through the output.
274 foreach my $line (@df) {
275 # Ignore header line.
276 next if $line =~ m/^Filesystem/;
278 # Search for a line with the device information.
279 if ($line =~ m/dev/ ) {
280 # Split the line into single pieces.
281 my @values = split(' ', $line);
282 my ($filesystem, $blocks, $used, $available, $used_perenctage, $mounted_on) = @values;
284 # Check if the available disk space is more than 300MB.
285 if ($available < 300) {
286 # Exit function and return the available disk space.
292 # Everything okay, return nothing.
297 ## This function is responsible for downloading the ruleset for a given provider.
299 ## * At first it initialize the downloader and sets an upstream proxy if configured.
300 ## * The next step will be to generate the final download url, by obtaining the URL for the desired
301 ## ruleset and add the settings for the upstream proxy.
302 ## * Finally the function will grab the rule file or tarball from the server.
303 ## It tries to reduce the amount of download by using the "If-Modified-Since" HTTP header.
307 ## * "no url" - If no download URL could be gathered for the provider.
308 ## * "not modified" - In case the already stored rules file is up to date.
309 ## * "incomplete download" - When the remote file size differs from the downloaded file size.
310 ## * "$error" - The error message generated from the LWP::User Agent module.
312 sub downloadruleset
($) {
315 # The amount of download attempts before giving up and
317 my $max_dl_attempts = 3;
319 # Read proxysettings.
320 my %proxysettings=();
321 &General
::readhash
("${General::swroot}/proxy/settings", \
%proxysettings);
323 # Init the download module.
325 # Request SSL hostname verification and specify path
327 my $downloader = LWP
::UserAgent
->new(
329 SSL_ca_file
=> '/etc/ssl/cert.pem',
330 verify_hostname
=> 1,
334 # Set timeout to 10 seconds.
335 $downloader->timeout(10);
337 # Check if an upstream proxy is configured.
338 if ($proxysettings{'UPSTREAM_PROXY'}) {
341 $proxy_url = "http://";
343 # Check if the proxy requires authentication.
344 if (($proxysettings{'UPSTREAM_USER'}) && ($proxysettings{'UPSTREAM_PASSWORD'})) {
345 $proxy_url .= "$proxysettings{'UPSTREAM_USER'}\:$proxysettings{'UPSTREAM_PASSWORD'}\@";
348 # Add proxy server address and port.
349 $proxy_url .= $proxysettings{'UPSTREAM_PROXY'};
351 # Setup proxy settings.
352 $downloader->proxy(['http', 'https'], $proxy_url);
355 # Grab the download url for the provider.
356 my $url = $IDS::Ruleset
::Providers
{$provider}{'dl_url'};
358 # Check if the provider requires a subscription.
359 if ($IDS::Ruleset
::Providers
{$provider}{'requires_subscription'} eq "True") {
360 # Grab the subscription code.
361 my $subscription_code = &get_subscription_code
($provider);
363 # Add the subscription code to the download url.
364 $url =~ s/\<subscription_code\>/$subscription_code/g;
368 # Abort and return "no url", if no url could be determined for the provider.
369 return "no url" unless ($url);
371 # Pass the requested URL to the downloader.
372 my $request = HTTP
::Request
->new(GET
=> $url);
374 # Generate temporary file name, located in the tempoary download directory and with a suffix of ".tmp".
375 # The downloaded file will be stored there until some sanity checks are performed.
376 my $tmp = File
::Temp
->new( SUFFIX
=> ".tmp", DIR
=> "$tmp_dl_directory/", UNLINK
=> 0 );
377 my $tmpfile = $tmp->filename();
379 # Call function to get the final path and filename for the downloaded file.
380 my $dl_rulesfile = &_get_dl_rulesfile
($provider);
382 # Check if the rulesfile already exits, because it has been downloaded in the past.
384 # In this case we are requesting the server if the remote file has been changed or not.
385 # This will be done by sending the modification time in a special HTTP header.
386 if (-f
$dl_rulesfile) {
387 # Call stat on the file.
388 my $stat = stat($dl_rulesfile);
390 # Omit the mtime of the existing file.
391 my $mtime = $stat->mtime;
393 # Convert the timestamp into right format.
394 my $http_date = time2str
($mtime);
396 # Add the If-Modified-Since header to the request to ask the server if the
397 # file has been modified.
398 $request->header( 'If-Modified-Since' => "$http_date" );
401 # Read-in Etags file for known Etags if the file is present.
403 &General
::readhash
("$etags_file", \
%etags) if (-f
$etags_file);
405 # Check if an Etag for the current provider is stored.
406 if ($etags{$provider}) {
407 # Grab the stored tag.
408 my $etag = $etags{$provider};
410 # Add an "If-None-Match header to the request to ask the server if the
411 # file has been modified.
412 $request->header( 'If-None-Match' => $etag );
418 # Download and retry on failure.
419 while ($dl_attempt <= $max_dl_attempts) {
420 # Perform the request and save the output into the tmpfile.
421 $response = $downloader->request($request, $tmpfile);
423 # Check if the download was successfull.
424 if($response->is_success) {
428 # Check if the server responds with 304 (Not Modified).
429 } elsif ($response->code == 304) {
430 # Remove temporary file, if one exists.
431 unlink("$tmpfile") if (-e
"$tmpfile");
433 # Return "not modified".
434 return "not modified";
436 # Check if we ran out of download re-tries.
437 } elsif ($dl_attempt eq $max_dl_attempts) {
439 my $error = $response->content;
441 # Remove temporary file, if one exists.
442 unlink("$tmpfile") if (-e
"$tmpfile");
444 # Return the error message from response..
448 # Remove temporary file, if one exists.
449 unlink("$tmpfile") if (-e
"$tmpfile");
451 # Increase download attempt counter.
455 # Obtain the connection headers.
456 my $headers = $response->headers;
458 # Get the timestamp from header, when the file has been modified the
460 my $last_modified = $headers->last_modified;
462 # Get the remote size of the downloaded file.
463 my $remote_filesize = $headers->content_length;
465 # Grab the Etag from response it the server provides one.
466 if ($response->header('Etag')) {
467 # Add the Etag to the etags hash.
468 $etags{$provider} = $response->header('Etag');
470 # Write the etags file.
471 &General
::writehash
($etags_file, \
%etags);
474 # Perform stat on the tmpfile.
475 my $stat = stat($tmpfile);
477 # Grab the local filesize of the downloaded tarball.
478 my $local_filesize = $stat->size;
480 # Check if both file sizes match.
481 if (($remote_filesize) && ($remote_filesize ne $local_filesize)) {
482 # Delete temporary file.
485 # Return "1" - false.
486 return "incomplete download";
489 # Overwrite the may existing rulefile or tarball with the downloaded one.
490 move
("$tmpfile", "$dl_rulesfile");
492 # Check if we got a last-modified value from the server.
493 if ($last_modified) {
494 # Assign the last-modified timestamp as mtime to the
496 utime(time(), "$last_modified", "$dl_rulesfile");
499 # Delete temporary file.
502 # Set correct ownership for the tarball.
503 set_ownership
("$dl_rulesfile");
505 # If we got here, everything worked fine. Return nothing.
510 ## Function to extract a given ruleset.
512 ## In case the ruleset provider offers a plain file, it simply will
515 sub extractruleset
($) {
518 # Get full path and downloaded rulesfile for the given provider.
519 my $tarball = &_get_dl_rulesfile
($provider);
521 # Check if the file exists.
522 unless (-f
$tarball) {
523 &_log_to_syslog
("Could not find ruleset file: $tarball");
529 # Check if the temporary directories exist, otherwise create them.
530 mkdir("$tmp_directory") unless (-d
"$tmp_directory");
531 mkdir("$tmp_rules_directory") unless (-d
"$tmp_rules_directory");
532 mkdir("$tmp_conf_directory") unless (-d
"$tmp_conf_directory");
534 # Omit the type (dl_type) of the stored ruleset.
535 my $type = $IDS::Ruleset
::Providers
{$provider}{'dl_type'};
537 # Handle the different ruleset types.
538 if ($type eq "plain") {
539 # Generate destination filename an full path.
540 my $destination = "$tmp_rules_directory/$provider\-ruleset.rules";
542 # Copy the file into the temporary rules directory.
543 copy
($tarball, $destination);
545 } elsif ( $type eq "archive") {
546 # Initialize the tar module.
547 my $tar = Archive
::Peek
::Libarchive
->new(filename
=> $tarball);
549 # Loop through the archive
551 my ($packed_file, $content) = @_;
554 # Splitt the packed file into chunks.
555 my $file = fileparse
($packed_file);
557 # Handle msg-id.map file.
558 if ("$file" eq "sid-msg.map") {
559 # Set extract destination to temporary config_dir.
560 $destination = "$tmp_conf_directory/$provider\-sid-msg.map";
562 # Handle classification.conf
563 } elsif ("$file" eq "classification.config") {
564 # Set extract destination to temporary config_dir.
565 $destination = "$tmp_conf_directory/$provider\-classification.config";
567 # Handle rules files.
568 } elsif ($file =~ m/\.rules$/) {
569 # Skip rule files which are not located in the rules directory or archive root.
570 return unless(($packed_file =~ /^rules\//) || ($packed_file =~ /^$provider-rules\
//) || ($packed_file !~ /\//));
572 # Skip deleted.rules.
574 # Mostly they have been taken out for correctness or performance reasons and therfore
575 # it is not a great idea to enable any of them.
576 return if($file =~ m/deleted.rules$/);
580 # Splitt the filename into chunks.
581 my @filename = split("-", $file);
584 @filename = reverse(@filename);
586 # Get the amount of elements in the array.
587 my $elements = @filename;
589 # Remove last element of the hash.
590 # It contains the vendor name, which will be replaced.
591 if ($elements >= 3) {
592 # Remove last element from hash.
596 # Check if the last element of the filename does not
597 # contain the providers name.
598 if ($filename[-1] ne "$provider") {
599 # Add provider name as last element.
600 push(@filename, $provider);
603 # Reverse the array back.
604 @filename = reverse(@filename);
606 # Generate the name for the rulesfile.
607 $rulesfilename = join("-", @filename);
609 # Set extract destination to temporaray rules_dir.
610 $destination = "$tmp_rules_directory/$rulesfilename";
612 # Skip all other files.
616 # Check if the destination file exists.
617 unless(-e
"$destination") {
618 # Open filehandle to write the content to a new file.
619 open(FILE
, ">", "$destination") or die "Could not open $destination. $!\n";
621 # Open filehandle to append the content to the existing file.
622 open(FILE
, ">>", "$destination") or die "Could not open $destination. $!\n";
625 # Write the extracted file content to the filehandle.
626 print FILE
"$content" if ($content);
628 # Close the file handle.
635 ## A wrapper function to call the oinkmaster script, setup the rules structues and
636 ## call the functions to merge the additional config files. (classification, sid-msg, etc.).
639 # Check if the files in rulesdir have the correct permissions.
640 &_check_rulesdir_permissions
();
642 # Cleanup the rules directory before filling it with the new rulests.
643 &_cleanup_rulesdir
();
645 # Get all enabled providers.
646 my @enabled_providers = &get_enabled_providers
();
648 # Loop through the array of enabled providers.
649 foreach my $provider (@enabled_providers) {
650 # Call the extractruleset function.
651 &extractruleset
($provider);
654 # Call function to process the ruleset and do all modifications.
655 &process_ruleset
(@enabled_providers);
657 # Call function to merge the classification files.
658 &merge_classifications
(@enabled_providers);
660 # Call function to merge the sid to message mapping files.
661 &merge_sid_msg
(@enabled_providers);
663 # Cleanup temporary directory.
664 &cleanup_tmp_directory
();
668 ## Function to alter the ruleset.
670 sub process_ruleset
(@
) {
671 my (@providers) = @_;
673 # Hash to store the configured provider modes.
674 my %providers_mode = &get_providers_mode
();
676 # Array to store the extracted rulefile from the temporary rules directory.
677 my @extracted_rulefiles;
679 # Get names of the extracted raw rulefiles.
680 opendir(DIR
, $tmp_rules_directory) or die "Could not read from $tmp_rules_directory. $!\n";
681 while (my $file = readdir(DIR
)) {
682 # Ignore single and double dotted files.
683 next if $file =~ /^\.\.?$/;
685 # Add file to the array of extracted files.
686 push(@extracted_rulefiles, $file);
689 # Close directory handle.
692 # Loop through the array of providers.
693 foreach my $provider (@providers) {
694 # Hash to store the obtained SIDs and REV of each provider.
697 # Hash which holds modifications to apply to the rules.
698 my %modifications = ();
700 # Loop through the array of extraced rulefiles.
701 foreach my $file (@extracted_rulefiles) {
702 # Skip file if it does not belong to the current processed provider.
703 next unless ($file =~ m/^$provider/);
706 open(FILE
, "$tmp_rules_directory/$file") or die "Could not read $tmp_rules_directory/$file. $!\n";
708 # Loop through the file content.
709 while (my $line = <FILE
>) {
711 next if ($line =~ /^\s*$/);
713 # Call function to get the sid and rev of the rule.
714 my ($sid, $rev) = &_get_sid_and_rev
($line);
716 # Skip rule if a sid with a higher rev already has added to the rules hash.
717 next if ($rev le $rules{$sid});
719 # Add the new or rule with higher rev to the hash of rules.
727 # Get filename which contains the ruleset modifications for this provider.
728 my $modification_file = &get_provider_ruleset_modifications_file
($provider);
730 # Read file which holds the modifications of the ruleset for the current provider.
731 &General
::readhash
($modification_file, \
%modifications) if (-f
$modification_file);
733 # Loop again through the array of extracted rulesfiles.
734 foreach my $file (@extracted_rulefiles) {
735 # Skip the file if it does not belong to the current provider.
736 next unless ($file =~ m/^$provider/);
738 # Open the rulefile for writing.
739 open(RULEFILE
, ">", "$rulespath/$file") or die "Could not write to file $rulespath/$file. $!\n";
741 # Open the rulefile for reading.
742 open(TMP_RULEFILE
, "$tmp_rules_directory/$file") or die "Could not read $tmp_rules_directory/$file. $!\n";
744 # Loop through the raw temporary rulefile.
745 while (my $line = <TMP_RULEFILE
>) {
746 # Get the sid and rev of the rule.
747 my ($sid, $rev) = &_get_sid_and_rev
($line);
749 # Check if the current rule is obsoleted by a newer one.
751 # In this case the rev number in the rules hash is higher than the current one.
752 next if ($rev lt $rules{$sid});
754 # Check if the rule should be enabled or disabled.
755 if ($modifications{$sid} eq "enabled") {
756 # Drop the # at the start of the line.
758 } elsif ($modifications{$sid} eq "disabled") {
759 # Add a # at the start of the line to disable the rule.
760 $line = "#$line" unless ($line =~ /^#/);
763 # Check if the Provider is set so IPS mode.
764 if ($providers_mode{$provider} eq "IPS") {
765 # Replacements for sourcefire rules.
766 $line =~ s/^#\s*(?:alert|drop)(.+policy balanced-ips alert)/alert${1}/;
767 $line =~ s/^#\s*(?:alert|drop)(.+policy balanced-ips drop)/drop${1}/;
769 # Replacements for generic rules.
770 $line =~ s/^(#?)\s*(?:alert|drop)/${1}drop/;
771 $line =~ s/^(#?)\s*drop(.+flowbits:noalert;)/${1}alert${2}/;
774 # Write line / rule to the target rule file.
775 print RULEFILE
"$line";
786 ## Function to merge the classifications for a given amount of providers and write them
787 ## to the classifications file.
789 sub merge_classifications
(@
) {
792 # Hash to store all collected classifications.
793 my %classifications = ();
795 # Loop through the given array of providers.
796 foreach my $provider (@providers) {
797 # Generate full path to classification file.
798 my $classification_file = "$tmp_conf_directory/$provider\-classification.config";
800 # Skip provider if no classification file exists.
801 next unless (-f
"$classification_file");
803 # Open the classification file.
804 open(CLASSIFICATION
, $classification_file) or die "Could not open file $classification_file. $!\n";
806 # Loop through the file content.
807 while(<CLASSIFICATION
>) {
808 # Parse the file and grab the classification details.
809 if ($_ =~/.*config classification\: (.*)/) {
810 # Split the grabbed details.
811 my ($short_name, $short_desc, $priority) = split("\,", $1);
813 # Check if the grabbed classification is allready known and the priority value is greater
814 # than the stored one (which causes less priority in the IDS).
815 if (($classifications{$short_name}) && ($classifications{$short_name}[1] >= $priority)) {
816 #Change the priority value to the stricter one.
817 $classifications{$short_name} = [ "$classifications{$short_name}[0]", "$priority" ];
819 # Add the classification to the hash.
820 $classifications{$short_name} = [ "$short_desc", "$priority" ];
826 close(CLASSIFICATION
);
829 # Open classification file for writing.
830 open(FILE
, ">", "$classification_file") or die "Could not write to $classification_file. $!\n";
832 # Print notice about autogenerated file.
833 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n\n";
835 # Sort and loop through the hash of classifications.
836 foreach my $key (sort keys %classifications) {
837 # Assign some nice variable names for the items.
838 my $short_name = $key;
839 my $short_desc = $classifications{$key}[0];
840 my $priority = $classifications{$key}[1];
842 # Write the classification to the file.
843 print FILE
"config classification: $short_name,$short_desc,$priority\n";
851 ## Function to merge the "sid to message mapping" files of various given providers.
853 sub merge_sid_msg
(@
) {
856 # Hash which contains all the sid to message mappings.
859 # Loop through the array of given providers.
860 foreach my $provider (@providers) {
861 # Generate full path and filename.
862 my $sid_msg_file = "$tmp_conf_directory/$provider\-sid-msg.map";
864 # Skip provider if no sid to msg mapping file for this provider exists.
865 next unless (-f
$sid_msg_file);
868 open(MAPPING
, $sid_msg_file) or die "Could not open $sid_msg_file. $!\n";
870 # Loop through the file content.
875 # Skip lines which do not start with a number,
876 next unless ($_ =~ /^\d+/);
878 # Split line content and assign it to an array.
879 my @line = split(/ \|\| /, $_);
881 # Grab the first element (and remove it) from the line array.
882 # It contains the sid.
883 my $sid = shift(@line);
885 # Store the grabbed sid and the remain array as hash value.
886 # It still contains the messages, references etc.
887 $mappings{$sid} = [@line];
894 # Open mappings file for writing.
895 open(FILE
, ">", $sid_msg_file) or die "Could not write $sid_msg_file. $!\n";
897 # Write notice about autogenerated file.
898 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n\n";
900 # Loop through the hash of mappings.
901 foreach my $sid ( sort keys %mappings) {
902 # Grab data for the sid.
903 my @data = @
{$mappings{$sid}};
905 # Add the sid to the data array.
906 unshift(@data, $sid);
909 my $line = join(" \|\| ", @data);
911 print FILE
"$line\n";
920 ## A very tiny function to move an extracted ruleset from the temporary directory into
921 ## the rules directory.
923 sub move_tmp_ruleset
() {
924 # Do a directory listing of the temporary directory.
925 opendir DH
, $tmp_rules_directory;
927 # Loop over all files.
928 while(my $file = readdir DH
) {
929 # Move them to the rules directory.
930 move
"$tmp_rules_directory/$file" , "$rulespath/$file";
933 # Close directory handle.
938 ## Function to cleanup the temporary IDS directroy.
940 sub cleanup_tmp_directory
() {
942 # Delete temporary directory and all containing files.
943 rmtree
([ "$tmp_directory" ]);
947 ## Function to do all the logging stuff if the downloading or updating of the ruleset fails.
952 # Remove any newline.
955 # Call private function to log the error message to syslog.
956 &_log_to_syslog
($error);
958 # Call private function to write/store the error message in the storederrorfile.
959 &_store_error_message
($error);
963 ## Function to log a given error message to the kernel syslog.
965 sub _log_to_syslog
($) {
968 # The syslog function works best with an array based input,
969 # so generate one before passing the message details to syslog.
970 my @syslog = ("ERR", "<ERROR> $message");
972 # Establish the connection to the syslog service.
973 openlog
('oinkmaster', 'cons,pid', 'user');
975 # Send the log message.
978 # Close the log handle.
983 ## Private function to write a given error message to the storederror file.
985 sub _store_error_message
($) {
988 # Remove any newline.
991 # Open file for writing.
992 open (ERRORFILE
, ">$storederrorfile") or die "Could not write to $storederrorfile. $!\n";
994 # Write error to file.
995 print ERRORFILE
"$message\n";
1000 # Set correct ownership for the file.
1001 &set_ownership
("$storederrorfile");
1005 ## Private function to get the path and filename for a downloaded ruleset by a given provider.
1007 sub _get_dl_rulesfile
($) {
1008 my ($provider) = @_;
1010 # Abort if the requested provider is not known.
1011 return unless($IDS::Ruleset
::Providers
{$provider});
1013 # Try to gather the download type for the given provider.
1014 my $dl_type = $IDS::Ruleset
::Providers
{$provider}{'dl_type'};
1016 # Check if a download type could be grabbed.
1018 # Obtain the file suffix for the download file type.
1019 my $suffix = $dl_type_to_suffix{$dl_type};
1021 # Check if a suffix has been found.
1023 # Abort return - nothing.
1027 # Generate the full filename and path for the stored rules file.
1028 my $rulesfile = "$dl_rules_path/$dl_rulesfile_prefix-$provider$suffix";
1030 # Return the generated filename.
1034 # A downloaded ruleset for a provider which is not supported anymore is requested.
1036 # Try to enumerate the downloaded ruleset file.
1037 foreach my $dl_type (keys %dl_type_to_suffix) {
1038 # Get the file suffix for the supported type.
1039 my $suffix = $dl_type_to_suffix{$dl_type};
1041 # Generate possible ruleset file name.
1042 my $rulesfile = "$dl_rules_path/$dl_rulesfile_prefix-$provider$suffix";
1044 # Check if such a file exists.
1045 if (-f
$rulesfile) {
1046 # Downloaded rulesfile found - Return the filename.
1052 # If we got here, no rulesfile could be determined - return nothing.
1057 ## Private function to obtain the sid and rev of a rule.
1059 ## Returns an array with the sid as first and the rev as second value.
1061 sub _get_sid_and_rev
($) {
1066 # Use regex to obtain the sid and rev.
1067 if ($line =~ m/.*sid:\s*(.*?);.*rev:\s*(.*?);/) {
1068 # Add the sid and rev to the array.
1078 ## Tiny function to delete the stored ruleset file or tarball for a given provider.
1080 sub drop_dl_rulesfile
($) {
1081 my ($provider) = @_;
1083 # Gather the full path and name of the stored rulesfile.
1084 my $rulesfile = &_get_dl_rulesfile
($provider);
1086 # Check if the given rulesfile exists.
1087 if (-f
$rulesfile) {
1088 # Delete the stored rulesfile.
1089 unlink($rulesfile) or die "Could not delete $rulesfile. $!\n";
1094 ## Function to check if the IDS is running.
1096 sub ids_is_running
() {
1097 if(-f
$idspidfile) {
1098 # Open PID file for reading.
1099 open(PIDFILE
, "$idspidfile") or die "Could not open $idspidfile. $!\n";
1101 # Grab the process-id.
1102 my $pid = <PIDFILE
>;
1107 # Remove any newline.
1110 # Check if a directory for the process-id exists in proc.
1111 if(-d
"/proc/$pid") {
1112 # The IDS daemon is running return the process id.
1117 # Return nothing - IDS is not running.
1122 ## Function to call suricatactrl binary with a given command.
1124 sub call_suricatactrl
($) {
1125 # Get called option.
1126 my ($option, $interval) = @_;
1128 # Loop through the array of supported commands and check if
1129 # the given one is part of it.
1130 foreach my $cmd (@suricatactrl_cmds) {
1131 # Skip current command unless the given one has been found.
1132 next unless($cmd eq $option);
1134 # Call the suricatactrl binary and pass the requrested
1136 &General
::system("$suricatactrl", "$option");
1138 # Return "1" - True.
1142 # Command not found - return nothing.
1147 ## Function to create a new empty file.
1149 sub create_empty_file
($) {
1152 # Check if the given file exists.
1154 # Do nothing to prevent from overwriting existing files.
1158 # Open the file for writing.
1159 open(FILE
, ">$file") or die "Could not write to $file. $!\n";
1161 # Close file handle.
1169 ## Private function to check if the file permission of the rulespath are correct.
1170 ## If not, call suricatactrl to fix them.
1172 sub _check_rulesdir_permissions
() {
1173 # Check if the rulepath main directory is writable.
1174 unless (-W
$rulespath) {
1175 # If not call suricatctrl to fix it.
1176 &call_suricatactrl
("fix-rules-dir");
1179 # Open snort rules directory and do a directory listing.
1180 opendir(DIR
, $rulespath) or die $!;
1181 # Loop through the direcory.
1182 while (my $file = readdir(DIR
)) {
1183 # We only want files.
1184 next unless (-f
"$rulespath/$file");
1186 # Check if the file is writable by the user.
1187 if (-W
"$rulespath/$file") {
1188 # Everything is okay - go on to the next file.
1191 # There are wrong permissions, call suricatactrl to fix it.
1192 &call_suricatactrl
("fix-rules-dir");
1198 ## Private function to cleanup the directory which contains
1199 ## the IDS rules, before extracting and modifing the new ruleset.
1201 sub _cleanup_rulesdir
() {
1202 # Open rules directory and do a directory listing.
1203 opendir(DIR
, $rulespath) or die $!;
1205 # Loop through the direcory.
1206 while (my $file = readdir(DIR
)) {
1207 # We only want files.
1208 next unless (-f
"$rulespath/$file");
1210 # Skip rules file for whitelisted hosts.
1211 next if ("$rulespath/$file" eq $whitelist_file);
1213 # Skip rules file with local rules.
1214 next if ("$rulespath/$file" eq $local_rules_file);
1216 # Delete the current processed file, if not, exit this function
1217 # and return an error message.
1218 unlink("$rulespath/$file") or return "Could not delete $rulespath/$file. $!\n";
1226 ## Function to generate the file which contains the home net information.
1228 sub generate_home_net_file
() {
1231 # Read-in network settings.
1232 &General
::readhash
("${General::swroot}/ethernet/settings", \
%netsettings);
1234 # Get available network zones.
1235 my @network_zones = &Network
::get_available_network_zones
();
1237 # Temporary array to store network address and prefix of the configured
1241 # Loop through the array of available network zones.
1242 foreach my $zone (@network_zones) {
1243 # Check if the current processed zone is red.
1244 if($zone eq "red") {
1245 # Grab the IP-address of the red interface.
1246 my $red_address = &get_red_address
();
1248 # Check if an address has been obtained.
1250 # Generate full network string.
1251 my $red_network = join("/", $red_address, "32");
1253 # Add the red network to the array of networks.
1254 push(@networks, $red_network);
1257 # Check if the configured RED_TYPE is static.
1258 if ($netsettings{'RED_TYPE'} eq "STATIC") {
1259 # Get configured and enabled aliases.
1260 my @aliases = &get_aliases
();
1262 # Loop through the array.
1263 foreach my $alias (@aliases) {
1265 my $network = join("/", $alias, "32");
1267 # Add the generated network to the array of networks.
1268 push(@networks, $network);
1271 # Process remaining network zones.
1273 # Convert current zone name into upper case.
1276 # Generate key to access the required data from the netsettings hash.
1277 my $zone_netaddress = $zone . "_NETADDRESS";
1278 my $zone_netmask = $zone . "_NETMASK";
1280 # Obtain the settings from the netsettings hash.
1281 my $netaddress = $netsettings{$zone_netaddress};
1282 my $netmask = $netsettings{$zone_netmask};
1284 # Convert the subnetmask into prefix notation.
1285 my $prefix = &Network
::convert_netmask2prefix
($netmask);
1287 # Generate full network string.
1288 my $network = join("/", $netaddress,$prefix);
1290 # Check if the network is valid.
1291 if(&Network
::check_subnet
($network)) {
1292 # Add the generated network to the array of networks.
1293 push(@networks, $network);
1298 # Format home net declaration.
1299 my $line = "\"[" . join(',', @networks) . "]\"";
1301 # Open file to store the addresses of the home net.
1302 open(FILE
, ">$homenet_file") or die "Could not open $homenet_file. $!\n";
1304 # Print yaml header.
1305 print FILE
"%YAML 1.1\n";
1306 print FILE
"---\n\n";
1308 # Print notice about autogenerated file.
1309 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1311 # Print the generated and required HOME_NET declaration to the file.
1312 print FILE
"HOME_NET:\t$line\n";
1314 # Close file handle.
1319 # Function to generate and write the file which contains the configured and used DNS servers.
1321 sub generate_dns_servers_file
() {
1322 # Get the used DNS servers.
1323 my @nameservers = &General
::get_nameservers
();
1325 # Get network settings.
1327 &General
::readhash
("${General::swroot}/ethernet/settings", \
%netsettings);
1329 # Format dns servers declaration.
1332 # Check if the system has configured nameservers.
1334 # Add the GREEN address as DNS servers.
1335 push(@nameservers, $netsettings{'GREEN_ADDRESS'});
1337 # Check if a BLUE zone exists.
1338 if ($netsettings{'BLUE_ADDRESS'}) {
1339 # Add the BLUE address to the array of nameservers.
1340 push(@nameservers, $netsettings{'BLUE_ADDRESS'});
1343 # Generate the line which will be written to the DNS servers file.
1344 $line = join(",", @nameservers);
1346 # External net simply contains (any).
1347 $line = "\$EXTERNAL_NET";
1350 # Open file to store the used DNS server addresses.
1351 open(FILE
, ">$dns_servers_file") or die "Could not open $dns_servers_file. $!\n";
1353 # Print yaml header.
1354 print FILE
"%YAML 1.1\n";
1355 print FILE
"---\n\n";
1357 # Print notice about autogenerated file.
1358 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1360 # Print the generated DNS declaration to the file.
1361 print FILE
"DNS_SERVERS:\t\"[$line]\"\n";
1363 # Close file handle.
1368 # Function to generate and write the file which contains the HTTP_PORTS definition.
1370 sub generate_http_ports_file
() {
1373 # Read-in proxy settings
1374 &General
::readhash
("${General::swroot}/proxy/advanced/settings", \
%proxysettings);
1376 # Check if the proxy is enabled.
1377 if (( -e
"${General::swroot}/proxy/enable") || (-e
"${General::swroot}/proxy/enable_blue")) {
1378 # Add the proxy port to the array of HTTP ports.
1379 push(@http_ports, $proxysettings{'PROXY_PORT'});
1382 # Check if the transparent mode of the proxy is enabled.
1383 if ((-e
"${General::swroot}/proxy/transparent") || (-e
"${General::swroot}/proxy/transparent_blue")) {
1384 # Add the transparent proxy port to the array of HTTP ports.
1385 push(@http_ports, $proxysettings{'TRANSPARENT_PORT'});
1388 # Format HTTP_PORTS declaration.
1391 # Generate line which will be written to the http ports file.
1392 $line = join(",", @http_ports);
1394 # Open file to store the HTTP_PORTS.
1395 open(FILE
, ">$http_ports_file") or die "Could not open $http_ports_file. $!\n";
1397 # Print yaml header.
1398 print FILE
"%YAML 1.1\n";
1399 print FILE
"---\n\n";
1401 # Print notice about autogenerated file.
1402 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1404 # Print the generated HTTP_PORTS declaration to the file.
1405 print FILE
"HTTP_PORTS:\t\"[$line]\"\n";
1407 # Close file handle.
1412 ## Function to write the file that contains the rulefiles which are loaded by suricaa.
1414 ## This function requires an array of used provider handles.
1416 sub write_used_rulefiles_file
(@
) {
1417 my (@providers) = @_;
1419 # Get the enabled application layer protocols.
1420 my @enabled_app_layer_protos = &get_suricata_enabled_app_layer_protos
();
1423 open (FILE
, ">", $suricata_used_rulesfiles_file) or die "Could not write to $suricata_used_rulesfiles_file. $!\n";
1425 print FILE
"%YAML 1.1\n";
1426 print FILE
"---\n\n";
1428 # Write notice about autogenerated file.
1429 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1431 # Loop through the array of static included rulesfiles.
1432 foreach my $file (@static_included_rulefiles) {
1433 # Check if the file exists.
1434 if (-f
"$rulespath/$file") {
1435 # Write the rulesfile name to the file.
1436 print FILE
" - $rulespath/$file\n";
1440 print FILE
"\n#Default rules for used application layer protocols.\n";
1441 foreach my $enabled_app_layer_proto (@enabled_app_layer_protos) {
1442 # Check if the current processed app layer proto needs to be translated
1443 # into an application name.
1444 if (exists($tr_app_layer_proto{$enabled_app_layer_proto})) {
1445 # Obtain the translated application name for this protocol.
1446 $enabled_app_layer_proto = $tr_app_layer_proto{$enabled_app_layer_proto};
1449 # Generate filename.
1450 my $rulesfile = "$default_rulespath/$enabled_app_layer_proto\.rules";
1452 # Check if such a file exists.
1453 if (-f
"$rulesfile") {
1454 # Write the rulesfile name to the file.
1455 print FILE
" - $rulesfile\n";
1458 # Generate filename with "events" in filename.
1459 $rulesfile = "$default_rulespath/$enabled_app_layer_proto\-events.rules";
1461 # Check if this file exists.
1462 if (-f
"$rulesfile" ) {
1463 # Write the rulesfile name to the file.
1464 print FILE
" - $rulesfile\n";
1468 # Loop through the array of enabled providers.
1469 foreach my $provider (@providers) {
1470 # Skip unsupported providers.
1471 next unless ($IDS::Ruleset
::Providers
{$provider});
1473 # Get the used rulefile for this provider.
1474 my @used_rulesfiles = &get_provider_used_rulesfiles
($provider);
1476 # Check if there are
1477 if(@used_rulesfiles) {
1478 # Add notice to the file.
1479 print FILE
"\n#Used Rulesfiles for provider $provider.\n";
1481 # Loop through the array of used rulefiles.
1482 foreach my $enabled_rulesfile (@used_rulesfiles) {
1483 # Generate name and full path to the rulesfile.
1484 my $rulesfile = "$rulespath/$enabled_rulesfile";
1486 # Write the ruelsfile name to the file.
1487 print FILE
" - $rulesfile\n";
1492 # Close the file handle
1497 ## Tiny function to generate the full path and name for the file which stores the used rulefiles of a given provider.
1499 sub get_provider_used_rulesfiles_file
($) {
1500 my ($provider) = @_;
1502 my $filename = "$settingsdir/$provider\-used\-rulesfiles";
1504 # Return the gernerated file.
1509 ## Tiny function to generate the full path and name for the file which stores the modifications of a ruleset.
1511 sub get_provider_ruleset_modifications_file
($) {
1512 my ($provider) = @_;
1514 my $filename = "$settingsdir/$provider\-modifications";
1516 # Return the filename.
1521 ## Function to get the subscription code of a configured provider.
1523 sub get_subscription_code
($) {
1524 my ($provider) = @_;
1526 my %configured_providers = ();
1528 # Read-in providers settings file.
1529 &General
::readhasharray
($providers_settings_file, \
%configured_providers);
1531 # Loop through the hash of configured providers.
1532 foreach my $id (keys %configured_providers) {
1533 # Assign nice human-readable values to the data fields.
1534 my $provider_handle = $configured_providers{$id}[0];
1535 my $subscription_code = $configured_providers{$id}[1];
1537 # Check if the current processed provider is the requested one.
1538 if ($provider_handle eq $provider) {
1539 # Return the obtained subscription code.
1540 return $subscription_code;
1544 # No subscription code found - return nothing.
1549 ## Function to get the ruleset date for a given provider.
1551 ## The function simply return the creation date in a human read-able format
1552 ## of the stored providers rulesfile.
1554 sub get_ruleset_date
($) {
1555 my ($provider) = @_;
1559 # Get the stored rulesfile for this provider.
1560 my $stored_rulesfile = &_get_dl_rulesfile
($provider);
1562 # Check if we got a file.
1563 if (-f
$stored_rulesfile) {
1564 # Call stat on the rulestarball.
1565 my $stat = stat("$stored_rulesfile");
1567 # Get timestamp the file creation.
1568 $mtime = $stat->mtime;
1571 # Check if the timestamp has not been grabbed.
1573 # Return N/A for Not available.
1577 # Convert into human read-able format.
1578 $date = strftime
('%Y-%m-%d %H:%M:%S', localtime($mtime));
1585 ## Function to gather the version of suricata.
1587 sub get_suricata_version
($) {
1590 # Execute piped suricata command and return the version information.
1591 open(SURICATA
, "suricata -V |") or die "Couldn't execute program: $!";
1593 # Grab and store the output of the piped program.
1594 my $version_string = <SURICATA
>;
1600 chomp($version_string);
1602 # Grab the version from the version string.
1603 $version_string =~ /([0-9]+([.][0-9]+)+)/;
1605 # Splitt the version into single chunks.
1606 my ($major_ver, $minor_ver, $patchlevel) = split(/\./, $1);
1608 # Check and return the requested version sheme.
1609 if ($format eq "major") {
1610 # Return the full version.
1611 return "$major_ver";
1612 } elsif ($format eq "minor") {
1613 # Return the major and minor part.
1614 return "$major_ver.$minor_ver";
1616 # Return the full version string.
1617 return "$major_ver.$minor_ver.$patchlevel";
1622 ## Function to get the enabled application layer protocols.
1624 sub get_suricata_enabled_app_layer_protos
() {
1625 # Array to store and return the enabled app layer protos.
1626 my @enabled_app_layer_protos = ();
1628 # Execute piped suricata command and return the list of
1629 # enabled application layer protocols.
1630 open(SURICATA
, "suricata --list-app-layer-protos |") or die "Could not execute program: $!";
1632 # Grab and store the list of enabled application layer protocols.
1633 my @output = <SURICATA
>;
1638 # Merge allways enabled static application layers protocols array.
1639 @enabled_app_layer_protos = @static_enabled_app_layer_protos;
1641 # Loop through the array which contains the output of suricata.
1642 foreach my $line (@output) {
1643 # Skip header line which starts with "===".
1644 next if ($line =~ /^\s*=/);
1646 # Skip info or warning lines.
1647 next if ($line =~ /\s*--/);
1652 # Add enabled app layer proto to the array.
1653 push(@enabled_app_layer_protos, $line);
1657 @enabled_app_layer_protos = sort(@enabled_app_layer_protos);
1660 return @enabled_app_layer_protos;
1664 ## Function to generate the rules file with whitelisted addresses.
1666 sub generate_ignore_file
() {
1669 # SID range 1000000-1999999 Reserved for Local Use
1670 # Put your custom rules in this range to avoid conflicts
1673 # Read-in ignoredfile.
1674 &General
::readhasharray
($IDS::ignored_file
, \
%ignored);
1676 # Open ignorefile for writing.
1677 open(FILE
, ">$IDS::whitelist_file") or die "Could not write to $IDS::whitelist_file. $!\n";
1679 # Config file header.
1680 print FILE
"# Autogenerated file.\n";
1681 print FILE
"# All user modifications will be overwritten.\n\n";
1683 # Add all user defined addresses to the whitelist.
1685 # Check if the hash contains any elements.
1686 if (keys (%ignored)) {
1687 # Loop through the entire hash and write the host/network
1688 # and remark to the ignore file.
1689 while ( (my $key) = each %ignored) {
1690 my $address = $ignored{$key}[0];
1691 my $remark = $ignored{$key}[1];
1692 my $status = $ignored{$key}[2];
1694 # Check if the status of the entry is "enabled".
1695 if ($status eq "enabled") {
1696 # Check if the address/network is valid.
1697 if ((&General
::validip
($address)) || (&General
::validipandmask
($address))) {
1698 # Write rule line to the file to pass any traffic from this IP
1699 print FILE
"pass ip $address any -> any any (msg:\"pass all traffic from/to $address\"\; bypass; sid:$sid\;)\n";
1712 ## Function to set correct ownership for single files and directories.
1715 sub set_ownership
($) {
1718 # User and group of the WUI.
1719 my $uname = "nobody";
1720 my $grname = "nobody";
1722 # The chown function implemented in perl requies the user and group as nummeric id's.
1723 my $uid = getpwnam($uname);
1724 my $gid = getgrnam($grname);
1726 # Check if the given target exists.
1728 # Stop the script and print error message.
1729 die "The $target does not exist. Cannot change the ownership!\n";
1732 # Check weather the target is a file or directory.
1734 # Change ownership ot the single file.
1735 chown($uid, $gid, "$target");
1736 } elsif (-d
$target) {
1737 # Do a directory listing.
1738 opendir(DIR
, $target) or die $!;
1739 # Loop through the direcory.
1740 while (my $file = readdir(DIR
)) {
1742 # We only want files.
1743 next unless (-f
"$target/$file");
1745 # Set correct ownership for the files.
1746 chown($uid, $gid, "$target/$file");
1751 # Change ownership of the directory.
1752 chown($uid, $gid, "$target");
1757 ## Function to read-in the aliases file and returns all configured and enabled aliases.
1760 # Location of the aliases file.
1761 my $aliases_file = "${General::swroot}/ethernet/aliases";
1763 # Array to store the aliases.
1766 # Check if the file is empty.
1767 if (-z
$aliases_file) {
1768 # Abort nothing to do.
1772 # Open the aliases file.
1773 open(ALIASES
, $aliases_file) or die "Could not open $aliases_file. $!\n";
1775 # Loop through the file content.
1776 while (my $line = <ALIASES
>) {
1780 # Splitt line content into single chunks.
1781 my ($address, $state, $remark) = split(/\,/, $line);
1783 # Check if the state of the current processed alias is "on".
1784 if ($state eq "on") {
1785 # Check if the address is valid.
1786 if(&Network
::check_ip_address
($address)) {
1787 # Add the alias to the array of aliases.
1788 push(@aliases, $address);
1793 # Close file handle.
1801 ## Function to grab the current assigned IP-address on red.
1803 sub get_red_address
() {
1804 # File, which contains the current IP-address of the red interface.
1805 my $file = "${General::swroot}/red/local-ipaddress";
1807 # Check if the file exists.
1809 # Open the given file.
1810 open(FILE
, "$file") or die "Could not open $file.";
1812 # Obtain the address from the first line of the file.
1813 my $address = <FILE
>;
1821 # Check if the grabbed address is valid.
1822 if (&General
::validip
($address)) {
1823 # Return the address.
1833 ## Function to get the used rules files of a given provider.
1835 sub get_provider_used_rulesfiles
($) {
1836 my ($provider) = @_;
1838 # Hash to store the used rulefiles of the provider.
1839 my %provider_rulefiles = ();
1841 # Array to store the used rulefiles.
1842 my @used_rulesfiles = ();
1844 # Get the filename which contains the used rulefiles for this provider.
1845 my $used_rulesfiles_file = &get_provider_used_rulesfiles_file
($provider);
1847 # Read-in file, if it exists.
1848 &General
::readhash
("$used_rulesfiles_file", \
%provider_rulefiles) if (-f
$used_rulesfiles_file);
1850 # Loop through the hash of rulefiles which does the provider offer.
1851 foreach my $rulefile (keys %provider_rulefiles) {
1852 # Skip disabled rulefiles.
1853 next unless($provider_rulefiles{$rulefile} eq "enabled");
1855 # The General::readhash function does not allow dots as
1856 # key value and limits the key "string" to the part before
1857 # the dot, in case it contains one.
1859 # So add the file extension for the rules file manually again.
1860 $rulefile = "$rulefile.rules";
1862 # Add the enabled rulefile to the array of enabled rulefiles.
1863 push(@used_rulesfiles, $rulefile);
1866 # Return the array of used rulesfiles.
1867 return @used_rulesfiles;
1871 ## Function to delete the stored etag data of a given provider.
1873 sub remove_from_etags
($) {
1874 my ($provider) = @_;
1878 # Early exit function if the etags file does not exist.
1879 return unless (-f
$etags_file);
1881 # Read-in etag file.
1882 &General
::readhash
("$etags_file", \
%etags);
1884 # Check if the hash contains an entry for the given provider.
1885 if ($etags{$provider}) {
1887 delete($etags{$provider});
1889 # Write back the etags file.
1890 &General
::writehash
("$etags_file", \
%etags);
1895 ## Function to write the lock file for locking the WUI, while
1896 ## the autoupdate script runs.
1898 sub lock_ids_page
() {
1899 # Call subfunction to create the file.
1900 &create_empty_file
($ids_page_lock_file);
1904 ## Function to release the lock of the WUI, again.
1906 sub unlock_ids_page
() {
1908 unlink($ids_page_lock_file);