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.
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 # Return "not modified".
431 return "not modified";
433 # Check if we ran out of download re-tries.
434 } elsif ($dl_attempt eq $max_dl_attempts) {
436 my $error = $response->content;
438 # Return the error message from response..
442 # Remove temporary file, if one exists.
443 unlink("$tmpfile") if (-e
"$tmpfile");
445 # Increase download attempt counter.
449 # Obtain the connection headers.
450 my $headers = $response->headers;
452 # Get the timestamp from header, when the file has been modified the
454 my $last_modified = $headers->last_modified;
456 # Get the remote size of the downloaded file.
457 my $remote_filesize = $headers->content_length;
459 # Grab the Etag from response it the server provides one.
460 if ($response->header('Etag')) {
461 # Add the Etag to the etags hash.
462 $etags{$provider} = $response->header('Etag');
464 # Write the etags file.
465 &General
::writehash
($etags_file, \
%etags);
468 # Perform stat on the tmpfile.
469 my $stat = stat($tmpfile);
471 # Grab the local filesize of the downloaded tarball.
472 my $local_filesize = $stat->size;
474 # Check if both file sizes match.
475 if (($remote_filesize) && ($remote_filesize ne $local_filesize)) {
476 # Delete temporary file.
479 # Return "1" - false.
480 return "incomplete download";
483 # Overwrite the may existing rulefile or tarball with the downloaded one.
484 move
("$tmpfile", "$dl_rulesfile");
486 # Check if we got a last-modified value from the server.
487 if ($last_modified) {
488 # Assign the last-modified timestamp as mtime to the
490 utime(time(), "$last_modified", "$dl_rulesfile");
493 # Delete temporary file.
496 # Set correct ownership for the tarball.
497 set_ownership
("$dl_rulesfile");
499 # If we got here, everything worked fine. Return nothing.
504 ## Function to extract a given ruleset.
506 ## In case the ruleset provider offers a plain file, it simply will
509 sub extractruleset
($) {
512 # Disable chown functionality when uncompressing files.
513 $Archive::Tar
::CHOWN
= "0";
515 # Get full path and downloaded rulesfile for the given provider.
516 my $tarball = &_get_dl_rulesfile
($provider);
518 # Check if the file exists.
519 unless (-f
$tarball) {
520 &_log_to_syslog
("Could not find ruleset file: $tarball");
526 # Check if the temporary directories exist, otherwise create them.
527 mkdir("$tmp_directory") unless (-d
"$tmp_directory");
528 mkdir("$tmp_rules_directory") unless (-d
"$tmp_rules_directory");
529 mkdir("$tmp_conf_directory") unless (-d
"$tmp_conf_directory");
531 # Omit the type (dl_type) of the stored ruleset.
532 my $type = $IDS::Ruleset
::Providers
{$provider}{'dl_type'};
534 # Handle the different ruleset types.
535 if ($type eq "plain") {
536 # Generate destination filename an full path.
537 my $destination = "$tmp_rules_directory/$provider\-ruleset.rules";
539 # Copy the file into the temporary rules directory.
540 copy
($tarball, $destination);
542 } elsif ( $type eq "archive") {
543 # Initialize the tar module.
544 my $tar = Archive
::Tar
->new($tarball);
546 # Get the filelist inside the tarball.
547 my @packed_files = $tar->list_files;
549 # Loop through the filelist.
550 foreach my $packed_file (@packed_files) {
553 # Splitt the packed file into chunks.
554 my $file = fileparse
($packed_file);
556 # Handle msg-id.map file.
557 if ("$file" eq "sid-msg.map") {
558 # Set extract destination to temporary config_dir.
559 $destination = "$tmp_conf_directory/$provider\-sid-msg.map";
561 # Handle classification.conf
562 } elsif ("$file" eq "classification.config") {
563 # Set extract destination to temporary config_dir.
564 $destination = "$tmp_conf_directory/$provider\-classification.config";
566 # Handle rules files.
567 } elsif ($file =~ m/\.rules$/) {
568 # Skip rule files which are not located in the rules directory or archive root.
569 next unless(($packed_file =~ /^rules\//) || ($packed_file !~ /\
//));
571 # Skip deleted.rules.
573 # Mostly they have been taken out for correctness or performance reasons and therfore
574 # it is not a great idea to enable any of them.
575 next if($file =~ m/deleted.rules$/);
579 # Splitt the filename into chunks.
580 my @filename = split("-", $file);
583 @filename = reverse(@filename);
585 # Get the amount of elements in the array.
586 my $elements = @filename;
588 # Remove last element of the hash.
589 # It contains the vendor name, which will be replaced.
590 if ($elements >= 3) {
591 # Remove last element from hash.
595 # Check if the last element of the filename does not
596 # contain the providers name.
597 if ($filename[-1] ne "$provider") {
598 # Add provider name as last element.
599 push(@filename, $provider);
602 # Reverse the array back.
603 @filename = reverse(@filename);
605 # Generate the name for the rulesfile.
606 $rulesfilename = join("-", @filename);
608 # Set extract destination to temporaray rules_dir.
609 $destination = "$tmp_rules_directory/$rulesfilename";
611 # Skip all other files.
615 # Check if the destination file exists.
616 unless(-e
"$destination") {
617 # Extract the file to the temporary directory.
618 $tar->extract_file("$packed_file", "$destination");
620 # Generate temporary file name, located in the temporary rules directory and a suffix of ".tmp".
621 my $tmp = File
::Temp
->new( SUFFIX
=> ".tmp", DIR
=> "$tmp_rules_directory", UNLINK
=> 0 );
622 my $tmpfile = $tmp->filename();
624 # Extract the file to the new temporary file name.
625 $tar->extract_file("$packed_file", "$tmpfile");
627 # Open the the existing file.
628 open(DESTFILE
, ">>", "$destination") or die "Could not open $destination. $!\n";
629 open(TMPFILE
, "<", "$tmpfile") or die "Could not open $tmpfile. $!\n";
631 # Loop through the content of the temporary file.
633 # Append the content line by line to the destination file.
637 # Close the file handles.
641 # Remove the temporary file.
649 ## A wrapper function to call the oinkmaster script, setup the rules structues and
650 ## call the functions to merge the additional config files. (classification, sid-msg, etc.).
653 # Check if the files in rulesdir have the correct permissions.
654 &_check_rulesdir_permissions
();
656 # Cleanup the rules directory before filling it with the new rulests.
657 &_cleanup_rulesdir
();
659 # Get all enabled providers.
660 my @enabled_providers = &get_enabled_providers
();
662 # Loop through the array of enabled providers.
663 foreach my $provider (@enabled_providers) {
664 # Call the extractruleset function.
665 &extractruleset
($provider);
668 # Call function to process the ruleset and do all modifications.
669 &process_ruleset
(@enabled_providers);
671 # Call function to merge the classification files.
672 &merge_classifications
(@enabled_providers);
674 # Call function to merge the sid to message mapping files.
675 &merge_sid_msg
(@enabled_providers);
677 # Cleanup temporary directory.
678 &cleanup_tmp_directory
();
682 ## Function to alter the ruleset.
684 sub process_ruleset
(@
) {
685 my (@providers) = @_;
687 # Hash to store the configured provider modes.
688 my %providers_mode = &get_providers_mode
();
690 # Array to store the extracted rulefile from the temporary rules directory.
691 my @extracted_rulefiles;
693 # Get names of the extracted raw rulefiles.
694 opendir(DIR
, $tmp_rules_directory) or die "Could not read from $tmp_rules_directory. $!\n";
695 while (my $file = readdir(DIR
)) {
696 # Ignore single and double dotted files.
697 next if $file =~ /^\.\.?$/;
699 # Add file to the array of extracted files.
700 push(@extracted_rulefiles, $file);
703 # Close directory handle.
706 # Loop through the array of providers.
707 foreach my $provider (@providers) {
708 # Hash to store the obtained SIDs and REV of each provider.
711 # Hash which holds modifications to apply to the rules.
712 my %modifications = ();
714 # Loop through the array of extraced rulefiles.
715 foreach my $file (@extracted_rulefiles) {
716 # Skip file if it does not belong to the current processed provider.
717 next unless ($file =~ m/^$provider/);
720 open(FILE
, "$tmp_rules_directory/$file") or die "Could not read $tmp_rules_directory/$file. $!\n";
722 # Loop through the file content.
723 while (my $line = <FILE
>) {
725 next if ($line =~ /^\s*$/);
727 # Call function to get the sid and rev of the rule.
728 my ($sid, $rev) = &_get_sid_and_rev
($line);
730 # Skip rule if a sid with a higher rev already has added to the rules hash.
731 next if ($rev le $rules{$sid});
733 # Add the new or rule with higher rev to the hash of rules.
741 # Get filename which contains the ruleset modifications for this provider.
742 my $modification_file = &get_provider_ruleset_modifications_file
($provider);
744 # Read file which holds the modifications of the ruleset for the current provider.
745 &General
::readhash
($modification_file, \
%modifications) if (-f
$modification_file);
747 # Loop again through the array of extracted rulesfiles.
748 foreach my $file (@extracted_rulefiles) {
749 # Skip the file if it does not belong to the current provider.
750 next unless ($file =~ m/^$provider/);
752 # Open the rulefile for writing.
753 open(RULEFILE
, ">", "$rulespath/$file") or die "Could not write to file $rulespath/$file. $!\n";
755 # Open the rulefile for reading.
756 open(TMP_RULEFILE
, "$tmp_rules_directory/$file") or die "Could not read $tmp_rules_directory/$file. $!\n";
758 # Loop through the raw temporary rulefile.
759 while (my $line = <TMP_RULEFILE
>) {
760 # Get the sid and rev of the rule.
761 my ($sid, $rev) = &_get_sid_and_rev
($line);
763 # Check if the current rule is obsoleted by a newer one.
765 # In this case the rev number in the rules hash is higher than the current one.
766 next if ($rev lt $rules{$sid});
768 # Check if the rule should be enabled or disabled.
769 if ($modifications{$sid} eq "enabled") {
770 # Drop the # at the start of the line.
772 } elsif ($modifications{$sid} eq "disabled") {
773 # Add a # at the start of the line to disable the rule.
774 $line = "#$line" unless ($line =~ /^#/);
777 # Check if the Provider is set so IPS mode.
778 if ($providers_mode{$provider} eq "IPS") {
779 # Replacements for sourcefire rules.
780 $line =~ s/^#\s*(?:alert|drop)(.+policy balanced-ips alert)/alert${1}/;
781 $line =~ s/^#\s*(?:alert|drop)(.+policy balanced-ips drop)/drop${1}/;
783 # Replacements for generic rules.
784 $line =~ s/^(#?)\s*(?:alert|drop)/${1}drop/;
785 $line =~ s/^(#?)\s*drop(.+flowbits:noalert;)/${1}alert${2}/;
788 # Write line / rule to the target rule file.
789 print RULEFILE
"$line";
800 ## Function to merge the classifications for a given amount of providers and write them
801 ## to the classifications file.
803 sub merge_classifications
(@
) {
806 # Hash to store all collected classifications.
807 my %classifications = ();
809 # Loop through the given array of providers.
810 foreach my $provider (@providers) {
811 # Generate full path to classification file.
812 my $classification_file = "$tmp_conf_directory/$provider\-classification.config";
814 # Skip provider if no classification file exists.
815 next unless (-f
"$classification_file");
817 # Open the classification file.
818 open(CLASSIFICATION
, $classification_file) or die "Could not open file $classification_file. $!\n";
820 # Loop through the file content.
821 while(<CLASSIFICATION
>) {
822 # Parse the file and grab the classification details.
823 if ($_ =~/.*config classification\: (.*)/) {
824 # Split the grabbed details.
825 my ($short_name, $short_desc, $priority) = split("\,", $1);
827 # Check if the grabbed classification is allready known and the priority value is greater
828 # than the stored one (which causes less priority in the IDS).
829 if (($classifications{$short_name}) && ($classifications{$short_name}[1] >= $priority)) {
830 #Change the priority value to the stricter one.
831 $classifications{$short_name} = [ "$classifications{$short_name}[0]", "$priority" ];
833 # Add the classification to the hash.
834 $classifications{$short_name} = [ "$short_desc", "$priority" ];
840 close(CLASSIFICATION
);
843 # Open classification file for writing.
844 open(FILE
, ">", "$classification_file") or die "Could not write to $classification_file. $!\n";
846 # Print notice about autogenerated file.
847 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n\n";
849 # Sort and loop through the hash of classifications.
850 foreach my $key (sort keys %classifications) {
851 # Assign some nice variable names for the items.
852 my $short_name = $key;
853 my $short_desc = $classifications{$key}[0];
854 my $priority = $classifications{$key}[1];
856 # Write the classification to the file.
857 print FILE
"config classification: $short_name,$short_desc,$priority\n";
865 ## Function to merge the "sid to message mapping" files of various given providers.
867 sub merge_sid_msg
(@
) {
870 # Hash which contains all the sid to message mappings.
873 # Loop through the array of given providers.
874 foreach my $provider (@providers) {
875 # Generate full path and filename.
876 my $sid_msg_file = "$tmp_conf_directory/$provider\-sid-msg.map";
878 # Skip provider if no sid to msg mapping file for this provider exists.
879 next unless (-f
$sid_msg_file);
882 open(MAPPING
, $sid_msg_file) or die "Could not open $sid_msg_file. $!\n";
884 # Loop through the file content.
889 # Skip lines which do not start with a number,
890 next unless ($_ =~ /^\d+/);
892 # Split line content and assign it to an array.
893 my @line = split(/ \|\| /, $_);
895 # Grab the first element (and remove it) from the line array.
896 # It contains the sid.
897 my $sid = shift(@line);
899 # Store the grabbed sid and the remain array as hash value.
900 # It still contains the messages, references etc.
901 $mappings{$sid} = [@line];
908 # Open mappings file for writing.
909 open(FILE
, ">", $sid_msg_file) or die "Could not write $sid_msg_file. $!\n";
911 # Write notice about autogenerated file.
912 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n\n";
914 # Loop through the hash of mappings.
915 foreach my $sid ( sort keys %mappings) {
916 # Grab data for the sid.
917 my @data = @
{$mappings{$sid}};
919 # Add the sid to the data array.
920 unshift(@data, $sid);
923 my $line = join(" \|\| ", @data);
925 print FILE
"$line\n";
934 ## A very tiny function to move an extracted ruleset from the temporary directory into
935 ## the rules directory.
937 sub move_tmp_ruleset
() {
938 # Do a directory listing of the temporary directory.
939 opendir DH
, $tmp_rules_directory;
941 # Loop over all files.
942 while(my $file = readdir DH
) {
943 # Move them to the rules directory.
944 move
"$tmp_rules_directory/$file" , "$rulespath/$file";
947 # Close directory handle.
952 ## Function to cleanup the temporary IDS directroy.
954 sub cleanup_tmp_directory
() {
956 # Delete temporary directory and all containing files.
957 rmtree
([ "$tmp_directory" ]);
961 ## Function to do all the logging stuff if the downloading or updating of the ruleset fails.
966 # Remove any newline.
969 # Call private function to log the error message to syslog.
970 &_log_to_syslog
($error);
972 # Call private function to write/store the error message in the storederrorfile.
973 &_store_error_message
($error);
977 ## Function to log a given error message to the kernel syslog.
979 sub _log_to_syslog
($) {
982 # The syslog function works best with an array based input,
983 # so generate one before passing the message details to syslog.
984 my @syslog = ("ERR", "<ERROR> $message");
986 # Establish the connection to the syslog service.
987 openlog
('oinkmaster', 'cons,pid', 'user');
989 # Send the log message.
992 # Close the log handle.
997 ## Private function to write a given error message to the storederror file.
999 sub _store_error_message
($) {
1002 # Remove any newline.
1005 # Open file for writing.
1006 open (ERRORFILE
, ">$storederrorfile") or die "Could not write to $storederrorfile. $!\n";
1008 # Write error to file.
1009 print ERRORFILE
"$message\n";
1014 # Set correct ownership for the file.
1015 &set_ownership
("$storederrorfile");
1019 ## Private function to get the path and filename for a downloaded ruleset by a given provider.
1021 sub _get_dl_rulesfile
($) {
1022 my ($provider) = @_;
1024 # Gather the download type for the given provider.
1025 my $dl_type = $IDS::Ruleset
::Providers
{$provider}{'dl_type'};
1027 # Obtain the file suffix for the download file type.
1028 my $suffix = $dl_type_to_suffix{$dl_type};
1030 # Check if a suffix has been found.
1032 # Abort return - nothing.
1036 # Generate the full filename and path for the stored rules file.
1037 my $rulesfile = "$dl_rules_path/$dl_rulesfile_prefix-$provider$suffix";
1039 # Return the generated filename.
1044 ## Private function to obtain the sid and rev of a rule.
1046 ## Returns an array with the sid as first and the rev as second value.
1048 sub _get_sid_and_rev
($) {
1053 # Use regex to obtain the sid and rev.
1054 if ($line =~ m/.*sid:\s*(.*?);.*rev:\s*(.*?);/) {
1055 # Add the sid and rev to the array.
1065 ## Tiny function to delete the stored ruleset file or tarball for a given provider.
1067 sub drop_dl_rulesfile
($) {
1068 my ($provider) = @_;
1070 # Gather the full path and name of the stored rulesfile.
1071 my $rulesfile = &_get_dl_rulesfile
($provider);
1073 # Check if the given rulesfile exists.
1074 if (-f
$rulesfile) {
1075 # Delete the stored rulesfile.
1076 unlink($rulesfile) or die "Could not delete $rulesfile. $!\n";
1081 ## Function to read-in the given enabled or disables sids file.
1083 sub read_enabled_disabled_sids_file
($) {
1086 # Temporary hash to store the sids and their state. It will be
1087 # returned at the end of this function.
1090 # Open the given filename.
1091 open(FILE
, "$file") or die "Could not open $file. $!\n";
1093 # Loop through the file.
1099 next if ($_ =~ /^\s*$/);
1102 next if ($_ =~ /^\#/);
1104 # Splitt line into sid and state part.
1105 my ($state, $sid) = split(" ", $_);
1107 # Skip line if the sid is not numeric.
1108 next unless ($sid =~ /\d+/ );
1110 # Check if the sid was enabled.
1111 if ($state eq "enablesid") {
1112 # Add the sid and its state as enabled to the temporary hash.
1113 $temphash{$sid} = "enabled";
1114 # Check if the sid was disabled.
1115 } elsif ($state eq "disablesid") {
1116 # Add the sid and its state as disabled to the temporary hash.
1117 $temphash{$sid} = "disabled";
1118 # Invalid state - skip the current sid and state.
1132 ## Function to check if the IDS is running.
1134 sub ids_is_running
() {
1135 if(-f
$idspidfile) {
1136 # Open PID file for reading.
1137 open(PIDFILE
, "$idspidfile") or die "Could not open $idspidfile. $!\n";
1139 # Grab the process-id.
1140 my $pid = <PIDFILE
>;
1145 # Remove any newline.
1148 # Check if a directory for the process-id exists in proc.
1149 if(-d
"/proc/$pid") {
1150 # The IDS daemon is running return the process id.
1155 # Return nothing - IDS is not running.
1160 ## Function to call suricatactrl binary with a given command.
1162 sub call_suricatactrl
($) {
1163 # Get called option.
1164 my ($option, $interval) = @_;
1166 # Loop through the array of supported commands and check if
1167 # the given one is part of it.
1168 foreach my $cmd (@suricatactrl_cmds) {
1169 # Skip current command unless the given one has been found.
1170 next unless($cmd eq $option);
1172 # Call the suricatactrl binary and pass the requrested
1174 &General
::system("$suricatactrl", "$option");
1176 # Return "1" - True.
1180 # Command not found - return nothing.
1185 ## Function to create a new empty file.
1187 sub create_empty_file
($) {
1190 # Check if the given file exists.
1192 # Do nothing to prevent from overwriting existing files.
1196 # Open the file for writing.
1197 open(FILE
, ">$file") or die "Could not write to $file. $!\n";
1199 # Close file handle.
1207 ## Private function to check if the file permission of the rulespath are correct.
1208 ## If not, call suricatactrl to fix them.
1210 sub _check_rulesdir_permissions
() {
1211 # Check if the rulepath main directory is writable.
1212 unless (-W
$rulespath) {
1213 # If not call suricatctrl to fix it.
1214 &call_suricatactrl
("fix-rules-dir");
1217 # Open snort rules directory and do a directory listing.
1218 opendir(DIR
, $rulespath) or die $!;
1219 # Loop through the direcory.
1220 while (my $file = readdir(DIR
)) {
1221 # We only want files.
1222 next unless (-f
"$rulespath/$file");
1224 # Check if the file is writable by the user.
1225 if (-W
"$rulespath/$file") {
1226 # Everything is okay - go on to the next file.
1229 # There are wrong permissions, call suricatactrl to fix it.
1230 &call_suricatactrl
("fix-rules-dir");
1236 ## Private function to cleanup the directory which contains
1237 ## the IDS rules, before extracting and modifing the new ruleset.
1239 sub _cleanup_rulesdir
() {
1240 # Open rules directory and do a directory listing.
1241 opendir(DIR
, $rulespath) or die $!;
1243 # Loop through the direcory.
1244 while (my $file = readdir(DIR
)) {
1245 # We only want files.
1246 next unless (-f
"$rulespath/$file");
1248 # Skip rules file for whitelisted hosts.
1249 next if ("$rulespath/$file" eq $whitelist_file);
1251 # Skip rules file with local rules.
1252 next if ("$rulespath/$file" eq $local_rules_file);
1254 # Delete the current processed file, if not, exit this function
1255 # and return an error message.
1256 unlink("$rulespath/$file") or return "Could not delete $rulespath/$file. $!\n";
1264 ## Function to generate the file which contains the home net information.
1266 sub generate_home_net_file
() {
1269 # Read-in network settings.
1270 &General
::readhash
("${General::swroot}/ethernet/settings", \
%netsettings);
1272 # Get available network zones.
1273 my @network_zones = &Network
::get_available_network_zones
();
1275 # Temporary array to store network address and prefix of the configured
1279 # Loop through the array of available network zones.
1280 foreach my $zone (@network_zones) {
1281 # Check if the current processed zone is red.
1282 if($zone eq "red") {
1283 # Grab the IP-address of the red interface.
1284 my $red_address = &get_red_address
();
1286 # Check if an address has been obtained.
1288 # Generate full network string.
1289 my $red_network = join("/", $red_address, "32");
1291 # Add the red network to the array of networks.
1292 push(@networks, $red_network);
1295 # Check if the configured RED_TYPE is static.
1296 if ($netsettings{'RED_TYPE'} eq "STATIC") {
1297 # Get configured and enabled aliases.
1298 my @aliases = &get_aliases
();
1300 # Loop through the array.
1301 foreach my $alias (@aliases) {
1303 my $network = join("/", $alias, "32");
1305 # Add the generated network to the array of networks.
1306 push(@networks, $network);
1309 # Process remaining network zones.
1311 # Convert current zone name into upper case.
1314 # Generate key to access the required data from the netsettings hash.
1315 my $zone_netaddress = $zone . "_NETADDRESS";
1316 my $zone_netmask = $zone . "_NETMASK";
1318 # Obtain the settings from the netsettings hash.
1319 my $netaddress = $netsettings{$zone_netaddress};
1320 my $netmask = $netsettings{$zone_netmask};
1322 # Convert the subnetmask into prefix notation.
1323 my $prefix = &Network
::convert_netmask2prefix
($netmask);
1325 # Generate full network string.
1326 my $network = join("/", $netaddress,$prefix);
1328 # Check if the network is valid.
1329 if(&Network
::check_subnet
($network)) {
1330 # Add the generated network to the array of networks.
1331 push(@networks, $network);
1336 # Format home net declaration.
1337 my $line = "\"[" . join(',', @networks) . "]\"";
1339 # Open file to store the addresses of the home net.
1340 open(FILE
, ">$homenet_file") or die "Could not open $homenet_file. $!\n";
1342 # Print yaml header.
1343 print FILE
"%YAML 1.1\n";
1344 print FILE
"---\n\n";
1346 # Print notice about autogenerated file.
1347 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1349 # Print the generated and required HOME_NET declaration to the file.
1350 print FILE
"HOME_NET:\t$line\n";
1352 # Close file handle.
1357 # Function to generate and write the file which contains the configured and used DNS servers.
1359 sub generate_dns_servers_file
() {
1360 # Get the used DNS servers.
1361 my @nameservers = &General
::get_nameservers
();
1363 # Get network settings.
1365 &General
::readhash
("${General::swroot}/ethernet/settings", \
%netsettings);
1367 # Format dns servers declaration.
1370 # Check if the system has configured nameservers.
1372 # Add the GREEN address as DNS servers.
1373 push(@nameservers, $netsettings{'GREEN_ADDRESS'});
1375 # Check if a BLUE zone exists.
1376 if ($netsettings{'BLUE_ADDRESS'}) {
1377 # Add the BLUE address to the array of nameservers.
1378 push(@nameservers, $netsettings{'BLUE_ADDRESS'});
1381 # Generate the line which will be written to the DNS servers file.
1382 $line = join(",", @nameservers);
1384 # External net simply contains (any).
1385 $line = "\$EXTERNAL_NET";
1388 # Open file to store the used DNS server addresses.
1389 open(FILE
, ">$dns_servers_file") or die "Could not open $dns_servers_file. $!\n";
1391 # Print yaml header.
1392 print FILE
"%YAML 1.1\n";
1393 print FILE
"---\n\n";
1395 # Print notice about autogenerated file.
1396 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1398 # Print the generated DNS declaration to the file.
1399 print FILE
"DNS_SERVERS:\t\"[$line]\"\n";
1401 # Close file handle.
1406 # Function to generate and write the file which contains the HTTP_PORTS definition.
1408 sub generate_http_ports_file
() {
1411 # Read-in proxy settings
1412 &General
::readhash
("${General::swroot}/proxy/advanced/settings", \
%proxysettings);
1414 # Check if the proxy is enabled.
1415 if (( -e
"${General::swroot}/proxy/enable") || (-e
"${General::swroot}/proxy/enable_blue")) {
1416 # Add the proxy port to the array of HTTP ports.
1417 push(@http_ports, $proxysettings{'PROXY_PORT'});
1420 # Check if the transparent mode of the proxy is enabled.
1421 if ((-e
"${General::swroot}/proxy/transparent") || (-e
"${General::swroot}/proxy/transparent_blue")) {
1422 # Add the transparent proxy port to the array of HTTP ports.
1423 push(@http_ports, $proxysettings{'TRANSPARENT_PORT'});
1426 # Format HTTP_PORTS declaration.
1429 # Generate line which will be written to the http ports file.
1430 $line = join(",", @http_ports);
1432 # Open file to store the HTTP_PORTS.
1433 open(FILE
, ">$http_ports_file") or die "Could not open $http_ports_file. $!\n";
1435 # Print yaml header.
1436 print FILE
"%YAML 1.1\n";
1437 print FILE
"---\n\n";
1439 # Print notice about autogenerated file.
1440 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1442 # Print the generated HTTP_PORTS declaration to the file.
1443 print FILE
"HTTP_PORTS:\t\"[$line]\"\n";
1445 # Close file handle.
1450 ## Function to write the file that contains the rulefiles which are loaded by suricaa.
1452 ## This function requires an array of used provider handles.
1454 sub write_used_rulefiles_file
(@
) {
1455 my (@providers) = @_;
1457 # Get the enabled application layer protocols.
1458 my @enabled_app_layer_protos = &get_suricata_enabled_app_layer_protos
();
1461 open (FILE
, ">", $suricata_used_rulesfiles_file) or die "Could not write to $suricata_used_rulesfiles_file. $!\n";
1463 print FILE
"%YAML 1.1\n";
1464 print FILE
"---\n\n";
1466 # Write notice about autogenerated file.
1467 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1469 # Loop through the array of static included rulesfiles.
1470 foreach my $file (@static_included_rulefiles) {
1471 # Check if the file exists.
1472 if (-f
"$rulespath/$file") {
1473 # Write the rulesfile name to the file.
1474 print FILE
" - $rulespath/$file\n";
1478 print FILE
"\n#Default rules for used application layer protocols.\n";
1479 foreach my $enabled_app_layer_proto (@enabled_app_layer_protos) {
1480 # Check if the current processed app layer proto needs to be translated
1481 # into an application name.
1482 if (exists($tr_app_layer_proto{$enabled_app_layer_proto})) {
1483 # Obtain the translated application name for this protocol.
1484 $enabled_app_layer_proto = $tr_app_layer_proto{$enabled_app_layer_proto};
1487 # Generate filename.
1488 my $rulesfile = "$default_rulespath/$enabled_app_layer_proto\.rules";
1490 # Check if such a file exists.
1491 if (-f
"$rulesfile") {
1492 # Write the rulesfile name to the file.
1493 print FILE
" - $rulesfile\n";
1496 # Generate filename with "events" in filename.
1497 $rulesfile = "$default_rulespath/$enabled_app_layer_proto\-events.rules";
1499 # Check if this file exists.
1500 if (-f
"$rulesfile" ) {
1501 # Write the rulesfile name to the file.
1502 print FILE
" - $rulesfile\n";
1506 # Loop through the array of enabled providers.
1507 foreach my $provider (@providers) {
1508 # Get the used rulefile for this provider.
1509 my @used_rulesfiles = &get_provider_used_rulesfiles
($provider);
1511 # Check if there are
1512 if(@used_rulesfiles) {
1513 # Add notice to the file.
1514 print FILE
"\n#Used Rulesfiles for provider $provider.\n";
1516 # Loop through the array of used rulefiles.
1517 foreach my $enabled_rulesfile (@used_rulesfiles) {
1518 # Generate name and full path to the rulesfile.
1519 my $rulesfile = "$rulespath/$enabled_rulesfile";
1521 # Write the ruelsfile name to the file.
1522 print FILE
" - $rulesfile\n";
1527 # Close the file handle
1532 ## Tiny function to generate the full path and name for the file which stores the used rulefiles of a given provider.
1534 sub get_provider_used_rulesfiles_file
($) {
1535 my ($provider) = @_;
1537 my $filename = "$settingsdir/$provider\-used\-rulesfiles";
1539 # Return the gernerated file.
1544 ## Tiny function to generate the full path and name for the file which stores the modifications of a ruleset.
1546 sub get_provider_ruleset_modifications_file
($) {
1547 my ($provider) = @_;
1549 my $filename = "$settingsdir/$provider\-modifications";
1551 # Return the filename.
1556 ## Function to get the subscription code of a configured provider.
1558 sub get_subscription_code
($) {
1559 my ($provider) = @_;
1561 my %configured_providers = ();
1563 # Read-in providers settings file.
1564 &General
::readhasharray
($providers_settings_file, \
%configured_providers);
1566 # Loop through the hash of configured providers.
1567 foreach my $id (keys %configured_providers) {
1568 # Assign nice human-readable values to the data fields.
1569 my $provider_handle = $configured_providers{$id}[0];
1570 my $subscription_code = $configured_providers{$id}[1];
1572 # Check if the current processed provider is the requested one.
1573 if ($provider_handle eq $provider) {
1574 # Return the obtained subscription code.
1575 return $subscription_code;
1579 # No subscription code found - return nothing.
1584 ## Function to get the ruleset date for a given provider.
1586 ## The function simply return the creation date in a human read-able format
1587 ## of the stored providers rulesfile.
1589 sub get_ruleset_date
($) {
1590 my ($provider) = @_;
1594 # Get the stored rulesfile for this provider.
1595 my $stored_rulesfile = &_get_dl_rulesfile
($provider);
1597 # Check if we got a file.
1598 if (-f
$stored_rulesfile) {
1599 # Call stat on the rulestarball.
1600 my $stat = stat("$stored_rulesfile");
1602 # Get timestamp the file creation.
1603 $mtime = $stat->mtime;
1606 # Check if the timestamp has not been grabbed.
1608 # Return N/A for Not available.
1612 # Convert into human read-able format.
1613 $date = strftime
('%Y-%m-%d %H:%M:%S', localtime($mtime));
1620 ## Function to gather the version of suricata.
1622 sub get_suricata_version
($) {
1625 # Execute piped suricata command and return the version information.
1626 open(SURICATA
, "suricata -V |") or die "Couldn't execute program: $!";
1628 # Grab and store the output of the piped program.
1629 my $version_string = <SURICATA
>;
1635 chomp($version_string);
1637 # Grab the version from the version string.
1638 $version_string =~ /([0-9]+([.][0-9]+)+)/;
1640 # Splitt the version into single chunks.
1641 my ($major_ver, $minor_ver, $patchlevel) = split(/\./, $1);
1643 # Check and return the requested version sheme.
1644 if ($format eq "major") {
1645 # Return the full version.
1646 return "$major_ver";
1647 } elsif ($format eq "minor") {
1648 # Return the major and minor part.
1649 return "$major_ver.$minor_ver";
1651 # Return the full version string.
1652 return "$major_ver.$minor_ver.$patchlevel";
1657 ## Function to get the enabled application layer protocols.
1659 sub get_suricata_enabled_app_layer_protos
() {
1660 # Array to store and return the enabled app layer protos.
1661 my @enabled_app_layer_protos = ();
1663 # Execute piped suricata command and return the list of
1664 # enabled application layer protocols.
1665 open(SURICATA
, "suricata --list-app-layer-protos |") or die "Could not execute program: $!";
1667 # Grab and store the list of enabled application layer protocols.
1668 my @output = <SURICATA
>;
1673 # Merge allways enabled static application layers protocols array.
1674 @enabled_app_layer_protos = @static_enabled_app_layer_protos;
1676 # Loop through the array which contains the output of suricata.
1677 foreach my $line (@output) {
1678 # Skip header line which starts with "===".
1679 next if ($line =~ /^\s*=/);
1681 # Skip info or warning lines.
1682 next if ($line =~ /\s*--/);
1687 # Add enabled app layer proto to the array.
1688 push(@enabled_app_layer_protos, $line);
1692 @enabled_app_layer_protos = sort(@enabled_app_layer_protos);
1695 return @enabled_app_layer_protos;
1699 ## Function to generate the rules file with whitelisted addresses.
1701 sub generate_ignore_file
() {
1704 # SID range 1000000-1999999 Reserved for Local Use
1705 # Put your custom rules in this range to avoid conflicts
1708 # Read-in ignoredfile.
1709 &General
::readhasharray
($IDS::ignored_file
, \
%ignored);
1711 # Open ignorefile for writing.
1712 open(FILE
, ">$IDS::whitelist_file") or die "Could not write to $IDS::whitelist_file. $!\n";
1714 # Config file header.
1715 print FILE
"# Autogenerated file.\n";
1716 print FILE
"# All user modifications will be overwritten.\n\n";
1718 # Add all user defined addresses to the whitelist.
1720 # Check if the hash contains any elements.
1721 if (keys (%ignored)) {
1722 # Loop through the entire hash and write the host/network
1723 # and remark to the ignore file.
1724 while ( (my $key) = each %ignored) {
1725 my $address = $ignored{$key}[0];
1726 my $remark = $ignored{$key}[1];
1727 my $status = $ignored{$key}[2];
1729 # Check if the status of the entry is "enabled".
1730 if ($status eq "enabled") {
1731 # Check if the address/network is valid.
1732 if ((&General
::validip
($address)) || (&General
::validipandmask
($address))) {
1733 # Write rule line to the file to pass any traffic from this IP
1734 print FILE
"pass ip $address any -> any any (msg:\"pass all traffic from/to $address\"\; bypass; sid:$sid\;)\n";
1747 ## Function to set correct ownership for single files and directories.
1750 sub set_ownership
($) {
1753 # User and group of the WUI.
1754 my $uname = "nobody";
1755 my $grname = "nobody";
1757 # The chown function implemented in perl requies the user and group as nummeric id's.
1758 my $uid = getpwnam($uname);
1759 my $gid = getgrnam($grname);
1761 # Check if the given target exists.
1763 # Stop the script and print error message.
1764 die "The $target does not exist. Cannot change the ownership!\n";
1767 # Check weather the target is a file or directory.
1769 # Change ownership ot the single file.
1770 chown($uid, $gid, "$target");
1771 } elsif (-d
$target) {
1772 # Do a directory listing.
1773 opendir(DIR
, $target) or die $!;
1774 # Loop through the direcory.
1775 while (my $file = readdir(DIR
)) {
1777 # We only want files.
1778 next unless (-f
"$target/$file");
1780 # Set correct ownership for the files.
1781 chown($uid, $gid, "$target/$file");
1786 # Change ownership of the directory.
1787 chown($uid, $gid, "$target");
1792 ## Function to read-in the aliases file and returns all configured and enabled aliases.
1795 # Location of the aliases file.
1796 my $aliases_file = "${General::swroot}/ethernet/aliases";
1798 # Array to store the aliases.
1801 # Check if the file is empty.
1802 if (-z
$aliases_file) {
1803 # Abort nothing to do.
1807 # Open the aliases file.
1808 open(ALIASES
, $aliases_file) or die "Could not open $aliases_file. $!\n";
1810 # Loop through the file content.
1811 while (my $line = <ALIASES
>) {
1815 # Splitt line content into single chunks.
1816 my ($address, $state, $remark) = split(/\,/, $line);
1818 # Check if the state of the current processed alias is "on".
1819 if ($state eq "on") {
1820 # Check if the address is valid.
1821 if(&Network
::check_ip_address
($address)) {
1822 # Add the alias to the array of aliases.
1823 push(@aliases, $address);
1828 # Close file handle.
1836 ## Function to grab the current assigned IP-address on red.
1838 sub get_red_address
() {
1839 # File, which contains the current IP-address of the red interface.
1840 my $file = "${General::swroot}/red/local-ipaddress";
1842 # Check if the file exists.
1844 # Open the given file.
1845 open(FILE
, "$file") or die "Could not open $file.";
1847 # Obtain the address from the first line of the file.
1848 my $address = <FILE
>;
1856 # Check if the grabbed address is valid.
1857 if (&General
::validip
($address)) {
1858 # Return the address.
1868 ## Function to get the used rules files of a given provider.
1870 sub get_provider_used_rulesfiles
($) {
1871 my ($provider) = @_;
1873 # Hash to store the used rulefiles of the provider.
1874 my %provider_rulefiles = ();
1876 # Array to store the used rulefiles.
1877 my @used_rulesfiles = ();
1879 # Get the filename which contains the used rulefiles for this provider.
1880 my $used_rulesfiles_file = &get_provider_used_rulesfiles_file
($provider);
1882 # Read-in file, if it exists.
1883 &General
::readhash
("$used_rulesfiles_file", \
%provider_rulefiles) if (-f
$used_rulesfiles_file);
1885 # Loop through the hash of rulefiles which does the provider offer.
1886 foreach my $rulefile (keys %provider_rulefiles) {
1887 # Skip disabled rulefiles.
1888 next unless($provider_rulefiles{$rulefile} eq "enabled");
1890 # The General::readhash function does not allow dots as
1891 # key value and limits the key "string" to the part before
1892 # the dot, in case it contains one.
1894 # So add the file extension for the rules file manually again.
1895 $rulefile = "$rulefile.rules";
1897 # Add the enabled rulefile to the array of enabled rulefiles.
1898 push(@used_rulesfiles, $rulefile);
1901 # Return the array of used rulesfiles.
1902 return @used_rulesfiles;
1906 ## Function to write the lock file for locking the WUI, while
1907 ## the autoupdate script runs.
1909 sub lock_ids_page
() {
1910 # Call subfunction to create the file.
1911 &create_empty_file
($ids_page_lock_file);
1915 ## Function to release the lock of the WUI, again.
1917 sub unlock_ids_page
() {
1919 unlink($ids_page_lock_file);