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 # Log App Layer Events? (Useful for debugging only)
156 my $LOG_APP_LAYER_EVENTS = 0;
158 # Array which contains a list of allways enabled application layer protocols.
159 my @static_enabled_app_layer_protos = ('app-layer', 'decoder', 'files', 'stream');
161 # Hash which allows to convert the download type (dl_type) to a file suffix.
162 my %dl_type_to_suffix = (
163 "archive" => ".tar.gz",
167 # Hash to translate an application layer protocol to the application name.
168 my %tr_app_layer_proto = (
170 "krb5" => "kerberos",
174 ## Function to check and create all IDS related files, if the does not exist.
176 sub check_and_create_filelayout
() {
177 # Check if the files exist and if not, create them.
178 unless (-f
"$suricata_used_rulesfiles_file") { &create_empty_file
($suricata_used_rulesfiles_file); }
179 unless (-f
"$ids_settings_file") { &create_empty_file
($ids_settings_file); }
180 unless (-f
"$providers_settings_file") { &create_empty_file
($providers_settings_file); }
181 unless (-f
"$whitelist_file" ) { &create_empty_file
($whitelist_file); }
185 ## Function to get a list of all available ruleset providers.
187 ## They will be returned as a sorted array.
189 sub get_ruleset_providers
() {
192 # Loop through the hash of providers.
193 foreach my $provider ( keys %IDS::Ruleset
::Providers
) {
194 # Add the provider to the array.
195 push(@providers, $provider);
198 # Sort and return the array.
199 return sort(@providers);
203 ## Function to get a list of all enabled ruleset providers.
205 ## They will be returned as an array.
207 sub get_enabled_providers
() {
208 my %used_providers = ();
210 # Array to store the enabled providers.
211 my @enabled_providers = ();
213 # Read-in the providers config file.
214 &General
::readhasharray
("$providers_settings_file", \
%used_providers);
216 # Loop through the hash of used_providers.
217 foreach my $id (keys %used_providers) {
218 # Skip disabled providers.
219 next unless ($used_providers{$id}[3] eq "enabled");
221 # Grab the provider handle.
222 my $provider = "$used_providers{$id}[0]";
224 # Add the provider to the array of enabled providers.
225 push(@enabled_providers, $provider);
229 return @enabled_providers;
233 ## Function to get a hash of provider handles and their configured modes (IDS/IPS).
235 sub get_providers_mode
() {
236 my %used_providers = ();
238 # Hash to store the providers and their configured modes.
239 my %providers_mode = ();
241 # Read-in the providers config file.
242 &General
::readhasharray
("$providers_settings_file", \
%used_providers);
244 # Loop through the hash of used_providers.
245 foreach my $id (keys %used_providers) {
246 # Skip disabled providers.
247 next unless ($used_providers{$id}[3] eq "enabled");
249 # Grab the provider handle.
250 my $provider = "$used_providers{$id}[0]";
252 # Grab the provider mode.
253 my $mode = "$used_providers{$id}[4]";
255 # Fall back to IDS if no mode could be obtained.
260 # Add details to provider_modes hash.
261 $providers_mode{$provider} = $mode;
265 return %providers_mode;
269 ## Function for checking if at least 300MB of free disk space are available
270 ## on the "/var" partition.
272 sub checkdiskspace
() {
273 # Call diskfree to gather the free disk space of /var.
274 my @df = &General
::system_output
("/bin/df", "-B", "M", "/var");
276 # Loop through the output.
277 foreach my $line (@df) {
278 # Ignore header line.
279 next if $line =~ m/^Filesystem/;
281 # Search for a line with the device information.
282 if ($line =~ m/dev/ ) {
283 # Split the line into single pieces.
284 my @values = split(' ', $line);
285 my ($filesystem, $blocks, $used, $available, $used_perenctage, $mounted_on) = @values;
287 # Check if the available disk space is more than 300MB.
288 if ($available < 300) {
289 # Exit function and return the available disk space.
295 # Everything okay, return nothing.
300 ## This function is responsible for downloading the ruleset for a given provider.
302 ## * At first it initialize the downloader and sets an upstream proxy if configured.
303 ## * The next step will be to generate the final download url, by obtaining the URL for the desired
304 ## ruleset and add the settings for the upstream proxy.
305 ## * Finally the function will grab the rule file or tarball from the server.
306 ## It tries to reduce the amount of download by using the "If-Modified-Since" HTTP header.
310 ## * "no url" - If no download URL could be gathered for the provider.
311 ## * "not modified" - In case the already stored rules file is up to date.
312 ## * "incomplete download" - When the remote file size differs from the downloaded file size.
313 ## * "$error" - The error message generated from the LWP::User Agent module.
315 sub downloadruleset
($) {
318 # The amount of download attempts before giving up and
320 my $max_dl_attempts = 3;
322 # Read proxysettings.
323 my %proxysettings=();
324 &General
::readhash
("${General::swroot}/proxy/settings", \
%proxysettings);
326 # Init the download module.
328 # Request SSL hostname verification and specify path
330 my $downloader = LWP
::UserAgent
->new(
332 SSL_ca_file
=> '/etc/ssl/cert.pem',
333 verify_hostname
=> 1,
337 # Set timeout to 10 seconds.
338 $downloader->timeout(10);
340 # Check if an upstream proxy is configured.
341 if ($proxysettings{'UPSTREAM_PROXY'}) {
344 $proxy_url = "http://";
346 # Check if the proxy requires authentication.
347 if (($proxysettings{'UPSTREAM_USER'}) && ($proxysettings{'UPSTREAM_PASSWORD'})) {
348 $proxy_url .= "$proxysettings{'UPSTREAM_USER'}\:$proxysettings{'UPSTREAM_PASSWORD'}\@";
351 # Add proxy server address and port.
352 $proxy_url .= $proxysettings{'UPSTREAM_PROXY'};
354 # Setup proxy settings.
355 $downloader->proxy(['http', 'https'], $proxy_url);
358 # Grab the download url for the provider.
359 my $url = $IDS::Ruleset
::Providers
{$provider}{'dl_url'};
361 # Check if the provider requires a subscription.
362 if ($IDS::Ruleset
::Providers
{$provider}{'requires_subscription'} eq "True") {
363 # Grab the subscription code.
364 my $subscription_code = &get_subscription_code
($provider);
366 # Add the subscription code to the download url.
367 $url =~ s/\<subscription_code\>/$subscription_code/g;
371 # Abort and return "no url", if no url could be determined for the provider.
372 return "no url" unless ($url);
374 # Pass the requested URL to the downloader.
375 my $request = HTTP
::Request
->new(GET
=> $url);
377 # Generate temporary file name, located in the tempoary download directory and with a suffix of ".tmp".
378 # The downloaded file will be stored there until some sanity checks are performed.
379 my $tmp = File
::Temp
->new( SUFFIX
=> ".tmp", DIR
=> "$tmp_dl_directory/", UNLINK
=> 0 );
380 my $tmpfile = $tmp->filename();
382 # Call function to get the final path and filename for the downloaded file.
383 my $dl_rulesfile = &_get_dl_rulesfile
($provider);
385 # Check if the rulesfile already exits, because it has been downloaded in the past.
387 # In this case we are requesting the server if the remote file has been changed or not.
388 # This will be done by sending the modification time in a special HTTP header.
389 if (-f
$dl_rulesfile) {
390 # Call stat on the file.
391 my $stat = stat($dl_rulesfile);
393 # Omit the mtime of the existing file.
394 my $mtime = $stat->mtime;
396 # Convert the timestamp into right format.
397 my $http_date = time2str
($mtime);
399 # Add the If-Modified-Since header to the request to ask the server if the
400 # file has been modified.
401 $request->header( 'If-Modified-Since' => "$http_date" );
404 # Read-in Etags file for known Etags if the file is present.
406 &General
::readhash
("$etags_file", \
%etags) if (-f
$etags_file);
408 # Check if an Etag for the current provider is stored.
409 if ($etags{$provider}) {
410 # Grab the stored tag.
411 my $etag = $etags{$provider};
413 # Add an "If-None-Match header to the request to ask the server if the
414 # file has been modified.
415 $request->header( 'If-None-Match' => $etag );
421 # Download and retry on failure.
422 while ($dl_attempt <= $max_dl_attempts) {
423 # Perform the request and save the output into the tmpfile.
424 $response = $downloader->request($request, $tmpfile);
426 # Check if the download was successfull.
427 if($response->is_success) {
431 # Check if the server responds with 304 (Not Modified).
432 } elsif ($response->code == 304) {
433 # Remove temporary file, if one exists.
434 unlink("$tmpfile") if (-e
"$tmpfile");
436 # Return "not modified".
437 return "not modified";
439 # Check if we ran out of download re-tries.
440 } elsif ($dl_attempt eq $max_dl_attempts) {
442 my $error = $response->content;
444 # Remove temporary file, if one exists.
445 unlink("$tmpfile") if (-e
"$tmpfile");
447 # Return the error message from response..
451 # Remove temporary file, if one exists.
452 unlink("$tmpfile") if (-e
"$tmpfile");
454 # Increase download attempt counter.
458 # Obtain the connection headers.
459 my $headers = $response->headers;
461 # Get the timestamp from header, when the file has been modified the
463 my $last_modified = $headers->last_modified;
465 # Get the remote size of the downloaded file.
466 my $remote_filesize = $headers->content_length;
468 # Grab the Etag from response it the server provides one.
469 if ($response->header('Etag')) {
470 # Add the Etag to the etags hash.
471 $etags{$provider} = $response->header('Etag');
473 # Write the etags file.
474 &General
::writehash
($etags_file, \
%etags);
477 # Perform stat on the tmpfile.
478 my $stat = stat($tmpfile);
480 # Grab the local filesize of the downloaded tarball.
481 my $local_filesize = $stat->size;
483 # Check if both file sizes match.
484 if (($remote_filesize) && ($remote_filesize ne $local_filesize)) {
485 # Delete temporary file.
488 # Return "1" - false.
489 return "incomplete download";
492 # Overwrite the may existing rulefile or tarball with the downloaded one.
493 move
("$tmpfile", "$dl_rulesfile");
495 # Check if we got a last-modified value from the server.
496 if ($last_modified) {
497 # Assign the last-modified timestamp as mtime to the
499 utime(time(), "$last_modified", "$dl_rulesfile");
502 # Delete temporary file.
505 # Set correct ownership for the tarball.
506 set_ownership
("$dl_rulesfile");
508 # If we got here, everything worked fine. Return nothing.
513 ## Function to extract a given ruleset.
515 ## In case the ruleset provider offers a plain file, it simply will
518 sub extractruleset
($) {
521 # Get full path and downloaded rulesfile for the given provider.
522 my $tarball = &_get_dl_rulesfile
($provider);
524 # Check if the file exists.
525 unless (-f
$tarball) {
526 &_log_to_syslog
("Could not find ruleset file: $tarball");
532 # Check if the temporary directories exist, otherwise create them.
533 mkdir("$tmp_directory") unless (-d
"$tmp_directory");
534 mkdir("$tmp_rules_directory") unless (-d
"$tmp_rules_directory");
535 mkdir("$tmp_conf_directory") unless (-d
"$tmp_conf_directory");
537 # Omit the type (dl_type) of the stored ruleset.
538 my $type = $IDS::Ruleset
::Providers
{$provider}{'dl_type'};
540 # Handle the different ruleset types.
541 if ($type eq "plain") {
542 # Generate destination filename an full path.
543 my $destination = "$tmp_rules_directory/$provider\-ruleset.rules";
545 # Copy the file into the temporary rules directory.
546 copy
($tarball, $destination);
548 } elsif ( $type eq "archive") {
549 # Initialize the tar module.
550 my $tar = Archive
::Peek
::Libarchive
->new(filename
=> $tarball);
552 # Loop through the archive
554 my ($packed_file, $content) = @_;
557 # Splitt the packed file into chunks.
558 my $file = fileparse
($packed_file);
560 # Handle msg-id.map file.
561 if ("$file" eq "sid-msg.map") {
562 # Set extract destination to temporary config_dir.
563 $destination = "$tmp_conf_directory/$provider\-sid-msg.map";
565 # Handle classification.conf
566 } elsif ("$file" eq "classification.config") {
567 # Set extract destination to temporary config_dir.
568 $destination = "$tmp_conf_directory/$provider\-classification.config";
570 # Handle rules files.
571 } elsif ($file =~ m/\.rules$/) {
572 # Skip rule files which are not located in the rules directory or archive root.
573 return unless(($packed_file =~ /^rules\//) || ($packed_file =~ /^$provider-rules\
//) || ($packed_file !~ /\//));
575 # Skip deleted.rules.
577 # Mostly they have been taken out for correctness or performance reasons and therfore
578 # it is not a great idea to enable any of them.
579 return if($file =~ m/deleted.rules$/);
583 # Splitt the filename into chunks.
584 my @filename = split("-", $file);
587 @filename = reverse(@filename);
589 # Get the amount of elements in the array.
590 my $elements = @filename;
592 # Remove last element of the hash.
593 # It contains the vendor name, which will be replaced.
594 if ($elements >= 3) {
595 # Remove last element from hash.
599 # Check if the last element of the filename does not
600 # contain the providers name.
601 if ($filename[-1] ne "$provider") {
602 # Add provider name as last element.
603 push(@filename, $provider);
606 # Reverse the array back.
607 @filename = reverse(@filename);
609 # Generate the name for the rulesfile.
610 $rulesfilename = join("-", @filename);
612 # Set extract destination to temporaray rules_dir.
613 $destination = "$tmp_rules_directory/$rulesfilename";
615 # Skip all other files.
619 # Check if the destination file exists.
620 unless(-e
"$destination") {
621 # Open filehandle to write the content to a new file.
622 open(FILE
, ">", "$destination") or die "Could not open $destination. $!\n";
624 # Open filehandle to append the content to the existing file.
625 open(FILE
, ">>", "$destination") or die "Could not open $destination. $!\n";
628 # Write the extracted file content to the filehandle.
629 print FILE
"$content" if ($content);
631 # Close the file handle.
638 ## A wrapper function to call the oinkmaster script, setup the rules structues and
639 ## call the functions to merge the additional config files. (classification, sid-msg, etc.).
642 # Check if the files in rulesdir have the correct permissions.
643 &_check_rulesdir_permissions
();
645 # Cleanup the rules directory before filling it with the new rulests.
646 &_cleanup_rulesdir
();
648 # Get all enabled providers.
649 my @enabled_providers = &get_enabled_providers
();
651 # Loop through the array of enabled providers.
652 foreach my $provider (@enabled_providers) {
653 # Call the extractruleset function.
654 &extractruleset
($provider);
657 # Call function to process the ruleset and do all modifications.
658 &process_ruleset
(@enabled_providers);
660 # Call function to merge the classification files.
661 &merge_classifications
(@enabled_providers);
663 # Call function to merge the sid to message mapping files.
664 &merge_sid_msg
(@enabled_providers);
666 # Cleanup temporary directory.
667 &cleanup_tmp_directory
();
671 ## Function to alter the ruleset.
673 sub process_ruleset
(@
) {
674 my (@providers) = @_;
676 # Hash to store the configured provider modes.
677 my %providers_mode = &get_providers_mode
();
679 # Array to store the extracted rulefile from the temporary rules directory.
680 my @extracted_rulefiles;
682 # Get names of the extracted raw rulefiles.
683 opendir(DIR
, $tmp_rules_directory) or die "Could not read from $tmp_rules_directory. $!\n";
684 while (my $file = readdir(DIR
)) {
685 # Ignore single and double dotted files.
686 next if $file =~ /^\.\.?$/;
688 # Add file to the array of extracted files.
689 push(@extracted_rulefiles, $file);
692 # Close directory handle.
695 # Loop through the array of providers.
696 foreach my $provider (@providers) {
697 # Hash to store the obtained SIDs and REV of each provider.
700 # Hash which holds modifications to apply to the rules.
701 my %modifications = ();
703 # Loop through the array of extraced rulefiles.
704 foreach my $file (@extracted_rulefiles) {
705 # Skip file if it does not belong to the current processed provider.
706 next unless ($file =~ m/^$provider/);
709 open(FILE
, "$tmp_rules_directory/$file") or die "Could not read $tmp_rules_directory/$file. $!\n";
711 # Loop through the file content.
712 while (my $line = <FILE
>) {
714 next if ($line =~ /^\s*$/);
716 # Call function to get the sid and rev of the rule.
717 my ($sid, $rev) = &_get_sid_and_rev
($line);
719 # Skip rule if a sid with a higher rev already has added to the rules hash.
720 next if ($rev le $rules{$sid});
722 # Add the new or rule with higher rev to the hash of rules.
730 # Get filename which contains the ruleset modifications for this provider.
731 my $modification_file = &get_provider_ruleset_modifications_file
($provider);
733 # Read file which holds the modifications of the ruleset for the current provider.
734 &General
::readhash
($modification_file, \
%modifications) if (-f
$modification_file);
736 # Loop again through the array of extracted rulesfiles.
737 foreach my $file (@extracted_rulefiles) {
738 # Skip the file if it does not belong to the current provider.
739 next unless ($file =~ m/^$provider/);
741 # Open the rulefile for writing.
742 open(RULEFILE
, ">", "$rulespath/$file") or die "Could not write to file $rulespath/$file. $!\n";
744 # Open the rulefile for reading.
745 open(TMP_RULEFILE
, "$tmp_rules_directory/$file") or die "Could not read $tmp_rules_directory/$file. $!\n";
747 # Loop through the raw temporary rulefile.
748 while (my $line = <TMP_RULEFILE
>) {
749 # Get the sid and rev of the rule.
750 my ($sid, $rev) = &_get_sid_and_rev
($line);
752 # Check if the current rule is obsoleted by a newer one.
754 # In this case the rev number in the rules hash is higher than the current one.
755 next if ($rev lt $rules{$sid});
757 # Check if the rule should be enabled or disabled.
758 if ($modifications{$sid} eq "enabled") {
759 # Drop the # at the start of the line.
761 } elsif ($modifications{$sid} eq "disabled") {
762 # Add a # at the start of the line to disable the rule.
763 $line = "#$line" unless ($line =~ /^#/);
766 # Check if the Provider is set so IPS mode.
767 if ($providers_mode{$provider} eq "IPS") {
768 # Replacements for sourcefire rules.
769 $line =~ s/^#\s*(?:alert|drop)(.+policy balanced-ips alert)/alert${1}/;
770 $line =~ s/^#\s*(?:alert|drop)(.+policy balanced-ips drop)/drop${1}/;
772 # Replacements for generic rules.
773 $line =~ s/^(#?)\s*(?:alert|drop)/${1}drop/;
774 $line =~ s/^(#?)\s*drop(.+flowbits:noalert;)/${1}alert${2}/;
777 # Write line / rule to the target rule file.
778 print RULEFILE
"$line";
789 ## Function to merge the classifications for a given amount of providers and write them
790 ## to the classifications file.
792 sub merge_classifications
(@
) {
795 # Hash to store all collected classifications.
796 my %classifications = ();
798 # Loop through the given array of providers.
799 foreach my $provider (@providers) {
800 # Generate full path to classification file.
801 my $classification_file = "$tmp_conf_directory/$provider\-classification.config";
803 # Skip provider if no classification file exists.
804 next unless (-f
"$classification_file");
806 # Open the classification file.
807 open(CLASSIFICATION
, $classification_file) or die "Could not open file $classification_file. $!\n";
809 # Loop through the file content.
810 while(<CLASSIFICATION
>) {
811 # Parse the file and grab the classification details.
812 if ($_ =~/.*config classification\: (.*)/) {
813 # Split the grabbed details.
814 my ($short_name, $short_desc, $priority) = split("\,", $1);
816 # Check if the grabbed classification is allready known and the priority value is greater
817 # than the stored one (which causes less priority in the IDS).
818 if (($classifications{$short_name}) && ($classifications{$short_name}[1] >= $priority)) {
819 #Change the priority value to the stricter one.
820 $classifications{$short_name} = [ "$classifications{$short_name}[0]", "$priority" ];
822 # Add the classification to the hash.
823 $classifications{$short_name} = [ "$short_desc", "$priority" ];
829 close(CLASSIFICATION
);
832 # Open classification file for writing.
833 open(FILE
, ">", "$classification_file") or die "Could not write to $classification_file. $!\n";
835 # Print notice about autogenerated file.
836 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n\n";
838 # Sort and loop through the hash of classifications.
839 foreach my $key (sort keys %classifications) {
840 # Assign some nice variable names for the items.
841 my $short_name = $key;
842 my $short_desc = $classifications{$key}[0];
843 my $priority = $classifications{$key}[1];
845 # Write the classification to the file.
846 print FILE
"config classification: $short_name,$short_desc,$priority\n";
854 ## Function to merge the "sid to message mapping" files of various given providers.
856 sub merge_sid_msg
(@
) {
859 # Hash which contains all the sid to message mappings.
862 # Loop through the array of given providers.
863 foreach my $provider (@providers) {
864 # Generate full path and filename.
865 my $sid_msg_file = "$tmp_conf_directory/$provider\-sid-msg.map";
867 # Skip provider if no sid to msg mapping file for this provider exists.
868 next unless (-f
$sid_msg_file);
871 open(MAPPING
, $sid_msg_file) or die "Could not open $sid_msg_file. $!\n";
873 # Loop through the file content.
878 # Skip lines which do not start with a number,
879 next unless ($_ =~ /^\d+/);
881 # Split line content and assign it to an array.
882 my @line = split(/ \|\| /, $_);
884 # Grab the first element (and remove it) from the line array.
885 # It contains the sid.
886 my $sid = shift(@line);
888 # Store the grabbed sid and the remain array as hash value.
889 # It still contains the messages, references etc.
890 $mappings{$sid} = [@line];
897 # Open mappings file for writing.
898 open(FILE
, ">", $sid_msg_file) or die "Could not write $sid_msg_file. $!\n";
900 # Write notice about autogenerated file.
901 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n\n";
903 # Loop through the hash of mappings.
904 foreach my $sid ( sort keys %mappings) {
905 # Grab data for the sid.
906 my @data = @
{$mappings{$sid}};
908 # Add the sid to the data array.
909 unshift(@data, $sid);
912 my $line = join(" \|\| ", @data);
914 print FILE
"$line\n";
923 ## A very tiny function to move an extracted ruleset from the temporary directory into
924 ## the rules directory.
926 sub move_tmp_ruleset
() {
927 # Do a directory listing of the temporary directory.
928 opendir DH
, $tmp_rules_directory;
930 # Loop over all files.
931 while(my $file = readdir DH
) {
932 # Move them to the rules directory.
933 move
"$tmp_rules_directory/$file" , "$rulespath/$file";
936 # Close directory handle.
941 ## Function to cleanup the temporary IDS directroy.
943 sub cleanup_tmp_directory
() {
945 # Delete temporary directory and all containing files.
946 rmtree
([ "$tmp_directory" ]);
950 ## Function to do all the logging stuff if the downloading or updating of the ruleset fails.
955 # Remove any newline.
958 # Call private function to log the error message to syslog.
959 &_log_to_syslog
($error);
961 # Call private function to write/store the error message in the storederrorfile.
962 &_store_error_message
($error);
966 ## Function to log a given error message to the kernel syslog.
968 sub _log_to_syslog
($) {
971 # The syslog function works best with an array based input,
972 # so generate one before passing the message details to syslog.
973 my @syslog = ("ERR", "<ERROR> $message");
975 # Establish the connection to the syslog service.
976 openlog
('oinkmaster', 'cons,pid', 'user');
978 # Send the log message.
981 # Close the log handle.
986 ## Private function to write a given error message to the storederror file.
988 sub _store_error_message
($) {
991 # Remove any newline.
994 # Open file for writing.
995 open (ERRORFILE
, ">$storederrorfile") or die "Could not write to $storederrorfile. $!\n";
997 # Write error to file.
998 print ERRORFILE
"$message\n";
1003 # Set correct ownership for the file.
1004 &set_ownership
("$storederrorfile");
1008 ## Private function to get the path and filename for a downloaded ruleset by a given provider.
1010 sub _get_dl_rulesfile
($) {
1011 my ($provider) = @_;
1013 # Abort if the requested provider is not known.
1014 return unless($IDS::Ruleset
::Providers
{$provider});
1016 # Try to gather the download type for the given provider.
1017 my $dl_type = $IDS::Ruleset
::Providers
{$provider}{'dl_type'};
1019 # Check if a download type could be grabbed.
1021 # Obtain the file suffix for the download file type.
1022 my $suffix = $dl_type_to_suffix{$dl_type};
1024 # Check if a suffix has been found.
1026 # Abort return - nothing.
1030 # Generate the full filename and path for the stored rules file.
1031 my $rulesfile = "$dl_rules_path/$dl_rulesfile_prefix-$provider$suffix";
1033 # Return the generated filename.
1037 # A downloaded ruleset for a provider which is not supported anymore is requested.
1039 # Try to enumerate the downloaded ruleset file.
1040 foreach my $dl_type (keys %dl_type_to_suffix) {
1041 # Get the file suffix for the supported type.
1042 my $suffix = $dl_type_to_suffix{$dl_type};
1044 # Generate possible ruleset file name.
1045 my $rulesfile = "$dl_rules_path/$dl_rulesfile_prefix-$provider$suffix";
1047 # Check if such a file exists.
1048 if (-f
$rulesfile) {
1049 # Downloaded rulesfile found - Return the filename.
1055 # If we got here, no rulesfile could be determined - return nothing.
1060 ## Private function to obtain the sid and rev of a rule.
1062 ## Returns an array with the sid as first and the rev as second value.
1064 sub _get_sid_and_rev
($) {
1069 # Use regex to obtain the sid and rev.
1070 if ($line =~ m/.*sid:\s*(.*?);.*rev:\s*(.*?);/) {
1071 # Add the sid and rev to the array.
1081 ## Tiny function to delete the stored ruleset file or tarball for a given provider.
1083 sub drop_dl_rulesfile
($) {
1084 my ($provider) = @_;
1086 # Gather the full path and name of the stored rulesfile.
1087 my $rulesfile = &_get_dl_rulesfile
($provider);
1089 # Check if the given rulesfile exists.
1090 if (-f
$rulesfile) {
1091 # Delete the stored rulesfile.
1092 unlink($rulesfile) or die "Could not delete $rulesfile. $!\n";
1097 ## Function to check if the IDS is running.
1099 sub ids_is_running
() {
1100 if(-f
$idspidfile) {
1101 # Open PID file for reading.
1102 open(PIDFILE
, "$idspidfile") or die "Could not open $idspidfile. $!\n";
1104 # Grab the process-id.
1105 my $pid = <PIDFILE
>;
1110 # Remove any newline.
1113 # Check if a directory for the process-id exists in proc.
1114 if(-d
"/proc/$pid") {
1115 # The IDS daemon is running return the process id.
1120 # Return nothing - IDS is not running.
1125 ## Function to call suricatactrl binary with a given command.
1127 sub call_suricatactrl
($) {
1128 # Get called option.
1129 my ($option, $interval) = @_;
1131 # Loop through the array of supported commands and check if
1132 # the given one is part of it.
1133 foreach my $cmd (@suricatactrl_cmds) {
1134 # Skip current command unless the given one has been found.
1135 next unless($cmd eq $option);
1137 # Call the suricatactrl binary and pass the requrested
1139 &General
::system("$suricatactrl", "$option");
1141 # Return "1" - True.
1145 # Command not found - return nothing.
1150 ## Function to create a new empty file.
1152 sub create_empty_file
($) {
1155 # Check if the given file exists.
1157 # Do nothing to prevent from overwriting existing files.
1161 # Open the file for writing.
1162 open(FILE
, ">$file") or die "Could not write to $file. $!\n";
1164 # Close file handle.
1172 ## Private function to check if the file permission of the rulespath are correct.
1173 ## If not, call suricatactrl to fix them.
1175 sub _check_rulesdir_permissions
() {
1176 # Check if the rulepath main directory is writable.
1177 unless (-W
$rulespath) {
1178 # If not call suricatctrl to fix it.
1179 &call_suricatactrl
("fix-rules-dir");
1182 # Open snort rules directory and do a directory listing.
1183 opendir(DIR
, $rulespath) or die $!;
1184 # Loop through the direcory.
1185 while (my $file = readdir(DIR
)) {
1186 # We only want files.
1187 next unless (-f
"$rulespath/$file");
1189 # Check if the file is writable by the user.
1190 if (-W
"$rulespath/$file") {
1191 # Everything is okay - go on to the next file.
1194 # There are wrong permissions, call suricatactrl to fix it.
1195 &call_suricatactrl
("fix-rules-dir");
1201 ## Private function to cleanup the directory which contains
1202 ## the IDS rules, before extracting and modifing the new ruleset.
1204 sub _cleanup_rulesdir
() {
1205 # Open rules directory and do a directory listing.
1206 opendir(DIR
, $rulespath) or die $!;
1208 # Loop through the direcory.
1209 while (my $file = readdir(DIR
)) {
1210 # We only want files.
1211 next unless (-f
"$rulespath/$file");
1213 # Skip rules file for whitelisted hosts.
1214 next if ("$rulespath/$file" eq $whitelist_file);
1216 # Skip rules file with local rules.
1217 next if ("$rulespath/$file" eq $local_rules_file);
1219 # Delete the current processed file, if not, exit this function
1220 # and return an error message.
1221 unlink("$rulespath/$file") or return "Could not delete $rulespath/$file. $!\n";
1229 ## Function to generate the file which contains the home net information.
1231 sub generate_home_net_file
() {
1234 # Read-in network settings.
1235 &General
::readhash
("${General::swroot}/ethernet/settings", \
%netsettings);
1237 # Get available network zones.
1238 my @network_zones = &Network
::get_available_network_zones
();
1240 # Temporary array to store network address and prefix of the configured
1244 # Loop through the array of available network zones.
1245 foreach my $zone (@network_zones) {
1246 # Check if the current processed zone is red.
1247 if($zone eq "red") {
1248 # Grab the IP-address of the red interface.
1249 my $red_address = &get_red_address
();
1251 # Check if an address has been obtained.
1253 # Generate full network string.
1254 my $red_network = join("/", $red_address, "32");
1256 # Add the red network to the array of networks.
1257 push(@networks, $red_network);
1260 # Check if the configured RED_TYPE is static.
1261 if ($netsettings{'RED_TYPE'} eq "STATIC") {
1262 # Get configured and enabled aliases.
1263 my @aliases = &get_aliases
();
1265 # Loop through the array.
1266 foreach my $alias (@aliases) {
1268 my $network = join("/", $alias, "32");
1270 # Add the generated network to the array of networks.
1271 push(@networks, $network);
1274 # Process remaining network zones.
1276 # Convert current zone name into upper case.
1279 # Generate key to access the required data from the netsettings hash.
1280 my $zone_netaddress = $zone . "_NETADDRESS";
1281 my $zone_netmask = $zone . "_NETMASK";
1283 # Obtain the settings from the netsettings hash.
1284 my $netaddress = $netsettings{$zone_netaddress};
1285 my $netmask = $netsettings{$zone_netmask};
1287 # Convert the subnetmask into prefix notation.
1288 my $prefix = &Network
::convert_netmask2prefix
($netmask);
1290 # Generate full network string.
1291 my $network = join("/", $netaddress,$prefix);
1293 # Check if the network is valid.
1294 if(&Network
::check_subnet
($network)) {
1295 # Add the generated network to the array of networks.
1296 push(@networks, $network);
1301 # Format home net declaration.
1302 my $line = "\"[" . join(',', @networks) . "]\"";
1304 # Open file to store the addresses of the home net.
1305 open(FILE
, ">$homenet_file") or die "Could not open $homenet_file. $!\n";
1307 # Print yaml header.
1308 print FILE
"%YAML 1.1\n";
1309 print FILE
"---\n\n";
1311 # Print notice about autogenerated file.
1312 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1314 # Print the generated and required HOME_NET declaration to the file.
1315 print FILE
"HOME_NET:\t$line\n";
1317 # Close file handle.
1322 # Function to generate and write the file which contains the configured and used DNS servers.
1324 sub generate_dns_servers_file
() {
1325 # Get the used DNS servers.
1326 my @nameservers = &General
::get_nameservers
();
1328 # Get network settings.
1330 &General
::readhash
("${General::swroot}/ethernet/settings", \
%netsettings);
1332 # Format dns servers declaration.
1335 # Check if the system has configured nameservers.
1337 # Add the GREEN address as DNS servers.
1338 push(@nameservers, $netsettings{'GREEN_ADDRESS'});
1340 # Check if a BLUE zone exists.
1341 if ($netsettings{'BLUE_ADDRESS'}) {
1342 # Add the BLUE address to the array of nameservers.
1343 push(@nameservers, $netsettings{'BLUE_ADDRESS'});
1346 # Generate the line which will be written to the DNS servers file.
1347 $line = join(",", @nameservers);
1349 # External net simply contains (any).
1350 $line = "\$EXTERNAL_NET";
1353 # Open file to store the used DNS server addresses.
1354 open(FILE
, ">$dns_servers_file") or die "Could not open $dns_servers_file. $!\n";
1356 # Print yaml header.
1357 print FILE
"%YAML 1.1\n";
1358 print FILE
"---\n\n";
1360 # Print notice about autogenerated file.
1361 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1363 # Print the generated DNS declaration to the file.
1364 print FILE
"DNS_SERVERS:\t\"[$line]\"\n";
1366 # Close file handle.
1371 # Function to generate and write the file which contains the HTTP_PORTS definition.
1373 sub generate_http_ports_file
() {
1376 # Read-in proxy settings
1377 &General
::readhash
("${General::swroot}/proxy/advanced/settings", \
%proxysettings);
1379 # Check if the proxy is enabled.
1380 if (( -e
"${General::swroot}/proxy/enable") || (-e
"${General::swroot}/proxy/enable_blue")) {
1381 # Add the proxy port to the array of HTTP ports.
1382 push(@http_ports, $proxysettings{'PROXY_PORT'});
1385 # Check if the transparent mode of the proxy is enabled.
1386 if ((-e
"${General::swroot}/proxy/transparent") || (-e
"${General::swroot}/proxy/transparent_blue")) {
1387 # Add the transparent proxy port to the array of HTTP ports.
1388 push(@http_ports, $proxysettings{'TRANSPARENT_PORT'});
1391 # Format HTTP_PORTS declaration.
1394 # Generate line which will be written to the http ports file.
1395 $line = join(",", @http_ports);
1397 # Open file to store the HTTP_PORTS.
1398 open(FILE
, ">$http_ports_file") or die "Could not open $http_ports_file. $!\n";
1400 # Print yaml header.
1401 print FILE
"%YAML 1.1\n";
1402 print FILE
"---\n\n";
1404 # Print notice about autogenerated file.
1405 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1407 # Print the generated HTTP_PORTS declaration to the file.
1408 print FILE
"HTTP_PORTS:\t\"[$line]\"\n";
1410 # Close file handle.
1415 ## Function to write the file that contains the rulefiles which are loaded by suricaa.
1417 ## This function requires an array of used provider handles.
1419 sub write_used_rulefiles_file
(@
) {
1420 my (@providers) = @_;
1422 # Get the enabled application layer protocols.
1423 my @enabled_app_layer_protos = &get_suricata_enabled_app_layer_protos
();
1426 open (FILE
, ">", $suricata_used_rulesfiles_file) or die "Could not write to $suricata_used_rulesfiles_file. $!\n";
1428 print FILE
"%YAML 1.1\n";
1429 print FILE
"---\n\n";
1431 # Write notice about autogenerated file.
1432 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1434 # Loop through the array of static included rulesfiles.
1435 foreach my $file (@static_included_rulefiles) {
1436 # Check if the file exists.
1437 if (-f
"$rulespath/$file") {
1438 # Write the rulesfile name to the file.
1439 print FILE
" - $rulespath/$file\n";
1443 if ($LOG_APP_LAYER_EVENTS) {
1444 print FILE
"\n#Default rules for used application layer protocols.\n";
1445 foreach my $enabled_app_layer_proto (@enabled_app_layer_protos) {
1446 # Check if the current processed app layer proto needs to be translated
1447 # into an application name.
1448 if (exists($tr_app_layer_proto{$enabled_app_layer_proto})) {
1449 # Obtain the translated application name for this protocol.
1450 $enabled_app_layer_proto = $tr_app_layer_proto{$enabled_app_layer_proto};
1453 # Generate filename.
1454 my $rulesfile = "$default_rulespath/$enabled_app_layer_proto\.rules";
1456 # Check if such a file exists.
1457 if (-f
"$rulesfile") {
1458 # Write the rulesfile name to the file.
1459 print FILE
" - $rulesfile\n";
1462 # Generate filename with "events" in filename.
1463 $rulesfile = "$default_rulespath/$enabled_app_layer_proto\-events.rules";
1465 # Check if this file exists.
1466 if (-f
"$rulesfile" ) {
1467 # Write the rulesfile name to the file.
1468 print FILE
" - $rulesfile\n";
1473 # Loop through the array of enabled providers.
1474 foreach my $provider (@providers) {
1475 # Skip unsupported providers.
1476 next unless ($IDS::Ruleset
::Providers
{$provider});
1478 # Get the used rulefile for this provider.
1479 my @used_rulesfiles = &get_provider_used_rulesfiles
($provider);
1481 # Check if there are
1482 if(@used_rulesfiles) {
1483 # Add notice to the file.
1484 print FILE
"\n#Used Rulesfiles for provider $provider.\n";
1486 # Loop through the array of used rulefiles.
1487 foreach my $enabled_rulesfile (@used_rulesfiles) {
1488 # Generate name and full path to the rulesfile.
1489 my $rulesfile = "$rulespath/$enabled_rulesfile";
1491 # Write the ruelsfile name to the file.
1492 print FILE
" - $rulesfile\n";
1497 # Close the file handle
1502 ## Tiny function to generate the full path and name for the file which stores the used rulefiles of a given provider.
1504 sub get_provider_used_rulesfiles_file
($) {
1505 my ($provider) = @_;
1507 my $filename = "$settingsdir/$provider\-used\-rulesfiles";
1509 # Return the gernerated file.
1514 ## Tiny function to generate the full path and name for the file which stores the modifications of a ruleset.
1516 sub get_provider_ruleset_modifications_file
($) {
1517 my ($provider) = @_;
1519 my $filename = "$settingsdir/$provider\-modifications";
1521 # Return the filename.
1526 ## Function to get the subscription code of a configured provider.
1528 sub get_subscription_code
($) {
1529 my ($provider) = @_;
1531 my %configured_providers = ();
1533 # Read-in providers settings file.
1534 &General
::readhasharray
($providers_settings_file, \
%configured_providers);
1536 # Loop through the hash of configured providers.
1537 foreach my $id (keys %configured_providers) {
1538 # Assign nice human-readable values to the data fields.
1539 my $provider_handle = $configured_providers{$id}[0];
1540 my $subscription_code = $configured_providers{$id}[1];
1542 # Check if the current processed provider is the requested one.
1543 if ($provider_handle eq $provider) {
1544 # Return the obtained subscription code.
1545 return $subscription_code;
1549 # No subscription code found - return nothing.
1554 ## Function to get the ruleset date for a given provider.
1556 ## The function simply return the creation date in a human read-able format
1557 ## of the stored providers rulesfile.
1559 sub get_ruleset_date
($) {
1560 my ($provider) = @_;
1564 # Get the stored rulesfile for this provider.
1565 my $stored_rulesfile = &_get_dl_rulesfile
($provider);
1567 # Check if we got a file.
1568 if (-f
$stored_rulesfile) {
1569 # Call stat on the rulestarball.
1570 my $stat = stat("$stored_rulesfile");
1572 # Get timestamp the file creation.
1573 $mtime = $stat->mtime;
1576 # Check if the timestamp has not been grabbed.
1578 # Return N/A for Not available.
1582 # Convert into human read-able format.
1583 $date = strftime
('%Y-%m-%d %H:%M:%S', localtime($mtime));
1590 ## Function to gather the version of suricata.
1592 sub get_suricata_version
($) {
1595 # Execute piped suricata command and return the version information.
1596 open(SURICATA
, "suricata -V |") or die "Couldn't execute program: $!";
1598 # Grab and store the output of the piped program.
1599 my $version_string = <SURICATA
>;
1605 chomp($version_string);
1607 # Grab the version from the version string.
1608 $version_string =~ /([0-9]+([.][0-9]+)+)/;
1610 # Splitt the version into single chunks.
1611 my ($major_ver, $minor_ver, $patchlevel) = split(/\./, $1);
1613 # Check and return the requested version sheme.
1614 if ($format eq "major") {
1615 # Return the full version.
1616 return "$major_ver";
1617 } elsif ($format eq "minor") {
1618 # Return the major and minor part.
1619 return "$major_ver.$minor_ver";
1621 # Return the full version string.
1622 return "$major_ver.$minor_ver.$patchlevel";
1627 ## Function to get the enabled application layer protocols.
1629 sub get_suricata_enabled_app_layer_protos
() {
1630 # Array to store and return the enabled app layer protos.
1631 my @enabled_app_layer_protos = ();
1633 # Execute piped suricata command and return the list of
1634 # enabled application layer protocols.
1635 open(SURICATA
, "suricata --list-app-layer-protos |") or die "Could not execute program: $!";
1637 # Grab and store the list of enabled application layer protocols.
1638 my @output = <SURICATA
>;
1643 # Merge allways enabled static application layers protocols array.
1644 @enabled_app_layer_protos = @static_enabled_app_layer_protos;
1646 # Loop through the array which contains the output of suricata.
1647 foreach my $line (@output) {
1648 # Skip header line which starts with "===".
1649 next if ($line =~ /^\s*=/);
1651 # Skip info or warning lines.
1652 next if ($line =~ /\s*--/);
1657 # Add enabled app layer proto to the array.
1658 push(@enabled_app_layer_protos, $line);
1662 @enabled_app_layer_protos = sort(@enabled_app_layer_protos);
1665 return @enabled_app_layer_protos;
1669 ## Function to generate the rules file with whitelisted addresses.
1671 sub generate_ignore_file
() {
1674 # SID range 1000000-1999999 Reserved for Local Use
1675 # Put your custom rules in this range to avoid conflicts
1678 # Read-in ignoredfile.
1679 &General
::readhasharray
($IDS::ignored_file
, \
%ignored);
1681 # Open ignorefile for writing.
1682 open(FILE
, ">$IDS::whitelist_file") or die "Could not write to $IDS::whitelist_file. $!\n";
1684 # Config file header.
1685 print FILE
"# Autogenerated file.\n";
1686 print FILE
"# All user modifications will be overwritten.\n\n";
1688 # Add all user defined addresses to the whitelist.
1690 # Check if the hash contains any elements.
1691 if (keys (%ignored)) {
1692 # Loop through the entire hash and write the host/network
1693 # and remark to the ignore file.
1694 while ( (my $key) = each %ignored) {
1695 my $address = $ignored{$key}[0];
1696 my $remark = $ignored{$key}[1];
1697 my $status = $ignored{$key}[2];
1699 # Check if the status of the entry is "enabled".
1700 if ($status eq "enabled") {
1701 # Check if the address/network is valid.
1702 if ((&General
::validip
($address)) || (&General
::validipandmask
($address))) {
1703 # Write rule line to the file to pass any traffic from this IP
1704 print FILE
"pass ip $address any -> any any (msg:\"pass all traffic from/to $address\"\; bypass; sid:$sid\;)\n";
1717 ## Function to set correct ownership for single files and directories.
1720 sub set_ownership
($) {
1723 # User and group of the WUI.
1724 my $uname = "nobody";
1725 my $grname = "nobody";
1727 # The chown function implemented in perl requies the user and group as nummeric id's.
1728 my $uid = getpwnam($uname);
1729 my $gid = getgrnam($grname);
1731 # Check if the given target exists.
1733 # Stop the script and print error message.
1734 die "The $target does not exist. Cannot change the ownership!\n";
1737 # Check weather the target is a file or directory.
1739 # Change ownership ot the single file.
1740 chown($uid, $gid, "$target");
1741 } elsif (-d
$target) {
1742 # Do a directory listing.
1743 opendir(DIR
, $target) or die $!;
1744 # Loop through the direcory.
1745 while (my $file = readdir(DIR
)) {
1747 # We only want files.
1748 next unless (-f
"$target/$file");
1750 # Set correct ownership for the files.
1751 chown($uid, $gid, "$target/$file");
1756 # Change ownership of the directory.
1757 chown($uid, $gid, "$target");
1762 ## Function to read-in the aliases file and returns all configured and enabled aliases.
1765 # Location of the aliases file.
1766 my $aliases_file = "${General::swroot}/ethernet/aliases";
1768 # Array to store the aliases.
1771 # Check if the file is empty.
1772 if (-z
$aliases_file) {
1773 # Abort nothing to do.
1777 # Open the aliases file.
1778 open(ALIASES
, $aliases_file) or die "Could not open $aliases_file. $!\n";
1780 # Loop through the file content.
1781 while (my $line = <ALIASES
>) {
1785 # Splitt line content into single chunks.
1786 my ($address, $state, $remark) = split(/\,/, $line);
1788 # Check if the state of the current processed alias is "on".
1789 if ($state eq "on") {
1790 # Check if the address is valid.
1791 if(&Network
::check_ip_address
($address)) {
1792 # Add the alias to the array of aliases.
1793 push(@aliases, $address);
1798 # Close file handle.
1806 ## Function to grab the current assigned IP-address on red.
1808 sub get_red_address
() {
1809 # File, which contains the current IP-address of the red interface.
1810 my $file = "${General::swroot}/red/local-ipaddress";
1812 # Check if the file exists.
1814 # Open the given file.
1815 open(FILE
, "$file") or die "Could not open $file.";
1817 # Obtain the address from the first line of the file.
1818 my $address = <FILE
>;
1826 # Check if the grabbed address is valid.
1827 if (&General
::validip
($address)) {
1828 # Return the address.
1838 ## Function to get the used rules files of a given provider.
1840 sub get_provider_used_rulesfiles
($) {
1841 my ($provider) = @_;
1843 # Hash to store the used rulefiles of the provider.
1844 my %provider_rulefiles = ();
1846 # Array to store the used rulefiles.
1847 my @used_rulesfiles = ();
1849 # Get the filename which contains the used rulefiles for this provider.
1850 my $used_rulesfiles_file = &get_provider_used_rulesfiles_file
($provider);
1852 # Read-in file, if it exists.
1853 &General
::readhash
("$used_rulesfiles_file", \
%provider_rulefiles) if (-f
$used_rulesfiles_file);
1855 # Loop through the hash of rulefiles which does the provider offer.
1856 foreach my $rulefile (keys %provider_rulefiles) {
1857 # Skip disabled rulefiles.
1858 next unless($provider_rulefiles{$rulefile} eq "enabled");
1860 # The General::readhash function does not allow dots as
1861 # key value and limits the key "string" to the part before
1862 # the dot, in case it contains one.
1864 # So add the file extension for the rules file manually again.
1865 $rulefile = "$rulefile.rules";
1867 # Add the enabled rulefile to the array of enabled rulefiles.
1868 push(@used_rulesfiles, $rulefile);
1871 # Return the array of used rulesfiles.
1872 return @used_rulesfiles;
1876 ## Function to delete the stored etag data of a given provider.
1878 sub remove_from_etags
($) {
1879 my ($provider) = @_;
1883 # Early exit function if the etags file does not exist.
1884 return unless (-f
$etags_file);
1886 # Read-in etag file.
1887 &General
::readhash
("$etags_file", \
%etags);
1889 # Check if the hash contains an entry for the given provider.
1890 if ($etags{$provider}) {
1892 delete($etags{$provider});
1894 # Write back the etags file.
1895 &General
::writehash
("$etags_file", \
%etags);
1900 ## Function to write the lock file for locking the WUI, while
1901 ## the autoupdate script runs.
1903 sub lock_ids_page
() {
1904 # Call subfunction to create the file.
1905 &create_empty_file
($ids_page_lock_file);
1909 ## Function to release the lock of the WUI, again.
1911 sub unlock_ids_page
() {
1913 unlink($ids_page_lock_file);