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 the libwwwperl User Agent module.
53 # Load function from posix module to format time strings.
54 use POSIX qw
(strftime
);
56 # Load module to talk to the kernel log daemon.
57 use Sys
::Syslog
qw(:DEFAULT setlogsock);
59 # Location where all config and settings files are stored.
60 our $settingsdir = "${General::swroot}/suricata";
62 # File where the main file for providers ruleset inclusion exists.
63 our $suricata_used_providers_file = "$settingsdir/suricata-used-providers.yaml";
65 # File for static ruleset inclusions.
66 our $suricata_default_rulefiles_file = "$settingsdir/suricata-default-rules.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 contains includes for provider specific rule modifications.
78 our $oinkmaster_provider_includes_file = "$settingsdir/oinkmaster-provider-includes.conf";
80 # File which contains wheater the rules should be changed.
81 our $modify_sids_file = "$settingsdir/oinkmaster-modify-sids.conf";
83 # File which stores the configured IPS settings.
84 our $ids_settings_file = "$settingsdir/settings";
86 # File which stores the used and configured ruleset providers.
87 our $providers_settings_file = "$settingsdir/providers-settings";
89 # File which stores the configured settings for whitelisted addresses.
90 our $ignored_file = "$settingsdir/ignored";
92 # Location where the downloaded rulesets are stored.
93 our $dl_rules_path = "/var/tmp";
95 # File to store any errors, which also will be read and displayed by the wui.
96 our $storederrorfile = "/tmp/ids_storederror";
98 # File to lock the WUI, while the autoupdate script runs.
99 our $ids_page_lock_file = "/tmp/ids_page_locked";
101 # Location where the rulefiles are stored.
102 our $rulespath = "/var/lib/suricata";
104 # Location where the default rulefils are stored.
105 our $default_rulespath = "/usr/share/suricata/rules";
107 # Location where the addition config files are stored.
108 our $configspath = "/usr/share/suricata";
110 # Location of the classification file.
111 our $classification_file = "$configspath/classification.config";
113 # Location of the sid to msg mappings file.
114 our $sid_msg_file = "$rulespath/sid-msg.map";
116 # Location to store local rules. This file will not be touched.
117 our $local_rules_file = "$rulespath/local.rules";
119 # File which contains the rules to whitelist addresses on suricata.
120 our $whitelist_file = "$rulespath/whitelist.rules";
122 # File which contains a list of all supported ruleset sources.
123 # (Sourcefire, Emergingthreads, etc..)
124 our $rulesetsourcesfile = "$settingsdir/ruleset-sources";
126 # The pidfile of the IDS.
127 our $idspidfile = "/var/run/suricata.pid";
129 # Location of suricatactrl.
130 my $suricatactrl = "/usr/local/bin/suricatactrl";
132 # Prefix for each downloaded ruleset.
133 my $dl_rulesfile_prefix = "idsrules";
135 # Temporary directory where the rulesets will be extracted.
136 my $tmp_directory = "/tmp/ids_tmp";
138 # Temporary directory where the extracted rules files will be stored.
139 my $tmp_rules_directory = "$tmp_directory/rules";
141 # Temporary directory where the extracted additional config files will be stored.
142 my $tmp_conf_directory = "$tmp_directory/conf";
144 # Array with allowed commands of suricatactrl.
145 my @suricatactrl_cmds = ( 'start', 'stop', 'restart', 'reload', 'fix-rules-dir', 'cron' );
147 # Array with supported cron intervals.
148 my @cron_intervals = ('off', 'daily', 'weekly' );
150 # Array which contains the HTTP ports, which statically will be declared as HTTP_PORTS in the
152 my @http_ports = ('80', '81');
154 # Array which contains a list of rulefiles which always will be included if they exist.
155 my @static_included_rulefiles = ('local.rules', 'whitelist.rules');
157 # Array which contains a list of allways enabled application layer protocols.
158 my @static_enabled_app_layer_protos = ('app-layer', 'decoder', 'files', 'stream');
160 # Hash which allows to convert the download type (dl_type) to a file suffix.
161 my %dl_type_to_suffix = (
162 "archive" => ".tar.gz",
166 # Hash to translate an application layer protocol to the application name.
167 my %tr_app_layer_proto = (
169 "krb5" => "kerberos",
173 ## Function to check and create all IDS related files, if the does not exist.
175 sub check_and_create_filelayout
() {
176 # Check if the files exist and if not, create them.
177 unless (-f
"$oinkmaster_provider_includes_file") { &create_empty_file
($oinkmaster_provider_includes_file); }
178 unless (-f
"$modify_sids_file") { &create_empty_file
($modify_sids_file); }
179 unless (-f
"$suricata_used_providers_file") { &create_empty_file
($suricata_used_providers_file); }
180 unless (-f
"$suricata_default_rulefiles_file") { &create_empty_file
($suricata_default_rulefiles_file); }
181 unless (-f
"$ids_settings_file") { &create_empty_file
($ids_settings_file); }
182 unless (-f
"$providers_settings_file") { &create_empty_file
($providers_settings_file); }
183 unless (-f
"$whitelist_file" ) { &create_empty_file
($whitelist_file); }
187 ## Function to get a list of all available ruleset providers.
189 ## They will be returned as a sorted array.
191 sub get_ruleset_providers
() {
194 # Loop through the hash of providers.
195 foreach my $provider ( keys %IDS::Ruleset
::Providers
) {
196 # Add the provider to the array.
197 push(@providers, $provider);
200 # Sort and return the array.
201 return sort(@providers);
205 ## Function to get a list of all enabled ruleset providers.
207 ## They will be returned as an array.
209 sub get_enabled_providers
() {
210 my %used_providers = ();
212 # Array to store the enabled providers.
213 my @enabled_providers = ();
215 # Read-in the providers config file.
216 &General
::readhasharray
("$providers_settings_file", \
%used_providers);
218 # Loop through the hash of used_providers.
219 foreach my $id (keys %used_providers) {
220 # Skip disabled providers.
221 next unless ($used_providers{$id}[3] eq "enabled");
223 # Grab the provider handle.
224 my $provider = "$used_providers{$id}[0]";
226 # Add the provider to the array of enabled providers.
227 push(@enabled_providers, $provider);
231 return @enabled_providers;
235 ## Function for checking if at least 300MB of free disk space are available
236 ## on the "/var" partition.
238 sub checkdiskspace
() {
239 # Call diskfree to gather the free disk space of /var.
240 my @df = &General
::system_output
("/bin/df", "-B", "M", "/var");
242 # Loop through the output.
243 foreach my $line (@df) {
244 # Ignore header line.
245 next if $line =~ m/^Filesystem/;
247 # Search for a line with the device information.
248 if ($line =~ m/dev/ ) {
249 # Split the line into single pieces.
250 my @values = split(' ', $line);
251 my ($filesystem, $blocks, $used, $available, $used_perenctage, $mounted_on) = @values;
253 # Check if the available disk space is more than 300MB.
254 if ($available < 300) {
255 # Log error to syslog.
256 &_log_to_syslog
("Not enough free disk space on /var. Only $available MB from 300 MB available.");
258 # Exit function and return "1" - False.
264 # Everything okay, return nothing.
269 ## This function is responsible for downloading the configured IDS rulesets or if no one is specified
270 ## all configured rulesets will be downloaded.
272 ## * At first it gathers all configured ruleset providers, initialize the downloader and sets an
273 ## upstream proxy if configured.
274 ## * After that, the given ruleset or in case all rulesets should be downloaded, it will determine wether it
275 ## is enabled or not.
276 ## * The next step will be to generate the final download url, by obtaining the URL for the desired
277 ## ruleset, add the settings for the upstream proxy.
278 ## * Finally the function will grab all the rules files or tarballs from the servers.
280 sub downloadruleset
($) {
283 # If no provider is given default to "all".
286 # The amount of download attempts before giving up and
288 my $max_dl_attempts = 3;
290 # Hash to store the providers and access id's, for which rules should be downloaded.
291 my %sheduled_providers = ();
293 # Get used provider settings.
294 my %used_providers = ();
295 &General
::readhasharray
("$providers_settings_file", \
%used_providers);
297 # Check if a ruleset has been configured.
298 unless(%used_providers) {
299 # Log that no ruleset has been configured and abort.
300 &_log_to_syslog
("No ruleset provider has been configured.");
306 # Read proxysettings.
307 my %proxysettings=();
308 &General
::readhash
("${General::swroot}/proxy/settings", \
%proxysettings);
310 # Init the download module.
312 # Request SSL hostname verification and specify path
314 my $downloader = LWP
::UserAgent
->new(
316 SSL_ca_file
=> '/etc/ssl/cert.pem',
317 verify_hostname
=> 1,
321 # Set timeout to 10 seconds.
322 $downloader->timeout(10);
324 # Check if an upstream proxy is configured.
325 if ($proxysettings{'UPSTREAM_PROXY'}) {
328 $proxy_url = "http://";
330 # Check if the proxy requires authentication.
331 if (($proxysettings{'UPSTREAM_USER'}) && ($proxysettings{'UPSTREAM_PASSWORD'})) {
332 $proxy_url .= "$proxysettings{'UPSTREAM_USER'}\:$proxysettings{'UPSTREAM_PASSWORD'}\@";
335 # Add proxy server address and port.
336 $proxy_url .= $proxysettings{'UPSTREAM_PROXY'};
338 # Setup proxy settings.
339 $downloader->proxy(['http', 'https'], $proxy_url);
342 # Loop through the hash of configured providers.
343 foreach my $id ( keys %used_providers ) {
344 # Skip providers which are not enabled.
345 next if ($used_providers{$id}[3] ne "enabled");
347 # Obtain the provider handle.
348 my $provider_handle = $used_providers{$id}[0];
350 # Handle update off all providers.
351 if (($provider eq "all") || ($provider_handle eq "$provider")) {
352 # Add provider handle and it's id to the hash of sheduled providers.
353 $sheduled_providers{$provider_handle} = $id;
357 # Loop through the hash of sheduled providers.
358 foreach my $provider ( keys %sheduled_providers) {
359 # Log download/update of the ruleset.
360 &_log_to_syslog
("Downloading ruleset for provider: $provider.");
362 # Grab the download url for the provider.
363 my $url = $IDS::Ruleset
::Providers
{$provider}{'dl_url'};
365 # Check if the provider requires a subscription.
366 if ($IDS::Ruleset
::Providers
{$provider}{'requires_subscription'} eq "True") {
367 # Grab the previously stored access id for the provider from hash.
368 my $id = $sheduled_providers{$provider};
370 # Grab the subscription code.
371 my $subscription_code = $used_providers{$id}[1];
373 # Add the subscription code to the download url.
374 $url =~ s/\<subscription_code\>/$subscription_code/g;
378 # Abort if no url could be determined for the provider.
380 # Log error and abort.
381 &_log_to_syslog
("Unable to gather a download URL for the selected ruleset provider.");
385 # Generate temporary file name, located in "/var/tmp" and with a suffix of ".tmp".
386 my $tmp = File
::Temp
->new( SUFFIX
=> ".tmp", DIR
=> "/var/tmp/", UNLINK
=> 0 );
387 my $tmpfile = $tmp->filename();
389 # Pass the requested url to the downloader.
390 my $request = HTTP
::Request
->new(GET
=> $url);
395 # Download and retry on failure.
396 while ($dl_attempt <= $max_dl_attempts) {
397 # Perform the request and save the output into the tmpfile.
398 $response = $downloader->request($request, $tmpfile);
400 # Check if the download was successfull.
401 if($response->is_success) {
405 # Check if we ran out of download re-tries.
406 } elsif ($dl_attempt eq $max_dl_attempts) {
408 my $error = $response->content;
411 &_log_to_syslog
("Unable to download the ruleset. \($error\)");
413 # Return "1" - false.
417 # Remove temporary file, if one exists.
418 unlink("$tmpfile") if (-e
"$tmpfile");
420 # Increase download attempt counter.
424 # Obtain the connection headers.
425 my $headers = $response->headers;
427 # Get the remote size of the downloaded file.
428 my $remote_filesize = $headers->content_length;
430 # Perform stat on the tmpfile.
431 my $stat = stat($tmpfile);
433 # Grab the local filesize of the downloaded tarball.
434 my $local_filesize = $stat->size;
436 # Check if both file sizes match.
437 if (($remote_filesize) && ($remote_filesize ne $local_filesize)) {
439 &_log_to_syslog
("Unable to completely download the ruleset. ");
440 &_log_to_syslog
("Only got $local_filesize Bytes instead of $remote_filesize Bytes. ");
442 # Delete temporary file.
445 # Return "1" - false.
449 # Genarate and assign file name and path to store the downloaded rules file.
450 my $dl_rulesfile = &_get_dl_rulesfile
($provider);
452 # Check if a file name could be obtained.
453 unless ($dl_rulesfile) {
455 &_log_to_syslog
("Unable to store the downloaded rules file. ");
457 # Delete downloaded temporary file.
460 # Return "1" - false.
464 # Overwrite the may existing rulefile or tarball with the downloaded one.
465 move
("$tmpfile", "$dl_rulesfile");
467 # Delete temporary file.
470 # Set correct ownership for the tarball.
471 set_ownership
("$dl_rulesfile");
474 # If we got here, everything worked fine. Return nothing.
479 ## Function to extract a given ruleset.
481 ## In case the ruleset provider offers a plain file, it simply will
484 sub extractruleset
($) {
487 # Disable chown functionality when uncompressing files.
488 $Archive::Tar
::CHOWN
= "0";
490 # Get full path and downloaded rulesfile for the given provider.
491 my $tarball = &_get_dl_rulesfile
($provider);
493 # Check if the file exists.
494 unless (-f
$tarball) {
495 &_log_to_syslog
("Could not find ruleset file: $tarball");
501 # Check if the temporary directories exist, otherwise create them.
502 mkdir("$tmp_directory") unless (-d
"$tmp_directory");
503 mkdir("$tmp_rules_directory") unless (-d
"$tmp_rules_directory");
504 mkdir("$tmp_conf_directory") unless (-d
"$tmp_conf_directory");
506 # Omit the type (dl_type) of the stored ruleset.
507 my $type = $IDS::Ruleset
::Providers
{$provider}{'dl_type'};
509 # Handle the different ruleset types.
510 if ($type eq "plain") {
511 # Generate destination filename an full path.
512 my $destination = "$tmp_rules_directory/$provider\-ruleset.rules";
514 # Copy the file into the temporary rules directory.
515 copy
($tarball, $destination);
517 } elsif ( $type eq "archive") {
518 # Initialize the tar module.
519 my $tar = Archive
::Tar
->new($tarball);
521 # Get the filelist inside the tarball.
522 my @packed_files = $tar->list_files;
524 # Loop through the filelist.
525 foreach my $packed_file (@packed_files) {
528 # Splitt the packed file into chunks.
529 my $file = fileparse
($packed_file);
531 # Handle msg-id.map file.
532 if ("$file" eq "sid-msg.map") {
533 # Set extract destination to temporary config_dir.
534 $destination = "$tmp_conf_directory/$provider\-sid-msg.map";
536 # Handle classification.conf
537 } elsif ("$file" eq "classification.config") {
538 # Set extract destination to temporary config_dir.
539 $destination = "$tmp_conf_directory/$provider\-classification.config";
541 # Handle rules files.
542 } elsif ($file =~ m/\.rules$/) {
543 # Skip rule files which are not located in the rules directory or archive root.
544 next unless(($packed_file =~ /^rules\//) || ($packed_file !~ /\
//));
546 # Skip deleted.rules.
548 # Mostly they have been taken out for correctness or performance reasons and therfore
549 # it is not a great idea to enable any of them.
550 next if($file =~ m/deleted.rules$/);
554 # Splitt the filename into chunks.
555 my @filename = split("-", $file);
558 @filename = reverse(@filename);
560 # Get the amount of elements in the array.
561 my $elements = @filename;
563 # Remove last element of the hash.
564 # It contains the vendor name, which will be replaced.
565 if ($elements >= 3) {
566 # Remove last element from hash.
570 # Check if the last element of the filename does not
571 # contain the providers name.
572 if ($filename[-1] ne "$provider") {
573 # Add provider name as last element.
574 push(@filename, $provider);
577 # Reverse the array back.
578 @filename = reverse(@filename);
580 # Generate the name for the rulesfile.
581 $rulesfilename = join("-", @filename);
583 # Set extract destination to temporaray rules_dir.
584 $destination = "$tmp_rules_directory/$rulesfilename";
586 # Skip all other files.
590 # Check if the destination file exists.
591 unless(-e
"$destination") {
592 # Extract the file to the temporary directory.
593 $tar->extract_file("$packed_file", "$destination");
595 # Generate temporary file name, located in the temporary rules directory and a suffix of ".tmp".
596 my $tmp = File
::Temp
->new( SUFFIX
=> ".tmp", DIR
=> "$tmp_rules_directory", UNLINK
=> 0 );
597 my $tmpfile = $tmp->filename();
599 # Extract the file to the new temporary file name.
600 $tar->extract_file("$packed_file", "$tmpfile");
602 # Open the the existing file.
603 open(DESTFILE
, ">>", "$destination") or die "Could not open $destination. $!\n";
604 open(TMPFILE
, "<", "$tmpfile") or die "Could not open $tmpfile. $!\n";
606 # Loop through the content of the temporary file.
608 # Append the content line by line to the destination file.
612 # Close the file handles.
616 # Remove the temporary file.
624 ## A wrapper function to call the oinkmaster script, setup the rules structues and
625 ## call the functions to merge the additional config files. (classification, sid-msg, etc.).
628 # Check if the files in rulesdir have the correct permissions.
629 &_check_rulesdir_permissions
();
631 # Cleanup the rules directory before filling it with the new rulests.
632 &_cleanup_rulesdir
();
634 # Get all enabled providers.
635 my @enabled_providers = &get_enabled_providers
();
637 # Loop through the array of enabled providers.
638 foreach my $provider (@enabled_providers) {
639 # Call the extractruleset function.
640 &extractruleset
($provider);
643 # Establish the connection to the syslog service.
644 openlog
('oinkmaster', 'cons,pid', 'user');
646 # Call oinkmaster to generate ruleset.
647 open(OINKMASTER
, "/usr/local/bin/oinkmaster.pl -s -u dir://$tmp_rules_directory -C $settingsdir/oinkmaster.conf -o $rulespath 2>&1 |") or die "Could not execute oinkmaster $!\n";
649 # Log output of oinkmaster to syslog.
650 while(<OINKMASTER
>) {
651 # The syslog function works best with an array based input,
652 # so generate one before passing the message details to syslog.
653 my @syslog = ("INFO", "$_");
655 # Send the log message.
659 # Close the pipe to oinkmaster process.
662 # Close the log handle.
665 # Call function to merge the classification files.
666 &merge_classifications
(@enabled_providers);
668 # Call function to merge the sid to message mapping files.
669 &merge_sid_msg
(@enabled_providers);
671 # Cleanup temporary directory.
672 &cleanup_tmp_directory
();
676 ## Function to merge the classifications for a given amount of providers and write them
677 ## to the classifications file.
679 sub merge_classifications
(@
) {
682 # Hash to store all collected classifications.
683 my %classifications = ();
685 # Loop through the given array of providers.
686 foreach my $provider (@providers) {
687 # Generate full path to classification file.
688 my $classification_file = "$tmp_conf_directory/$provider\-classification.config";
690 # Skip provider if no classification file exists.
691 next unless (-f
"$classification_file");
693 # Open the classification file.
694 open(CLASSIFICATION
, $classification_file) or die "Could not open file $classification_file. $!\n";
696 # Loop through the file content.
697 while(<CLASSIFICATION
>) {
698 # Parse the file and grab the classification details.
699 if ($_ =~/.*config classification\: (.*)/) {
700 # Split the grabbed details.
701 my ($short_name, $short_desc, $priority) = split("\,", $1);
703 # Check if the grabbed classification is allready known and the priority value is greater
704 # than the stored one (which causes less priority in the IDS).
705 if (($classifications{$short_name}) && ($classifications{$short_name}[1] >= $priority)) {
706 #Change the priority value to the stricter one.
707 $classifications{$short_name} = [ "$classifications{$short_name}[0]", "$priority" ];
709 # Add the classification to the hash.
710 $classifications{$short_name} = [ "$short_desc", "$priority" ];
716 close(CLASSIFICATION
);
719 # Open classification file for writing.
720 open(FILE
, ">", "$classification_file") or die "Could not write to $classification_file. $!\n";
722 # Print notice about autogenerated file.
723 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n\n";
725 # Sort and loop through the hash of classifications.
726 foreach my $key (sort keys %classifications) {
727 # Assign some nice variable names for the items.
728 my $short_name = $key;
729 my $short_desc = $classifications{$key}[0];
730 my $priority = $classifications{$key}[1];
732 # Write the classification to the file.
733 print FILE
"config classification: $short_name,$short_desc,$priority\n";
741 ## Function to merge the "sid to message mapping" files of various given providers.
743 sub merge_sid_msg
(@
) {
746 # Hash which contains all the sid to message mappings.
749 # Loop through the array of given providers.
750 foreach my $provider (@providers) {
751 # Generate full path and filename.
752 my $sid_msg_file = "$tmp_conf_directory/$provider\-sid-msg.map";
754 # Skip provider if no sid to msg mapping file for this provider exists.
755 next unless (-f
$sid_msg_file);
758 open(MAPPING
, $sid_msg_file) or die "Could not open $sid_msg_file. $!\n";
760 # Loop through the file content.
765 # Skip lines which do not start with a number,
766 next unless ($_ =~ /^\d+/);
768 # Split line content and assign it to an array.
769 my @line = split(/ \|\| /, $_);
771 # Grab the first element (and remove it) from the line array.
772 # It contains the sid.
773 my $sid = shift(@line);
775 # Store the grabbed sid and the remain array as hash value.
776 # It still contains the messages, references etc.
777 $mappings{$sid} = [@line];
784 # Open mappings file for writing.
785 open(FILE
, ">", $sid_msg_file) or die "Could not write $sid_msg_file. $!\n";
787 # Write notice about autogenerated file.
788 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n\n";
790 # Loop through the hash of mappings.
791 foreach my $sid ( sort keys %mappings) {
792 # Grab data for the sid.
793 my @data = @
{$mappings{$sid}};
795 # Add the sid to the data array.
796 unshift(@data, $sid);
799 my $line = join(" \|\| ", @data);
801 print FILE
"$line\n";
810 ## A very tiny function to move an extracted ruleset from the temporary directory into
811 ## the rules directory.
813 sub move_tmp_ruleset
() {
814 # Do a directory listing of the temporary directory.
815 opendir DH
, $tmp_rules_directory;
817 # Loop over all files.
818 while(my $file = readdir DH
) {
819 # Move them to the rules directory.
820 move
"$tmp_rules_directory/$file" , "$rulespath/$file";
823 # Close directory handle.
828 ## Function to cleanup the temporary IDS directroy.
830 sub cleanup_tmp_directory
() {
832 # Delete temporary directory and all containing files.
833 rmtree
([ "$tmp_directory" ]);
837 ## Function to do all the logging stuff if the downloading or updating of the ruleset fails.
842 # Remove any newline.
845 # Call private function to log the error message to syslog.
846 &_log_to_syslog
($error);
848 # Call private function to write/store the error message in the storederrorfile.
849 &_store_error_message
($error);
853 ## Function to log a given error message to the kernel syslog.
855 sub _log_to_syslog
($) {
858 # The syslog function works best with an array based input,
859 # so generate one before passing the message details to syslog.
860 my @syslog = ("ERR", "<ERROR> $message");
862 # Establish the connection to the syslog service.
863 openlog
('oinkmaster', 'cons,pid', 'user');
865 # Send the log message.
868 # Close the log handle.
873 ## Private function to write a given error message to the storederror file.
875 sub _store_error_message
($) {
878 # Remove any newline.
881 # Open file for writing.
882 open (ERRORFILE
, ">$storederrorfile") or die "Could not write to $storederrorfile. $!\n";
884 # Write error to file.
885 print ERRORFILE
"$message\n";
890 # Set correct ownership for the file.
891 &set_ownership
("$storederrorfile");
895 ## Private function to get the path and filename for a downloaded ruleset by a given provider.
897 sub _get_dl_rulesfile
($) {
900 # Gather the download type for the given provider.
901 my $dl_type = $IDS::Ruleset
::Providers
{$provider}{'dl_type'};
903 # Obtain the file suffix for the download file type.
904 my $suffix = $dl_type_to_suffix{$dl_type};
906 # Check if a suffix has been found.
908 # Abort return - nothing.
912 # Generate the full filename and path for the stored rules file.
913 my $rulesfile = "$dl_rules_path/$dl_rulesfile_prefix-$provider$suffix";
915 # Return the generated filename.
920 ## Tiny function to delete the stored ruleset file or tarball for a given provider.
922 sub drop_dl_rulesfile
($) {
925 # Gather the full path and name of the stored rulesfile.
926 my $rulesfile = &_get_dl_rulesfile
($provider);
928 # Check if the given rulesfile exists.
930 # Delete the stored rulesfile.
931 unlink($rulesfile) or die "Could not delete $rulesfile. $!\n";
936 ## Tiny function to get/generate the full path and filename for the providers oinkmaster
937 ## modified sids file.
939 sub get_oinkmaster_provider_modified_sids_file
($) {
942 # Generate the filename.
943 my $filename = "$settingsdir/oinkmaster-$provider-modified-sids.conf";
945 # Return the filename.
950 ## Function to directly altering the oinkmaster provider includes file.
952 ## Requires tha acition "remove" or "add" and a provider handle.
954 sub alter_oinkmaster_provider_includes_file
($$) {
955 my ($action, $provider) = @_;
957 # Call function to get the path and name for the given providers
958 # oinkmaster modified sids file.
959 my $provider_modified_sids_file = &get_oinkmaster_provider_modified_sids_file
($provider);
961 # Open the file for reading..
962 open (FILE
, $oinkmaster_provider_includes_file) or die "Could not read $oinkmaster_provider_includes_file. $!\n";
964 # Read-in file content.
967 # Close file after reading.
970 # Re-open the file for writing.
971 open(FILE
, ">", $oinkmaster_provider_includes_file) or die "Could not write to $oinkmaster_provider_includes_file. $!\n";
973 # Loop through the file content.
974 foreach my $line (@lines) {
978 # Skip line if we found our given provider and the action should be remove.
979 next if (($line =~ /$provider/) && ($action eq "remove"));
981 # Write the read-in line back to the file.
982 print FILE
"$line\n";
985 # Check if the file exists and add the provider if requested.
986 if ((-f
$provider_modified_sids_file) && ($action eq "add")) {
987 print FILE
"include $provider_modified_sids_file\n";
995 ## Function to read-in the given enabled or disables sids file.
997 sub read_enabled_disabled_sids_file
($) {
1000 # Temporary hash to store the sids and their state. It will be
1001 # returned at the end of this function.
1004 # Open the given filename.
1005 open(FILE
, "$file") or die "Could not open $file. $!\n";
1007 # Loop through the file.
1013 next if ($_ =~ /^\s*$/);
1016 next if ($_ =~ /^\#/);
1018 # Splitt line into sid and state part.
1019 my ($state, $sid) = split(" ", $_);
1021 # Skip line if the sid is not numeric.
1022 next unless ($sid =~ /\d+/ );
1024 # Check if the sid was enabled.
1025 if ($state eq "enablesid") {
1026 # Add the sid and its state as enabled to the temporary hash.
1027 $temphash{$sid} = "enabled";
1028 # Check if the sid was disabled.
1029 } elsif ($state eq "disablesid") {
1030 # Add the sid and its state as disabled to the temporary hash.
1031 $temphash{$sid} = "disabled";
1032 # Invalid state - skip the current sid and state.
1046 ## Function to check if the IDS is running.
1048 sub ids_is_running
() {
1049 if(-f
$idspidfile) {
1050 # Open PID file for reading.
1051 open(PIDFILE
, "$idspidfile") or die "Could not open $idspidfile. $!\n";
1053 # Grab the process-id.
1054 my $pid = <PIDFILE
>;
1059 # Remove any newline.
1062 # Check if a directory for the process-id exists in proc.
1063 if(-d
"/proc/$pid") {
1064 # The IDS daemon is running return the process id.
1069 # Return nothing - IDS is not running.
1074 ## Function to call suricatactrl binary with a given command.
1076 sub call_suricatactrl
($) {
1077 # Get called option.
1078 my ($option, $interval) = @_;
1080 # Loop through the array of supported commands and check if
1081 # the given one is part of it.
1082 foreach my $cmd (@suricatactrl_cmds) {
1083 # Skip current command unless the given one has been found.
1084 next unless($cmd eq $option);
1086 # Check if the given command is "cron".
1087 if ($option eq "cron") {
1088 # Check if an interval has been given.
1090 # Check if the given interval is valid.
1091 foreach my $element (@cron_intervals) {
1092 # Skip current element until the given one has been found.
1093 next unless($element eq $interval);
1095 # Call the suricatactrl binary and pass the "cron" command
1096 # with the requrested interval.
1097 &General
::system("$suricatactrl", "$option", "$interval");
1099 # Return "1" - True.
1104 # If we got here, the given interval is not supported or none has been given. - Return nothing.
1107 # Call the suricatactrl binary and pass the requrested
1109 &General
::system("$suricatactrl", "$option");
1111 # Return "1" - True.
1116 # Command not found - return nothing.
1121 ## Function to create a new empty file.
1123 sub create_empty_file
($) {
1126 # Check if the given file exists.
1128 # Do nothing to prevent from overwriting existing files.
1132 # Open the file for writing.
1133 open(FILE
, ">$file") or die "Could not write to $file. $!\n";
1135 # Close file handle.
1143 ## Private function to check if the file permission of the rulespath are correct.
1144 ## If not, call suricatactrl to fix them.
1146 sub _check_rulesdir_permissions
() {
1147 # Check if the rulepath main directory is writable.
1148 unless (-W
$rulespath) {
1149 # If not call suricatctrl to fix it.
1150 &call_suricatactrl
("fix-rules-dir");
1153 # Open snort rules directory and do a directory listing.
1154 opendir(DIR
, $rulespath) or die $!;
1155 # Loop through the direcory.
1156 while (my $file = readdir(DIR
)) {
1157 # We only want files.
1158 next unless (-f
"$rulespath/$file");
1160 # Check if the file is writable by the user.
1161 if (-W
"$rulespath/$file") {
1162 # Everything is okay - go on to the next file.
1165 # There are wrong permissions, call suricatactrl to fix it.
1166 &call_suricatactrl
("fix-rules-dir");
1172 ## Private function to cleanup the directory which contains
1173 ## the IDS rules, before extracting and modifing the new ruleset.
1175 sub _cleanup_rulesdir
() {
1176 # Open rules directory and do a directory listing.
1177 opendir(DIR
, $rulespath) or die $!;
1179 # Loop through the direcory.
1180 while (my $file = readdir(DIR
)) {
1181 # We only want files.
1182 next unless (-f
"$rulespath/$file");
1184 # Skip rules file for whitelisted hosts.
1185 next if ("$rulespath/$file" eq $whitelist_file);
1187 # Skip rules file with local rules.
1188 next if ("$rulespath/$file" eq $local_rules_file);
1190 # Delete the current processed file, if not, exit this function
1191 # and return an error message.
1192 unlink("$rulespath/$file") or return "Could not delete $rulespath/$file. $!\n";
1200 ## Function to generate the file which contains the home net information.
1202 sub generate_home_net_file
() {
1205 # Read-in network settings.
1206 &General
::readhash
("${General::swroot}/ethernet/settings", \
%netsettings);
1208 # Get available network zones.
1209 my @network_zones = &Network
::get_available_network_zones
();
1211 # Temporary array to store network address and prefix of the configured
1215 # Loop through the array of available network zones.
1216 foreach my $zone (@network_zones) {
1217 # Check if the current processed zone is red.
1218 if($zone eq "red") {
1219 # Grab the IP-address of the red interface.
1220 my $red_address = &get_red_address
();
1222 # Check if an address has been obtained.
1224 # Generate full network string.
1225 my $red_network = join("/", $red_address, "32");
1227 # Add the red network to the array of networks.
1228 push(@networks, $red_network);
1231 # Check if the configured RED_TYPE is static.
1232 if ($netsettings{'RED_TYPE'} eq "STATIC") {
1233 # Get configured and enabled aliases.
1234 my @aliases = &get_aliases
();
1236 # Loop through the array.
1237 foreach my $alias (@aliases) {
1239 my $network = join("/", $alias, "32");
1241 # Add the generated network to the array of networks.
1242 push(@networks, $network);
1245 # Process remaining network zones.
1247 # Convert current zone name into upper case.
1250 # Generate key to access the required data from the netsettings hash.
1251 my $zone_netaddress = $zone . "_NETADDRESS";
1252 my $zone_netmask = $zone . "_NETMASK";
1254 # Obtain the settings from the netsettings hash.
1255 my $netaddress = $netsettings{$zone_netaddress};
1256 my $netmask = $netsettings{$zone_netmask};
1258 # Convert the subnetmask into prefix notation.
1259 my $prefix = &Network
::convert_netmask2prefix
($netmask);
1261 # Generate full network string.
1262 my $network = join("/", $netaddress,$prefix);
1264 # Check if the network is valid.
1265 if(&Network
::check_subnet
($network)) {
1266 # Add the generated network to the array of networks.
1267 push(@networks, $network);
1272 # Format home net declaration.
1273 my $line = "\"[" . join(',', @networks) . "]\"";
1275 # Open file to store the addresses of the home net.
1276 open(FILE
, ">$homenet_file") or die "Could not open $homenet_file. $!\n";
1278 # Print yaml header.
1279 print FILE
"%YAML 1.1\n";
1280 print FILE
"---\n\n";
1282 # Print notice about autogenerated file.
1283 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1285 # Print the generated and required HOME_NET declaration to the file.
1286 print FILE
"HOME_NET:\t$line\n";
1288 # Close file handle.
1293 # Function to generate and write the file which contains the configured and used DNS servers.
1295 sub generate_dns_servers_file
() {
1296 # Get the used DNS servers.
1297 my @nameservers = &General
::get_nameservers
();
1299 # Get network settings.
1301 &General
::readhash
("${General::swroot}/ethernet/settings", \
%netsettings);
1303 # Format dns servers declaration.
1306 # Check if the system has configured nameservers.
1308 # Add the GREEN address as DNS servers.
1309 push(@nameservers, $netsettings{'GREEN_ADDRESS'});
1311 # Check if a BLUE zone exists.
1312 if ($netsettings{'BLUE_ADDRESS'}) {
1313 # Add the BLUE address to the array of nameservers.
1314 push(@nameservers, $netsettings{'BLUE_ADDRESS'});
1317 # Generate the line which will be written to the DNS servers file.
1318 $line = join(",", @nameservers);
1320 # External net simply contains (any).
1321 $line = "\$EXTERNAL_NET";
1324 # Open file to store the used DNS server addresses.
1325 open(FILE
, ">$dns_servers_file") or die "Could not open $dns_servers_file. $!\n";
1327 # Print yaml header.
1328 print FILE
"%YAML 1.1\n";
1329 print FILE
"---\n\n";
1331 # Print notice about autogenerated file.
1332 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1334 # Print the generated DNS declaration to the file.
1335 print FILE
"DNS_SERVERS:\t\"[$line]\"\n";
1337 # Close file handle.
1342 # Function to generate and write the file which contains the HTTP_PORTS definition.
1344 sub generate_http_ports_file
() {
1347 # Read-in proxy settings
1348 &General
::readhash
("${General::swroot}/proxy/advanced/settings", \
%proxysettings);
1350 # Check if the proxy is enabled.
1351 if (( -e
"${General::swroot}/proxy/enable") || (-e
"${General::swroot}/proxy/enable_blue")) {
1352 # Add the proxy port to the array of HTTP ports.
1353 push(@http_ports, $proxysettings{'PROXY_PORT'});
1356 # Check if the transparent mode of the proxy is enabled.
1357 if ((-e
"${General::swroot}/proxy/transparent") || (-e
"${General::swroot}/proxy/transparent_blue")) {
1358 # Add the transparent proxy port to the array of HTTP ports.
1359 push(@http_ports, $proxysettings{'TRANSPARENT_PORT'});
1362 # Format HTTP_PORTS declaration.
1365 # Generate line which will be written to the http ports file.
1366 $line = join(",", @http_ports);
1368 # Open file to store the HTTP_PORTS.
1369 open(FILE
, ">$http_ports_file") or die "Could not open $http_ports_file. $!\n";
1371 # Print yaml header.
1372 print FILE
"%YAML 1.1\n";
1373 print FILE
"---\n\n";
1375 # Print notice about autogenerated file.
1376 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1378 # Print the generated HTTP_PORTS declaration to the file.
1379 print FILE
"HTTP_PORTS:\t\"[$line]\"\n";
1381 # Close file handle.
1386 ## Function to generate and write the file for used rulefiles file for a given provider.
1388 ## The function requires as first argument a provider handle, and as second an array with files.
1390 sub write_used_provider_rulefiles_file
($@
) {
1391 my ($provider, @files) = @_;
1393 # Get the path and file for the provider specific used rulefiles file.
1394 my $used_provider_rulesfile_file = &get_used_provider_rulesfile_file
($provider);
1396 # Open file for used rulefiles.
1397 open (FILE
, ">", "$used_provider_rulesfile_file") or die "Could not write to $used_provider_rulesfile_file. $!\n";
1399 # Write yaml header to the file.
1400 print FILE
"%YAML 1.1\n";
1401 print FILE
"---\n\n";
1403 # Write header to file.
1404 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1406 # Loop through the array of given files.
1407 foreach my $file (@files) {
1408 # Check if the given filename exists and write it to the file of used rulefiles.
1409 if(-f
"$rulespath/$file") {
1410 print FILE
" - $file\n";
1414 # Close file after writing.
1419 ## Function to write the main file for provider rulesfiles inclusions.
1421 ## This function requires an array of provider handles.
1423 sub write_main_used_rulefiles_file
(@
) {
1424 my (@providers) = @_;
1426 # Call function to write the static rulefiles file.
1427 &_write_default_rulefiles_file
();
1429 # Open file for used rulefils inclusion.
1430 open (FILE
, ">", "$suricata_used_providers_file") or die "Could not write to $suricata_used_providers_file. $!\n";
1432 # Write yaml header to the file.
1433 print FILE
"%YAML 1.1\n";
1434 print FILE
"---\n\n";
1436 # Write header to file.
1437 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1439 # Loop through the list of given providers.
1440 foreach my $provider (@providers) {
1441 # Call function to get the providers used rulefiles file.
1442 my $filename = &get_used_provider_rulesfile_file
($provider);
1444 # Check if the file exists and write it into the used rulefiles file.
1446 # Print the provider to the file.
1447 print FILE
"include\: $filename\n";
1451 # Close the filehandle after writing.
1455 sub _write_default_rulefiles_file
() {
1456 # Get enabled application layer protocols.
1457 my @enabled_app_layer_protos = &get_suricata_enabled_app_layer_protos
();
1460 open (FILE
, ">", $suricata_default_rulefiles_file) or die "Could not write to $suricata_default_rulefiles_file. $!\n";
1462 # Write yaml header to the file.
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 # Close the file handle
1511 ## Tiny function to generate the full path and name for the used_provider_rulesfile file of a given provider.
1513 sub get_used_provider_rulesfile_file
($) {
1514 my ($provider) = @_;
1516 my $filename = "$settingsdir/suricata\-$provider\-used\-rulefiles.yaml";
1518 # Return the gernerated file.
1523 ## Function to generate and write the file for modify the ruleset.
1525 sub write_modify_sids_file
() {
1526 # Get configured settings.
1528 &General
::readhash
("$ids_settings_file", \
%idssettings);
1530 # Open modify sid's file for writing.
1531 open(FILE
, ">$modify_sids_file") or die "Could not write to $modify_sids_file. $!\n";
1533 # Write file header.
1534 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1536 # Check if the traffic only should be monitored.
1537 unless($idssettings{'MONITOR_TRAFFIC_ONLY'} eq 'on') {
1538 # Suricata is in IPS mode, which means that the rule actions have to be changed
1539 # from 'alert' to 'drop', however not all rules should be changed. Some rules
1540 # exist purely to set a flowbit which is used to convey other information, such
1541 # as a specific type of file being downloaded, to other rulewhich then check for
1542 # malware in that file. Rules which fall into the first category should stay as
1543 # alert since not all flows of that type contain malware.
1545 # These types of rulesfiles contain meta-data which gives the action that should
1546 # be used when in IPS mode. Do the following:
1548 # 1. Disable all rules and set the action to 'drop'
1549 # 2. Set the action back to 'alert' if the rule contains 'flowbits:noalert;'
1550 # This should give rules not in the policy a reasonable default if the user
1551 # manually enables them.
1552 # 3. Enable rules and set actions according to the meta-data strings.
1554 my $policy = 'balanced'; # Placeholder to allow policy to be changed.
1557 modifysid * "^#(?:alert|drop)(.+policy $policy-ips alert)" | "alert\${1}"
1558 modifysid * "^#(?:alert|drop)(.+policy $policy-ips drop)" | "drop\${1}"
1559 modifysid * "^(#?)(?:alert|drop)" | "\${1}drop"
1560 modifysid * "^(#?)drop(.+flowbits:noalert;)" | "\${1}alert\${2}"
1564 # Close file handle.
1569 ## Function to get the ruleset date for a given provider.
1571 ## The function simply return the creation date in a human read-able format
1572 ## of the stored providers rulesfile.
1574 sub get_ruleset_date
($) {
1575 my ($provider) = @_;
1579 # Get the stored rulesfile for this provider.
1580 my $stored_rulesfile = &_get_dl_rulesfile
($provider);
1582 # Check if we got a file.
1583 if (-f
$stored_rulesfile) {
1584 # Call stat on the rulestarball.
1585 my $stat = stat("$stored_rulesfile");
1587 # Get timestamp the file creation.
1588 $mtime = $stat->mtime;
1591 # Check if the timestamp has not been grabbed.
1593 # Return N/A for Not available.
1597 # Convert into human read-able format.
1598 $date = strftime
('%Y-%m-%d %H:%M:%S', localtime($mtime));
1605 ## Function to gather the version of suricata.
1607 sub get_suricata_version
($) {
1610 # Execute piped suricata command and return the version information.
1611 open(SURICATA
, "suricata -V |") or die "Couldn't execute program: $!";
1613 # Grab and store the output of the piped program.
1614 my $version_string = <SURICATA
>;
1620 chomp($version_string);
1622 # Grab the version from the version string.
1623 $version_string =~ /([0-9]+([.][0-9]+)+)/;
1625 # Splitt the version into single chunks.
1626 my ($major_ver, $minor_ver, $patchlevel) = split(/\./, $1);
1628 # Check and return the requested version sheme.
1629 if ($format eq "major") {
1630 # Return the full version.
1631 return "$major_ver";
1632 } elsif ($format eq "minor") {
1633 # Return the major and minor part.
1634 return "$major_ver.$minor_ver";
1636 # Return the full version string.
1637 return "$major_ver.$minor_ver.$patchlevel";
1642 ## Function to get the enabled application layer protocols.
1644 sub get_suricata_enabled_app_layer_protos
() {
1645 # Array to store and return the enabled app layer protos.
1646 my @enabled_app_layer_protos = ();
1648 # Execute piped suricata command and return the list of
1649 # enabled application layer protocols.
1650 open(SURICATA
, "suricata --list-app-layer-protos |") or die "Could not execute program: $!";
1652 # Grab and store the list of enabled application layer protocols.
1653 my @output = <SURICATA
>;
1658 # Merge allways enabled static application layers protocols array.
1659 @enabled_app_layer_protos = @static_enabled_app_layer_protos;
1661 # Loop through the array which contains the output of suricata.
1662 foreach my $line (@output) {
1663 # Skip header line which starts with "===".
1664 next if ($line =~ /^\s*=/);
1666 # Skip info or warning lines.
1667 next if ($line =~ /\s*--/);
1672 # Add enabled app layer proto to the array.
1673 push(@enabled_app_layer_protos, $line);
1677 @enabled_app_layer_protos = sort(@enabled_app_layer_protos);
1680 return @enabled_app_layer_protos;
1684 ## Function to generate the rules file with whitelisted addresses.
1686 sub generate_ignore_file
() {
1689 # SID range 1000000-1999999 Reserved for Local Use
1690 # Put your custom rules in this range to avoid conflicts
1693 # Read-in ignoredfile.
1694 &General
::readhasharray
($IDS::ignored_file
, \
%ignored);
1696 # Open ignorefile for writing.
1697 open(FILE
, ">$IDS::whitelist_file") or die "Could not write to $IDS::whitelist_file. $!\n";
1699 # Config file header.
1700 print FILE
"# Autogenerated file.\n";
1701 print FILE
"# All user modifications will be overwritten.\n\n";
1703 # Add all user defined addresses to the whitelist.
1705 # Check if the hash contains any elements.
1706 if (keys (%ignored)) {
1707 # Loop through the entire hash and write the host/network
1708 # and remark to the ignore file.
1709 while ( (my $key) = each %ignored) {
1710 my $address = $ignored{$key}[0];
1711 my $remark = $ignored{$key}[1];
1712 my $status = $ignored{$key}[2];
1714 # Check if the status of the entry is "enabled".
1715 if ($status eq "enabled") {
1716 # Check if the address/network is valid.
1717 if ((&General
::validip
($address)) || (&General
::validipandmask
($address))) {
1718 # Write rule line to the file to pass any traffic from this IP
1719 print FILE
"pass ip $address any -> any any (msg:\"pass all traffic from/to $address\"\; bypass; sid:$sid\;)\n";
1732 ## Function to set correct ownership for single files and directories.
1735 sub set_ownership
($) {
1738 # User and group of the WUI.
1739 my $uname = "nobody";
1740 my $grname = "nobody";
1742 # The chown function implemented in perl requies the user and group as nummeric id's.
1743 my $uid = getpwnam($uname);
1744 my $gid = getgrnam($grname);
1746 # Check if the given target exists.
1748 # Stop the script and print error message.
1749 die "The $target does not exist. Cannot change the ownership!\n";
1752 # Check weather the target is a file or directory.
1754 # Change ownership ot the single file.
1755 chown($uid, $gid, "$target");
1756 } elsif (-d
$target) {
1757 # Do a directory listing.
1758 opendir(DIR
, $target) or die $!;
1759 # Loop through the direcory.
1760 while (my $file = readdir(DIR
)) {
1762 # We only want files.
1763 next unless (-f
"$target/$file");
1765 # Set correct ownership for the files.
1766 chown($uid, $gid, "$target/$file");
1771 # Change ownership of the directory.
1772 chown($uid, $gid, "$target");
1777 ## Function to read-in the aliases file and returns all configured and enabled aliases.
1780 # Location of the aliases file.
1781 my $aliases_file = "${General::swroot}/ethernet/aliases";
1783 # Array to store the aliases.
1786 # Check if the file is empty.
1787 if (-z
$aliases_file) {
1788 # Abort nothing to do.
1792 # Open the aliases file.
1793 open(ALIASES
, $aliases_file) or die "Could not open $aliases_file. $!\n";
1795 # Loop through the file content.
1796 while (my $line = <ALIASES
>) {
1800 # Splitt line content into single chunks.
1801 my ($address, $state, $remark) = split(/\,/, $line);
1803 # Check if the state of the current processed alias is "on".
1804 if ($state eq "on") {
1805 # Check if the address is valid.
1806 if(&Network
::check_ip_address
($address)) {
1807 # Add the alias to the array of aliases.
1808 push(@aliases, $address);
1813 # Close file handle.
1821 ## Function to grab the current assigned IP-address on red.
1823 sub get_red_address
() {
1824 # File, which contains the current IP-address of the red interface.
1825 my $file = "${General::swroot}/red/local-ipaddress";
1827 # Check if the file exists.
1829 # Open the given file.
1830 open(FILE
, "$file") or die "Could not open $file.";
1832 # Obtain the address from the first line of the file.
1833 my $address = <FILE
>;
1841 # Check if the grabbed address is valid.
1842 if (&General
::validip
($address)) {
1843 # Return the address.
1853 ## Function to get the used rules files of a given provider.
1855 sub read_used_provider_rulesfiles
($) {
1856 my ($provider) = @_;
1858 # Array to store the used rulefiles.
1859 my @used_rulesfiles = ();
1861 # Get the used rulesefile file for the provider.
1862 my $rulesfile_file = &get_used_provider_rulesfile_file
($provider);
1864 # Check if the a used rulesfile exists for this provider.
1865 if (-f
$rulesfile_file) {
1866 # Open the file or used rulefiles and read-in content.
1867 open(FILE
, $rulesfile_file) or die "Could not open $rulesfile_file. $!\n";
1870 # Assign the current line to a nice variable.
1877 next if ($line =~ /\#/);
1880 next if ($line =~ /^\s*$/);
1882 # Gather the rulefile.
1883 if ($line =~ /.*- (.*)/) {
1886 # Add the rulefile to the array of used rulesfiles.
1887 push(@used_rulesfiles, $rulefile);
1895 # Return the array of used rulesfiles.
1896 return @used_rulesfiles;
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);