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 # Location where all config and settings files are stored.
33 our $settingsdir = "${General::swroot}/suricata";
35 # File where the main file for providers ruleset inclusion exists.
36 our $suricata_used_providers_file = "$settingsdir/suricata-used-providers.yaml";
38 # File for static ruleset inclusions.
39 our $suricata_default_rulefiles_file = "$settingsdir/suricata-default-rules.yaml";
41 # File where the addresses of the homenet are stored.
42 our $homenet_file = "$settingsdir/suricata-homenet.yaml";
44 # File where the addresses of the used DNS servers are stored.
45 our $dns_servers_file = "$settingsdir/suricata-dns-servers.yaml";
47 # File where the HTTP ports definition is stored.
48 our $http_ports_file = "$settingsdir/suricata-http-ports.yaml";
50 # File which contains includes for provider specific rule modifications.
51 our $oinkmaster_provider_includes_file = "$settingsdir/oinkmaster-provider-includes.conf";
53 # File which contains wheater the rules should be changed.
54 our $modify_sids_file = "$settingsdir/oinkmaster-modify-sids.conf";
56 # File which stores the configured IPS settings.
57 our $ids_settings_file = "$settingsdir/settings";
59 # File which stores the used and configured ruleset providers.
60 our $providers_settings_file = "$settingsdir/providers-settings";
62 # File which stores the configured settings for whitelisted addresses.
63 our $ignored_file = "$settingsdir/ignored";
65 # Location where the downloaded rulesets are stored.
66 our $dl_rules_path = "/var/tmp";
68 # File to store any errors, which also will be read and displayed by the wui.
69 our $storederrorfile = "/tmp/ids_storederror";
71 # File to lock the WUI, while the autoupdate script runs.
72 our $ids_page_lock_file = "/tmp/ids_page_locked";
74 # Location where the rulefiles are stored.
75 our $rulespath = "/var/lib/suricata";
77 # Location where the default rulefils are stored.
78 our $default_rulespath = "/usr/share/suricata/rules";
80 # Location where the addition config files are stored.
81 our $configspath = "/usr/share/suricata";
83 # Location of the classification file.
84 our $classification_file = "$configspath/classification.config";
86 # Location of the sid to msg mappings file.
87 our $sid_msg_file = "$rulespath/sid-msg.map";
89 # Location to store local rules. This file will not be touched.
90 our $local_rules_file = "$rulespath/local.rules";
92 # File which contains the rules to whitelist addresses on suricata.
93 our $whitelist_file = "$rulespath/whitelist.rules";
95 # File which contains a list of all supported ruleset sources.
96 # (Sourcefire, Emergingthreads, etc..)
97 our $rulesetsourcesfile = "$settingsdir/ruleset-sources";
99 # The pidfile of the IDS.
100 our $idspidfile = "/var/run/suricata.pid";
102 # Location of suricatactrl.
103 my $suricatactrl = "/usr/local/bin/suricatactrl";
105 # Prefix for each downloaded ruleset.
106 my $dl_rulesfile_prefix = "idsrules";
108 # Temporary directory where the rulesets will be extracted.
109 my $tmp_directory = "/tmp/ids_tmp";
111 # Temporary directory where the extracted rules files will be stored.
112 my $tmp_rules_directory = "$tmp_directory/rules";
114 # Temporary directory where the extracted additional config files will be stored.
115 my $tmp_conf_directory = "$tmp_directory/conf";
117 # Array with allowed commands of suricatactrl.
118 my @suricatactrl_cmds = ( 'start', 'stop', 'restart', 'reload', 'fix-rules-dir', 'cron' );
120 # Array with supported cron intervals.
121 my @cron_intervals = ('off', 'daily', 'weekly' );
123 # Array which contains the HTTP ports, which statically will be declared as HTTP_PORTS in the
125 my @http_ports = ('80', '81');
127 # Array which contains a list of rulefiles which always will be included if they exist.
128 my @static_included_rulefiles = ('local.rules', 'whitelist.rules');
130 # Array which contains a list of allways enabled application layer protocols.
131 my @static_enabled_app_layer_protos = ('app-layer', 'decoder', 'files', 'stream');
133 # Hash which allows to convert the download type (dl_type) to a file suffix.
134 my %dl_type_to_suffix = (
135 "archive" => ".tar.gz",
139 # Hash to translate an application layer protocol to the application name.
140 my %tr_app_layer_proto = (
142 "krb5" => "kerberos",
146 ## Function to check and create all IDS related files, if the does not exist.
148 sub check_and_create_filelayout
() {
149 # Check if the files exist and if not, create them.
150 unless (-f
"$oinkmaster_provider_includes_file") { &create_empty_file
($oinkmaster_provider_includes_file); }
151 unless (-f
"$modify_sids_file") { &create_empty_file
($modify_sids_file); }
152 unless (-f
"$suricata_used_providers_file") { &create_empty_file
($suricata_used_providers_file); }
153 unless (-f
"$suricata_default_rulefiles_file") { &create_empty_file
($suricata_default_rulefiles_file); }
154 unless (-f
"$ids_settings_file") { &create_empty_file
($ids_settings_file); }
155 unless (-f
"$providers_settings_file") { &create_empty_file
($providers_settings_file); }
156 unless (-f
"$ignored_file") { &create_empty_file
($ignored_file); }
157 unless (-f
"$whitelist_file" ) { &create_empty_file
($whitelist_file); }
161 ## Function to get a list of all available ruleset providers.
163 ## They will be returned as a sorted array.
165 sub get_ruleset_providers
() {
168 # Loop through the hash of providers.
169 foreach my $provider ( keys %IDS::Ruleset
::Providers
) {
170 # Add the provider to the array.
171 push(@providers, $provider);
174 # Sort and return the array.
175 return sort(@providers);
179 ## Function to get a list of all enabled ruleset providers.
181 ## They will be returned as an array.
183 sub get_enabled_providers
() {
184 my %used_providers = ();
186 # Array to store the enabled providers.
187 my @enabled_providers = ();
189 # Read-in the providers config file.
190 &General
::readhasharray
("$providers_settings_file", \
%used_providers);
192 # Loop through the hash of used_providers.
193 foreach my $id (keys %used_providers) {
194 # Skip disabled providers.
195 next unless ($used_providers{$id}[3] eq "enabled");
197 # Grab the provider handle.
198 my $provider = "$used_providers{$id}[0]";
200 # Add the provider to the array of enabled providers.
201 push(@enabled_providers, $provider);
205 return @enabled_providers;
209 ## Function for checking if at least 300MB of free disk space are available
210 ## on the "/var" partition.
212 sub checkdiskspace
() {
213 # Call diskfree to gather the free disk space of /var.
214 my @df = &General
::system_output
("/bin/df", "-B", "M", "/var");
216 # Loop through the output.
217 foreach my $line (@df) {
218 # Ignore header line.
219 next if $line =~ m/^Filesystem/;
221 # Search for a line with the device information.
222 if ($line =~ m/dev/ ) {
223 # Split the line into single pieces.
224 my @values = split(' ', $line);
225 my ($filesystem, $blocks, $used, $available, $used_perenctage, $mounted_on) = @values;
227 # Check if the available disk space is more than 300MB.
228 if ($available < 300) {
229 # Log error to syslog.
230 &_log_to_syslog
("Not enough free disk space on /var. Only $available MB from 300 MB available.");
232 # Exit function and return "1" - False.
238 # Everything okay, return nothing.
243 ## This function is responsible for downloading the configured IDS rulesets or if no one is specified
244 ## all configured rulesets will be downloaded.
246 ## * At first it gathers all configured ruleset providers, initialize the downloader and sets an
247 ## upstream proxy if configured.
248 ## * After that, the given ruleset or in case all rulesets should be downloaded, it will determine wether it
249 ## is enabled or not.
250 ## * The next step will be to generate the final download url, by obtaining the URL for the desired
251 ## ruleset, add the settings for the upstream proxy.
252 ## * Finally the function will grab all the rules files or tarballs from the servers.
254 sub downloadruleset
($) {
257 # If no provider is given default to "all".
260 # Hash to store the providers and access id's, for which rules should be downloaded.
261 my %sheduled_providers = ();
263 # Get used provider settings.
264 my %used_providers = ();
265 &General
::readhasharray
("$providers_settings_file", \
%used_providers);
267 # Check if a ruleset has been configured.
268 unless(%used_providers) {
269 # Log that no ruleset has been configured and abort.
270 &_log_to_syslog
("No ruleset provider has been configured.");
276 # Read proxysettings.
277 my %proxysettings=();
278 &General
::readhash
("${General::swroot}/proxy/settings", \
%proxysettings);
280 # Load required perl module to handle the download.
283 # Init the download module.
284 my $downloader = LWP
::UserAgent
->new;
286 # Set timeout to 10 seconds.
287 $downloader->timeout(10);
289 # Check if an upstream proxy is configured.
290 if ($proxysettings{'UPSTREAM_PROXY'}) {
293 $proxy_url = "http://";
295 # Check if the proxy requires authentication.
296 if (($proxysettings{'UPSTREAM_USER'}) && ($proxysettings{'UPSTREAM_PASSWORD'})) {
297 $proxy_url .= "$proxysettings{'UPSTREAM_USER'}\:$proxysettings{'UPSTREAM_PASSWORD'}\@";
300 # Add proxy server address and port.
301 $proxy_url .= $proxysettings{'UPSTREAM_PROXY'};
303 # Setup proxy settings.
304 $downloader->proxy(['http', 'https'], $proxy_url);
307 # Loop through the hash of configured providers.
308 foreach my $id ( keys %used_providers ) {
309 # Skip providers which are not enabled.
310 next if ($used_providers{$id}[3] ne "enabled");
312 # Obtain the provider handle.
313 my $provider_handle = $used_providers{$id}[0];
315 # Handle update off all providers.
316 if (($provider eq "all") || ($provider_handle eq "$provider")) {
317 # Add provider handle and it's id to the hash of sheduled providers.
318 $sheduled_providers{$provider_handle} = $id;
322 # Loop through the hash of sheduled providers.
323 foreach my $provider ( keys %sheduled_providers) {
324 # Log download/update of the ruleset.
325 &_log_to_syslog
("Downloading ruleset for provider: $provider.");
327 # Grab the download url for the provider.
328 my $url = $IDS::Ruleset
::Providers
{$provider}{'dl_url'};
330 # Check if the provider requires a subscription.
331 if ($IDS::Ruleset
::Providers
{$provider}{'requires_subscription'} eq "True") {
332 # Grab the previously stored access id for the provider from hash.
333 my $id = $sheduled_providers{$provider};
335 # Grab the subscription code.
336 my $subscription_code = $used_providers{$id}[1];
338 # Add the subscription code to the download url.
339 $url =~ s/\<subscription_code\>/$subscription_code/g;
343 # Abort if no url could be determined for the provider.
345 # Log error and abort.
346 &_log_to_syslog
("Unable to gather a download URL for the selected ruleset provider.");
350 # Variable to store the filesize of the remote object.
353 # The sourcfire (snort rules) does not allow to send "HEAD" requests, so skip this check
354 # for this webserver.
356 # Check if the ruleset source contains "snort.org".
357 unless ($url =~ /\.snort\.org/) {
358 # Pass the requrested url to the downloader.
359 my $request = HTTP
::Request
->new(HEAD
=> $url);
361 # Accept the html header.
362 $request->header('Accept' => 'text/html');
364 # Perform the request and fetch the html header.
365 my $response = $downloader->request($request);
367 # Check if there was any error.
368 unless ($response->is_success) {
370 my $error = $response->status_line();
373 &_log_to_syslog
("Unable to download the ruleset. \($error\)");
375 # Return "1" - false.
379 # Assign the fetched header object.
380 my $header = $response->headers();
382 # Grab the remote file size from the object and store it in the
384 $remote_filesize = $header->content_length;
387 # Load perl module to deal with temporary files.
390 # Generate temporary file name, located in "/var/tmp" and with a suffix of ".tmp".
391 my $tmp = File
::Temp
->new( SUFFIX
=> ".tmp", DIR
=> "/var/tmp/", UNLINK
=> 0 );
392 my $tmpfile = $tmp->filename();
394 # Pass the requested url to the downloader.
395 my $request = HTTP
::Request
->new(GET
=> $url);
397 # Perform the request and save the output into the tmpfile.
398 my $response = $downloader->request($request, $tmpfile);
400 # Check if there was any error.
401 unless ($response->is_success) {
403 my $error = $response->content;
406 &_log_to_syslog
("Unable to download the ruleset. \($error\)");
408 # Return "1" - false.
412 # Load perl stat module.
415 # Perform stat on the tmpfile.
416 my $stat = stat($tmpfile);
418 # Grab the local filesize of the downloaded tarball.
419 my $local_filesize = $stat->size;
421 # Check if both file sizes match.
422 if (($remote_filesize) && ($remote_filesize ne $local_filesize)) {
424 &_log_to_syslog
("Unable to completely download the ruleset. ");
425 &_log_to_syslog
("Only got $local_filesize Bytes instead of $remote_filesize Bytes. ");
427 # Delete temporary file.
430 # Return "1" - false.
434 # Genarate and assign file name and path to store the downloaded rules file.
435 my $dl_rulesfile = &_get_dl_rulesfile
($provider);
437 # Check if a file name could be obtained.
438 unless ($dl_rulesfile) {
440 &_log_to_syslog
("Unable to store the downloaded rules file. ");
442 # Delete downloaded temporary file.
445 # Return "1" - false.
449 # Load file copy module, which contains the move() function.
452 # Overwrite the may existing rulefile or tarball with the downloaded one.
453 move
("$tmpfile", "$dl_rulesfile");
455 # Delete temporary file.
458 # Set correct ownership for the tarball.
459 set_ownership
("$dl_rulesfile");
462 # If we got here, everything worked fine. Return nothing.
467 ## Function to extract a given ruleset.
469 ## In case the ruleset provider offers a plain file, it simply will
472 sub extractruleset
($) {
475 # Load perl module to deal with archives.
478 # Load perl module to deal with files and path.
481 # Load perl module for file copying.
484 # Get full path and downloaded rulesfile for the given provider.
485 my $tarball = &_get_dl_rulesfile
($provider);
487 # Check if the file exists.
488 unless (-f
$tarball) {
489 &_log_to_syslog
("Could not find ruleset file: $tarball");
495 # Check if the temporary directories exist, otherwise create them.
496 mkdir("$tmp_directory") unless (-d
"$tmp_directory");
497 mkdir("$tmp_rules_directory") unless (-d
"$tmp_rules_directory");
498 mkdir("$tmp_conf_directory") unless (-d
"$tmp_conf_directory");
500 # Omit the type (dl_type) of the stored ruleset.
501 my $type = $IDS::Ruleset
::Providers
{$provider}{'dl_type'};
503 # Handle the different ruleset types.
504 if ($type eq "plain") {
505 # Generate destination filename an full path.
506 my $destination = "$tmp_rules_directory/$provider\-ruleset.rules";
508 # Copy the file into the temporary rules directory.
509 copy
($tarball, $destination);
511 } elsif ( $type eq "archive") {
512 # Initialize the tar module.
513 my $tar = Archive
::Tar
->new($tarball);
515 # Get the filelist inside the tarball.
516 my @packed_files = $tar->list_files;
518 # Loop through the filelist.
519 foreach my $packed_file (@packed_files) {
522 # Splitt the packed file into chunks.
523 my $file = fileparse
($packed_file);
525 # Handle msg-id.map file.
526 if ("$file" eq "sid-msg.map") {
527 # Set extract destination to temporary config_dir.
528 $destination = "$tmp_conf_directory/$provider\-sid-msg.map";
530 # Handle classification.conf
531 } elsif ("$file" eq "classification.config") {
532 # Set extract destination to temporary config_dir.
533 $destination = "$tmp_conf_directory/$provider\-classification.config";
535 # Handle rules files.
536 } elsif ($file =~ m/\.rules$/) {
539 # Splitt the filename into chunks.
540 my @filename = split("-", $file);
543 @filename = reverse(@filename);
545 # Get the amount of elements in the array.
546 my $elements = @filename;
548 # Remove last element of the hash.
549 # It contains the vendor name, which will be replaced.
550 if ($elements >= 3) {
551 # Remove last element from hash.
555 # Check if the last element of the filename does not
556 # contain the providers name.
557 if ($filename[-1] ne "$provider") {
558 # Add provider name as last element.
559 push(@filename, $provider);
562 # Reverse the array back.
563 @filename = reverse(@filename);
565 # Generate the name for the rulesfile.
566 $rulesfilename = join("-", @filename);
568 # Set extract destination to temporaray rules_dir.
569 $destination = "$tmp_rules_directory/$rulesfilename";
571 # Skip all other files.
575 # Check if the destination file exists.
576 unless(-e
"$destination") {
577 # Extract the file to the temporary directory.
578 $tar->extract_file("$packed_file", "$destination");
580 # Load perl module to deal with temporary files.
583 # Generate temporary file name, located in the temporary rules directory and a suffix of ".tmp".
584 my $tmp = File
::Temp
->new( SUFFIX
=> ".tmp", DIR
=> "$tmp_rules_directory", UNLINK
=> 0 );
585 my $tmpfile = $tmp->filename();
587 # Extract the file to the new temporary file name.
588 $tar->extract_file("$packed_file", "$tmpfile");
590 # Open the the existing file.
591 open(DESTFILE
, ">>", "$destination") or die "Could not open $destination. $!\n";
592 open(TMPFILE
, "<", "$tmpfile") or die "Could not open $tmpfile. $!\n";
594 # Loop through the content of the temporary file.
596 # Append the content line by line to the destination file.
600 # Close the file handles.
604 # Remove the temporary file.
612 ## A wrapper function to call the oinkmaster script, setup the rules structues and
613 ## call the functions to merge the additional config files. (classification, sid-msg, etc.).
616 # Check if the files in rulesdir have the correct permissions.
617 &_check_rulesdir_permissions
();
619 # Cleanup the rules directory before filling it with the new rulests.
620 &_cleanup_rulesdir
();
622 # Get all enabled providers.
623 my @enabled_providers = &get_enabled_providers
();
625 # Loop through the array of enabled providers.
626 foreach my $provider (@enabled_providers) {
627 # Call the extractruleset function.
628 &extractruleset
($provider);
631 # Load perl module to talk to the kernel syslog.
632 use Sys
::Syslog
qw(:DEFAULT setlogsock);
634 # Establish the connection to the syslog service.
635 openlog
('oinkmaster', 'cons,pid', 'user');
637 # Call oinkmaster to generate ruleset.
638 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";
640 # Log output of oinkmaster to syslog.
641 while(<OINKMASTER
>) {
642 # The syslog function works best with an array based input,
643 # so generate one before passing the message details to syslog.
644 my @syslog = ("INFO", "$_");
646 # Send the log message.
650 # Close the pipe to oinkmaster process.
653 # Close the log handle.
656 # Call function to merge the classification files.
657 &merge_classifications
(@enabled_providers);
659 # Call function to merge the sid to message mapping files.
660 &merge_sid_msg
(@enabled_providers);
662 # Cleanup temporary directory.
663 &cleanup_tmp_directory
();
667 ## Function to merge the classifications for a given amount of providers and write them
668 ## to the classifications file.
670 sub merge_classifications
(@
) {
673 # Hash to store all collected classifications.
674 my %classifications = ();
676 # Loop through the given array of providers.
677 foreach my $provider (@providers) {
678 # Generate full path to classification file.
679 my $classification_file = "$tmp_conf_directory/$provider\-classification.config";
681 # Skip provider if no classification file exists.
682 next unless (-f
"$classification_file");
684 # Open the classification file.
685 open(CLASSIFICATION
, $classification_file) or die "Could not open file $classification_file. $!\n";
687 # Loop through the file content.
688 while(<CLASSIFICATION
>) {
689 # Parse the file and grab the classification details.
690 if ($_ =~/.*config classification\: (.*)/) {
691 # Split the grabbed details.
692 my ($short_name, $short_desc, $priority) = split("\,", $1);
694 # Check if the grabbed classification is allready known and the priority value is greater
695 # than the stored one (which causes less priority in the IDS).
696 if (($classifications{$short_name}) && ($classifications{$short_name}[1] >= $priority)) {
697 #Change the priority value to the stricter one.
698 $classifications{$short_name} = [ "$classifications{$short_name}[0]", "$priority" ];
700 # Add the classification to the hash.
701 $classifications{$short_name} = [ "$short_desc", "$priority" ];
707 close(CLASSIFICATION
);
710 # Open classification file for writing.
711 open(FILE
, ">", "$classification_file") or die "Could not write to $classification_file. $!\n";
713 # Print notice about autogenerated file.
714 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n\n";
716 # Sort and loop through the hash of classifications.
717 foreach my $key (sort keys %classifications) {
718 # Assign some nice variable names for the items.
719 my $short_name = $key;
720 my $short_desc = $classifications{$key}[0];
721 my $priority = $classifications{$key}[1];
723 # Write the classification to the file.
724 print FILE
"config classification: $short_name,$short_desc,$priority\n";
732 ## Function to merge the "sid to message mapping" files of various given providers.
734 sub merge_sid_msg
(@
) {
737 # Hash which contains all the sid to message mappings.
740 # Loop through the array of given providers.
741 foreach my $provider (@providers) {
742 # Generate full path and filename.
743 my $sid_msg_file = "$tmp_conf_directory/$provider\-sid-msg.map";
745 # Skip provider if no sid to msg mapping file for this provider exists.
746 next unless (-f
$sid_msg_file);
749 open(MAPPING
, $sid_msg_file) or die "Could not open $sid_msg_file. $!\n";
751 # Loop through the file content.
756 # Skip lines which do not start with a number,
757 next unless ($_ =~ /^\d+/);
759 # Split line content and assign it to an array.
760 my @line = split(/ \|\| /, $_);
762 # Grab the first element (and remove it) from the line array.
763 # It contains the sid.
764 my $sid = shift(@line);
766 # Store the grabbed sid and the remain array as hash value.
767 # It still contains the messages, references etc.
768 $mappings{$sid} = [@line];
775 # Open mappings file for writing.
776 open(FILE
, ">", $sid_msg_file) or die "Could not write $sid_msg_file. $!\n";
778 # Write notice about autogenerated file.
779 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n\n";
781 # Loop through the hash of mappings.
782 foreach my $sid ( sort keys %mappings) {
783 # Grab data for the sid.
784 my @data = @
{$mappings{$sid}};
786 # Add the sid to the data array.
787 unshift(@data, $sid);
790 my $line = join(" \|\| ", @data);
792 print FILE
"$line\n";
801 ## A very tiny function to move an extracted ruleset from the temporary directory into
802 ## the rules directory.
804 sub move_tmp_ruleset
() {
808 # Do a directory listing of the temporary directory.
809 opendir DH
, $tmp_rules_directory;
811 # Loop over all files.
812 while(my $file = readdir DH
) {
813 # Move them to the rules directory.
814 move
"$tmp_rules_directory/$file" , "$rulespath/$file";
817 # Close directory handle.
822 ## Function to cleanup the temporary IDS directroy.
824 sub cleanup_tmp_directory
() {
825 # Load rmtree() function from file path perl module.
826 use File
::Path
'rmtree';
828 # Delete temporary directory and all containing files.
829 rmtree
([ "$tmp_directory" ]);
833 ## Function to do all the logging stuff if the downloading or updating of the ruleset fails.
838 # Remove any newline.
841 # Call private function to log the error message to syslog.
842 &_log_to_syslog
($error);
844 # Call private function to write/store the error message in the storederrorfile.
845 &_store_error_message
($error);
849 ## Function to log a given error message to the kernel syslog.
851 sub _log_to_syslog
($) {
854 # Load perl module to talk to the kernel syslog.
855 use Sys
::Syslog
qw(:DEFAULT setlogsock);
857 # The syslog function works best with an array based input,
858 # so generate one before passing the message details to syslog.
859 my @syslog = ("ERR", "<ERROR> $message");
861 # Establish the connection to the syslog service.
862 openlog
('oinkmaster', 'cons,pid', 'user');
864 # Send the log message.
867 # Close the log handle.
872 ## Private function to write a given error message to the storederror file.
874 sub _store_error_message
($) {
877 # Remove any newline.
880 # Open file for writing.
881 open (ERRORFILE
, ">$storederrorfile") or die "Could not write to $storederrorfile. $!\n";
883 # Write error to file.
884 print ERRORFILE
"$message\n";
889 # Set correct ownership for the file.
890 &set_ownership
("$storederrorfile");
894 ## Private function to get the path and filename for a downloaded ruleset by a given provider.
896 sub _get_dl_rulesfile
($) {
899 # Gather the download type for the given provider.
900 my $dl_type = $IDS::Ruleset
::Providers
{$provider}{'dl_type'};
902 # Obtain the file suffix for the download file type.
903 my $suffix = $dl_type_to_suffix{$dl_type};
905 # Check if a suffix has been found.
907 # Abort return - nothing.
911 # Generate the full filename and path for the stored rules file.
912 my $rulesfile = "$dl_rules_path/$dl_rulesfile_prefix-$provider$suffix";
914 # Return the generated filename.
919 ## Tiny function to delete the stored ruleset file or tarball for a given provider.
921 sub drop_dl_rulesfile
($) {
924 # Gather the full path and name of the stored rulesfile.
925 my $rulesfile = &_get_dl_rulesfile
($provider);
927 # Check if the given rulesfile exists.
929 # Delete the stored rulesfile.
930 unlink($rulesfile) or die "Could not delete $rulesfile. $!\n";
935 ## Tiny function to get/generate the full path and filename for the providers oinkmaster
936 ## modified sids file.
938 sub get_oinkmaster_provider_modified_sids_file
($) {
941 # Generate the filename.
942 my $filename = "$settingsdir/oinkmaster-$provider-modified-sids.conf";
944 # Return the filename.
949 ## Function to directly altering the oinkmaster provider includes file.
951 ## Requires tha acition "remove" or "add" and a provider handle.
953 sub alter_oinkmaster_provider_includes_file
($$) {
954 my ($action, $provider) = @_;
956 # Call function to get the path and name for the given providers
957 # oinkmaster modified sids file.
958 my $provider_modified_sids_file = &get_oinkmaster_provider_modified_sids_file
($provider);
960 # Open the file for reading..
961 open (FILE
, $oinkmaster_provider_includes_file) or die "Could not read $oinkmaster_provider_includes_file. $!\n";
963 # Read-in file content.
966 # Close file after reading.
969 # Re-open the file for writing.
970 open(FILE
, ">", $oinkmaster_provider_includes_file) or die "Could not write to $oinkmaster_provider_includes_file. $!\n";
972 # Loop through the file content.
973 foreach my $line (@lines) {
977 # Skip line if we found our given provider and the action should be remove.
978 next if (($line =~ /$provider/) && ($action eq "remove"));
980 # Write the read-in line back to the file.
981 print FILE
"$line\n";
984 # Check if the file exists and add the provider if requested.
985 if ((-f
$provider_modified_sids_file) && ($action eq "add")) {
986 print FILE
"include $provider_modified_sids_file\n";
994 ## Function to read-in the given enabled or disables sids file.
996 sub read_enabled_disabled_sids_file
($) {
999 # Temporary hash to store the sids and their state. It will be
1000 # returned at the end of this function.
1003 # Open the given filename.
1004 open(FILE
, "$file") or die "Could not open $file. $!\n";
1006 # Loop through the file.
1012 next if ($_ =~ /^\s*$/);
1015 next if ($_ =~ /^\#/);
1017 # Splitt line into sid and state part.
1018 my ($state, $sid) = split(" ", $_);
1020 # Skip line if the sid is not numeric.
1021 next unless ($sid =~ /\d+/ );
1023 # Check if the sid was enabled.
1024 if ($state eq "enablesid") {
1025 # Add the sid and its state as enabled to the temporary hash.
1026 $temphash{$sid} = "enabled";
1027 # Check if the sid was disabled.
1028 } elsif ($state eq "disablesid") {
1029 # Add the sid and its state as disabled to the temporary hash.
1030 $temphash{$sid} = "disabled";
1031 # Invalid state - skip the current sid and state.
1045 ## Function to check if the IDS is running.
1047 sub ids_is_running
() {
1048 if(-f
$idspidfile) {
1049 # Open PID file for reading.
1050 open(PIDFILE
, "$idspidfile") or die "Could not open $idspidfile. $!\n";
1052 # Grab the process-id.
1053 my $pid = <PIDFILE
>;
1058 # Remove any newline.
1061 # Check if a directory for the process-id exists in proc.
1062 if(-d
"/proc/$pid") {
1063 # The IDS daemon is running return the process id.
1068 # Return nothing - IDS is not running.
1073 ## Function to call suricatactrl binary with a given command.
1075 sub call_suricatactrl
($) {
1076 # Get called option.
1077 my ($option, $interval) = @_;
1079 # Loop through the array of supported commands and check if
1080 # the given one is part of it.
1081 foreach my $cmd (@suricatactrl_cmds) {
1082 # Skip current command unless the given one has been found.
1083 next unless($cmd eq $option);
1085 # Check if the given command is "cron".
1086 if ($option eq "cron") {
1087 # Check if an interval has been given.
1089 # Check if the given interval is valid.
1090 foreach my $element (@cron_intervals) {
1091 # Skip current element until the given one has been found.
1092 next unless($element eq $interval);
1094 # Call the suricatactrl binary and pass the "cron" command
1095 # with the requrested interval.
1096 &General
::system("$suricatactrl", "$option", "$interval");
1098 # Return "1" - True.
1103 # If we got here, the given interval is not supported or none has been given. - Return nothing.
1106 # Call the suricatactrl binary and pass the requrested
1108 &General
::system("$suricatactrl", "$option");
1110 # Return "1" - True.
1115 # Command not found - return nothing.
1120 ## Function to create a new empty file.
1122 sub create_empty_file
($) {
1125 # Check if the given file exists.
1127 # Do nothing to prevent from overwriting existing files.
1131 # Open the file for writing.
1132 open(FILE
, ">$file") or die "Could not write to $file. $!\n";
1134 # Close file handle.
1142 ## Private function to check if the file permission of the rulespath are correct.
1143 ## If not, call suricatactrl to fix them.
1145 sub _check_rulesdir_permissions
() {
1146 # Check if the rulepath main directory is writable.
1147 unless (-W
$rulespath) {
1148 # If not call suricatctrl to fix it.
1149 &call_suricatactrl
("fix-rules-dir");
1152 # Open snort rules directory and do a directory listing.
1153 opendir(DIR
, $rulespath) or die $!;
1154 # Loop through the direcory.
1155 while (my $file = readdir(DIR
)) {
1156 # We only want files.
1157 next unless (-f
"$rulespath/$file");
1159 # Check if the file is writable by the user.
1160 if (-W
"$rulespath/$file") {
1161 # Everything is okay - go on to the next file.
1164 # There are wrong permissions, call suricatactrl to fix it.
1165 &call_suricatactrl
("fix-rules-dir");
1171 ## Private function to cleanup the directory which contains
1172 ## the IDS rules, before extracting and modifing the new ruleset.
1174 sub _cleanup_rulesdir
() {
1175 # Open rules directory and do a directory listing.
1176 opendir(DIR
, $rulespath) or die $!;
1178 # Loop through the direcory.
1179 while (my $file = readdir(DIR
)) {
1180 # We only want files.
1181 next unless (-f
"$rulespath/$file");
1183 # Skip rules file for whitelisted hosts.
1184 next if ("$rulespath/$file" eq $whitelist_file);
1186 # Skip rules file with local rules.
1187 next if ("$rulespath/$file" eq $local_rules_file);
1189 # Delete the current processed file, if not, exit this function
1190 # and return an error message.
1191 unlink("$rulespath/$file") or return "Could not delete $rulespath/$file. $!\n";
1199 ## Function to generate the file which contains the home net information.
1201 sub generate_home_net_file
() {
1204 # Read-in network settings.
1205 &General
::readhash
("${General::swroot}/ethernet/settings", \
%netsettings);
1207 # Get available network zones.
1208 my @network_zones = &Network
::get_available_network_zones
();
1210 # Temporary array to store network address and prefix of the configured
1214 # Loop through the array of available network zones.
1215 foreach my $zone (@network_zones) {
1216 # Check if the current processed zone is red.
1217 if($zone eq "red") {
1218 # Grab the IP-address of the red interface.
1219 my $red_address = &get_red_address
();
1221 # Check if an address has been obtained.
1223 # Generate full network string.
1224 my $red_network = join("/", $red_address, "32");
1226 # Add the red network to the array of networks.
1227 push(@networks, $red_network);
1230 # Check if the configured RED_TYPE is static.
1231 if ($netsettings{'RED_TYPE'} eq "STATIC") {
1232 # Get configured and enabled aliases.
1233 my @aliases = &get_aliases
();
1235 # Loop through the array.
1236 foreach my $alias (@aliases) {
1238 my $network = join("/", $alias, "32");
1240 # Add the generated network to the array of networks.
1241 push(@networks, $network);
1244 # Process remaining network zones.
1246 # Convert current zone name into upper case.
1249 # Generate key to access the required data from the netsettings hash.
1250 my $zone_netaddress = $zone . "_NETADDRESS";
1251 my $zone_netmask = $zone . "_NETMASK";
1253 # Obtain the settings from the netsettings hash.
1254 my $netaddress = $netsettings{$zone_netaddress};
1255 my $netmask = $netsettings{$zone_netmask};
1257 # Convert the subnetmask into prefix notation.
1258 my $prefix = &Network
::convert_netmask2prefix
($netmask);
1260 # Generate full network string.
1261 my $network = join("/", $netaddress,$prefix);
1263 # Check if the network is valid.
1264 if(&Network
::check_subnet
($network)) {
1265 # Add the generated network to the array of networks.
1266 push(@networks, $network);
1271 # Format home net declaration.
1272 my $line = "\"[" . join(',', @networks) . "]\"";
1274 # Open file to store the addresses of the home net.
1275 open(FILE
, ">$homenet_file") or die "Could not open $homenet_file. $!\n";
1277 # Print yaml header.
1278 print FILE
"%YAML 1.1\n";
1279 print FILE
"---\n\n";
1281 # Print notice about autogenerated file.
1282 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1284 # Print the generated and required HOME_NET declaration to the file.
1285 print FILE
"HOME_NET:\t$line\n";
1287 # Close file handle.
1292 # Function to generate and write the file which contains the configured and used DNS servers.
1294 sub generate_dns_servers_file
() {
1295 # Get the used DNS servers.
1296 my @nameservers = &General
::get_nameservers
();
1298 # Get network settings.
1300 &General
::readhash
("${General::swroot}/ethernet/settings", \
%netsettings);
1302 # Format dns servers declaration.
1305 # Check if the system has configured nameservers.
1307 # Add the GREEN address as DNS servers.
1308 push(@nameservers, $netsettings{'GREEN_ADDRESS'});
1310 # Check if a BLUE zone exists.
1311 if ($netsettings{'BLUE_ADDRESS'}) {
1312 # Add the BLUE address to the array of nameservers.
1313 push(@nameservers, $netsettings{'BLUE_ADDRESS'});
1316 # Generate the line which will be written to the DNS servers file.
1317 $line = join(",", @nameservers);
1319 # External net simply contains (any).
1320 $line = "\$EXTERNAL_NET";
1323 # Open file to store the used DNS server addresses.
1324 open(FILE
, ">$dns_servers_file") or die "Could not open $dns_servers_file. $!\n";
1326 # Print yaml header.
1327 print FILE
"%YAML 1.1\n";
1328 print FILE
"---\n\n";
1330 # Print notice about autogenerated file.
1331 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1333 # Print the generated DNS declaration to the file.
1334 print FILE
"DNS_SERVERS:\t\"[$line]\"\n";
1336 # Close file handle.
1341 # Function to generate and write the file which contains the HTTP_PORTS definition.
1343 sub generate_http_ports_file
() {
1346 # Read-in proxy settings
1347 &General
::readhash
("${General::swroot}/proxy/advanced/settings", \
%proxysettings);
1349 # Check if the proxy is enabled.
1350 if (( -e
"${General::swroot}/proxy/enable") || (-e
"${General::swroot}/proxy/enable_blue")) {
1351 # Add the proxy port to the array of HTTP ports.
1352 push(@http_ports, $proxysettings{'PROXY_PORT'});
1355 # Check if the transparent mode of the proxy is enabled.
1356 if ((-e
"${General::swroot}/proxy/transparent") || (-e
"${General::swroot}/proxy/transparent_blue")) {
1357 # Add the transparent proxy port to the array of HTTP ports.
1358 push(@http_ports, $proxysettings{'TRANSPARENT_PORT'});
1361 # Format HTTP_PORTS declaration.
1364 # Generate line which will be written to the http ports file.
1365 $line = join(",", @http_ports);
1367 # Open file to store the HTTP_PORTS.
1368 open(FILE
, ">$http_ports_file") or die "Could not open $http_ports_file. $!\n";
1370 # Print yaml header.
1371 print FILE
"%YAML 1.1\n";
1372 print FILE
"---\n\n";
1374 # Print notice about autogenerated file.
1375 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1377 # Print the generated HTTP_PORTS declaration to the file.
1378 print FILE
"HTTP_PORTS:\t\"[$line]\"\n";
1380 # Close file handle.
1385 ## Function to generate and write the file for used rulefiles file for a given provider.
1387 ## The function requires as first argument a provider handle, and as second an array with files.
1389 sub write_used_provider_rulefiles_file
($@
) {
1390 my ($provider, @files) = @_;
1392 # Get the path and file for the provider specific used rulefiles file.
1393 my $used_provider_rulesfile_file = &get_used_provider_rulesfile_file
($provider);
1395 # Open file for used rulefiles.
1396 open (FILE
, ">", "$used_provider_rulesfile_file") or die "Could not write to $used_provider_rulesfile_file. $!\n";
1398 # Write yaml header to the file.
1399 print FILE
"%YAML 1.1\n";
1400 print FILE
"---\n\n";
1402 # Write header to file.
1403 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1405 # Loop through the array of given files.
1406 foreach my $file (@files) {
1407 # Check if the given filename exists and write it to the file of used rulefiles.
1408 if(-f
"$rulespath/$file") {
1409 print FILE
" - $file\n";
1413 # Close file after writing.
1418 ## Function to write the main file for provider rulesfiles inclusions.
1420 ## This function requires an array of provider handles.
1422 sub write_main_used_rulefiles_file
(@
) {
1423 my (@providers) = @_;
1425 # Call function to write the static rulefiles file.
1426 &_write_default_rulefiles_file
();
1428 # Open file for used rulefils inclusion.
1429 open (FILE
, ">", "$suricata_used_providers_file") or die "Could not write to $suricata_used_providers_file. $!\n";
1431 # Write yaml header to the file.
1432 print FILE
"%YAML 1.1\n";
1433 print FILE
"---\n\n";
1435 # Write header to file.
1436 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1438 # Loop through the list of given providers.
1439 foreach my $provider (@providers) {
1440 # Call function to get the providers used rulefiles file.
1441 my $filename = &get_used_provider_rulesfile_file
($provider);
1443 # Check if the file exists and write it into the used rulefiles file.
1445 # Print the provider to the file.
1446 print FILE
"include\: $filename\n";
1450 # Close the filehandle after writing.
1454 sub _write_default_rulefiles_file
() {
1455 # Get enabled application layer protocols.
1456 my @enabled_app_layer_protos = &get_suricata_enabled_app_layer_protos
();
1459 open (FILE
, ">", $suricata_default_rulefiles_file) or die "Could not write to $suricata_default_rulefiles_file. $!\n";
1461 # Write yaml header to the file.
1462 print FILE
"%YAML 1.1\n";
1463 print FILE
"---\n\n";
1465 # Write notice about autogenerated file.
1466 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1468 # Loop through the array of static included rulesfiles.
1469 foreach my $file (@static_included_rulefiles) {
1470 # Check if the file exists.
1471 if (-f
"$rulespath/$file") {
1472 # Write the rulesfile name to the file.
1473 print FILE
" - $rulespath/$file\n";
1477 print FILE
"\n#Default rules for used application layer protocols.\n";
1478 foreach my $enabled_app_layer_proto (@enabled_app_layer_protos) {
1479 # Check if the current processed app layer proto needs to be translated
1480 # into an application name.
1481 if (exists($tr_app_layer_proto{$enabled_app_layer_proto})) {
1482 # Obtain the translated application name for this protocol.
1483 $enabled_app_layer_proto = $tr_app_layer_proto{$enabled_app_layer_proto};
1486 # Generate filename.
1487 my $rulesfile = "$default_rulespath/$enabled_app_layer_proto\.rules";
1489 # Check if such a file exists.
1490 if (-f
"$rulesfile") {
1491 # Write the rulesfile name to the file.
1492 print FILE
" - $rulesfile\n";
1495 # Generate filename with "events" in filename.
1496 $rulesfile = "$default_rulespath/$enabled_app_layer_proto\-events.rules";
1498 # Check if this file exists.
1499 if (-f
"$rulesfile" ) {
1500 # Write the rulesfile name to the file.
1501 print FILE
" - $rulesfile\n";
1505 # Close the file handle
1510 ## Tiny function to generate the full path and name for the used_provider_rulesfile file of a given provider.
1512 sub get_used_provider_rulesfile_file
($) {
1513 my ($provider) = @_;
1515 my $filename = "$settingsdir/suricata\-$provider\-used\-rulefiles.yaml";
1517 # Return the gernerated file.
1522 ## Function to generate and write the file for modify the ruleset.
1524 sub write_modify_sids_file
() {
1525 # Get configured settings.
1527 &General
::readhash
("$ids_settings_file", \
%idssettings);
1529 # Open modify sid's file for writing.
1530 open(FILE
, ">$modify_sids_file") or die "Could not write to $modify_sids_file. $!\n";
1532 # Write file header.
1533 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1535 # Check if the traffic only should be monitored.
1536 unless($idssettings{'MONITOR_TRAFFIC_ONLY'} eq 'on') {
1537 # Suricata is in IPS mode, which means that the rule actions have to be changed
1538 # from 'alert' to 'drop', however not all rules should be changed. Some rules
1539 # exist purely to set a flowbit which is used to convey other information, such
1540 # as a specific type of file being downloaded, to other rulewhich then check for
1541 # malware in that file. Rules which fall into the first category should stay as
1542 # alert since not all flows of that type contain malware.
1544 # These types of rulesfiles contain meta-data which gives the action that should
1545 # be used when in IPS mode. Do the following:
1547 # 1. Disable all rules and set the action to 'drop'
1548 # 2. Set the action back to 'alert' if the rule contains 'flowbits:noalert;'
1549 # This should give rules not in the policy a reasonable default if the user
1550 # manually enables them.
1551 # 3. Enable rules and set actions according to the meta-data strings.
1553 my $policy = 'balanced'; # Placeholder to allow policy to be changed.
1556 modifysid * "^#(?:alert|drop)(.+policy $policy-ips alert)" | "alert\${1}"
1557 modifysid * "^#(?:alert|drop)(.+policy $policy-ips drop)" | "drop\${1}"
1558 modifysid * "^(#?)(?:alert|drop)" | "\${1}drop"
1559 modifysid * "^(#?)drop(.+flowbits:noalert;)" | "\${1}alert\${2}"
1563 # Close file handle.
1568 ## Function to get the ruleset date for a given provider.
1570 ## The function simply return the creation date in a human read-able format
1571 ## of the stored providers rulesfile.
1573 sub get_ruleset_date
($) {
1574 my ($provider) = @_;
1578 # Load neccessary perl modules for file stat and to format the timestamp.
1580 use POSIX
qw( strftime );
1582 # Get the stored rulesfile for this provider.
1583 my $stored_rulesfile = &_get_dl_rulesfile
($provider);
1585 # Check if we got a file.
1586 if (-f
$stored_rulesfile) {
1587 # Call stat on the rulestarball.
1588 my $stat = stat("$stored_rulesfile");
1590 # Get timestamp the file creation.
1591 $mtime = $stat->mtime;
1594 # Check if the timestamp has not been grabbed.
1596 # Return N/A for Not available.
1600 # Convert into human read-able format.
1601 $date = strftime
('%Y-%m-%d %H:%M:%S', localtime($mtime));
1608 ## Function to gather the version of suricata.
1610 sub get_suricata_version
($) {
1613 # Execute piped suricata command and return the version information.
1614 open(SURICATA
, "suricata -V |") or die "Couldn't execute program: $!";
1616 # Grab and store the output of the piped program.
1617 my $version_string = <SURICATA
>;
1623 chomp($version_string);
1625 # Grab the version from the version string.
1626 $version_string =~ /([0-9]+([.][0-9]+)+)/;
1628 # Splitt the version into single chunks.
1629 my ($major_ver, $minor_ver, $patchlevel) = split(/\./, $1);
1631 # Check and return the requested version sheme.
1632 if ($format eq "major") {
1633 # Return the full version.
1634 return "$major_ver";
1635 } elsif ($format eq "minor") {
1636 # Return the major and minor part.
1637 return "$major_ver.$minor_ver";
1639 # Return the full version string.
1640 return "$major_ver.$minor_ver.$patchlevel";
1645 ## Function to get the enabled application layer protocols.
1647 sub get_suricata_enabled_app_layer_protos
() {
1648 # Array to store and return the enabled app layer protos.
1649 my @enabled_app_layer_protos = ();
1651 # Execute piped suricata command and return the list of
1652 # enabled application layer protocols.
1653 open(SURICATA
, "suricata --list-app-layer-protos |") or die "Could not execute program: $!";
1655 # Grab and store the list of enabled application layer protocols.
1656 my @output = <SURICATA
>;
1661 # Merge allways enabled static application layers protocols array.
1662 @enabled_app_layer_protos = @static_enabled_app_layer_protos;
1664 # Loop through the array which contains the output of suricata.
1665 foreach my $line (@output) {
1666 # Skip header line which starts with "===".
1667 next if ($line =~ /^\s*=/);
1669 # Skip info or warning lines.
1670 next if ($line =~ /\s*--/);
1675 # Add enabled app layer proto to the array.
1676 push(@enabled_app_layer_protos, $line);
1680 @enabled_app_layer_protos = sort(@enabled_app_layer_protos);
1683 return @enabled_app_layer_protos;
1687 ## Function to generate the rules file with whitelisted addresses.
1689 sub generate_ignore_file
() {
1692 # SID range 1000000-1999999 Reserved for Local Use
1693 # Put your custom rules in this range to avoid conflicts
1696 # Read-in ignoredfile.
1697 &General
::readhasharray
($IDS::ignored_file
, \
%ignored);
1699 # Open ignorefile for writing.
1700 open(FILE
, ">$IDS::whitelist_file") or die "Could not write to $IDS::whitelist_file. $!\n";
1702 # Config file header.
1703 print FILE
"# Autogenerated file.\n";
1704 print FILE
"# All user modifications will be overwritten.\n\n";
1706 # Add all user defined addresses to the whitelist.
1708 # Check if the hash contains any elements.
1709 if (keys (%ignored)) {
1710 # Loop through the entire hash and write the host/network
1711 # and remark to the ignore file.
1712 while ( (my $key) = each %ignored) {
1713 my $address = $ignored{$key}[0];
1714 my $remark = $ignored{$key}[1];
1715 my $status = $ignored{$key}[2];
1717 # Check if the status of the entry is "enabled".
1718 if ($status eq "enabled") {
1719 # Check if the address/network is valid.
1720 if ((&General
::validip
($address)) || (&General
::validipandmask
($address))) {
1721 # Write rule line to the file to pass any traffic from this IP
1722 print FILE
"pass ip $address any -> any any (msg:\"pass all traffic from/to $address\"\; bypass; sid:$sid\;)\n";
1735 ## Function to set correct ownership for single files and directories.
1738 sub set_ownership
($) {
1741 # User and group of the WUI.
1742 my $uname = "nobody";
1743 my $grname = "nobody";
1745 # The chown function implemented in perl requies the user and group as nummeric id's.
1746 my $uid = getpwnam($uname);
1747 my $gid = getgrnam($grname);
1749 # Check if the given target exists.
1751 # Stop the script and print error message.
1752 die "The $target does not exist. Cannot change the ownership!\n";
1755 # Check weather the target is a file or directory.
1757 # Change ownership ot the single file.
1758 chown($uid, $gid, "$target");
1759 } elsif (-d
$target) {
1760 # Do a directory listing.
1761 opendir(DIR
, $target) or die $!;
1762 # Loop through the direcory.
1763 while (my $file = readdir(DIR
)) {
1765 # We only want files.
1766 next unless (-f
"$target/$file");
1768 # Set correct ownership for the files.
1769 chown($uid, $gid, "$target/$file");
1774 # Change ownership of the directory.
1775 chown($uid, $gid, "$target");
1780 ## Function to read-in the aliases file and returns all configured and enabled aliases.
1783 # Location of the aliases file.
1784 my $aliases_file = "${General::swroot}/ethernet/aliases";
1786 # Array to store the aliases.
1789 # Check if the file is empty.
1790 if (-z
$aliases_file) {
1791 # Abort nothing to do.
1795 # Open the aliases file.
1796 open(ALIASES
, $aliases_file) or die "Could not open $aliases_file. $!\n";
1798 # Loop through the file content.
1799 while (my $line = <ALIASES
>) {
1803 # Splitt line content into single chunks.
1804 my ($address, $state, $remark) = split(/\,/, $line);
1806 # Check if the state of the current processed alias is "on".
1807 if ($state eq "on") {
1808 # Check if the address is valid.
1809 if(&Network
::check_ip_address
($address)) {
1810 # Add the alias to the array of aliases.
1811 push(@aliases, $address);
1816 # Close file handle.
1824 ## Function to grab the current assigned IP-address on red.
1826 sub get_red_address
() {
1827 # File, which contains the current IP-address of the red interface.
1828 my $file = "${General::swroot}/red/local-ipaddress";
1830 # Check if the file exists.
1832 # Open the given file.
1833 open(FILE
, "$file") or die "Could not open $file.";
1835 # Obtain the address from the first line of the file.
1836 my $address = <FILE
>;
1844 # Check if the grabbed address is valid.
1845 if (&General
::validip
($address)) {
1846 # Return the address.
1856 ## Function to get the used rules files of a given provider.
1858 sub read_used_provider_rulesfiles
($) {
1859 my ($provider) = @_;
1861 # Array to store the used rulefiles.
1862 my @used_rulesfiles = ();
1864 # Get the used rulesefile file for the provider.
1865 my $rulesfile_file = &get_used_provider_rulesfile_file
($provider);
1867 # Check if the a used rulesfile exists for this provider.
1868 if (-f
$rulesfile_file) {
1869 # Open the file or used rulefiles and read-in content.
1870 open(FILE
, $rulesfile_file) or die "Could not open $rulesfile_file. $!\n";
1873 # Assign the current line to a nice variable.
1880 next if ($line =~ /\#/);
1883 next if ($line =~ /^\s*$/);
1885 # Gather the rulefile.
1886 if ($line =~ /.*- (.*)/) {
1889 # Add the rulefile to the array of used rulesfiles.
1890 push(@used_rulesfiles, $rulefile);
1898 # Return the array of used rulesfiles.
1899 return @used_rulesfiles;
1903 ## Function to write the lock file for locking the WUI, while
1904 ## the autoupdate script runs.
1906 sub lock_ids_page
() {
1907 # Call subfunction to create the file.
1908 &create_empty_file
($ids_page_lock_file);
1912 ## Function to release the lock of the WUI, again.
1914 sub unlock_ids_page
() {
1916 unlink($ids_page_lock_file);