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
"$whitelist_file" ) { &create_empty_file
($whitelist_file); }
160 ## Function to get a list of all available ruleset providers.
162 ## They will be returned as a sorted array.
164 sub get_ruleset_providers
() {
167 # Loop through the hash of providers.
168 foreach my $provider ( keys %IDS::Ruleset
::Providers
) {
169 # Add the provider to the array.
170 push(@providers, $provider);
173 # Sort and return the array.
174 return sort(@providers);
178 ## Function to get a list of all enabled ruleset providers.
180 ## They will be returned as an array.
182 sub get_enabled_providers
() {
183 my %used_providers = ();
185 # Array to store the enabled providers.
186 my @enabled_providers = ();
188 # Read-in the providers config file.
189 &General
::readhasharray
("$providers_settings_file", \
%used_providers);
191 # Loop through the hash of used_providers.
192 foreach my $id (keys %used_providers) {
193 # Skip disabled providers.
194 next unless ($used_providers{$id}[3] eq "enabled");
196 # Grab the provider handle.
197 my $provider = "$used_providers{$id}[0]";
199 # Add the provider to the array of enabled providers.
200 push(@enabled_providers, $provider);
204 return @enabled_providers;
208 ## Function for checking if at least 300MB of free disk space are available
209 ## on the "/var" partition.
211 sub checkdiskspace
() {
212 # Call diskfree to gather the free disk space of /var.
213 my @df = &General
::system_output
("/bin/df", "-B", "M", "/var");
215 # Loop through the output.
216 foreach my $line (@df) {
217 # Ignore header line.
218 next if $line =~ m/^Filesystem/;
220 # Search for a line with the device information.
221 if ($line =~ m/dev/ ) {
222 # Split the line into single pieces.
223 my @values = split(' ', $line);
224 my ($filesystem, $blocks, $used, $available, $used_perenctage, $mounted_on) = @values;
226 # Check if the available disk space is more than 300MB.
227 if ($available < 300) {
228 # Log error to syslog.
229 &_log_to_syslog
("Not enough free disk space on /var. Only $available MB from 300 MB available.");
231 # Exit function and return "1" - False.
237 # Everything okay, return nothing.
242 ## This function is responsible for downloading the configured IDS rulesets or if no one is specified
243 ## all configured rulesets will be downloaded.
245 ## * At first it gathers all configured ruleset providers, initialize the downloader and sets an
246 ## upstream proxy if configured.
247 ## * After that, the given ruleset or in case all rulesets should be downloaded, it will determine wether it
248 ## is enabled or not.
249 ## * The next step will be to generate the final download url, by obtaining the URL for the desired
250 ## ruleset, add the settings for the upstream proxy.
251 ## * Finally the function will grab all the rules files or tarballs from the servers.
253 sub downloadruleset
($) {
256 # If no provider is given default to "all".
259 # Hash to store the providers and access id's, for which rules should be downloaded.
260 my %sheduled_providers = ();
262 # Get used provider settings.
263 my %used_providers = ();
264 &General
::readhasharray
("$providers_settings_file", \
%used_providers);
266 # Check if a ruleset has been configured.
267 unless(%used_providers) {
268 # Log that no ruleset has been configured and abort.
269 &_log_to_syslog
("No ruleset provider has been configured.");
275 # Read proxysettings.
276 my %proxysettings=();
277 &General
::readhash
("${General::swroot}/proxy/settings", \
%proxysettings);
279 # Load required perl module to handle the download.
282 # Init the download module.
284 # Request SSL hostname verification and specify path
286 my $downloader = LWP
::UserAgent
->new(
288 SSL_ca_file
=> '/etc/ssl/cert.pem',
289 verify_hostname
=> 1,
293 # Set timeout to 10 seconds.
294 $downloader->timeout(10);
296 # Check if an upstream proxy is configured.
297 if ($proxysettings{'UPSTREAM_PROXY'}) {
300 $proxy_url = "http://";
302 # Check if the proxy requires authentication.
303 if (($proxysettings{'UPSTREAM_USER'}) && ($proxysettings{'UPSTREAM_PASSWORD'})) {
304 $proxy_url .= "$proxysettings{'UPSTREAM_USER'}\:$proxysettings{'UPSTREAM_PASSWORD'}\@";
307 # Add proxy server address and port.
308 $proxy_url .= $proxysettings{'UPSTREAM_PROXY'};
310 # Setup proxy settings.
311 $downloader->proxy(['http', 'https'], $proxy_url);
314 # Loop through the hash of configured providers.
315 foreach my $id ( keys %used_providers ) {
316 # Skip providers which are not enabled.
317 next if ($used_providers{$id}[3] ne "enabled");
319 # Obtain the provider handle.
320 my $provider_handle = $used_providers{$id}[0];
322 # Handle update off all providers.
323 if (($provider eq "all") || ($provider_handle eq "$provider")) {
324 # Add provider handle and it's id to the hash of sheduled providers.
325 $sheduled_providers{$provider_handle} = $id;
329 # Loop through the hash of sheduled providers.
330 foreach my $provider ( keys %sheduled_providers) {
331 # Log download/update of the ruleset.
332 &_log_to_syslog
("Downloading ruleset for provider: $provider.");
334 # Grab the download url for the provider.
335 my $url = $IDS::Ruleset
::Providers
{$provider}{'dl_url'};
337 # Check if the provider requires a subscription.
338 if ($IDS::Ruleset
::Providers
{$provider}{'requires_subscription'} eq "True") {
339 # Grab the previously stored access id for the provider from hash.
340 my $id = $sheduled_providers{$provider};
342 # Grab the subscription code.
343 my $subscription_code = $used_providers{$id}[1];
345 # Add the subscription code to the download url.
346 $url =~ s/\<subscription_code\>/$subscription_code/g;
350 # Abort if no url could be determined for the provider.
352 # Log error and abort.
353 &_log_to_syslog
("Unable to gather a download URL for the selected ruleset provider.");
357 # Variable to store the filesize of the remote object.
360 # The sourcfire (snort rules) does not allow to send "HEAD" requests, so skip this check
361 # for this webserver.
363 # Check if the ruleset source contains "snort.org".
364 unless ($url =~ /\.snort\.org/) {
365 # Pass the requrested url to the downloader.
366 my $request = HTTP
::Request
->new(HEAD
=> $url);
368 # Accept the html header.
369 $request->header('Accept' => 'text/html');
371 # Perform the request and fetch the html header.
372 my $response = $downloader->request($request);
374 # Check if there was any error.
375 unless ($response->is_success) {
377 my $error = $response->status_line();
380 &_log_to_syslog
("Unable to download the ruleset. \($error\)");
382 # Return "1" - false.
386 # Assign the fetched header object.
387 my $header = $response->headers();
389 # Grab the remote file size from the object and store it in the
391 $remote_filesize = $header->content_length;
394 # Load perl module to deal with temporary files.
397 # Generate temporary file name, located in "/var/tmp" and with a suffix of ".tmp".
398 my $tmp = File
::Temp
->new( SUFFIX
=> ".tmp", DIR
=> "/var/tmp/", UNLINK
=> 0 );
399 my $tmpfile = $tmp->filename();
401 # Pass the requested url to the downloader.
402 my $request = HTTP
::Request
->new(GET
=> $url);
404 # Perform the request and save the output into the tmpfile.
405 my $response = $downloader->request($request, $tmpfile);
407 # Check if there was any error.
408 unless ($response->is_success) {
410 my $error = $response->content;
413 &_log_to_syslog
("Unable to download the ruleset. \($error\)");
415 # Return "1" - false.
419 # Load perl stat module.
422 # Perform stat on the tmpfile.
423 my $stat = stat($tmpfile);
425 # Grab the local filesize of the downloaded tarball.
426 my $local_filesize = $stat->size;
428 # Check if both file sizes match.
429 if (($remote_filesize) && ($remote_filesize ne $local_filesize)) {
431 &_log_to_syslog
("Unable to completely download the ruleset. ");
432 &_log_to_syslog
("Only got $local_filesize Bytes instead of $remote_filesize Bytes. ");
434 # Delete temporary file.
437 # Return "1" - false.
441 # Genarate and assign file name and path to store the downloaded rules file.
442 my $dl_rulesfile = &_get_dl_rulesfile
($provider);
444 # Check if a file name could be obtained.
445 unless ($dl_rulesfile) {
447 &_log_to_syslog
("Unable to store the downloaded rules file. ");
449 # Delete downloaded temporary file.
452 # Return "1" - false.
456 # Load file copy module, which contains the move() function.
459 # Overwrite the may existing rulefile or tarball with the downloaded one.
460 move
("$tmpfile", "$dl_rulesfile");
462 # Delete temporary file.
465 # Set correct ownership for the tarball.
466 set_ownership
("$dl_rulesfile");
469 # If we got here, everything worked fine. Return nothing.
474 ## Function to extract a given ruleset.
476 ## In case the ruleset provider offers a plain file, it simply will
479 sub extractruleset
($) {
482 # Load perl module to deal with archives.
485 # Disable chown functionality when uncompressing files.
486 $Archive::Tar
::CHOWN
= "0";
488 # Load perl module to deal with files and path.
491 # Load perl module for file copying.
494 # Get full path and downloaded rulesfile for the given provider.
495 my $tarball = &_get_dl_rulesfile
($provider);
497 # Check if the file exists.
498 unless (-f
$tarball) {
499 &_log_to_syslog
("Could not find ruleset file: $tarball");
505 # Check if the temporary directories exist, otherwise create them.
506 mkdir("$tmp_directory") unless (-d
"$tmp_directory");
507 mkdir("$tmp_rules_directory") unless (-d
"$tmp_rules_directory");
508 mkdir("$tmp_conf_directory") unless (-d
"$tmp_conf_directory");
510 # Omit the type (dl_type) of the stored ruleset.
511 my $type = $IDS::Ruleset
::Providers
{$provider}{'dl_type'};
513 # Handle the different ruleset types.
514 if ($type eq "plain") {
515 # Generate destination filename an full path.
516 my $destination = "$tmp_rules_directory/$provider\-ruleset.rules";
518 # Copy the file into the temporary rules directory.
519 copy
($tarball, $destination);
521 } elsif ( $type eq "archive") {
522 # Initialize the tar module.
523 my $tar = Archive
::Tar
->new($tarball);
525 # Get the filelist inside the tarball.
526 my @packed_files = $tar->list_files;
528 # Loop through the filelist.
529 foreach my $packed_file (@packed_files) {
532 # Splitt the packed file into chunks.
533 my $file = fileparse
($packed_file);
535 # Handle msg-id.map file.
536 if ("$file" eq "sid-msg.map") {
537 # Set extract destination to temporary config_dir.
538 $destination = "$tmp_conf_directory/$provider\-sid-msg.map";
540 # Handle classification.conf
541 } elsif ("$file" eq "classification.config") {
542 # Set extract destination to temporary config_dir.
543 $destination = "$tmp_conf_directory/$provider\-classification.config";
545 # Handle rules files.
546 } elsif ($file =~ m/\.rules$/) {
547 # Skip rule files which are not located in the rules directory or archive root.
548 next unless(($packed_file =~ /^rules\//) || ($packed_file !~ /\
//));
552 # Splitt the filename into chunks.
553 my @filename = split("-", $file);
556 @filename = reverse(@filename);
558 # Get the amount of elements in the array.
559 my $elements = @filename;
561 # Remove last element of the hash.
562 # It contains the vendor name, which will be replaced.
563 if ($elements >= 3) {
564 # Remove last element from hash.
568 # Check if the last element of the filename does not
569 # contain the providers name.
570 if ($filename[-1] ne "$provider") {
571 # Add provider name as last element.
572 push(@filename, $provider);
575 # Reverse the array back.
576 @filename = reverse(@filename);
578 # Generate the name for the rulesfile.
579 $rulesfilename = join("-", @filename);
581 # Set extract destination to temporaray rules_dir.
582 $destination = "$tmp_rules_directory/$rulesfilename";
584 # Skip all other files.
588 # Check if the destination file exists.
589 unless(-e
"$destination") {
590 # Extract the file to the temporary directory.
591 $tar->extract_file("$packed_file", "$destination");
593 # Load perl module to deal with temporary files.
596 # Generate temporary file name, located in the temporary rules directory and a suffix of ".tmp".
597 my $tmp = File
::Temp
->new( SUFFIX
=> ".tmp", DIR
=> "$tmp_rules_directory", UNLINK
=> 0 );
598 my $tmpfile = $tmp->filename();
600 # Extract the file to the new temporary file name.
601 $tar->extract_file("$packed_file", "$tmpfile");
603 # Open the the existing file.
604 open(DESTFILE
, ">>", "$destination") or die "Could not open $destination. $!\n";
605 open(TMPFILE
, "<", "$tmpfile") or die "Could not open $tmpfile. $!\n";
607 # Loop through the content of the temporary file.
609 # Append the content line by line to the destination file.
613 # Close the file handles.
617 # Remove the temporary file.
625 ## A wrapper function to call the oinkmaster script, setup the rules structues and
626 ## call the functions to merge the additional config files. (classification, sid-msg, etc.).
629 # Check if the files in rulesdir have the correct permissions.
630 &_check_rulesdir_permissions
();
632 # Cleanup the rules directory before filling it with the new rulests.
633 &_cleanup_rulesdir
();
635 # Get all enabled providers.
636 my @enabled_providers = &get_enabled_providers
();
638 # Loop through the array of enabled providers.
639 foreach my $provider (@enabled_providers) {
640 # Call the extractruleset function.
641 &extractruleset
($provider);
644 # Load perl module to talk to the kernel syslog.
645 use Sys
::Syslog
qw(:DEFAULT setlogsock);
647 # Establish the connection to the syslog service.
648 openlog
('oinkmaster', 'cons,pid', 'user');
650 # Call oinkmaster to generate ruleset.
651 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";
653 # Log output of oinkmaster to syslog.
654 while(<OINKMASTER
>) {
655 # The syslog function works best with an array based input,
656 # so generate one before passing the message details to syslog.
657 my @syslog = ("INFO", "$_");
659 # Send the log message.
663 # Close the pipe to oinkmaster process.
666 # Close the log handle.
669 # Call function to merge the classification files.
670 &merge_classifications
(@enabled_providers);
672 # Call function to merge the sid to message mapping files.
673 &merge_sid_msg
(@enabled_providers);
675 # Cleanup temporary directory.
676 &cleanup_tmp_directory
();
680 ## Function to merge the classifications for a given amount of providers and write them
681 ## to the classifications file.
683 sub merge_classifications
(@
) {
686 # Hash to store all collected classifications.
687 my %classifications = ();
689 # Loop through the given array of providers.
690 foreach my $provider (@providers) {
691 # Generate full path to classification file.
692 my $classification_file = "$tmp_conf_directory/$provider\-classification.config";
694 # Skip provider if no classification file exists.
695 next unless (-f
"$classification_file");
697 # Open the classification file.
698 open(CLASSIFICATION
, $classification_file) or die "Could not open file $classification_file. $!\n";
700 # Loop through the file content.
701 while(<CLASSIFICATION
>) {
702 # Parse the file and grab the classification details.
703 if ($_ =~/.*config classification\: (.*)/) {
704 # Split the grabbed details.
705 my ($short_name, $short_desc, $priority) = split("\,", $1);
707 # Check if the grabbed classification is allready known and the priority value is greater
708 # than the stored one (which causes less priority in the IDS).
709 if (($classifications{$short_name}) && ($classifications{$short_name}[1] >= $priority)) {
710 #Change the priority value to the stricter one.
711 $classifications{$short_name} = [ "$classifications{$short_name}[0]", "$priority" ];
713 # Add the classification to the hash.
714 $classifications{$short_name} = [ "$short_desc", "$priority" ];
720 close(CLASSIFICATION
);
723 # Open classification file for writing.
724 open(FILE
, ">", "$classification_file") or die "Could not write to $classification_file. $!\n";
726 # Print notice about autogenerated file.
727 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n\n";
729 # Sort and loop through the hash of classifications.
730 foreach my $key (sort keys %classifications) {
731 # Assign some nice variable names for the items.
732 my $short_name = $key;
733 my $short_desc = $classifications{$key}[0];
734 my $priority = $classifications{$key}[1];
736 # Write the classification to the file.
737 print FILE
"config classification: $short_name,$short_desc,$priority\n";
745 ## Function to merge the "sid to message mapping" files of various given providers.
747 sub merge_sid_msg
(@
) {
750 # Hash which contains all the sid to message mappings.
753 # Loop through the array of given providers.
754 foreach my $provider (@providers) {
755 # Generate full path and filename.
756 my $sid_msg_file = "$tmp_conf_directory/$provider\-sid-msg.map";
758 # Skip provider if no sid to msg mapping file for this provider exists.
759 next unless (-f
$sid_msg_file);
762 open(MAPPING
, $sid_msg_file) or die "Could not open $sid_msg_file. $!\n";
764 # Loop through the file content.
769 # Skip lines which do not start with a number,
770 next unless ($_ =~ /^\d+/);
772 # Split line content and assign it to an array.
773 my @line = split(/ \|\| /, $_);
775 # Grab the first element (and remove it) from the line array.
776 # It contains the sid.
777 my $sid = shift(@line);
779 # Store the grabbed sid and the remain array as hash value.
780 # It still contains the messages, references etc.
781 $mappings{$sid} = [@line];
788 # Open mappings file for writing.
789 open(FILE
, ">", $sid_msg_file) or die "Could not write $sid_msg_file. $!\n";
791 # Write notice about autogenerated file.
792 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n\n";
794 # Loop through the hash of mappings.
795 foreach my $sid ( sort keys %mappings) {
796 # Grab data for the sid.
797 my @data = @
{$mappings{$sid}};
799 # Add the sid to the data array.
800 unshift(@data, $sid);
803 my $line = join(" \|\| ", @data);
805 print FILE
"$line\n";
814 ## A very tiny function to move an extracted ruleset from the temporary directory into
815 ## the rules directory.
817 sub move_tmp_ruleset
() {
821 # Do a directory listing of the temporary directory.
822 opendir DH
, $tmp_rules_directory;
824 # Loop over all files.
825 while(my $file = readdir DH
) {
826 # Move them to the rules directory.
827 move
"$tmp_rules_directory/$file" , "$rulespath/$file";
830 # Close directory handle.
835 ## Function to cleanup the temporary IDS directroy.
837 sub cleanup_tmp_directory
() {
838 # Load rmtree() function from file path perl module.
839 use File
::Path
'rmtree';
841 # Delete temporary directory and all containing files.
842 rmtree
([ "$tmp_directory" ]);
846 ## Function to do all the logging stuff if the downloading or updating of the ruleset fails.
851 # Remove any newline.
854 # Call private function to log the error message to syslog.
855 &_log_to_syslog
($error);
857 # Call private function to write/store the error message in the storederrorfile.
858 &_store_error_message
($error);
862 ## Function to log a given error message to the kernel syslog.
864 sub _log_to_syslog
($) {
867 # Load perl module to talk to the kernel syslog.
868 use Sys
::Syslog
qw(:DEFAULT setlogsock);
870 # The syslog function works best with an array based input,
871 # so generate one before passing the message details to syslog.
872 my @syslog = ("ERR", "<ERROR> $message");
874 # Establish the connection to the syslog service.
875 openlog
('oinkmaster', 'cons,pid', 'user');
877 # Send the log message.
880 # Close the log handle.
885 ## Private function to write a given error message to the storederror file.
887 sub _store_error_message
($) {
890 # Remove any newline.
893 # Open file for writing.
894 open (ERRORFILE
, ">$storederrorfile") or die "Could not write to $storederrorfile. $!\n";
896 # Write error to file.
897 print ERRORFILE
"$message\n";
902 # Set correct ownership for the file.
903 &set_ownership
("$storederrorfile");
907 ## Private function to get the path and filename for a downloaded ruleset by a given provider.
909 sub _get_dl_rulesfile
($) {
912 # Gather the download type for the given provider.
913 my $dl_type = $IDS::Ruleset
::Providers
{$provider}{'dl_type'};
915 # Obtain the file suffix for the download file type.
916 my $suffix = $dl_type_to_suffix{$dl_type};
918 # Check if a suffix has been found.
920 # Abort return - nothing.
924 # Generate the full filename and path for the stored rules file.
925 my $rulesfile = "$dl_rules_path/$dl_rulesfile_prefix-$provider$suffix";
927 # Return the generated filename.
932 ## Tiny function to delete the stored ruleset file or tarball for a given provider.
934 sub drop_dl_rulesfile
($) {
937 # Gather the full path and name of the stored rulesfile.
938 my $rulesfile = &_get_dl_rulesfile
($provider);
940 # Check if the given rulesfile exists.
942 # Delete the stored rulesfile.
943 unlink($rulesfile) or die "Could not delete $rulesfile. $!\n";
948 ## Tiny function to get/generate the full path and filename for the providers oinkmaster
949 ## modified sids file.
951 sub get_oinkmaster_provider_modified_sids_file
($) {
954 # Generate the filename.
955 my $filename = "$settingsdir/oinkmaster-$provider-modified-sids.conf";
957 # Return the filename.
962 ## Function to directly altering the oinkmaster provider includes file.
964 ## Requires tha acition "remove" or "add" and a provider handle.
966 sub alter_oinkmaster_provider_includes_file
($$) {
967 my ($action, $provider) = @_;
969 # Call function to get the path and name for the given providers
970 # oinkmaster modified sids file.
971 my $provider_modified_sids_file = &get_oinkmaster_provider_modified_sids_file
($provider);
973 # Open the file for reading..
974 open (FILE
, $oinkmaster_provider_includes_file) or die "Could not read $oinkmaster_provider_includes_file. $!\n";
976 # Read-in file content.
979 # Close file after reading.
982 # Re-open the file for writing.
983 open(FILE
, ">", $oinkmaster_provider_includes_file) or die "Could not write to $oinkmaster_provider_includes_file. $!\n";
985 # Loop through the file content.
986 foreach my $line (@lines) {
990 # Skip line if we found our given provider and the action should be remove.
991 next if (($line =~ /$provider/) && ($action eq "remove"));
993 # Write the read-in line back to the file.
994 print FILE
"$line\n";
997 # Check if the file exists and add the provider if requested.
998 if ((-f
$provider_modified_sids_file) && ($action eq "add")) {
999 print FILE
"include $provider_modified_sids_file\n";
1002 # Close file handle.
1007 ## Function to read-in the given enabled or disables sids file.
1009 sub read_enabled_disabled_sids_file
($) {
1012 # Temporary hash to store the sids and their state. It will be
1013 # returned at the end of this function.
1016 # Open the given filename.
1017 open(FILE
, "$file") or die "Could not open $file. $!\n";
1019 # Loop through the file.
1025 next if ($_ =~ /^\s*$/);
1028 next if ($_ =~ /^\#/);
1030 # Splitt line into sid and state part.
1031 my ($state, $sid) = split(" ", $_);
1033 # Skip line if the sid is not numeric.
1034 next unless ($sid =~ /\d+/ );
1036 # Check if the sid was enabled.
1037 if ($state eq "enablesid") {
1038 # Add the sid and its state as enabled to the temporary hash.
1039 $temphash{$sid} = "enabled";
1040 # Check if the sid was disabled.
1041 } elsif ($state eq "disablesid") {
1042 # Add the sid and its state as disabled to the temporary hash.
1043 $temphash{$sid} = "disabled";
1044 # Invalid state - skip the current sid and state.
1058 ## Function to check if the IDS is running.
1060 sub ids_is_running
() {
1061 if(-f
$idspidfile) {
1062 # Open PID file for reading.
1063 open(PIDFILE
, "$idspidfile") or die "Could not open $idspidfile. $!\n";
1065 # Grab the process-id.
1066 my $pid = <PIDFILE
>;
1071 # Remove any newline.
1074 # Check if a directory for the process-id exists in proc.
1075 if(-d
"/proc/$pid") {
1076 # The IDS daemon is running return the process id.
1081 # Return nothing - IDS is not running.
1086 ## Function to call suricatactrl binary with a given command.
1088 sub call_suricatactrl
($) {
1089 # Get called option.
1090 my ($option, $interval) = @_;
1092 # Loop through the array of supported commands and check if
1093 # the given one is part of it.
1094 foreach my $cmd (@suricatactrl_cmds) {
1095 # Skip current command unless the given one has been found.
1096 next unless($cmd eq $option);
1098 # Check if the given command is "cron".
1099 if ($option eq "cron") {
1100 # Check if an interval has been given.
1102 # Check if the given interval is valid.
1103 foreach my $element (@cron_intervals) {
1104 # Skip current element until the given one has been found.
1105 next unless($element eq $interval);
1107 # Call the suricatactrl binary and pass the "cron" command
1108 # with the requrested interval.
1109 &General
::system("$suricatactrl", "$option", "$interval");
1111 # Return "1" - True.
1116 # If we got here, the given interval is not supported or none has been given. - Return nothing.
1119 # Call the suricatactrl binary and pass the requrested
1121 &General
::system("$suricatactrl", "$option");
1123 # Return "1" - True.
1128 # Command not found - return nothing.
1133 ## Function to create a new empty file.
1135 sub create_empty_file
($) {
1138 # Check if the given file exists.
1140 # Do nothing to prevent from overwriting existing files.
1144 # Open the file for writing.
1145 open(FILE
, ">$file") or die "Could not write to $file. $!\n";
1147 # Close file handle.
1155 ## Private function to check if the file permission of the rulespath are correct.
1156 ## If not, call suricatactrl to fix them.
1158 sub _check_rulesdir_permissions
() {
1159 # Check if the rulepath main directory is writable.
1160 unless (-W
$rulespath) {
1161 # If not call suricatctrl to fix it.
1162 &call_suricatactrl
("fix-rules-dir");
1165 # Open snort rules directory and do a directory listing.
1166 opendir(DIR
, $rulespath) or die $!;
1167 # Loop through the direcory.
1168 while (my $file = readdir(DIR
)) {
1169 # We only want files.
1170 next unless (-f
"$rulespath/$file");
1172 # Check if the file is writable by the user.
1173 if (-W
"$rulespath/$file") {
1174 # Everything is okay - go on to the next file.
1177 # There are wrong permissions, call suricatactrl to fix it.
1178 &call_suricatactrl
("fix-rules-dir");
1184 ## Private function to cleanup the directory which contains
1185 ## the IDS rules, before extracting and modifing the new ruleset.
1187 sub _cleanup_rulesdir
() {
1188 # Open rules directory and do a directory listing.
1189 opendir(DIR
, $rulespath) or die $!;
1191 # Loop through the direcory.
1192 while (my $file = readdir(DIR
)) {
1193 # We only want files.
1194 next unless (-f
"$rulespath/$file");
1196 # Skip rules file for whitelisted hosts.
1197 next if ("$rulespath/$file" eq $whitelist_file);
1199 # Skip rules file with local rules.
1200 next if ("$rulespath/$file" eq $local_rules_file);
1202 # Delete the current processed file, if not, exit this function
1203 # and return an error message.
1204 unlink("$rulespath/$file") or return "Could not delete $rulespath/$file. $!\n";
1212 ## Function to generate the file which contains the home net information.
1214 sub generate_home_net_file
() {
1217 # Read-in network settings.
1218 &General
::readhash
("${General::swroot}/ethernet/settings", \
%netsettings);
1220 # Get available network zones.
1221 my @network_zones = &Network
::get_available_network_zones
();
1223 # Temporary array to store network address and prefix of the configured
1227 # Loop through the array of available network zones.
1228 foreach my $zone (@network_zones) {
1229 # Check if the current processed zone is red.
1230 if($zone eq "red") {
1231 # Grab the IP-address of the red interface.
1232 my $red_address = &get_red_address
();
1234 # Check if an address has been obtained.
1236 # Generate full network string.
1237 my $red_network = join("/", $red_address, "32");
1239 # Add the red network to the array of networks.
1240 push(@networks, $red_network);
1243 # Check if the configured RED_TYPE is static.
1244 if ($netsettings{'RED_TYPE'} eq "STATIC") {
1245 # Get configured and enabled aliases.
1246 my @aliases = &get_aliases
();
1248 # Loop through the array.
1249 foreach my $alias (@aliases) {
1251 my $network = join("/", $alias, "32");
1253 # Add the generated network to the array of networks.
1254 push(@networks, $network);
1257 # Process remaining network zones.
1259 # Convert current zone name into upper case.
1262 # Generate key to access the required data from the netsettings hash.
1263 my $zone_netaddress = $zone . "_NETADDRESS";
1264 my $zone_netmask = $zone . "_NETMASK";
1266 # Obtain the settings from the netsettings hash.
1267 my $netaddress = $netsettings{$zone_netaddress};
1268 my $netmask = $netsettings{$zone_netmask};
1270 # Convert the subnetmask into prefix notation.
1271 my $prefix = &Network
::convert_netmask2prefix
($netmask);
1273 # Generate full network string.
1274 my $network = join("/", $netaddress,$prefix);
1276 # Check if the network is valid.
1277 if(&Network
::check_subnet
($network)) {
1278 # Add the generated network to the array of networks.
1279 push(@networks, $network);
1284 # Format home net declaration.
1285 my $line = "\"[" . join(',', @networks) . "]\"";
1287 # Open file to store the addresses of the home net.
1288 open(FILE
, ">$homenet_file") or die "Could not open $homenet_file. $!\n";
1290 # Print yaml header.
1291 print FILE
"%YAML 1.1\n";
1292 print FILE
"---\n\n";
1294 # Print notice about autogenerated file.
1295 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1297 # Print the generated and required HOME_NET declaration to the file.
1298 print FILE
"HOME_NET:\t$line\n";
1300 # Close file handle.
1305 # Function to generate and write the file which contains the configured and used DNS servers.
1307 sub generate_dns_servers_file
() {
1308 # Get the used DNS servers.
1309 my @nameservers = &General
::get_nameservers
();
1311 # Get network settings.
1313 &General
::readhash
("${General::swroot}/ethernet/settings", \
%netsettings);
1315 # Format dns servers declaration.
1318 # Check if the system has configured nameservers.
1320 # Add the GREEN address as DNS servers.
1321 push(@nameservers, $netsettings{'GREEN_ADDRESS'});
1323 # Check if a BLUE zone exists.
1324 if ($netsettings{'BLUE_ADDRESS'}) {
1325 # Add the BLUE address to the array of nameservers.
1326 push(@nameservers, $netsettings{'BLUE_ADDRESS'});
1329 # Generate the line which will be written to the DNS servers file.
1330 $line = join(",", @nameservers);
1332 # External net simply contains (any).
1333 $line = "\$EXTERNAL_NET";
1336 # Open file to store the used DNS server addresses.
1337 open(FILE
, ">$dns_servers_file") or die "Could not open $dns_servers_file. $!\n";
1339 # Print yaml header.
1340 print FILE
"%YAML 1.1\n";
1341 print FILE
"---\n\n";
1343 # Print notice about autogenerated file.
1344 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1346 # Print the generated DNS declaration to the file.
1347 print FILE
"DNS_SERVERS:\t\"[$line]\"\n";
1349 # Close file handle.
1354 # Function to generate and write the file which contains the HTTP_PORTS definition.
1356 sub generate_http_ports_file
() {
1359 # Read-in proxy settings
1360 &General
::readhash
("${General::swroot}/proxy/advanced/settings", \
%proxysettings);
1362 # Check if the proxy is enabled.
1363 if (( -e
"${General::swroot}/proxy/enable") || (-e
"${General::swroot}/proxy/enable_blue")) {
1364 # Add the proxy port to the array of HTTP ports.
1365 push(@http_ports, $proxysettings{'PROXY_PORT'});
1368 # Check if the transparent mode of the proxy is enabled.
1369 if ((-e
"${General::swroot}/proxy/transparent") || (-e
"${General::swroot}/proxy/transparent_blue")) {
1370 # Add the transparent proxy port to the array of HTTP ports.
1371 push(@http_ports, $proxysettings{'TRANSPARENT_PORT'});
1374 # Format HTTP_PORTS declaration.
1377 # Generate line which will be written to the http ports file.
1378 $line = join(",", @http_ports);
1380 # Open file to store the HTTP_PORTS.
1381 open(FILE
, ">$http_ports_file") or die "Could not open $http_ports_file. $!\n";
1383 # Print yaml header.
1384 print FILE
"%YAML 1.1\n";
1385 print FILE
"---\n\n";
1387 # Print notice about autogenerated file.
1388 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1390 # Print the generated HTTP_PORTS declaration to the file.
1391 print FILE
"HTTP_PORTS:\t\"[$line]\"\n";
1393 # Close file handle.
1398 ## Function to generate and write the file for used rulefiles file for a given provider.
1400 ## The function requires as first argument a provider handle, and as second an array with files.
1402 sub write_used_provider_rulefiles_file
($@
) {
1403 my ($provider, @files) = @_;
1405 # Get the path and file for the provider specific used rulefiles file.
1406 my $used_provider_rulesfile_file = &get_used_provider_rulesfile_file
($provider);
1408 # Open file for used rulefiles.
1409 open (FILE
, ">", "$used_provider_rulesfile_file") or die "Could not write to $used_provider_rulesfile_file. $!\n";
1411 # Write yaml header to the file.
1412 print FILE
"%YAML 1.1\n";
1413 print FILE
"---\n\n";
1415 # Write header to file.
1416 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1418 # Loop through the array of given files.
1419 foreach my $file (@files) {
1420 # Check if the given filename exists and write it to the file of used rulefiles.
1421 if(-f
"$rulespath/$file") {
1422 print FILE
" - $file\n";
1426 # Close file after writing.
1431 ## Function to write the main file for provider rulesfiles inclusions.
1433 ## This function requires an array of provider handles.
1435 sub write_main_used_rulefiles_file
(@
) {
1436 my (@providers) = @_;
1438 # Call function to write the static rulefiles file.
1439 &_write_default_rulefiles_file
();
1441 # Open file for used rulefils inclusion.
1442 open (FILE
, ">", "$suricata_used_providers_file") or die "Could not write to $suricata_used_providers_file. $!\n";
1444 # Write yaml header to the file.
1445 print FILE
"%YAML 1.1\n";
1446 print FILE
"---\n\n";
1448 # Write header to file.
1449 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1451 # Loop through the list of given providers.
1452 foreach my $provider (@providers) {
1453 # Call function to get the providers used rulefiles file.
1454 my $filename = &get_used_provider_rulesfile_file
($provider);
1456 # Check if the file exists and write it into the used rulefiles file.
1458 # Print the provider to the file.
1459 print FILE
"include\: $filename\n";
1463 # Close the filehandle after writing.
1467 sub _write_default_rulefiles_file
() {
1468 # Get enabled application layer protocols.
1469 my @enabled_app_layer_protos = &get_suricata_enabled_app_layer_protos
();
1472 open (FILE
, ">", $suricata_default_rulefiles_file) or die "Could not write to $suricata_default_rulefiles_file. $!\n";
1474 # Write yaml header to the file.
1475 print FILE
"%YAML 1.1\n";
1476 print FILE
"---\n\n";
1478 # Write notice about autogenerated file.
1479 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1481 # Loop through the array of static included rulesfiles.
1482 foreach my $file (@static_included_rulefiles) {
1483 # Check if the file exists.
1484 if (-f
"$rulespath/$file") {
1485 # Write the rulesfile name to the file.
1486 print FILE
" - $rulespath/$file\n";
1490 print FILE
"\n#Default rules for used application layer protocols.\n";
1491 foreach my $enabled_app_layer_proto (@enabled_app_layer_protos) {
1492 # Check if the current processed app layer proto needs to be translated
1493 # into an application name.
1494 if (exists($tr_app_layer_proto{$enabled_app_layer_proto})) {
1495 # Obtain the translated application name for this protocol.
1496 $enabled_app_layer_proto = $tr_app_layer_proto{$enabled_app_layer_proto};
1499 # Generate filename.
1500 my $rulesfile = "$default_rulespath/$enabled_app_layer_proto\.rules";
1502 # Check if such a file exists.
1503 if (-f
"$rulesfile") {
1504 # Write the rulesfile name to the file.
1505 print FILE
" - $rulesfile\n";
1508 # Generate filename with "events" in filename.
1509 $rulesfile = "$default_rulespath/$enabled_app_layer_proto\-events.rules";
1511 # Check if this file exists.
1512 if (-f
"$rulesfile" ) {
1513 # Write the rulesfile name to the file.
1514 print FILE
" - $rulesfile\n";
1518 # Close the file handle
1523 ## Tiny function to generate the full path and name for the used_provider_rulesfile file of a given provider.
1525 sub get_used_provider_rulesfile_file
($) {
1526 my ($provider) = @_;
1528 my $filename = "$settingsdir/suricata\-$provider\-used\-rulefiles.yaml";
1530 # Return the gernerated file.
1535 ## Function to generate and write the file for modify the ruleset.
1537 sub write_modify_sids_file
() {
1538 # Get configured settings.
1540 &General
::readhash
("$ids_settings_file", \
%idssettings);
1542 # Open modify sid's file for writing.
1543 open(FILE
, ">$modify_sids_file") or die "Could not write to $modify_sids_file. $!\n";
1545 # Write file header.
1546 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1548 # Check if the traffic only should be monitored.
1549 unless($idssettings{'MONITOR_TRAFFIC_ONLY'} eq 'on') {
1550 # Suricata is in IPS mode, which means that the rule actions have to be changed
1551 # from 'alert' to 'drop', however not all rules should be changed. Some rules
1552 # exist purely to set a flowbit which is used to convey other information, such
1553 # as a specific type of file being downloaded, to other rulewhich then check for
1554 # malware in that file. Rules which fall into the first category should stay as
1555 # alert since not all flows of that type contain malware.
1557 # These types of rulesfiles contain meta-data which gives the action that should
1558 # be used when in IPS mode. Do the following:
1560 # 1. Disable all rules and set the action to 'drop'
1561 # 2. Set the action back to 'alert' if the rule contains 'flowbits:noalert;'
1562 # This should give rules not in the policy a reasonable default if the user
1563 # manually enables them.
1564 # 3. Enable rules and set actions according to the meta-data strings.
1566 my $policy = 'balanced'; # Placeholder to allow policy to be changed.
1569 modifysid * "^#(?:alert|drop)(.+policy $policy-ips alert)" | "alert\${1}"
1570 modifysid * "^#(?:alert|drop)(.+policy $policy-ips drop)" | "drop\${1}"
1571 modifysid * "^(#?)(?:alert|drop)" | "\${1}drop"
1572 modifysid * "^(#?)drop(.+flowbits:noalert;)" | "\${1}alert\${2}"
1576 # Close file handle.
1581 ## Function to get the ruleset date for a given provider.
1583 ## The function simply return the creation date in a human read-able format
1584 ## of the stored providers rulesfile.
1586 sub get_ruleset_date
($) {
1587 my ($provider) = @_;
1591 # Load neccessary perl modules for file stat and to format the timestamp.
1593 use POSIX
qw( strftime );
1595 # Get the stored rulesfile for this provider.
1596 my $stored_rulesfile = &_get_dl_rulesfile
($provider);
1598 # Check if we got a file.
1599 if (-f
$stored_rulesfile) {
1600 # Call stat on the rulestarball.
1601 my $stat = stat("$stored_rulesfile");
1603 # Get timestamp the file creation.
1604 $mtime = $stat->mtime;
1607 # Check if the timestamp has not been grabbed.
1609 # Return N/A for Not available.
1613 # Convert into human read-able format.
1614 $date = strftime
('%Y-%m-%d %H:%M:%S', localtime($mtime));
1621 ## Function to gather the version of suricata.
1623 sub get_suricata_version
($) {
1626 # Execute piped suricata command and return the version information.
1627 open(SURICATA
, "suricata -V |") or die "Couldn't execute program: $!";
1629 # Grab and store the output of the piped program.
1630 my $version_string = <SURICATA
>;
1636 chomp($version_string);
1638 # Grab the version from the version string.
1639 $version_string =~ /([0-9]+([.][0-9]+)+)/;
1641 # Splitt the version into single chunks.
1642 my ($major_ver, $minor_ver, $patchlevel) = split(/\./, $1);
1644 # Check and return the requested version sheme.
1645 if ($format eq "major") {
1646 # Return the full version.
1647 return "$major_ver";
1648 } elsif ($format eq "minor") {
1649 # Return the major and minor part.
1650 return "$major_ver.$minor_ver";
1652 # Return the full version string.
1653 return "$major_ver.$minor_ver.$patchlevel";
1658 ## Function to get the enabled application layer protocols.
1660 sub get_suricata_enabled_app_layer_protos
() {
1661 # Array to store and return the enabled app layer protos.
1662 my @enabled_app_layer_protos = ();
1664 # Execute piped suricata command and return the list of
1665 # enabled application layer protocols.
1666 open(SURICATA
, "suricata --list-app-layer-protos |") or die "Could not execute program: $!";
1668 # Grab and store the list of enabled application layer protocols.
1669 my @output = <SURICATA
>;
1674 # Merge allways enabled static application layers protocols array.
1675 @enabled_app_layer_protos = @static_enabled_app_layer_protos;
1677 # Loop through the array which contains the output of suricata.
1678 foreach my $line (@output) {
1679 # Skip header line which starts with "===".
1680 next if ($line =~ /^\s*=/);
1682 # Skip info or warning lines.
1683 next if ($line =~ /\s*--/);
1688 # Add enabled app layer proto to the array.
1689 push(@enabled_app_layer_protos, $line);
1693 @enabled_app_layer_protos = sort(@enabled_app_layer_protos);
1696 return @enabled_app_layer_protos;
1700 ## Function to generate the rules file with whitelisted addresses.
1702 sub generate_ignore_file
() {
1705 # SID range 1000000-1999999 Reserved for Local Use
1706 # Put your custom rules in this range to avoid conflicts
1709 # Read-in ignoredfile.
1710 &General
::readhasharray
($IDS::ignored_file
, \
%ignored);
1712 # Open ignorefile for writing.
1713 open(FILE
, ">$IDS::whitelist_file") or die "Could not write to $IDS::whitelist_file. $!\n";
1715 # Config file header.
1716 print FILE
"# Autogenerated file.\n";
1717 print FILE
"# All user modifications will be overwritten.\n\n";
1719 # Add all user defined addresses to the whitelist.
1721 # Check if the hash contains any elements.
1722 if (keys (%ignored)) {
1723 # Loop through the entire hash and write the host/network
1724 # and remark to the ignore file.
1725 while ( (my $key) = each %ignored) {
1726 my $address = $ignored{$key}[0];
1727 my $remark = $ignored{$key}[1];
1728 my $status = $ignored{$key}[2];
1730 # Check if the status of the entry is "enabled".
1731 if ($status eq "enabled") {
1732 # Check if the address/network is valid.
1733 if ((&General
::validip
($address)) || (&General
::validipandmask
($address))) {
1734 # Write rule line to the file to pass any traffic from this IP
1735 print FILE
"pass ip $address any -> any any (msg:\"pass all traffic from/to $address\"\; bypass; sid:$sid\;)\n";
1748 ## Function to set correct ownership for single files and directories.
1751 sub set_ownership
($) {
1754 # User and group of the WUI.
1755 my $uname = "nobody";
1756 my $grname = "nobody";
1758 # The chown function implemented in perl requies the user and group as nummeric id's.
1759 my $uid = getpwnam($uname);
1760 my $gid = getgrnam($grname);
1762 # Check if the given target exists.
1764 # Stop the script and print error message.
1765 die "The $target does not exist. Cannot change the ownership!\n";
1768 # Check weather the target is a file or directory.
1770 # Change ownership ot the single file.
1771 chown($uid, $gid, "$target");
1772 } elsif (-d
$target) {
1773 # Do a directory listing.
1774 opendir(DIR
, $target) or die $!;
1775 # Loop through the direcory.
1776 while (my $file = readdir(DIR
)) {
1778 # We only want files.
1779 next unless (-f
"$target/$file");
1781 # Set correct ownership for the files.
1782 chown($uid, $gid, "$target/$file");
1787 # Change ownership of the directory.
1788 chown($uid, $gid, "$target");
1793 ## Function to read-in the aliases file and returns all configured and enabled aliases.
1796 # Location of the aliases file.
1797 my $aliases_file = "${General::swroot}/ethernet/aliases";
1799 # Array to store the aliases.
1802 # Check if the file is empty.
1803 if (-z
$aliases_file) {
1804 # Abort nothing to do.
1808 # Open the aliases file.
1809 open(ALIASES
, $aliases_file) or die "Could not open $aliases_file. $!\n";
1811 # Loop through the file content.
1812 while (my $line = <ALIASES
>) {
1816 # Splitt line content into single chunks.
1817 my ($address, $state, $remark) = split(/\,/, $line);
1819 # Check if the state of the current processed alias is "on".
1820 if ($state eq "on") {
1821 # Check if the address is valid.
1822 if(&Network
::check_ip_address
($address)) {
1823 # Add the alias to the array of aliases.
1824 push(@aliases, $address);
1829 # Close file handle.
1837 ## Function to grab the current assigned IP-address on red.
1839 sub get_red_address
() {
1840 # File, which contains the current IP-address of the red interface.
1841 my $file = "${General::swroot}/red/local-ipaddress";
1843 # Check if the file exists.
1845 # Open the given file.
1846 open(FILE
, "$file") or die "Could not open $file.";
1848 # Obtain the address from the first line of the file.
1849 my $address = <FILE
>;
1857 # Check if the grabbed address is valid.
1858 if (&General
::validip
($address)) {
1859 # Return the address.
1869 ## Function to get the used rules files of a given provider.
1871 sub read_used_provider_rulesfiles
($) {
1872 my ($provider) = @_;
1874 # Array to store the used rulefiles.
1875 my @used_rulesfiles = ();
1877 # Get the used rulesefile file for the provider.
1878 my $rulesfile_file = &get_used_provider_rulesfile_file
($provider);
1880 # Check if the a used rulesfile exists for this provider.
1881 if (-f
$rulesfile_file) {
1882 # Open the file or used rulefiles and read-in content.
1883 open(FILE
, $rulesfile_file) or die "Could not open $rulesfile_file. $!\n";
1886 # Assign the current line to a nice variable.
1893 next if ($line =~ /\#/);
1896 next if ($line =~ /^\s*$/);
1898 # Gather the rulefile.
1899 if ($line =~ /.*- (.*)/) {
1902 # Add the rulefile to the array of used rulesfiles.
1903 push(@used_rulesfiles, $rulefile);
1911 # Return the array of used rulesfiles.
1912 return @used_rulesfiles;
1916 ## Function to write the lock file for locking the WUI, while
1917 ## the autoupdate script runs.
1919 sub lock_ids_page
() {
1920 # Call subfunction to create the file.
1921 &create_empty_file
($ids_page_lock_file);
1925 ## Function to release the lock of the WUI, again.
1927 sub unlock_ids_page
() {
1929 unlink($ids_page_lock_file);