2 ############################################################################
4 # This file is part of the IPFire Firewall. #
6 # IPFire is free software; you can redistribute it and/or modify #
7 # it under the terms of the GNU General Public License as published by #
8 # the Free Software Foundation; either version 2 of the License, or #
9 # (at your option) any later version. #
11 # IPFire is distributed in the hope that it will be useful, #
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of #
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
14 # GNU General Public License for more details. #
16 # You should have received a copy of the GNU General Public License #
17 # along with IPFire; if not, write to the Free Software #
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #
20 # Copyright (C) 2018-2019 IPFire Team <info@ipfire.org> #
22 ############################################################################
28 require '/var/ipfire/general-functions.pl';
29 require "${General::swroot}/network-functions.pl";
30 require "${General::swroot}/suricata/ruleset-sources";
32 # Load perl module to deal with Archives.
35 # Load perl module to deal with files and path.
38 # Load module to move files.
41 # Load module to recursely remove files and a folder.
42 use File
::Path
qw(rmtree);
44 # Load module to get file stats.
47 # Load module to deal with temporary files.
50 # Load module to deal with the date formats used by the HTTP protocol.
53 # Load the libwwwperl User Agent module.
56 # Load function from posix module to format time strings.
57 use POSIX qw
(strftime
);
59 # Load module to talk to the kernel log daemon.
60 use Sys
::Syslog
qw(:DEFAULT setlogsock);
62 # Location where all config and settings files are stored.
63 our $settingsdir = "${General::swroot}/suricata";
65 # File where the main file for providers ruleset inclusion exists.
66 our $suricata_used_rulesfiles_file = "$settingsdir/suricata-used-rulesfiles.yaml";
68 # File where the addresses of the homenet are stored.
69 our $homenet_file = "$settingsdir/suricata-homenet.yaml";
71 # File where the addresses of the used DNS servers are stored.
72 our $dns_servers_file = "$settingsdir/suricata-dns-servers.yaml";
74 # File where the HTTP ports definition is stored.
75 our $http_ports_file = "$settingsdir/suricata-http-ports.yaml";
77 # File which stores the configured IPS settings.
78 our $ids_settings_file = "$settingsdir/settings";
80 # File which stores the used and configured ruleset providers.
81 our $providers_settings_file = "$settingsdir/providers-settings";
83 # File which stores the configured settings for whitelisted addresses.
84 our $ignored_file = "$settingsdir/ignored";
86 # File which stores HTTP Etags for providers which supports them
87 # for cache management.
88 our $etags_file = "$settingsdir/etags";
90 # Location where the downloaded rulesets are stored.
91 our $dl_rules_path = "/var/tmp";
93 # File to store any errors, which also will be read and displayed by the wui.
94 our $storederrorfile = "/tmp/ids_storederror";
96 # File to lock the WUI, while the autoupdate script runs.
97 our $ids_page_lock_file = "/tmp/ids_page_locked";
99 # Location where the rulefiles are stored.
100 our $rulespath = "/var/lib/suricata";
102 # Location where the default rulefils are stored.
103 our $default_rulespath = "/usr/share/suricata/rules";
105 # Location where the addition config files are stored.
106 our $configspath = "/usr/share/suricata";
108 # Location of the classification file.
109 our $classification_file = "$configspath/classification.config";
111 # Location of the sid to msg mappings file.
112 our $sid_msg_file = "$rulespath/sid-msg.map";
114 # Location to store local rules. This file will not be touched.
115 our $local_rules_file = "$rulespath/local.rules";
117 # File which contains the rules to whitelist addresses on suricata.
118 our $whitelist_file = "$rulespath/whitelist.rules";
120 # File which contains a list of all supported ruleset sources.
121 # (Sourcefire, Emergingthreads, etc..)
122 our $rulesetsourcesfile = "$settingsdir/ruleset-sources";
124 # The pidfile of the IDS.
125 our $idspidfile = "/var/run/suricata.pid";
127 # Location of suricatactrl.
128 my $suricatactrl = "/usr/local/bin/suricatactrl";
130 # Prefix for each downloaded ruleset.
131 my $dl_rulesfile_prefix = "idsrules";
133 # Temporary directory to download the rules files.
134 my $tmp_dl_directory = "/var/tmp";
136 # Temporary directory where the rulesets will be extracted.
137 my $tmp_directory = "/tmp/ids_tmp";
139 # Temporary directory where the extracted rules files will be stored.
140 my $tmp_rules_directory = "$tmp_directory/rules";
142 # Temporary directory where the extracted additional config files will be stored.
143 my $tmp_conf_directory = "$tmp_directory/conf";
145 # Array with allowed commands of suricatactrl.
146 my @suricatactrl_cmds = ( 'start', 'stop', 'restart', 'reload', 'fix-rules-dir', 'cron' );
148 # Array with supported cron intervals.
149 my @cron_intervals = ('off', 'daily', 'weekly' );
151 # Array which contains the HTTP ports, which statically will be declared as HTTP_PORTS in the
153 my @http_ports = ('80', '81');
155 # Array which contains a list of rulefiles which always will be included if they exist.
156 my @static_included_rulefiles = ('local.rules', 'whitelist.rules');
158 # Array which contains a list of allways enabled application layer protocols.
159 my @static_enabled_app_layer_protos = ('app-layer', 'decoder', 'files', 'stream');
161 # Hash which allows to convert the download type (dl_type) to a file suffix.
162 my %dl_type_to_suffix = (
163 "archive" => ".tar.gz",
167 # Hash to translate an application layer protocol to the application name.
168 my %tr_app_layer_proto = (
170 "krb5" => "kerberos",
174 ## Function to check and create all IDS related files, if the does not exist.
176 sub check_and_create_filelayout
() {
177 # Check if the files exist and if not, create them.
178 unless (-f
"$suricata_used_rulesfiles_file") { &create_empty_file
($suricata_used_rulesfiles_file); }
179 unless (-f
"$ids_settings_file") { &create_empty_file
($ids_settings_file); }
180 unless (-f
"$providers_settings_file") { &create_empty_file
($providers_settings_file); }
181 unless (-f
"$whitelist_file" ) { &create_empty_file
($whitelist_file); }
185 ## Function to get a list of all available ruleset providers.
187 ## They will be returned as a sorted array.
189 sub get_ruleset_providers
() {
192 # Loop through the hash of providers.
193 foreach my $provider ( keys %IDS::Ruleset
::Providers
) {
194 # Add the provider to the array.
195 push(@providers, $provider);
198 # Sort and return the array.
199 return sort(@providers);
203 ## Function to get a list of all enabled ruleset providers.
205 ## They will be returned as an array.
207 sub get_enabled_providers
() {
208 my %used_providers = ();
210 # Array to store the enabled providers.
211 my @enabled_providers = ();
213 # Read-in the providers config file.
214 &General
::readhasharray
("$providers_settings_file", \
%used_providers);
216 # Loop through the hash of used_providers.
217 foreach my $id (keys %used_providers) {
218 # Skip disabled providers.
219 next unless ($used_providers{$id}[3] eq "enabled");
221 # Grab the provider handle.
222 my $provider = "$used_providers{$id}[0]";
224 # Add the provider to the array of enabled providers.
225 push(@enabled_providers, $provider);
229 return @enabled_providers;
233 ## Function to get a hash of provider handles and their configured modes (IDS/IPS).
235 sub get_providers_mode
() {
236 my %used_providers = ();
238 # Hash to store the providers and their configured modes.
239 my %providers_mode = ();
241 # Read-in the providers config file.
242 &General
::readhasharray
("$providers_settings_file", \
%used_providers);
244 # Loop through the hash of used_providers.
245 foreach my $id (keys %used_providers) {
246 # Skip disabled providers.
247 next unless ($used_providers{$id}[3] eq "enabled");
249 # Grab the provider handle.
250 my $provider = "$used_providers{$id}[0]";
252 # Grab the provider mode.
253 my $mode = "$used_providers{$id}[4]";
255 # Fall back to IDS if no mode could be obtained.
260 # Add details to provider_modes hash.
261 $providers_mode{$provider} = $mode;
265 return %providers_mode;
269 ## Function for checking if at least 300MB of free disk space are available
270 ## on the "/var" partition.
272 sub checkdiskspace
() {
273 # Call diskfree to gather the free disk space of /var.
274 my @df = &General
::system_output
("/bin/df", "-B", "M", "/var");
276 # Loop through the output.
277 foreach my $line (@df) {
278 # Ignore header line.
279 next if $line =~ m/^Filesystem/;
281 # Search for a line with the device information.
282 if ($line =~ m/dev/ ) {
283 # Split the line into single pieces.
284 my @values = split(' ', $line);
285 my ($filesystem, $blocks, $used, $available, $used_perenctage, $mounted_on) = @values;
287 # Check if the available disk space is more than 300MB.
288 if ($available < 300) {
289 # Exit function and return the available disk space.
295 # Everything okay, return nothing.
300 ## This function is responsible for downloading the ruleset for a given provider.
302 ## * At first it initialize the downloader and sets an upstream proxy if configured.
303 ## * The next step will be to generate the final download url, by obtaining the URL for the desired
304 ## ruleset and add the settings for the upstream proxy.
305 ## * Finally the function will grab the rule file or tarball from the server.
306 ## It tries to reduce the amount of download by using the "If-Modified-Since" HTTP header.
310 ## * "no url" - If no download URL could be gathered for the provider.
311 ## * "not modified" - In case the already stored rules file is up to date.
312 ## * "incomplete download" - When the remote file size differs from the downloaded file size.
313 ## * "$error" - The error message generated from the LWP::User Agent module.
315 sub downloadruleset
($) {
318 # The amount of download attempts before giving up and
320 my $max_dl_attempts = 3;
322 # Read proxysettings.
323 my %proxysettings=();
324 &General
::readhash
("${General::swroot}/proxy/settings", \
%proxysettings);
326 # Init the download module.
328 # Request SSL hostname verification and specify path
330 my $downloader = LWP
::UserAgent
->new(
332 SSL_ca_file
=> '/etc/ssl/cert.pem',
333 verify_hostname
=> 1,
337 # Set timeout to 10 seconds.
338 $downloader->timeout(10);
340 # Check if an upstream proxy is configured.
341 if ($proxysettings{'UPSTREAM_PROXY'}) {
344 $proxy_url = "http://";
346 # Check if the proxy requires authentication.
347 if (($proxysettings{'UPSTREAM_USER'}) && ($proxysettings{'UPSTREAM_PASSWORD'})) {
348 $proxy_url .= "$proxysettings{'UPSTREAM_USER'}\:$proxysettings{'UPSTREAM_PASSWORD'}\@";
351 # Add proxy server address and port.
352 $proxy_url .= $proxysettings{'UPSTREAM_PROXY'};
354 # Setup proxy settings.
355 $downloader->proxy(['http', 'https'], $proxy_url);
358 # Grab the download url for the provider.
359 my $url = $IDS::Ruleset
::Providers
{$provider}{'dl_url'};
361 # Check if the provider requires a subscription.
362 if ($IDS::Ruleset
::Providers
{$provider}{'requires_subscription'} eq "True") {
363 # Grab the subscription code.
364 my $subscription_code = &get_subscription_code
($provider);
366 # Add the subscription code to the download url.
367 $url =~ s/\<subscription_code\>/$subscription_code/g;
371 # Abort and return "no url", if no url could be determined for the provider.
372 return "no url" unless ($url);
374 # Pass the requested URL to the downloader.
375 my $request = HTTP
::Request
->new(GET
=> $url);
377 # Generate temporary file name, located in the tempoary download directory and with a suffix of ".tmp".
378 # The downloaded file will be stored there until some sanity checks are performed.
379 my $tmp = File
::Temp
->new( SUFFIX
=> ".tmp", DIR
=> "$tmp_dl_directory/", UNLINK
=> 0 );
380 my $tmpfile = $tmp->filename();
382 # Call function to get the final path and filename for the downloaded file.
383 my $dl_rulesfile = &_get_dl_rulesfile
($provider);
385 # Check if the rulesfile already exits, because it has been downloaded in the past.
387 # In this case we are requesting the server if the remote file has been changed or not.
388 # This will be done by sending the modification time in a special HTTP header.
389 if (-f
$dl_rulesfile) {
390 # Call stat on the file.
391 my $stat = stat($dl_rulesfile);
393 # Omit the mtime of the existing file.
394 my $mtime = $stat->mtime;
396 # Convert the timestamp into right format.
397 my $http_date = time2str
($mtime);
399 # Add the If-Modified-Since header to the request to ask the server if the
400 # file has been modified.
401 $request->header( 'If-Modified-Since' => "$http_date" );
404 # Read-in Etags file for known Etags if the file is present.
406 &General
::readhash
("$etags_file", \
%etags) if (-f
$etags_file);
408 # Check if an Etag for the current provider is stored.
409 if ($etags{$provider}) {
410 # Grab the stored tag.
411 my $etag = $etags{$provider};
413 # Add an "If-None-Match header to the request to ask the server if the
414 # file has been modified.
415 $request->header( 'If-None-Match' => $etag );
421 # Download and retry on failure.
422 while ($dl_attempt <= $max_dl_attempts) {
423 # Perform the request and save the output into the tmpfile.
424 $response = $downloader->request($request, $tmpfile);
426 # Check if the download was successfull.
427 if($response->is_success) {
431 # Check if the server responds with 304 (Not Modified).
432 } elsif ($response->code == 304) {
433 # Return "not modified".
434 return "not modified";
436 # Check if we ran out of download re-tries.
437 } elsif ($dl_attempt eq $max_dl_attempts) {
439 my $error = $response->content;
441 # Return the error message from response..
445 # Remove temporary file, if one exists.
446 unlink("$tmpfile") if (-e
"$tmpfile");
448 # Increase download attempt counter.
452 # Obtain the connection headers.
453 my $headers = $response->headers;
455 # Get the timestamp from header, when the file has been modified the
457 my $last_modified = $headers->last_modified;
459 # Get the remote size of the downloaded file.
460 my $remote_filesize = $headers->content_length;
462 # Grab the Etag from response it the server provides one.
463 if ($response->header('Etag')) {
464 # Add the Etag to the etags hash.
465 $etags{$provider} = $response->header('Etag');
467 # Write the etags file.
468 &General
::writehash
($etags_file, \
%etags);
471 # Perform stat on the tmpfile.
472 my $stat = stat($tmpfile);
474 # Grab the local filesize of the downloaded tarball.
475 my $local_filesize = $stat->size;
477 # Check if both file sizes match.
478 if (($remote_filesize) && ($remote_filesize ne $local_filesize)) {
479 # Delete temporary file.
482 # Return "1" - false.
483 return "incomplete download";
486 # Overwrite the may existing rulefile or tarball with the downloaded one.
487 move
("$tmpfile", "$dl_rulesfile");
489 # Check if we got a last-modified value from the server.
490 if ($last_modified) {
491 # Assign the last-modified timestamp as mtime to the
493 utime(time(), "$last_modified", "$dl_rulesfile");
496 # Delete temporary file.
499 # Set correct ownership for the tarball.
500 set_ownership
("$dl_rulesfile");
502 # If we got here, everything worked fine. Return nothing.
507 ## Function to extract a given ruleset.
509 ## In case the ruleset provider offers a plain file, it simply will
512 sub extractruleset
($) {
515 # Disable chown functionality when uncompressing files.
516 $Archive::Tar
::CHOWN
= "0";
518 # Get full path and downloaded rulesfile for the given provider.
519 my $tarball = &_get_dl_rulesfile
($provider);
521 # Check if the file exists.
522 unless (-f
$tarball) {
523 &_log_to_syslog
("Could not find ruleset file: $tarball");
529 # Check if the temporary directories exist, otherwise create them.
530 mkdir("$tmp_directory") unless (-d
"$tmp_directory");
531 mkdir("$tmp_rules_directory") unless (-d
"$tmp_rules_directory");
532 mkdir("$tmp_conf_directory") unless (-d
"$tmp_conf_directory");
534 # Omit the type (dl_type) of the stored ruleset.
535 my $type = $IDS::Ruleset
::Providers
{$provider}{'dl_type'};
537 # Handle the different ruleset types.
538 if ($type eq "plain") {
539 # Generate destination filename an full path.
540 my $destination = "$tmp_rules_directory/$provider\-ruleset.rules";
542 # Copy the file into the temporary rules directory.
543 copy
($tarball, $destination);
545 } elsif ( $type eq "archive") {
546 # Initialize the tar module.
547 my $tar = Archive
::Tar
->new($tarball);
549 # Get the filelist inside the tarball.
550 my @packed_files = $tar->list_files;
552 # Loop through the filelist.
553 foreach my $packed_file (@packed_files) {
556 # Splitt the packed file into chunks.
557 my $file = fileparse
($packed_file);
559 # Handle msg-id.map file.
560 if ("$file" eq "sid-msg.map") {
561 # Set extract destination to temporary config_dir.
562 $destination = "$tmp_conf_directory/$provider\-sid-msg.map";
564 # Handle classification.conf
565 } elsif ("$file" eq "classification.config") {
566 # Set extract destination to temporary config_dir.
567 $destination = "$tmp_conf_directory/$provider\-classification.config";
569 # Handle rules files.
570 } elsif ($file =~ m/\.rules$/) {
571 # Skip rule files which are not located in the rules directory or archive root.
572 next unless(($packed_file =~ /^rules\//) || ($packed_file !~ /\
//));
574 # Skip deleted.rules.
576 # Mostly they have been taken out for correctness or performance reasons and therfore
577 # it is not a great idea to enable any of them.
578 next if($file =~ m/deleted.rules$/);
582 # Splitt the filename into chunks.
583 my @filename = split("-", $file);
586 @filename = reverse(@filename);
588 # Get the amount of elements in the array.
589 my $elements = @filename;
591 # Remove last element of the hash.
592 # It contains the vendor name, which will be replaced.
593 if ($elements >= 3) {
594 # Remove last element from hash.
598 # Check if the last element of the filename does not
599 # contain the providers name.
600 if ($filename[-1] ne "$provider") {
601 # Add provider name as last element.
602 push(@filename, $provider);
605 # Reverse the array back.
606 @filename = reverse(@filename);
608 # Generate the name for the rulesfile.
609 $rulesfilename = join("-", @filename);
611 # Set extract destination to temporaray rules_dir.
612 $destination = "$tmp_rules_directory/$rulesfilename";
614 # Skip all other files.
618 # Check if the destination file exists.
619 unless(-e
"$destination") {
620 # Extract the file to the temporary directory.
621 $tar->extract_file("$packed_file", "$destination");
623 # Generate temporary file name, located in the temporary rules directory and a suffix of ".tmp".
624 my $tmp = File
::Temp
->new( SUFFIX
=> ".tmp", DIR
=> "$tmp_rules_directory", UNLINK
=> 0 );
625 my $tmpfile = $tmp->filename();
627 # Extract the file to the new temporary file name.
628 $tar->extract_file("$packed_file", "$tmpfile");
630 # Open the the existing file.
631 open(DESTFILE
, ">>", "$destination") or die "Could not open $destination. $!\n";
632 open(TMPFILE
, "<", "$tmpfile") or die "Could not open $tmpfile. $!\n";
634 # Loop through the content of the temporary file.
636 # Append the content line by line to the destination file.
640 # Close the file handles.
644 # Remove the temporary file.
652 ## A wrapper function to call the oinkmaster script, setup the rules structues and
653 ## call the functions to merge the additional config files. (classification, sid-msg, etc.).
656 # Check if the files in rulesdir have the correct permissions.
657 &_check_rulesdir_permissions
();
659 # Cleanup the rules directory before filling it with the new rulests.
660 &_cleanup_rulesdir
();
662 # Get all enabled providers.
663 my @enabled_providers = &get_enabled_providers
();
665 # Loop through the array of enabled providers.
666 foreach my $provider (@enabled_providers) {
667 # Call the extractruleset function.
668 &extractruleset
($provider);
671 # Call function to process the ruleset and do all modifications.
672 &process_ruleset
(@enabled_providers);
674 # Call function to merge the classification files.
675 &merge_classifications
(@enabled_providers);
677 # Call function to merge the sid to message mapping files.
678 &merge_sid_msg
(@enabled_providers);
680 # Cleanup temporary directory.
681 &cleanup_tmp_directory
();
685 ## Function to alter the ruleset.
687 sub process_ruleset
(@
) {
688 my (@providers) = @_;
690 # Hash to store the configured provider modes.
691 my %providers_mode = &get_providers_mode
();
693 # Array to store the extracted rulefile from the temporary rules directory.
694 my @extracted_rulefiles;
696 # Get names of the extracted raw rulefiles.
697 opendir(DIR
, $tmp_rules_directory) or die "Could not read from $tmp_rules_directory. $!\n";
698 while (my $file = readdir(DIR
)) {
699 # Ignore single and double dotted files.
700 next if $file =~ /^\.\.?$/;
702 # Add file to the array of extracted files.
703 push(@extracted_rulefiles, $file);
706 # Close directory handle.
709 # Loop through the array of providers.
710 foreach my $provider (@providers) {
711 # Hash to store the obtained SIDs and REV of each provider.
714 # Hash which holds modifications to apply to the rules.
715 my %modifications = ();
717 # Loop through the array of extraced rulefiles.
718 foreach my $file (@extracted_rulefiles) {
719 # Skip file if it does not belong to the current processed provider.
720 next unless ($file =~ m/^$provider/);
723 open(FILE
, "$tmp_rules_directory/$file") or die "Could not read $tmp_rules_directory/$file. $!\n";
725 # Loop through the file content.
726 while (my $line = <FILE
>) {
728 next if ($line =~ /^\s*$/);
730 # Call function to get the sid and rev of the rule.
731 my ($sid, $rev) = &_get_sid_and_rev
($line);
733 # Skip rule if a sid with a higher rev already has added to the rules hash.
734 next if ($rev le $rules{$sid});
736 # Add the new or rule with higher rev to the hash of rules.
744 # Get filename which contains the ruleset modifications for this provider.
745 my $modification_file = &get_provider_ruleset_modifications_file
($provider);
747 # Read file which holds the modifications of the ruleset for the current provider.
748 &General
::readhash
($modification_file, \
%modifications) if (-f
$modification_file);
750 # Loop again through the array of extracted rulesfiles.
751 foreach my $file (@extracted_rulefiles) {
752 # Skip the file if it does not belong to the current provider.
753 next unless ($file =~ m/^$provider/);
755 # Open the rulefile for writing.
756 open(RULEFILE
, ">", "$rulespath/$file") or die "Could not write to file $rulespath/$file. $!\n";
758 # Open the rulefile for reading.
759 open(TMP_RULEFILE
, "$tmp_rules_directory/$file") or die "Could not read $tmp_rules_directory/$file. $!\n";
761 # Loop through the raw temporary rulefile.
762 while (my $line = <TMP_RULEFILE
>) {
763 # Get the sid and rev of the rule.
764 my ($sid, $rev) = &_get_sid_and_rev
($line);
766 # Check if the current rule is obsoleted by a newer one.
768 # In this case the rev number in the rules hash is higher than the current one.
769 next if ($rev lt $rules{$sid});
771 # Check if the rule should be enabled or disabled.
772 if ($modifications{$sid} eq "enabled") {
773 # Drop the # at the start of the line.
775 } elsif ($modifications{$sid} eq "disabled") {
776 # Add a # at the start of the line to disable the rule.
777 $line = "#$line" unless ($line =~ /^#/);
780 # Check if the Provider is set so IPS mode.
781 if ($providers_mode{$provider} eq "IPS") {
782 # Replacements for sourcefire rules.
783 $line =~ s/^#\s*(?:alert|drop)(.+policy balanced-ips alert)/alert${1}/;
784 $line =~ s/^#\s*(?:alert|drop)(.+policy balanced-ips drop)/drop${1}/;
786 # Replacements for generic rules.
787 $line =~ s/^(#?)\s*(?:alert|drop)/${1}drop/;
788 $line =~ s/^(#?)\s*drop(.+flowbits:noalert;)/${1}alert${2}/;
791 # Write line / rule to the target rule file.
792 print RULEFILE
"$line";
803 ## Function to merge the classifications for a given amount of providers and write them
804 ## to the classifications file.
806 sub merge_classifications
(@
) {
809 # Hash to store all collected classifications.
810 my %classifications = ();
812 # Loop through the given array of providers.
813 foreach my $provider (@providers) {
814 # Generate full path to classification file.
815 my $classification_file = "$tmp_conf_directory/$provider\-classification.config";
817 # Skip provider if no classification file exists.
818 next unless (-f
"$classification_file");
820 # Open the classification file.
821 open(CLASSIFICATION
, $classification_file) or die "Could not open file $classification_file. $!\n";
823 # Loop through the file content.
824 while(<CLASSIFICATION
>) {
825 # Parse the file and grab the classification details.
826 if ($_ =~/.*config classification\: (.*)/) {
827 # Split the grabbed details.
828 my ($short_name, $short_desc, $priority) = split("\,", $1);
830 # Check if the grabbed classification is allready known and the priority value is greater
831 # than the stored one (which causes less priority in the IDS).
832 if (($classifications{$short_name}) && ($classifications{$short_name}[1] >= $priority)) {
833 #Change the priority value to the stricter one.
834 $classifications{$short_name} = [ "$classifications{$short_name}[0]", "$priority" ];
836 # Add the classification to the hash.
837 $classifications{$short_name} = [ "$short_desc", "$priority" ];
843 close(CLASSIFICATION
);
846 # Open classification file for writing.
847 open(FILE
, ">", "$classification_file") or die "Could not write to $classification_file. $!\n";
849 # Print notice about autogenerated file.
850 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n\n";
852 # Sort and loop through the hash of classifications.
853 foreach my $key (sort keys %classifications) {
854 # Assign some nice variable names for the items.
855 my $short_name = $key;
856 my $short_desc = $classifications{$key}[0];
857 my $priority = $classifications{$key}[1];
859 # Write the classification to the file.
860 print FILE
"config classification: $short_name,$short_desc,$priority\n";
868 ## Function to merge the "sid to message mapping" files of various given providers.
870 sub merge_sid_msg
(@
) {
873 # Hash which contains all the sid to message mappings.
876 # Loop through the array of given providers.
877 foreach my $provider (@providers) {
878 # Generate full path and filename.
879 my $sid_msg_file = "$tmp_conf_directory/$provider\-sid-msg.map";
881 # Skip provider if no sid to msg mapping file for this provider exists.
882 next unless (-f
$sid_msg_file);
885 open(MAPPING
, $sid_msg_file) or die "Could not open $sid_msg_file. $!\n";
887 # Loop through the file content.
892 # Skip lines which do not start with a number,
893 next unless ($_ =~ /^\d+/);
895 # Split line content and assign it to an array.
896 my @line = split(/ \|\| /, $_);
898 # Grab the first element (and remove it) from the line array.
899 # It contains the sid.
900 my $sid = shift(@line);
902 # Store the grabbed sid and the remain array as hash value.
903 # It still contains the messages, references etc.
904 $mappings{$sid} = [@line];
911 # Open mappings file for writing.
912 open(FILE
, ">", $sid_msg_file) or die "Could not write $sid_msg_file. $!\n";
914 # Write notice about autogenerated file.
915 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n\n";
917 # Loop through the hash of mappings.
918 foreach my $sid ( sort keys %mappings) {
919 # Grab data for the sid.
920 my @data = @
{$mappings{$sid}};
922 # Add the sid to the data array.
923 unshift(@data, $sid);
926 my $line = join(" \|\| ", @data);
928 print FILE
"$line\n";
937 ## A very tiny function to move an extracted ruleset from the temporary directory into
938 ## the rules directory.
940 sub move_tmp_ruleset
() {
941 # Do a directory listing of the temporary directory.
942 opendir DH
, $tmp_rules_directory;
944 # Loop over all files.
945 while(my $file = readdir DH
) {
946 # Move them to the rules directory.
947 move
"$tmp_rules_directory/$file" , "$rulespath/$file";
950 # Close directory handle.
955 ## Function to cleanup the temporary IDS directroy.
957 sub cleanup_tmp_directory
() {
959 # Delete temporary directory and all containing files.
960 rmtree
([ "$tmp_directory" ]);
964 ## Function to do all the logging stuff if the downloading or updating of the ruleset fails.
969 # Remove any newline.
972 # Call private function to log the error message to syslog.
973 &_log_to_syslog
($error);
975 # Call private function to write/store the error message in the storederrorfile.
976 &_store_error_message
($error);
980 ## Function to log a given error message to the kernel syslog.
982 sub _log_to_syslog
($) {
985 # The syslog function works best with an array based input,
986 # so generate one before passing the message details to syslog.
987 my @syslog = ("ERR", "<ERROR> $message");
989 # Establish the connection to the syslog service.
990 openlog
('oinkmaster', 'cons,pid', 'user');
992 # Send the log message.
995 # Close the log handle.
1000 ## Private function to write a given error message to the storederror file.
1002 sub _store_error_message
($) {
1005 # Remove any newline.
1008 # Open file for writing.
1009 open (ERRORFILE
, ">$storederrorfile") or die "Could not write to $storederrorfile. $!\n";
1011 # Write error to file.
1012 print ERRORFILE
"$message\n";
1017 # Set correct ownership for the file.
1018 &set_ownership
("$storederrorfile");
1022 ## Private function to get the path and filename for a downloaded ruleset by a given provider.
1024 sub _get_dl_rulesfile
($) {
1025 my ($provider) = @_;
1027 # Gather the download type for the given provider.
1028 my $dl_type = $IDS::Ruleset
::Providers
{$provider}{'dl_type'};
1030 # Obtain the file suffix for the download file type.
1031 my $suffix = $dl_type_to_suffix{$dl_type};
1033 # Check if a suffix has been found.
1035 # Abort return - nothing.
1039 # Generate the full filename and path for the stored rules file.
1040 my $rulesfile = "$dl_rules_path/$dl_rulesfile_prefix-$provider$suffix";
1042 # Return the generated filename.
1047 ## Private function to obtain the sid and rev of a rule.
1049 ## Returns an array with the sid as first and the rev as second value.
1051 sub _get_sid_and_rev
($) {
1056 # Use regex to obtain the sid and rev.
1057 if ($line =~ m/.*sid:\s*(.*?);.*rev:\s*(.*?);/) {
1058 # Add the sid and rev to the array.
1068 ## Tiny function to delete the stored ruleset file or tarball for a given provider.
1070 sub drop_dl_rulesfile
($) {
1071 my ($provider) = @_;
1073 # Gather the full path and name of the stored rulesfile.
1074 my $rulesfile = &_get_dl_rulesfile
($provider);
1076 # Check if the given rulesfile exists.
1077 if (-f
$rulesfile) {
1078 # Delete the stored rulesfile.
1079 unlink($rulesfile) or die "Could not delete $rulesfile. $!\n";
1084 ## Function to read-in the given enabled or disables sids file.
1086 sub read_enabled_disabled_sids_file
($) {
1089 # Temporary hash to store the sids and their state. It will be
1090 # returned at the end of this function.
1093 # Open the given filename.
1094 open(FILE
, "$file") or die "Could not open $file. $!\n";
1096 # Loop through the file.
1102 next if ($_ =~ /^\s*$/);
1105 next if ($_ =~ /^\#/);
1107 # Splitt line into sid and state part.
1108 my ($state, $sid) = split(" ", $_);
1110 # Skip line if the sid is not numeric.
1111 next unless ($sid =~ /\d+/ );
1113 # Check if the sid was enabled.
1114 if ($state eq "enablesid") {
1115 # Add the sid and its state as enabled to the temporary hash.
1116 $temphash{$sid} = "enabled";
1117 # Check if the sid was disabled.
1118 } elsif ($state eq "disablesid") {
1119 # Add the sid and its state as disabled to the temporary hash.
1120 $temphash{$sid} = "disabled";
1121 # Invalid state - skip the current sid and state.
1135 ## Function to check if the IDS is running.
1137 sub ids_is_running
() {
1138 if(-f
$idspidfile) {
1139 # Open PID file for reading.
1140 open(PIDFILE
, "$idspidfile") or die "Could not open $idspidfile. $!\n";
1142 # Grab the process-id.
1143 my $pid = <PIDFILE
>;
1148 # Remove any newline.
1151 # Check if a directory for the process-id exists in proc.
1152 if(-d
"/proc/$pid") {
1153 # The IDS daemon is running return the process id.
1158 # Return nothing - IDS is not running.
1163 ## Function to call suricatactrl binary with a given command.
1165 sub call_suricatactrl
($) {
1166 # Get called option.
1167 my ($option, $interval) = @_;
1169 # Loop through the array of supported commands and check if
1170 # the given one is part of it.
1171 foreach my $cmd (@suricatactrl_cmds) {
1172 # Skip current command unless the given one has been found.
1173 next unless($cmd eq $option);
1175 # Check if the given command is "cron".
1176 if ($option eq "cron") {
1177 # Check if an interval has been given.
1179 # Check if the given interval is valid.
1180 foreach my $element (@cron_intervals) {
1181 # Skip current element until the given one has been found.
1182 next unless($element eq $interval);
1184 # Call the suricatactrl binary and pass the "cron" command
1185 # with the requrested interval.
1186 &General
::system("$suricatactrl", "$option", "$interval");
1188 # Return "1" - True.
1193 # If we got here, the given interval is not supported or none has been given. - Return nothing.
1196 # Call the suricatactrl binary and pass the requrested
1198 &General
::system("$suricatactrl", "$option");
1200 # Return "1" - True.
1205 # Command not found - return nothing.
1210 ## Function to create a new empty file.
1212 sub create_empty_file
($) {
1215 # Check if the given file exists.
1217 # Do nothing to prevent from overwriting existing files.
1221 # Open the file for writing.
1222 open(FILE
, ">$file") or die "Could not write to $file. $!\n";
1224 # Close file handle.
1232 ## Private function to check if the file permission of the rulespath are correct.
1233 ## If not, call suricatactrl to fix them.
1235 sub _check_rulesdir_permissions
() {
1236 # Check if the rulepath main directory is writable.
1237 unless (-W
$rulespath) {
1238 # If not call suricatctrl to fix it.
1239 &call_suricatactrl
("fix-rules-dir");
1242 # Open snort rules directory and do a directory listing.
1243 opendir(DIR
, $rulespath) or die $!;
1244 # Loop through the direcory.
1245 while (my $file = readdir(DIR
)) {
1246 # We only want files.
1247 next unless (-f
"$rulespath/$file");
1249 # Check if the file is writable by the user.
1250 if (-W
"$rulespath/$file") {
1251 # Everything is okay - go on to the next file.
1254 # There are wrong permissions, call suricatactrl to fix it.
1255 &call_suricatactrl
("fix-rules-dir");
1261 ## Private function to cleanup the directory which contains
1262 ## the IDS rules, before extracting and modifing the new ruleset.
1264 sub _cleanup_rulesdir
() {
1265 # Open rules directory and do a directory listing.
1266 opendir(DIR
, $rulespath) or die $!;
1268 # Loop through the direcory.
1269 while (my $file = readdir(DIR
)) {
1270 # We only want files.
1271 next unless (-f
"$rulespath/$file");
1273 # Skip rules file for whitelisted hosts.
1274 next if ("$rulespath/$file" eq $whitelist_file);
1276 # Skip rules file with local rules.
1277 next if ("$rulespath/$file" eq $local_rules_file);
1279 # Delete the current processed file, if not, exit this function
1280 # and return an error message.
1281 unlink("$rulespath/$file") or return "Could not delete $rulespath/$file. $!\n";
1289 ## Function to generate the file which contains the home net information.
1291 sub generate_home_net_file
() {
1294 # Read-in network settings.
1295 &General
::readhash
("${General::swroot}/ethernet/settings", \
%netsettings);
1297 # Get available network zones.
1298 my @network_zones = &Network
::get_available_network_zones
();
1300 # Temporary array to store network address and prefix of the configured
1304 # Loop through the array of available network zones.
1305 foreach my $zone (@network_zones) {
1306 # Check if the current processed zone is red.
1307 if($zone eq "red") {
1308 # Grab the IP-address of the red interface.
1309 my $red_address = &get_red_address
();
1311 # Check if an address has been obtained.
1313 # Generate full network string.
1314 my $red_network = join("/", $red_address, "32");
1316 # Add the red network to the array of networks.
1317 push(@networks, $red_network);
1320 # Check if the configured RED_TYPE is static.
1321 if ($netsettings{'RED_TYPE'} eq "STATIC") {
1322 # Get configured and enabled aliases.
1323 my @aliases = &get_aliases
();
1325 # Loop through the array.
1326 foreach my $alias (@aliases) {
1328 my $network = join("/", $alias, "32");
1330 # Add the generated network to the array of networks.
1331 push(@networks, $network);
1334 # Process remaining network zones.
1336 # Convert current zone name into upper case.
1339 # Generate key to access the required data from the netsettings hash.
1340 my $zone_netaddress = $zone . "_NETADDRESS";
1341 my $zone_netmask = $zone . "_NETMASK";
1343 # Obtain the settings from the netsettings hash.
1344 my $netaddress = $netsettings{$zone_netaddress};
1345 my $netmask = $netsettings{$zone_netmask};
1347 # Convert the subnetmask into prefix notation.
1348 my $prefix = &Network
::convert_netmask2prefix
($netmask);
1350 # Generate full network string.
1351 my $network = join("/", $netaddress,$prefix);
1353 # Check if the network is valid.
1354 if(&Network
::check_subnet
($network)) {
1355 # Add the generated network to the array of networks.
1356 push(@networks, $network);
1361 # Format home net declaration.
1362 my $line = "\"[" . join(',', @networks) . "]\"";
1364 # Open file to store the addresses of the home net.
1365 open(FILE
, ">$homenet_file") or die "Could not open $homenet_file. $!\n";
1367 # Print yaml header.
1368 print FILE
"%YAML 1.1\n";
1369 print FILE
"---\n\n";
1371 # Print notice about autogenerated file.
1372 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1374 # Print the generated and required HOME_NET declaration to the file.
1375 print FILE
"HOME_NET:\t$line\n";
1377 # Close file handle.
1382 # Function to generate and write the file which contains the configured and used DNS servers.
1384 sub generate_dns_servers_file
() {
1385 # Get the used DNS servers.
1386 my @nameservers = &General
::get_nameservers
();
1388 # Get network settings.
1390 &General
::readhash
("${General::swroot}/ethernet/settings", \
%netsettings);
1392 # Format dns servers declaration.
1395 # Check if the system has configured nameservers.
1397 # Add the GREEN address as DNS servers.
1398 push(@nameservers, $netsettings{'GREEN_ADDRESS'});
1400 # Check if a BLUE zone exists.
1401 if ($netsettings{'BLUE_ADDRESS'}) {
1402 # Add the BLUE address to the array of nameservers.
1403 push(@nameservers, $netsettings{'BLUE_ADDRESS'});
1406 # Generate the line which will be written to the DNS servers file.
1407 $line = join(",", @nameservers);
1409 # External net simply contains (any).
1410 $line = "\$EXTERNAL_NET";
1413 # Open file to store the used DNS server addresses.
1414 open(FILE
, ">$dns_servers_file") or die "Could not open $dns_servers_file. $!\n";
1416 # Print yaml header.
1417 print FILE
"%YAML 1.1\n";
1418 print FILE
"---\n\n";
1420 # Print notice about autogenerated file.
1421 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1423 # Print the generated DNS declaration to the file.
1424 print FILE
"DNS_SERVERS:\t\"[$line]\"\n";
1426 # Close file handle.
1431 # Function to generate and write the file which contains the HTTP_PORTS definition.
1433 sub generate_http_ports_file
() {
1436 # Read-in proxy settings
1437 &General
::readhash
("${General::swroot}/proxy/advanced/settings", \
%proxysettings);
1439 # Check if the proxy is enabled.
1440 if (( -e
"${General::swroot}/proxy/enable") || (-e
"${General::swroot}/proxy/enable_blue")) {
1441 # Add the proxy port to the array of HTTP ports.
1442 push(@http_ports, $proxysettings{'PROXY_PORT'});
1445 # Check if the transparent mode of the proxy is enabled.
1446 if ((-e
"${General::swroot}/proxy/transparent") || (-e
"${General::swroot}/proxy/transparent_blue")) {
1447 # Add the transparent proxy port to the array of HTTP ports.
1448 push(@http_ports, $proxysettings{'TRANSPARENT_PORT'});
1451 # Format HTTP_PORTS declaration.
1454 # Generate line which will be written to the http ports file.
1455 $line = join(",", @http_ports);
1457 # Open file to store the HTTP_PORTS.
1458 open(FILE
, ">$http_ports_file") or die "Could not open $http_ports_file. $!\n";
1460 # Print yaml header.
1461 print FILE
"%YAML 1.1\n";
1462 print FILE
"---\n\n";
1464 # Print notice about autogenerated file.
1465 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1467 # Print the generated HTTP_PORTS declaration to the file.
1468 print FILE
"HTTP_PORTS:\t\"[$line]\"\n";
1470 # Close file handle.
1475 ## Function to write the file that contains the rulefiles which are loaded by suricaa.
1477 ## This function requires an array of used provider handles.
1479 sub write_used_rulefiles_file
(@
) {
1480 my (@providers) = @_;
1482 # Get the enabled application layer protocols.
1483 my @enabled_app_layer_protos = &get_suricata_enabled_app_layer_protos
();
1486 open (FILE
, ">", $suricata_used_rulesfiles_file) or die "Could not write to $suricata_used_rulesfiles_file. $!\n";
1488 print FILE
"%YAML 1.1\n";
1489 print FILE
"---\n\n";
1491 # Write notice about autogenerated file.
1492 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1494 # Loop through the array of static included rulesfiles.
1495 foreach my $file (@static_included_rulefiles) {
1496 # Check if the file exists.
1497 if (-f
"$rulespath/$file") {
1498 # Write the rulesfile name to the file.
1499 print FILE
" - $rulespath/$file\n";
1503 print FILE
"\n#Default rules for used application layer protocols.\n";
1504 foreach my $enabled_app_layer_proto (@enabled_app_layer_protos) {
1505 # Check if the current processed app layer proto needs to be translated
1506 # into an application name.
1507 if (exists($tr_app_layer_proto{$enabled_app_layer_proto})) {
1508 # Obtain the translated application name for this protocol.
1509 $enabled_app_layer_proto = $tr_app_layer_proto{$enabled_app_layer_proto};
1512 # Generate filename.
1513 my $rulesfile = "$default_rulespath/$enabled_app_layer_proto\.rules";
1515 # Check if such a file exists.
1516 if (-f
"$rulesfile") {
1517 # Write the rulesfile name to the file.
1518 print FILE
" - $rulesfile\n";
1521 # Generate filename with "events" in filename.
1522 $rulesfile = "$default_rulespath/$enabled_app_layer_proto\-events.rules";
1524 # Check if this file exists.
1525 if (-f
"$rulesfile" ) {
1526 # Write the rulesfile name to the file.
1527 print FILE
" - $rulesfile\n";
1531 # Loop through the array of enabled providers.
1532 foreach my $provider (@providers) {
1533 # Get the used rulefile for this provider.
1534 my @used_rulesfiles = &get_provider_used_rulesfiles
($provider);
1536 # Check if there are
1537 if(@used_rulesfiles) {
1538 # Add notice to the file.
1539 print FILE
"\n#Used Rulesfiles for provider $provider.\n";
1541 # Loop through the array of used rulefiles.
1542 foreach my $enabled_rulesfile (@used_rulesfiles) {
1543 # Generate name and full path to the rulesfile.
1544 my $rulesfile = "$rulespath/$enabled_rulesfile";
1546 # Write the ruelsfile name to the file.
1547 print FILE
" - $rulesfile\n";
1552 # Close the file handle
1557 ## Tiny function to generate the full path and name for the file which stores the used rulefiles of a given provider.
1559 sub get_provider_used_rulesfiles_file
($) {
1560 my ($provider) = @_;
1562 my $filename = "$settingsdir/$provider\-used\-rulesfiles";
1564 # Return the gernerated file.
1569 ## Tiny function to generate the full path and name for the file which stores the modifications of a ruleset.
1571 sub get_provider_ruleset_modifications_file
($) {
1572 my ($provider) = @_;
1574 my $filename = "$settingsdir/$provider\-modifications";
1576 # Return the filename.
1581 ## Function to get the subscription code of a configured provider.
1583 sub get_subscription_code
($) {
1584 my ($provider) = @_;
1586 my %configured_providers = ();
1588 # Read-in providers settings file.
1589 &General
::readhasharray
($providers_settings_file, \
%configured_providers);
1591 # Loop through the hash of configured providers.
1592 foreach my $id (keys %configured_providers) {
1593 # Assign nice human-readable values to the data fields.
1594 my $provider_handle = $configured_providers{$id}[0];
1595 my $subscription_code = $configured_providers{$id}[1];
1597 # Check if the current processed provider is the requested one.
1598 if ($provider_handle eq $provider) {
1599 # Return the obtained subscription code.
1600 return $subscription_code;
1604 # No subscription code found - return nothing.
1609 ## Function to get the ruleset date for a given provider.
1611 ## The function simply return the creation date in a human read-able format
1612 ## of the stored providers rulesfile.
1614 sub get_ruleset_date
($) {
1615 my ($provider) = @_;
1619 # Get the stored rulesfile for this provider.
1620 my $stored_rulesfile = &_get_dl_rulesfile
($provider);
1622 # Check if we got a file.
1623 if (-f
$stored_rulesfile) {
1624 # Call stat on the rulestarball.
1625 my $stat = stat("$stored_rulesfile");
1627 # Get timestamp the file creation.
1628 $mtime = $stat->mtime;
1631 # Check if the timestamp has not been grabbed.
1633 # Return N/A for Not available.
1637 # Convert into human read-able format.
1638 $date = strftime
('%Y-%m-%d %H:%M:%S', localtime($mtime));
1645 ## Function to gather the version of suricata.
1647 sub get_suricata_version
($) {
1650 # Execute piped suricata command and return the version information.
1651 open(SURICATA
, "suricata -V |") or die "Couldn't execute program: $!";
1653 # Grab and store the output of the piped program.
1654 my $version_string = <SURICATA
>;
1660 chomp($version_string);
1662 # Grab the version from the version string.
1663 $version_string =~ /([0-9]+([.][0-9]+)+)/;
1665 # Splitt the version into single chunks.
1666 my ($major_ver, $minor_ver, $patchlevel) = split(/\./, $1);
1668 # Check and return the requested version sheme.
1669 if ($format eq "major") {
1670 # Return the full version.
1671 return "$major_ver";
1672 } elsif ($format eq "minor") {
1673 # Return the major and minor part.
1674 return "$major_ver.$minor_ver";
1676 # Return the full version string.
1677 return "$major_ver.$minor_ver.$patchlevel";
1682 ## Function to get the enabled application layer protocols.
1684 sub get_suricata_enabled_app_layer_protos
() {
1685 # Array to store and return the enabled app layer protos.
1686 my @enabled_app_layer_protos = ();
1688 # Execute piped suricata command and return the list of
1689 # enabled application layer protocols.
1690 open(SURICATA
, "suricata --list-app-layer-protos |") or die "Could not execute program: $!";
1692 # Grab and store the list of enabled application layer protocols.
1693 my @output = <SURICATA
>;
1698 # Merge allways enabled static application layers protocols array.
1699 @enabled_app_layer_protos = @static_enabled_app_layer_protos;
1701 # Loop through the array which contains the output of suricata.
1702 foreach my $line (@output) {
1703 # Skip header line which starts with "===".
1704 next if ($line =~ /^\s*=/);
1706 # Skip info or warning lines.
1707 next if ($line =~ /\s*--/);
1712 # Add enabled app layer proto to the array.
1713 push(@enabled_app_layer_protos, $line);
1717 @enabled_app_layer_protos = sort(@enabled_app_layer_protos);
1720 return @enabled_app_layer_protos;
1724 ## Function to generate the rules file with whitelisted addresses.
1726 sub generate_ignore_file
() {
1729 # SID range 1000000-1999999 Reserved for Local Use
1730 # Put your custom rules in this range to avoid conflicts
1733 # Read-in ignoredfile.
1734 &General
::readhasharray
($IDS::ignored_file
, \
%ignored);
1736 # Open ignorefile for writing.
1737 open(FILE
, ">$IDS::whitelist_file") or die "Could not write to $IDS::whitelist_file. $!\n";
1739 # Config file header.
1740 print FILE
"# Autogenerated file.\n";
1741 print FILE
"# All user modifications will be overwritten.\n\n";
1743 # Add all user defined addresses to the whitelist.
1745 # Check if the hash contains any elements.
1746 if (keys (%ignored)) {
1747 # Loop through the entire hash and write the host/network
1748 # and remark to the ignore file.
1749 while ( (my $key) = each %ignored) {
1750 my $address = $ignored{$key}[0];
1751 my $remark = $ignored{$key}[1];
1752 my $status = $ignored{$key}[2];
1754 # Check if the status of the entry is "enabled".
1755 if ($status eq "enabled") {
1756 # Check if the address/network is valid.
1757 if ((&General
::validip
($address)) || (&General
::validipandmask
($address))) {
1758 # Write rule line to the file to pass any traffic from this IP
1759 print FILE
"pass ip $address any -> any any (msg:\"pass all traffic from/to $address\"\; bypass; sid:$sid\;)\n";
1772 ## Function to set correct ownership for single files and directories.
1775 sub set_ownership
($) {
1778 # User and group of the WUI.
1779 my $uname = "nobody";
1780 my $grname = "nobody";
1782 # The chown function implemented in perl requies the user and group as nummeric id's.
1783 my $uid = getpwnam($uname);
1784 my $gid = getgrnam($grname);
1786 # Check if the given target exists.
1788 # Stop the script and print error message.
1789 die "The $target does not exist. Cannot change the ownership!\n";
1792 # Check weather the target is a file or directory.
1794 # Change ownership ot the single file.
1795 chown($uid, $gid, "$target");
1796 } elsif (-d
$target) {
1797 # Do a directory listing.
1798 opendir(DIR
, $target) or die $!;
1799 # Loop through the direcory.
1800 while (my $file = readdir(DIR
)) {
1802 # We only want files.
1803 next unless (-f
"$target/$file");
1805 # Set correct ownership for the files.
1806 chown($uid, $gid, "$target/$file");
1811 # Change ownership of the directory.
1812 chown($uid, $gid, "$target");
1817 ## Function to read-in the aliases file and returns all configured and enabled aliases.
1820 # Location of the aliases file.
1821 my $aliases_file = "${General::swroot}/ethernet/aliases";
1823 # Array to store the aliases.
1826 # Check if the file is empty.
1827 if (-z
$aliases_file) {
1828 # Abort nothing to do.
1832 # Open the aliases file.
1833 open(ALIASES
, $aliases_file) or die "Could not open $aliases_file. $!\n";
1835 # Loop through the file content.
1836 while (my $line = <ALIASES
>) {
1840 # Splitt line content into single chunks.
1841 my ($address, $state, $remark) = split(/\,/, $line);
1843 # Check if the state of the current processed alias is "on".
1844 if ($state eq "on") {
1845 # Check if the address is valid.
1846 if(&Network
::check_ip_address
($address)) {
1847 # Add the alias to the array of aliases.
1848 push(@aliases, $address);
1853 # Close file handle.
1861 ## Function to grab the current assigned IP-address on red.
1863 sub get_red_address
() {
1864 # File, which contains the current IP-address of the red interface.
1865 my $file = "${General::swroot}/red/local-ipaddress";
1867 # Check if the file exists.
1869 # Open the given file.
1870 open(FILE
, "$file") or die "Could not open $file.";
1872 # Obtain the address from the first line of the file.
1873 my $address = <FILE
>;
1881 # Check if the grabbed address is valid.
1882 if (&General
::validip
($address)) {
1883 # Return the address.
1893 ## Function to get the used rules files of a given provider.
1895 sub get_provider_used_rulesfiles
($) {
1896 my ($provider) = @_;
1898 # Hash to store the used rulefiles of the provider.
1899 my %provider_rulefiles = ();
1901 # Array to store the used rulefiles.
1902 my @used_rulesfiles = ();
1904 # Get the filename which contains the used rulefiles for this provider.
1905 my $used_rulesfiles_file = &get_provider_used_rulesfiles_file
($provider);
1907 # Read-in file, if it exists.
1908 &General
::readhash
("$used_rulesfiles_file", \
%provider_rulefiles) if (-f
$used_rulesfiles_file);
1910 # Loop through the hash of rulefiles which does the provider offer.
1911 foreach my $rulefile (keys %provider_rulefiles) {
1912 # Skip disabled rulefiles.
1913 next unless($provider_rulefiles{$rulefile} eq "enabled");
1915 # The General::readhash function does not allow dots as
1916 # key value and limits the key "string" to the part before
1917 # the dot, in case it contains one.
1919 # So add the file extension for the rules file manually again.
1920 $rulefile = "$rulefile.rules";
1922 # Add the enabled rulefile to the array of enabled rulefiles.
1923 push(@used_rulesfiles, $rulefile);
1926 # Return the array of used rulesfiles.
1927 return @used_rulesfiles;
1931 ## Function to write the lock file for locking the WUI, while
1932 ## the autoupdate script runs.
1934 sub lock_ids_page
() {
1935 # Call subfunction to create the file.
1936 &create_empty_file
($ids_page_lock_file);
1940 ## Function to release the lock of the WUI, again.
1942 sub unlock_ids_page
() {
1944 unlink($ids_page_lock_file);