]> git.ipfire.org Git - people/pmueller/ipfire-2.x.git/blobdiff - config/cfgroot/ids-functions.pl
suricata: Change midstream policy to "pass-flow"
[people/pmueller/ipfire-2.x.git] / config / cfgroot / ids-functions.pl
index 54d86f70f6b0a2ff2c8ef7f85f8d4b0e6e51dc78..3eb883aa94f558b0f9dba83c52adce21ca181f2f 100644 (file)
 # along with IPFire; if not, write to the Free Software                    #
 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA #
 #                                                                          #
-# Copyright (C) 2018 IPFire Team <info@ipfire.org>.                        #
+# Copyright (C) 2018-2019 IPFire Team <info@ipfire.org>                    #
 #                                                                          #
 ############################################################################
 
+use strict;
+
 package IDS;
 
 require '/var/ipfire/general-functions.pl';
+require "${General::swroot}/network-functions.pl";
+require "${General::swroot}/suricata/ruleset-sources";
+
+# Load perl module to deal with Archives.
+use Archive::Peek::Libarchive;
+
+# Load perl module to deal with files and path.
+use File::Basename;
+
+# Load module to move files.
+use File::Copy;
+
+# Load module to recursely remove files and a folder.
+use File::Path qw(rmtree);
+
+# Load module to get file stats.
+use File::stat;
+
+# Load module to deal with temporary files.
+use File::Temp;
+
+# Load module to deal with the date formats used by the HTTP protocol.
+use HTTP::Date;
+
+# Load the libwwwperl User Agent module.
+use LWP::UserAgent;
+
+# Load function from posix module to format time strings.
+use POSIX qw (strftime);
+
+# Load module to talk to the kernel log daemon.
+use Sys::Syslog qw(:DEFAULT setlogsock);
 
 # Location where all config and settings files are stored.
 our $settingsdir = "${General::swroot}/suricata";
 
-# File where the used rulefiles are stored.
-our $used_rulefiles_file = "$settingsdir/suricata-used-rulefiles.yaml";
+# File where the main file for providers ruleset inclusion exists.
+our $suricata_used_rulesfiles_file = "$settingsdir/suricata-used-rulesfiles.yaml";
 
 # File where the addresses of the homenet are stored.
 our $homenet_file = "$settingsdir/suricata-homenet.yaml";
@@ -37,26 +71,24 @@ our $homenet_file = "$settingsdir/suricata-homenet.yaml";
 # File where the addresses of the used DNS servers are stored.
 our $dns_servers_file = "$settingsdir/suricata-dns-servers.yaml";
 
-# File which contains the enabled sids.
-our $enabled_sids_file = "$settingsdir/oinkmaster-enabled-sids.conf";
-
-# File which contains the disabled sids.
-our $disabled_sids_file = "$settingsdir/oinkmaster-disabled-sids.conf";
-
-# File which contains wheater the rules should be changed.
-our $modify_sids_file = "$settingsdir/oinkmaster-modify-sids.conf";
+# File where the HTTP ports definition is stored.
+our $http_ports_file = "$settingsdir/suricata-http-ports.yaml";
 
 # File which stores the configured IPS settings.
 our $ids_settings_file = "$settingsdir/settings";
 
-# File which stores the configured rules-settings.
-our $rules_settings_file = "$settingsdir/rules-settings";
+# File which stores the used and configured ruleset providers.
+our $providers_settings_file = "$settingsdir/providers-settings";
 
 # File which stores the configured settings for whitelisted addresses.
 our $ignored_file = "$settingsdir/ignored";
 
-# Location and name of the tarball which contains the ruleset.
-our $rulestarball = "/var/tmp/idsrules.tar.gz";
+# File which stores HTTP Etags for providers which supports them
+# for cache management.
+our $etags_file = "$settingsdir/etags";
+
+# Location where the downloaded rulesets are stored.
+our $dl_rules_path = "/var/cache/suricata";
 
 # File to store any errors, which also will be read and displayed by the wui.
 our $storederrorfile = "/tmp/ids_storederror";
@@ -67,6 +99,21 @@ our $ids_page_lock_file = "/tmp/ids_page_locked";
 # Location where the rulefiles are stored.
 our $rulespath = "/var/lib/suricata";
 
+# Location where the default rulefils are stored.
+our $default_rulespath = "/usr/share/suricata/rules";
+
+# Location where the addition config files are stored.
+our $configspath = "/usr/share/suricata";
+
+# Location of the classification file.
+our $classification_file = "$configspath/classification.config";
+
+# Location of the sid to msg mappings file.
+our $sid_msg_file = "$rulespath/sid-msg.map";
+
+# Location to store local rules. This file will not be touched.
+our $local_rules_file = "$rulespath/local.rules";
+
 # File which contains the rules to whitelist addresses on suricata.
 our $whitelist_file = "$rulespath/whitelist.rules";
 
@@ -80,34 +127,148 @@ our $idspidfile = "/var/run/suricata.pid";
 # Location of suricatactrl.
 my $suricatactrl = "/usr/local/bin/suricatactrl";
 
+# Prefix for each downloaded ruleset.
+my $dl_rulesfile_prefix = "idsrules";
+
+# Temporary directory to download the rules files.
+my $tmp_dl_directory = "/var/tmp";
+
+# Temporary directory where the rulesets will be extracted.
+my $tmp_directory = "/tmp/ids_tmp";
+
+# Temporary directory where the extracted rules files will be stored.
+my $tmp_rules_directory = "$tmp_directory/rules";
+
+# Temporary directory where the extracted additional config files will be stored.
+my $tmp_conf_directory = "$tmp_directory/conf";
+
 # Array with allowed commands of suricatactrl.
-my @suricatactrl_cmds = ( 'start', 'stop', 'restart', 'reload', 'fix-rules-dir', 'cron' );
+my @suricatactrl_cmds = ( 'start', 'stop', 'restart', 'reload', 'fix-rules-dir' );
+
+# Array which contains the HTTP ports, which statically will be declared as HTTP_PORTS in the
+# http_ports_file.
+my @http_ports = ('80', '81');
+
+# Array which contains a list of rulefiles which always will be included if they exist.
+my @static_included_rulefiles = ('local.rules', 'whitelist.rules');
 
-# Array with supported cron intervals.
-my @cron_intervals = ('off', 'daily', 'weekly' );
+# Array which contains a list of allways enabled application layer protocols.
+my @static_enabled_app_layer_protos = ('app-layer', 'decoder', 'files', 'stream');
+
+# Hash which allows to convert the download type (dl_type) to a file suffix.
+my %dl_type_to_suffix = (
+       "archive" => ".tar.gz",
+       "plain" => ".rules",
+);
+
+# Hash to translate an application layer protocol to the application name.
+my %tr_app_layer_proto = (
+       "ikev2" => "ipsec",
+       "krb5" => "kerberos",
+);
 
 #
 ## Function to check and create all IDS related files, if the does not exist.
 #
 sub check_and_create_filelayout() {
        # Check if the files exist and if not, create them.
-       unless (-f "$enabled_sids_file") { &create_empty_file($enabled_sids_file); }
-       unless (-f "$disabled_sids_file") { &create_empty_file($disabled_sids_file); }
-       unless (-f "$modify_sids_file") { &create_empty_file($modify_sids_file); }
-       unless (-f "$used_rulefiles_file") { &create_empty_file($used_rulefiles_file); }
+       unless (-f "$suricata_used_rulesfiles_file") { &create_empty_file($suricata_used_rulesfiles_file); }
        unless (-f "$ids_settings_file") { &create_empty_file($ids_settings_file); }
-       unless (-f "$rules_settings_file") { &create_empty_file($rules_settings_file); }
-       unless (-f "$ignored_file") { &create_empty_file($ignored_file); }
+       unless (-f "$providers_settings_file") { &create_empty_file($providers_settings_file); }
        unless (-f "$whitelist_file" ) { &create_empty_file($whitelist_file); }
 }
 
+#
+## Function to get a list of all available ruleset providers.
+##
+## They will be returned as a sorted array.
+#
+sub get_ruleset_providers() {
+       my @providers;
+
+       # Loop through the hash of providers.
+       foreach my $provider ( keys %IDS::Ruleset::Providers ) {
+               # Add the provider to the array.
+               push(@providers, $provider);
+       }
+
+       # Sort and return the array.
+       return sort(@providers);
+}
+
+#
+## Function to get a list of all enabled ruleset providers.
+##
+## They will be returned as an array.
+#
+sub get_enabled_providers () {
+       my %used_providers = ();
+
+       # Array to store the enabled providers.
+       my @enabled_providers = ();
+
+       # Read-in the providers config file.
+       &General::readhasharray("$providers_settings_file", \%used_providers);
+
+       # Loop through the hash of used_providers.
+       foreach my $id (keys %used_providers) {
+               # Skip disabled providers.
+               next unless ($used_providers{$id}[3] eq "enabled");
+
+               # Grab the provider handle.
+               my $provider = "$used_providers{$id}[0]";
+
+               # Add the provider to the array of enabled providers.
+               push(@enabled_providers, $provider);
+       }
+
+       # Return the array.
+       return @enabled_providers;
+}
+
+#
+## Function to get a hash of provider handles and their configured modes (IDS/IPS).
+#
+sub get_providers_mode () {
+       my %used_providers = ();
+
+       # Hash to store the providers and their configured modes.
+       my %providers_mode = ();
+
+       # Read-in the providers config file.
+       &General::readhasharray("$providers_settings_file", \%used_providers);
+
+       # Loop through the hash of used_providers.
+       foreach my $id (keys %used_providers) {
+               # Skip disabled providers.
+               next unless ($used_providers{$id}[3] eq "enabled");
+
+               # Grab the provider handle.
+               my $provider = "$used_providers{$id}[0]";
+
+               # Grab the provider mode.
+               my $mode = "$used_providers{$id}[4]";
+
+               # Fall back to IDS if no mode could be obtained.
+               unless($mode) {
+                       $mode = "IDS";
+               }
+
+               # Add details to provider_modes hash.
+               $providers_mode{$provider} = $mode;
+       }
+
+       # Return the hash.
+       return %providers_mode;
+}
+
 #
 ## Function for checking if at least 300MB of free disk space are available
 ## on the "/var" partition.
 #
 sub checkdiskspace () {
        # Call diskfree to gather the free disk space of /var.
-       my @df = `/bin/df -B M /var`;
+       my @df = &General::system_output("/bin/df", "-B", "M", "/var");
 
        # Loop through the output.
        foreach my $line (@df) {
@@ -122,11 +283,8 @@ sub checkdiskspace () {
 
                        # Check if the available disk space is more than 300MB.
                        if ($available < 300) {
-                               # Log error to syslog.
-                               &_log_to_syslog("Not enough free disk space on /var. Only $available MB from 300 MB available.");
-
-                               # Exit function and return "1" - False.
-                               return 1;
+                               # Exit function and return the available disk space.
+                               return $available;
                        }
                }
        }
@@ -136,41 +294,42 @@ sub checkdiskspace () {
 }
 
 #
-## This function is responsible for downloading the configured IDS ruleset.
+## This function is responsible for downloading the ruleset for a given provider.
 ##
-## * At first it obtains from the stored rules settings which ruleset should be downloaded.
-## * The next step is to get the download locations for all available rulesets.
-## * After that, the function will check if an upstream proxy should be used and grab the settings.
-## * The last step will be to generate the final download url, by obtaining the URL for the desired
-##   ruleset, add the settings for the upstream proxy and final grab the rules tarball from the server.
-#
-sub downloadruleset {
-       # Get rules settings.
-       my %rulessettings=();
-       &General::readhash("$rules_settings_file", \%rulessettings);
-
-       # Check if a ruleset has been configured.
-       unless($rulessettings{'RULES'}) {
-               # Log that no ruleset has been configured and abort.
-               &_log_to_syslog("No ruleset source has been configured.");
-
-               # Return "1".
-               return 1;
-       }
+## * At first it initialize the downloader and sets an upstream proxy if configured.
+## * The next step will be to generate the final download url, by obtaining the URL for the desired
+##   ruleset and add the settings for the upstream proxy.
+## * Finally the function will grab the rule file or tarball from the server.
+##   It tries to reduce the amount of download by using the "If-Modified-Since" HTTP header.
+#
+## Return codes:
+##
+## * "no url" - If no download URL could be gathered for the provider.
+## * "not modified" - In case the already stored rules file is up to date.
+## * "incomplete download" - When the remote file size differs from the downloaded file size.
+## * "$error" - The error message generated from the LWP::User Agent module.
+#
+sub downloadruleset ($) {
+       my ($provider) = @_;
 
-       # Get all available ruleset locations.
-       my %rulesetsources=();
-       &General::readhash($rulesetsourcesfile, \%rulesetsources);
+       # The amount of download attempts before giving up and
+       # logging an error.
+       my $max_dl_attempts = 3;
 
        # Read proxysettings.
        my %proxysettings=();
        &General::readhash("${General::swroot}/proxy/settings", \%proxysettings);
 
-       # Load required perl module to handle the download.
-       use LWP::UserAgent;
-
        # Init the download module.
-       my $downloader = LWP::UserAgent->new;
+       #
+       # Request SSL hostname verification and specify path
+       # to the CA file.
+       my $downloader = LWP::UserAgent->new(
+               ssl_opts => {
+                       SSL_ca_file     => '/etc/ssl/cert.pem',
+                       verify_hostname => 1,
+               }
+       );
 
        # Set timeout to 10 seconds.
        $downloader->timeout(10);
@@ -193,83 +352,124 @@ sub downloadruleset {
                $downloader->proxy(['http', 'https'], $proxy_url);
        }
 
-       # Grab the right url based on the configured vendor.
-       my $url = $rulesetsources{$rulessettings{'RULES'}};
+       # Grab the download url for the provider.
+       my $url = $IDS::Ruleset::Providers{$provider}{'dl_url'};
 
-       # Check if the vendor requires an oinkcode and add it if needed.
-       $url =~ s/\<oinkcode\>/$rulessettings{'OINKCODE'}/g;
+       # Check if the provider requires a subscription.
+       if ($IDS::Ruleset::Providers{$provider}{'requires_subscription'} eq "True") {
+               # Grab the subscription code.
+               my $subscription_code = &get_subscription_code($provider);
+
+               # Add the subscription code to the download url.
+               $url =~ s/\<subscription_code\>/$subscription_code/g;
 
-       # Abort if no url could be determined for the vendor.
-       unless ($url) {
-               # Log error and abort.
-               &_log_to_syslog("Unable to gather a download URL for the selected ruleset.");
-               return 1;
        }
 
-       # Variable to store the filesize of the remote object.
-       my $remote_filesize;
+       # Abort and return "no url", if no url could be determined for the provider.
+       return "no url" unless ($url);
 
-       # The sourcfire (snort rules) does not allow to send "HEAD" requests, so skip this check
-       # for this webserver.
-       #
-       # Check if the ruleset source contains "snort.org".
-       unless ($url =~ /\.snort\.org/) {
-               # Pass the requrested url to the downloader.
-               my $request = HTTP::Request->new(HEAD => $url);
+       # Pass the requested URL to the downloader.
+       my $request = HTTP::Request->new(GET => $url);
 
-               # Accept the html header.
-               $request->header('Accept' => 'text/html');
+       # Generate temporary file name, located in the tempoary download directory and with a suffix of ".tmp".
+       # The downloaded file will be stored there until some sanity checks are performed.
+       my $tmp = File::Temp->new( SUFFIX => ".tmp", DIR => "$tmp_dl_directory/", UNLINK => 0 );
+       my $tmpfile = $tmp->filename();
 
-               # Perform the request and fetch the html header.
-               my $response = $downloader->request($request);
+       # Call function to get the final path and filename for the downloaded file.
+       my $dl_rulesfile = &_get_dl_rulesfile($provider);
 
-               # Check if there was any error.
-               unless ($response->is_success) {
-                       # Obtain error.
-                       my $error = $response->status_line();
+       # Check if the rulesfile already exits, because it has been downloaded in the past.
+       #
+       # In this case we are requesting the server if the remote file has been changed or not.
+       # This will be done by sending the modification time in a special HTTP header.
+       if (-f $dl_rulesfile) {
+               # Call stat on the file.
+               my $stat = stat($dl_rulesfile);
 
-                       # Log error message.
-                       &_log_to_syslog("Unable to download the ruleset. \($error\)");
+               # Omit the mtime of the existing file.
+               my $mtime = $stat->mtime;
 
-                       # Return "1" - false.
-                       return 1;
-               }
+               # Convert the timestamp into right format.
+               my $http_date = time2str($mtime);
 
-               # Assign the fetched header object.
-               my $header = $response->headers();
+               # Add the If-Modified-Since header to the request to ask the server if the
+               # file has been modified.
+               $request->header( 'If-Modified-Since' => "$http_date" );
+       }
 
-               # Grab the remote file size from the object and store it in the
-               # variable.
-               $remote_filesize = $header->content_length;
+       # Read-in Etags file for known Etags if the file is present.
+       my %etags = ();
+       &General::readhash("$etags_file", \%etags) if (-f $etags_file);
+
+       # Check if an Etag for the current provider is stored.
+       if ($etags{$provider}) {
+               # Grab the stored tag.
+               my $etag = $etags{$provider};
+
+               # Add an "If-None-Match header to the request to ask the server if the
+               # file has been modified.
+               $request->header( 'If-None-Match' => $etag );
        }
 
-       # Load perl module to deal with temporary files.
-       use File::Temp;
+       my $dl_attempt = 1;
+       my $response;
 
-       # Generate temporary file name, located in "/var/tmp" and with a suffix of ".tar.gz".
-       my $tmp = File::Temp->new( SUFFIX => ".tar.gz", DIR => "/var/tmp/", UNLINK => 0 );
-       my $tmpfile = $tmp->filename();
+       # Download and retry on failure.
+       while ($dl_attempt <= $max_dl_attempts) {
+               # Perform the request and save the output into the tmpfile.
+               $response = $downloader->request($request, $tmpfile);
 
-       # Pass the requested url to the downloader.
-       my $request = HTTP::Request->new(GET => $url);
+               # Check if the download was successfull.
+               if($response->is_success) {
+                       # Break loop.
+                       last;
 
-       # Perform the request and save the output into the tmpfile.
-       my $response = $downloader->request($request, $tmpfile);
+               # Check if the server responds with 304 (Not Modified).
+               } elsif ($response->code == 304) {
+                       # Remove temporary file, if one exists.
+                       unlink("$tmpfile") if (-e "$tmpfile");
 
-       # Check if there was any error.
-       unless ($response->is_success) {
-               # Obtain error.
-               my $error = $response->content;
+                       # Return "not modified".
+                       return "not modified";
 
-               # Log error message.
-               &_log_to_syslog("Unable to download the ruleset. \($error\)");
+               # Check if we ran out of download re-tries.
+               } elsif ($dl_attempt eq $max_dl_attempts) {
+                       # Obtain error.
+                       my $error = $response->content;
 
-               # Return "1" - false.
-               return 1;
+                       # Remove temporary file, if one exists.
+                       unlink("$tmpfile") if (-e "$tmpfile");
+
+                       # Return the error message from response..
+                       return "$error";
+               }
+
+               # Remove temporary file, if one exists.
+               unlink("$tmpfile") if (-e "$tmpfile");
+
+               # Increase download attempt counter.
+               $dl_attempt++;
        }
 
-       # Load perl stat module.
-       use File::stat;
+       # Obtain the connection headers.
+       my $headers = $response->headers;
+
+       # Get the timestamp from header, when the file has been modified the
+       # last time.
+       my $last_modified = $headers->last_modified;
+
+       # Get the remote size of the downloaded file.
+       my $remote_filesize = $headers->content_length;
+
+       # Grab the Etag from response it the server provides one.
+       if ($response->header('Etag')) {
+               # Add the Etag to the etags hash.
+               $etags{$provider} = $response->header('Etag');
+
+               # Write the etags file.
+               &General::writehash($etags_file, \%etags);
+       }
 
        # Perform stat on the tmpfile.
        my $stat = stat($tmpfile);
@@ -279,64 +479,468 @@ sub downloadruleset {
 
        # Check if both file sizes match.
        if (($remote_filesize) && ($remote_filesize ne $local_filesize)) {
-               # Log error message.
-               &_log_to_syslog("Unable to completely download the ruleset. ");
-               &_log_to_syslog("Only got $local_filesize Bytes instead of $remote_filesize Bytes. ");
-
                # Delete temporary file.
                unlink("$tmpfile");
 
                # Return "1" - false.
-               return 1;
+               return "incomplete download";
        }
 
-       # Load file copy module, which contains the move() function.
-       use File::Copy;
+       # Overwrite the may existing rulefile or tarball with the downloaded one.
+       move("$tmpfile", "$dl_rulesfile");
 
-       # Overwrite existing rules tarball with the new downloaded one.
-       move("$tmpfile", "$rulestarball");
+       # Check if we got a last-modified value from the server.
+       if ($last_modified) {
+               # Assign the last-modified timestamp as mtime to the
+               # rules file.
+               utime(time(), "$last_modified", "$dl_rulesfile");
+       }
+
+       # Delete temporary file.
+       unlink("$tmpfile");
 
-       # Set correct ownership for the rulesdir and files.
-       set_ownership("$rulestarball");
+       # Set correct ownership for the tarball.
+       set_ownership("$dl_rulesfile");
 
        # If we got here, everything worked fine. Return nothing.
        return;
 }
 
 #
-## A tiny wrapper function to call the oinkmaster script.
+## Function to extract a given ruleset.
+##
+## In case the ruleset provider offers a plain file, it simply will
+## be copied.
+#
+sub extractruleset ($) {
+       my ($provider) = @_;
+
+       # Get full path and downloaded rulesfile for the given provider.
+       my $tarball = &_get_dl_rulesfile($provider);
+
+       # Check if the file exists.
+       unless (-f $tarball) {
+               &_log_to_syslog("Could not find ruleset file: $tarball");
+
+               # Return nothing.
+               return;
+       }
+
+       # Check if the temporary directories exist, otherwise create them.
+       mkdir("$tmp_directory") unless (-d "$tmp_directory");
+       mkdir("$tmp_rules_directory") unless (-d "$tmp_rules_directory");
+       mkdir("$tmp_conf_directory") unless (-d "$tmp_conf_directory");
+
+       # Omit the type (dl_type) of the stored ruleset.
+       my $type = $IDS::Ruleset::Providers{$provider}{'dl_type'};
+
+       # Handle the different ruleset types.
+       if ($type eq "plain") {
+               # Generate destination filename an full path.
+               my $destination = "$tmp_rules_directory/$provider\-ruleset.rules";
+
+               # Copy the file into the temporary rules directory.
+               copy($tarball, $destination);
+
+       } elsif ( $type eq "archive") {
+               # Initialize the tar module.
+               my $tar = Archive::Peek::Libarchive->new(filename => $tarball);
+
+               # Loop through the archive
+               $tar->iterate( sub {
+                       my ($packed_file, $content) = @_;
+                       my $destination;
+
+                       # Splitt the packed file into chunks.
+                       my $file = fileparse($packed_file);
+
+                       # Handle msg-id.map file.
+                       if ("$file" eq "sid-msg.map") {
+                               # Set extract destination to temporary config_dir.
+                               $destination = "$tmp_conf_directory/$provider\-sid-msg.map";
+
+                       # Handle classification.conf
+                       } elsif ("$file" eq "classification.config") {
+                               # Set extract destination to temporary config_dir.
+                               $destination = "$tmp_conf_directory/$provider\-classification.config";
+
+                       # Handle rules files.
+                       } elsif ($file =~ m/\.rules$/) {
+                               # Skip rule files which are not located in the rules directory or archive root.
+                               return unless(($packed_file =~ /^rules\//) || ($packed_file =~ /^$provider-rules\//) || ($packed_file !~ /\//));
+
+                               # Skip deleted.rules.
+                               #
+                               # Mostly they have been taken out for correctness or performance reasons and therfore
+                               # it is not a great idea to enable any of them.
+                               return if($file =~ m/deleted.rules$/);
+
+                               my $rulesfilename;
+
+                               # Splitt the filename into chunks.
+                               my @filename = split("-", $file);
+
+                               # Reverse the array.
+                               @filename = reverse(@filename);
+
+                               # Get the amount of elements in the array.
+                               my $elements = @filename;
+
+                               # Remove last element of the hash.
+                               # It contains the vendor name, which will be replaced.
+                               if ($elements >= 3) {
+                               # Remove last element from hash.
+                                       pop(@filename);
+                               }
+
+                               # Check if the last element of the filename does not
+                               # contain the providers name.
+                               if ($filename[-1] ne "$provider") {
+                                       # Add provider name as last element.
+                                       push(@filename, $provider);
+                               }
+
+                               # Reverse the array back.
+                               @filename = reverse(@filename);
+
+                               # Generate the name for the rulesfile.
+                               $rulesfilename = join("-", @filename);
+
+                               # Set extract destination to temporaray rules_dir.
+                               $destination = "$tmp_rules_directory/$rulesfilename";
+                       } else {
+                               # Skip all other files.
+                               return;
+                       }
+
+                       # Check if the destination file exists.
+                       unless(-e "$destination") {
+                               # Open filehandle to write the content to a new file.
+                               open(FILE, ">", "$destination") or die "Could not open $destination. $!\n";
+                       } else {
+                               # Open filehandle to append the content to the existing file.
+                               open(FILE, ">>", "$destination") or die "Could not open $destination. $!\n";
+                       }
+
+                       # Write the extracted file content to the filehandle.
+                       print FILE "$content" if ($content);
+
+                       # Close the file handle.
+                       close(FILE);
+               });
+       }
+}
+
+#
+## A wrapper function to call the oinkmaster script, setup the rules structues and
+## call the functions to merge the additional config files. (classification, sid-msg, etc.).
 #
 sub oinkmaster () {
        # Check if the files in rulesdir have the correct permissions.
        &_check_rulesdir_permissions();
 
-       # Cleanup the rules directory before filling it with the new rulest.
+       # Cleanup the rules directory before filling it with the new rulests.
        &_cleanup_rulesdir();
 
-       # Load perl module to talk to the kernel syslog.
-       use Sys::Syslog qw(:DEFAULT setlogsock);
+       # Get all enabled providers.
+       my @enabled_providers = &get_enabled_providers();
 
-       # Establish the connection to the syslog service.
-       openlog('oinkmaster', 'cons,pid', 'user');
+       # Loop through the array of enabled providers.
+       foreach my $provider (@enabled_providers) {
+               # Call the extractruleset function.
+               &extractruleset($provider);
+       }
+
+       # Call function to process the ruleset and do all modifications.
+       &process_ruleset(@enabled_providers);
+
+       # Call function to merge the classification files.
+       &merge_classifications(@enabled_providers);
+
+       # Call function to merge the sid to message mapping files.
+       &merge_sid_msg(@enabled_providers);
+
+       # Cleanup temporary directory.
+       &cleanup_tmp_directory();
+}
+
+#
+## Function to alter the ruleset.
+#
+sub process_ruleset(@) {
+       my (@providers) = @_;
+
+       # Hash to store the configured provider modes.
+       my %providers_mode = &get_providers_mode();
+
+       # Array to store the extracted rulefile from the temporary rules directory.
+       my @extracted_rulefiles;
 
-       # Call oinkmaster to generate ruleset.
-       open(OINKMASTER, "/usr/local/bin/oinkmaster.pl -s -u file://$rulestarball -C $settingsdir/oinkmaster.conf -o $rulespath 2>&1 |") or die "Could not execute oinkmaster $!\n";
+       # Get names of the extracted raw rulefiles.
+       opendir(DIR, $tmp_rules_directory) or die "Could not read from $tmp_rules_directory. $!\n";
+       while (my $file = readdir(DIR)) {
+               # Ignore single and double dotted files.
+               next if $file =~ /^\.\.?$/;
+
+               # Add file to the array of extracted files.
+               push(@extracted_rulefiles, $file);
+       }
+
+       # Close directory handle.
+       closedir(DIR);
+
+       # Loop through the array of providers.
+       foreach my $provider (@providers) {
+               # Hash to store the obtained SIDs and REV of each provider.
+               my %rules = ();
+
+               # Hash which holds modifications to apply to the rules.
+               my %modifications = ();
+
+               # Loop through the array of extraced rulefiles.
+               foreach my $file (@extracted_rulefiles) {
+                       # Skip file if it does not belong to the current processed provider.
+                       next unless ($file =~ m/^$provider/);
+
+                       # Open the rulefile.
+                       open(FILE, "$tmp_rules_directory/$file") or die "Could not read $tmp_rules_directory/$file. $!\n";
+
+                       # Loop through the file content.
+                       while (my $line = <FILE>) {
+                               # Skip blank  lines.
+                               next if ($line =~ /^\s*$/);
+
+                               # Call function to get the sid and rev of the rule.
+                               my ($sid, $rev) = &_get_sid_and_rev($line);
+
+                               # Skip rule if a sid with a higher rev already has added to the rules hash.
+                               next if ($rev le $rules{$sid});
+
+                               # Add the new or rule with higher rev to the hash of rules.
+                               $rules{$sid} = $rev;
+                       }
 
-       # Log output of oinkmaster to syslog.
-       while(<OINKMASTER>) {
-               # The syslog function works best with an array based input,
-               # so generate one before passing the message details to syslog.
-               my @syslog = ("INFO", "$_");
+                       # Close file handle.
+                       close(FILE);
+               }
+
+               # Get filename which contains the ruleset modifications for this provider.
+               my $modification_file = &get_provider_ruleset_modifications_file($provider);
+
+               # Read file which holds the modifications of the ruleset for the current provider.
+               &General::readhash($modification_file, \%modifications) if (-f $modification_file);
+
+               # Loop again through the array of extracted rulesfiles.
+               foreach my $file (@extracted_rulefiles) {
+                       # Skip the file if it does not belong to the current provider.
+                       next unless ($file =~ m/^$provider/);
+
+                       # Open the rulefile for writing.
+                       open(RULEFILE, ">", "$rulespath/$file") or die "Could not write to file $rulespath/$file. $!\n";
+
+                       # Open the rulefile for reading.
+                       open(TMP_RULEFILE, "$tmp_rules_directory/$file") or die "Could not read $tmp_rules_directory/$file. $!\n";
+
+                       # Loop through the raw temporary rulefile.
+                       while (my $line = <TMP_RULEFILE>) {
+                               # Get the sid and rev of the rule.
+                               my ($sid, $rev) = &_get_sid_and_rev($line);
+
+                               # Check if the current rule is obsoleted by a newer one.
+                               #
+                               # In this case the rev number in the rules hash is higher than the current one.
+                               next if ($rev lt $rules{$sid});
+
+                               # Check if the rule should be enabled or disabled.
+                               if ($modifications{$sid} eq "enabled") {
+                                       # Drop the # at the start of the line.
+                                       $line =~ s/^\#//;
+                               } elsif ($modifications{$sid} eq "disabled") {
+                                       # Add a # at the start of the line to disable the rule.
+                                       $line = "#$line" unless ($line =~ /^#/);
+                               }
+
+                               # Check if the Provider is set so IPS mode.
+                               if ($providers_mode{$provider} eq "IPS") {
+                                       # Replacements for sourcefire rules.
+                                       $line =~ s/^#\s*(?:alert|drop)(.+policy balanced-ips alert)/alert${1}/;
+                                       $line =~ s/^#\s*(?:alert|drop)(.+policy balanced-ips drop)/drop${1}/;
+
+                                       # Replacements for generic rules.
+                                       $line =~ s/^(#?)\s*(?:alert|drop)/${1}drop/;
+                                       $line =~ s/^(#?)\s*drop(.+flowbits:noalert;)/${1}alert${2}/;
+                               }
 
-               # Send the log message.
-               syslog(@syslog);
+                               # Write line / rule to the target rule file.
+                               print RULEFILE "$line";
+                       }
+
+                       # Close filehandles.
+                       close(RULEFILE);
+                       close(TMP_RULEFILE);
+               }
        }
+}
 
-       # Close the pipe to oinkmaster process.
-       close(OINKMASTER);
+#
+## Function to merge the classifications for a given amount of providers and write them
+## to the classifications file.
+#
+sub merge_classifications(@) {
+       my @providers = @_;
+
+       # Hash to store all collected classifications.
+       my %classifications = ();
+
+       # Loop through the given array of providers.
+       foreach my $provider (@providers) {
+               # Generate full path to classification file.
+               my $classification_file = "$tmp_conf_directory/$provider\-classification.config";
+
+               # Skip provider if no classification file exists.
+               next unless (-f "$classification_file");
+
+               # Open the classification file.
+               open(CLASSIFICATION, $classification_file) or die "Could not open file $classification_file. $!\n";
+
+               # Loop through the file content.
+               while(<CLASSIFICATION>) {
+                       # Parse the file and grab the classification details.
+                       if ($_ =~/.*config classification\: (.*)/) {
+                               # Split the grabbed details.
+                               my ($short_name, $short_desc, $priority) = split("\,", $1);
+
+                               # Check if the grabbed classification is allready known and the priority value is greater
+                               # than the stored one (which causes less priority in the IDS).
+                               if (($classifications{$short_name}) && ($classifications{$short_name}[1] >= $priority)) {
+                                       #Change the priority value to the stricter one.
+                                       $classifications{$short_name} = [ "$classifications{$short_name}[0]", "$priority" ];
+                               } else {
+                                       # Add the classification to the hash.
+                                       $classifications{$short_name} = [ "$short_desc", "$priority" ];
+                               }
+                       }
+               }
 
-       # Close the log handle.
-       closelog();
+               # Close the file.
+               close(CLASSIFICATION);
+       }
+
+       # Open classification file for writing.
+       open(FILE, ">", "$classification_file") or die "Could not write to $classification_file. $!\n";
+
+       # Print notice about autogenerated file.
+       print FILE "#Autogenerated file. Any custom changes will be overwritten!\n\n";
+
+       # Sort and loop through the hash of classifications.
+       foreach my $key (sort keys %classifications) {
+               # Assign some nice variable names for the items.
+               my $short_name = $key;
+               my $short_desc = $classifications{$key}[0];
+               my $priority = $classifications{$key}[1];
+
+               # Write the classification to the file.
+               print FILE "config classification: $short_name,$short_desc,$priority\n";
+       }
+
+       # Close file handle.
+       close(FILE);
+}
+
+#
+## Function to merge the "sid to message mapping" files of various given providers.
+#
+sub merge_sid_msg (@) {
+       my @providers = @_;
+
+       # Hash which contains all the sid to message mappings.
+       my %mappings = ();
+
+       # Loop through the array of given providers.
+       foreach my $provider (@providers) {
+               # Generate full path and filename.
+               my $sid_msg_file = "$tmp_conf_directory/$provider\-sid-msg.map";
+
+               # Skip provider if no sid to msg mapping file for this provider exists.
+               next unless (-f $sid_msg_file);
+
+               # Open the file.
+               open(MAPPING, $sid_msg_file) or die "Could not open $sid_msg_file. $!\n";
+
+               # Loop through the file content.
+               while (<MAPPING>) {
+                       # Remove newlines.
+                       chomp($_);
+
+                       # Skip lines which do not start with a number,
+                       next unless ($_ =~ /^\d+/);
+
+                       # Split line content and assign it to an array.
+                       my @line = split(/ \|\| /, $_);
+
+                       # Grab the first element (and remove it) from the line array.
+                       # It contains the sid.
+                       my $sid = shift(@line);
+
+                       # Store the grabbed sid and the remain array as hash value.
+                       # It still contains the messages, references etc.
+                       $mappings{$sid} = [@line];
+               }
+
+               # Close file handle.
+               close(MAPPING);
+       }
+
+       # Open mappings file for writing.
+       open(FILE, ">", $sid_msg_file) or die "Could not write $sid_msg_file. $!\n";
+
+       # Write notice about autogenerated file.
+       print FILE "#Autogenerated file. Any custom changes will be overwritten!\n\n";
+
+       # Loop through the hash of mappings.
+       foreach my $sid ( sort keys %mappings) {
+               # Grab data for the sid.
+               my @data = @{$mappings{$sid}};
+
+               # Add the sid to the data array.
+               unshift(@data, $sid);
+
+               # Generate line.
+               my $line = join(" \|\| ", @data);
+
+               print FILE "$line\n";
+
+       }
+
+       # Close file handle.
+       close(FILE);
+}
+
+#
+## A very tiny function to move an extracted ruleset from the temporary directory into
+## the rules directory.
+#
+sub move_tmp_ruleset() {
+       # Do a directory listing of the temporary directory.
+       opendir  DH, $tmp_rules_directory;
+
+       # Loop over all files.
+       while(my $file = readdir DH) {
+               # Move them to the rules directory.
+               move "$tmp_rules_directory/$file" , "$rulespath/$file";
+       }
+
+       # Close directory handle.
+       closedir DH;
+}
+
+#
+## Function to cleanup the temporary IDS directroy.
+#
+sub cleanup_tmp_directory () {
+
+       # Delete temporary directory and all containing files.
+       rmtree([ "$tmp_directory" ]);
 }
 
 #
@@ -361,9 +965,6 @@ sub log_error ($) {
 sub _log_to_syslog ($) {
        my ($message) = @_;
 
-       # Load perl module to talk to the kernel syslog.
-       use Sys::Syslog qw(:DEFAULT setlogsock);
-
        # The syslog function works best with an array based input,
        # so generate one before passing the message details to syslog.
        my @syslog = ("ERR", "<ERROR> $message");
@@ -401,39 +1002,92 @@ sub _store_error_message ($) {
 }
 
 #
-## Function to get a list of all available network zones.
+## Private function to get the path and filename for a downloaded ruleset by a given provider.
 #
-sub get_available_network_zones () {
-       # Get netsettings.
-       my %netsettings = ();
-       &General::readhash("${General::swroot}/ethernet/settings", \%netsettings);
+sub _get_dl_rulesfile($) {
+       my ($provider) = @_;
 
-       # Obtain the configuration type from the netsettings hash.
-       my $config_type = $netsettings{'CONFIG_TYPE'};
+       # Abort if the requested provider is not known.
+       return unless($IDS::Ruleset::Providers{$provider});
 
-       # Hash which contains the conversation from the config mode
-       # to the existing network interface names. They are stored like
-       # an array.
-       #
-       # Mode "0" red is a modem and green
-       # Mode "1" red is a netdev and green
-       # Mode "2" red, green and orange
-       # Mode "3" red, green and blue
-       # Mode "4" red, green, blue, orange
-       my %config_type_to_interfaces = (
-               "0" => [ "red", "green" ],
-               "1" => [ "red", "green" ],
-               "2" => [ "red", "green", "orange" ],
-               "3" => [ "red", "green", "blue" ],
-               "4" => [ "red", "green", "blue", "orange" ]
-       );
+       # Try to gather the download type for the given provider.
+       my $dl_type = $IDS::Ruleset::Providers{$provider}{'dl_type'};
+
+       # Check if a download type could be grabbed.
+       if ($dl_type) {
+               # Obtain the file suffix for the download file type.
+               my $suffix = $dl_type_to_suffix{$dl_type};
+
+               # Check if a suffix has been found.
+               unless ($suffix) {
+                       # Abort return - nothing.
+                       return;
+               }
+
+               # Generate the full filename and path for the stored rules file.
+               my $rulesfile = "$dl_rules_path/$dl_rulesfile_prefix-$provider$suffix";
+
+               # Return the generated filename.
+               return $rulesfile;
+
+       } else {
+               # A downloaded ruleset for a provider which is not supported anymore is requested.
+               #
+               # Try to enumerate the downloaded ruleset file.
+               foreach my $dl_type (keys %dl_type_to_suffix) {
+                       # Get the file suffix for the supported type.
+                       my $suffix = $dl_type_to_suffix{$dl_type};
+
+                       # Generate possible ruleset file name.
+                       my $rulesfile = "$dl_rules_path/$dl_rulesfile_prefix-$provider$suffix";
+
+                       # Check if such a file exists.
+                       if (-f $rulesfile) {
+                               # Downloaded rulesfile found - Return the filename.
+                               return $rulesfile;
+                       }
+               }
+       }
+
+       # If we got here, no rulesfile could be determined - return nothing.
+       return;
+}
+
+#
+## Private function to obtain the sid and rev of a rule.
+#
+## Returns an array with the sid as first and the rev as second value.
+#
+sub _get_sid_and_rev ($) {
+       my ($line) = @_;
+
+       my @ret;
+
+       # Use regex to obtain the sid and rev.
+       if ($line =~ m/.*sid:\s*(.*?);.*rev:\s*(.*?);/) {
+               # Add the sid and rev to the array.
+               push(@ret, $1);
+               push(@ret, $2);
+       }
+
+       # Return the array.
+       return @ret;
+}
+
+#
+## Tiny function to delete the stored ruleset file or tarball for a given provider.
+#
+sub drop_dl_rulesfile ($) {
+       my ($provider) = @_;
 
-       # Obtain and dereference the corresponding network interaces based on the read
-       # network config type.
-       my @network_zones = @{ $config_type_to_interfaces{$config_type} };
+       # Gather the full path and name of the stored rulesfile.
+       my $rulesfile = &_get_dl_rulesfile($provider);
 
-       # Return them.
-       return @network_zones;
+       # Check if the given rulesfile exists.
+       if (-f $rulesfile) {
+               # Delete the stored rulesfile.
+               unlink($rulesfile) or die "Could not delete $rulesfile. $!\n";
+       }
 }
 
 #
@@ -477,34 +1131,12 @@ sub call_suricatactrl ($) {
                # Skip current command unless the given one has been found.
                next unless($cmd eq $option);
 
-               # Check if the given command is "cron".
-               if ($option eq "cron") {
-                       # Check if an interval has been given.
-                       if ($interval) {
-                               # Check if the given interval is valid.
-                               foreach my $element (@cron_intervals) {
-                                       # Skip current element until the given one has been found.
-                                       next unless($element eq $interval);
-
-                                       # Call the suricatactrl binary and pass the "cron" command
-                                       # with the requrested interval.
-                                       system("$suricatactrl $option $interval &>/dev/null");
-
-                                       # Return "1" - True.
-                                       return 1;
-                               }
-                       }
-
-                       # If we got here, the given interval is not supported or none has been given. - Return nothing.
-                       return;
-               } else {
-                       # Call the suricatactrl binary and pass the requrested
-                       # option to it.
-                       system("$suricatactrl $option &>/dev/null");
+               # Call the suricatactrl binary and pass the requrested
+               # option to it.
+               &General::system("$suricatactrl", "$option");
 
-                       # Return "1" - True.
-                       return 1;
-               }
+               # Return "1" - True.
+               return 1;
        }
 
        # Command not found - return nothing.
@@ -575,12 +1207,12 @@ sub _cleanup_rulesdir() {
                # We only want files.
                next unless (-f "$rulespath/$file");
 
-               # Skip element if it has config as file extension.
-               next if ($file =~ m/\.config$/);
-
                # Skip rules file for whitelisted hosts.
                next if ("$rulespath/$file" eq $whitelist_file);
 
+               # Skip rules file with local rules.
+               next if ("$rulespath/$file" eq $local_rules_file);
+
                # Delete the current processed file, if not, exit this function
                # and return an error message.
                unlink("$rulespath/$file") or return "Could not delete $rulespath/$file. $!\n";
@@ -600,7 +1232,7 @@ sub generate_home_net_file() {
        &General::readhash("${General::swroot}/ethernet/settings", \%netsettings);
 
        # Get available network zones.
-       my @network_zones = &get_available_network_zones();
+       my @network_zones = &Network::get_available_network_zones();
 
        # Temporary array to store network address and prefix of the configured
        # networks.
@@ -664,22 +1296,7 @@ sub generate_home_net_file() {
        }
 
        # Format home net declaration.
-       my $line = "\"\[";
-
-       # Loop through the array of networks.
-       foreach my $network (@networks) {
-               # Add the network to the line.
-               $line = "$line" . "$network";
-
-               # Check if the current network was the last in the array.
-               if ($network eq $networks[-1]) {
-                       # Close the line.
-                       $line = "$line" . "\]\"";
-               } else {
-                       # Add "," for the next network.
-                       $line = "$line" . "\,";
-               }
-       }
+       my $line = "\"[" . join(',', @networks) . "]\"";
 
        # Open file to store the addresses of the home net.
        open(FILE, ">$homenet_file") or die "Could not open $homenet_file. $!\n";
@@ -702,43 +1319,33 @@ sub generate_home_net_file() {
 # Function to generate and write the file which contains the configured and used DNS servers.
 #
 sub generate_dns_servers_file() {
-       # Open file which contains the current used DNS configuration.
-       open (FILE, "${General::swroot}/red/dns") or die "Could not read DNS configuration from ${General::swroot}/red/dns. $!\n";
-
-       # Read-in whole file content and store it in a temporary array.
-       my @file_content = <FILE>;
+       # Get the used DNS servers.
+       my @nameservers = &General::get_nameservers();
 
-       # Close file handle.
-       close(FILE);
+       # Get network settings.
+       my %netsettings;
+       &General::readhash("${General::swroot}/ethernet/settings", \%netsettings);
 
        # Format dns servers declaration.
-       my $line = "\"\[";
+       my $line = "";
 
-       # Loop through the array which contains the file content.
-       foreach my $server (@file_content) {
-               # Remove newlines.
-               chomp($server);
-
-               # Check if the current DNS configuration is using the local recursor mode.
-               if ($server eq "local recursor") {
-                       # The responsible DNS servers on red are directly used, and because we are not able
-                       # to specify each single DNS server address here, we currently have to thread each
-                       # address which is not part of the HOME_NET as possible DNS server.
-                       $line = "$line" . "!\$HOME_NET";
-               } else {
-                       # Add the DNS server to the line.
-                       $line = "$line" . "$server";
+       # Check if the system has configured nameservers.
+       if (@nameservers) {
+               # Add the GREEN address as DNS servers.
+               push(@nameservers, $netsettings{'GREEN_ADDRESS'});
+
+               # Check if a BLUE zone exists.
+               if ($netsettings{'BLUE_ADDRESS'}) {
+                       # Add the BLUE address to the array of nameservers.
+                       push(@nameservers, $netsettings{'BLUE_ADDRESS'});
                }
 
-                # Check if the current DNS server was the last in the array.
-                if ($server eq $file_content[-1]) {
-                        # Close the line.
-                        $line = "$line" . "\]\"";
-                } else {
-                        # Add "," for the next DNS server.
-                        $line = "$line" . "\,";
-                }
-        }
+               # Generate the line which will be written to the DNS servers file.
+               $line = join(",", @nameservers);
+       } else {
+               # External net simply contains (any).
+               $line = "\$EXTERNAL_NET";
+       }
 
        # Open file to store the used DNS server addresses.
        open(FILE, ">$dns_servers_file") or die "Could not open $dns_servers_file. $!\n";
@@ -751,101 +1358,227 @@ sub generate_dns_servers_file() {
        print FILE "#Autogenerated file. Any custom changes will be overwritten!\n";
 
        # Print the generated DNS declaration to the file.
-       print FILE "DNS_SERVERS:\t$line\n";
+       print FILE "DNS_SERVERS:\t\"[$line]\"\n";
+
+       # Close file handle.
+       close(FILE);
+}
+
+#
+# Function to generate and write the file which contains the HTTP_PORTS definition.
+#
+sub generate_http_ports_file() {
+       my %proxysettings;
+
+       # Read-in proxy settings
+       &General::readhash("${General::swroot}/proxy/advanced/settings", \%proxysettings);
+
+       # Check if the proxy is enabled.
+       if (( -e "${General::swroot}/proxy/enable") || (-e "${General::swroot}/proxy/enable_blue")) {
+               # Add the proxy port to the array of HTTP ports.
+               push(@http_ports, $proxysettings{'PROXY_PORT'});
+       }
+
+       # Check if the transparent mode of the proxy is enabled.
+       if ((-e "${General::swroot}/proxy/transparent") || (-e "${General::swroot}/proxy/transparent_blue")) {
+               # Add the transparent proxy port to the array of HTTP ports.
+               push(@http_ports, $proxysettings{'TRANSPARENT_PORT'});
+       }
+
+       # Format HTTP_PORTS declaration.
+       my $line = "";
+
+       # Generate line which will be written to the http ports file.
+       $line = join(",", @http_ports);
+
+       # Open file to store the HTTP_PORTS.
+       open(FILE, ">$http_ports_file") or die "Could not open $http_ports_file. $!\n";
+
+       # Print yaml header.
+       print FILE "%YAML 1.1\n";
+       print FILE "---\n\n";
+
+       # Print notice about autogenerated file.
+       print FILE "#Autogenerated file. Any custom changes will be overwritten!\n";
+
+       # Print the generated HTTP_PORTS declaration to the file.
+       print FILE "HTTP_PORTS:\t\"[$line]\"\n";
 
        # Close file handle.
        close(FILE);
 }
 
 #
-## Function to generate and write the file for used rulefiles.
+## Function to write the file that contains the rulefiles which are loaded by suricaa.
+##
+## This function requires an array of used provider handles.
 #
-sub write_used_rulefiles_file(@) {
-       my @files = @_;
+sub write_used_rulefiles_file (@) {
+       my (@providers) = @_;
+
+       # Get the enabled application layer protocols.
+       my @enabled_app_layer_protos = &get_suricata_enabled_app_layer_protos();
 
-       # Open file for used rulefiles.
-       open (FILE, ">$used_rulefiles_file") or die "Could not write to $used_rulefiles_file. $!\n";
+       # Open the file.
+       open (FILE, ">", $suricata_used_rulesfiles_file) or die "Could not write to $suricata_used_rulesfiles_file. $!\n";
 
-       # Write yaml header to the file.
        print FILE "%YAML 1.1\n";
        print FILE "---\n\n";
 
-       # Write header to file.
+       # Write notice about autogenerated file.
        print FILE "#Autogenerated file. Any custom changes will be overwritten!\n";
 
-       # Allways use the whitelist.
-       print FILE " - whitelist.rules\n";
+       # Loop through the array of static included rulesfiles.
+       foreach my $file (@static_included_rulefiles) {
+               # Check if the file exists.
+               if (-f "$rulespath/$file") {
+                       # Write the rulesfile name to the file.
+                       print FILE " - $rulespath/$file\n";
+               }
+       }
 
-       # Loop through the array of given files.
-       foreach my $file (@files) {
-               # Check if the given filename exists and write it to the file of used rulefiles.
-               if(-f "$rulespath/$file") {
-                       print FILE " - $file\n";
+       print FILE "\n#Default rules for used application layer protocols.\n";
+       foreach my $enabled_app_layer_proto (@enabled_app_layer_protos) {
+               # Check if the current processed app layer proto needs to be translated
+               # into an application name.
+               if (exists($tr_app_layer_proto{$enabled_app_layer_proto})) {
+                       # Obtain the translated application name for this protocol.
+                       $enabled_app_layer_proto = $tr_app_layer_proto{$enabled_app_layer_proto};
+               }
+
+               # Generate filename.
+               my $rulesfile = "$default_rulespath/$enabled_app_layer_proto\.rules";
+
+               # Check if such a file exists.
+               if (-f "$rulesfile") {
+                       # Write the rulesfile name to the file.
+                       print FILE " - $rulesfile\n";
+               }
+
+               # Generate filename with "events" in filename.
+               $rulesfile = "$default_rulespath/$enabled_app_layer_proto\-events.rules";
+
+               # Check if this file exists.
+               if (-f "$rulesfile" ) {
+                       # Write the rulesfile name to the file.
+                       print FILE " - $rulesfile\n";
                }
        }
 
-       # Close file after writing.
+       # Loop through the array of enabled providers.
+       foreach my $provider (@providers) {
+               # Skip unsupported providers.
+               next unless ($IDS::Ruleset::Providers{$provider});
+
+               # Get the used rulefile for this provider.
+               my @used_rulesfiles = &get_provider_used_rulesfiles($provider);
+
+               # Check if there are
+               if(@used_rulesfiles) {
+                       # Add notice to the file.
+                       print FILE "\n#Used Rulesfiles for provider $provider.\n";
+
+                       # Loop through the array of used rulefiles.
+                       foreach my $enabled_rulesfile (@used_rulesfiles) {
+                               # Generate name and full path to the rulesfile.
+                               my $rulesfile = "$rulespath/$enabled_rulesfile";
+
+                               # Write the ruelsfile name to the file.
+                               print FILE " - $rulesfile\n";
+                       }
+               }
+       }
+
+       # Close the file handle
        close(FILE);
 }
 
 #
-## Function to generate and write the file for modify the ruleset.
+## Tiny function to generate the full path and name for the file which stores the used rulefiles of a given provider.
 #
-sub write_modify_sids_file() {
-       # Get configured settings.
-       my %idssettings=();
-       my %rulessettings=();
-       &General::readhash("$ids_settings_file", \%idssettings);
-       &General::readhash("$rules_settings_file", \%rulessettings);
+sub get_provider_used_rulesfiles_file ($) {
+       my ($provider) = @_;
 
-       # Gather the configured ruleset.
-       my $ruleset = $rulessettings{'RULES'};
+       my $filename = "$settingsdir/$provider\-used\-rulesfiles";
 
-       # Open modify sid's file for writing.
-       open(FILE, ">$modify_sids_file") or die "Could not write to $modify_sids_file. $!\n";
+       # Return the gernerated file.
+       return $filename;
+}
 
-       # Write file header.
-       print FILE "#Autogenerated file. Any custom changes will be overwritten!\n";
+#
+## Tiny function to generate the full path and name for the file which stores the modifications of a ruleset.
+#
+sub get_provider_ruleset_modifications_file($) {
+       my ($provider) = @_;
 
-       # Check if the traffic only should be monitored.
-       unless($idssettings{'MONITOR_TRAFFIC_ONLY'} eq 'on') {
-               # Suricata is in IPS mode, which means that the rule actions have to be changed
-               # from 'alert' to 'drop', however not all rules should be changed.  Some rules
-               # exist purely to set a flowbit which is used to convey other information, such
-               # as a specific type of file being downloaded, to other rulewhich then check for
-               # malware in that file.  Rules which fall into the first category should stay as
-               # alert since not all flows of that type contain malware.
-
-               if($ruleset eq 'registered' or $ruleset eq 'subscripted' or $ruleset eq 'community') {
-                       # These types of rulesfiles contain meta-data which gives the action that should
-                       # be used when in IPS mode.  Do the following:
-                       #
-                       # 1. Disable all rules and set the action to 'drop'
-                       # 2. Set the action back to 'alert' if the rule contains 'flowbits:noalert;'
-                       #    This should give rules not in the policy a reasonable default if the user
-                       #    manually enables them.
-                       # 3. Enable rules and set actions according to the meta-data strings.
-
-                       my $policy = 'balanced';  # Placeholder to allow policy to be changed.
-
-                       print FILE <<END;
-modifysid * "^#?(?:alert|drop)" | "#drop"
-modifysid * "^#drop(.+flowbits:noalert;)" | "#alert\${1}"
-modifysid * "^#(?:alert|drop)(.+policy $policy-ips alert)" | "alert\${1}"
-modifysid * "^#(?:alert|drop)(.+policy $policy-ips drop)" | "drop\${1}"
-END
-               } else {
-                       # These rulefiles don't have the metadata, so set rules to 'drop' unless they
-                       # contain the string 'flowbits:noalert;'.
-                       print FILE <<END;
-modifysid * "^(#?)(?:alert|drop)" | "\${1}drop"
-modifysid * "^(#?)drop(.+flowbits:noalert;)" | "\${1}alert\${2}"
-END
+       my $filename = "$settingsdir/$provider\-modifications";
+
+       # Return the filename.
+       return $filename;
+}
+
+#
+## Function to get the subscription code of a configured provider.
+#
+sub get_subscription_code($) {
+       my ($provider) = @_;
+
+       my %configured_providers = ();
+
+       # Read-in providers settings file.
+       &General::readhasharray($providers_settings_file, \%configured_providers);
+
+       # Loop through the hash of configured providers.
+       foreach my $id (keys %configured_providers) {
+               # Assign nice human-readable values to the data fields.
+               my $provider_handle = $configured_providers{$id}[0];
+               my $subscription_code = $configured_providers{$id}[1];
+
+               # Check if the current processed provider is the requested one.
+               if ($provider_handle eq $provider) {
+                       # Return the obtained subscription code.
+                       return $subscription_code;
                }
        }
 
-       # Close file handle.
-       close(FILE);
+       # No subscription code found - return nothing.
+       return;
+}
+
+#
+## Function to get the ruleset date for a given provider.
+##
+## The function simply return the creation date in a human read-able format
+## of the stored providers rulesfile.
+#
+sub get_ruleset_date($) {
+       my ($provider) = @_;
+       my $date;
+       my $mtime;
+
+       # Get the stored rulesfile for this provider.
+       my $stored_rulesfile = &_get_dl_rulesfile($provider);
+
+       # Check if we got a file.
+       if (-f $stored_rulesfile) {
+               # Call stat on the rulestarball.
+               my $stat = stat("$stored_rulesfile");
+
+               # Get timestamp the file creation.
+               $mtime = $stat->mtime;
+       }
+
+       # Check if the timestamp has not been grabbed.
+       unless ($mtime) {
+               # Return N/A for Not available.
+               return "N/A";
+       }
+
+       # Convert into human read-able format.
+       $date = strftime('%Y-%m-%d %H:%M:%S', localtime($mtime));
+
+       # Return the date.
+       return $date;
 }
 
 #
@@ -866,7 +1599,7 @@ sub get_suricata_version($) {
        # Remove newlines.
         chomp($version_string);
 
-       # Grab the version from the version string. 
+       # Grab the version from the version string.
        $version_string =~ /([0-9]+([.][0-9]+)+)/;
 
        # Splitt the version into single chunks.
@@ -882,7 +1615,49 @@ sub get_suricata_version($) {
        } else {
                # Return the full version string.
                return "$major_ver.$minor_ver.$patchlevel";
-       } 
+       }
+}
+
+#
+## Function to get the enabled application layer protocols.
+#
+sub get_suricata_enabled_app_layer_protos() {
+       # Array to store and return the enabled app layer protos.
+       my @enabled_app_layer_protos = ();
+
+       # Execute piped suricata command and return the list of
+       # enabled application layer protocols.
+       open(SURICATA, "suricata --list-app-layer-protos |") or die "Could not execute program: $!";
+
+       # Grab and store the list of enabled application layer protocols.
+       my @output = <SURICATA>;
+
+       # Close pipe.
+       close(SURICATA);
+
+       # Merge allways enabled static application layers protocols array.
+       @enabled_app_layer_protos = @static_enabled_app_layer_protos;
+
+       # Loop through the array which contains the output of suricata.
+       foreach my $line (@output) {
+               # Skip header line which starts with "===".
+               next if ($line =~ /^\s*=/);
+
+               # Skip info or warning lines.
+               next if ($line =~ /\s*--/);
+
+               # Remove newlines.
+               chomp($line);
+
+               # Add enabled app layer proto to the array.
+               push(@enabled_app_layer_protos, $line);
+       }
+
+       # Sort the array.
+       @enabled_app_layer_protos = sort(@enabled_app_layer_protos);
+
+       # Return the array.
+       return @enabled_app_layer_protos;
 }
 
 #
@@ -921,7 +1696,7 @@ sub generate_ignore_file() {
                                # Check if the address/network is valid.
                                if ((&General::validip($address)) || (&General::validipandmask($address))) {
                                        # Write rule line to the file to pass any traffic from this IP
-                                       print FILE "pass ip $address any -> any any (msg:\"pass all traffic from/to $address\"\; sid:$sid\;)\n";
+                                       print FILE "pass ip $address any -> any any (msg:\"pass all traffic from/to $address\"\; bypass; sid:$sid\;)\n";
 
                                        # Increment sid.
                                        $sid++;
@@ -1054,6 +1829,68 @@ sub get_red_address() {
        return;
 }
 
+#
+## Function to get the used rules files of a given provider.
+#
+sub get_provider_used_rulesfiles($) {
+       my ($provider) = @_;
+
+       # Hash to store the used rulefiles of the provider.
+       my %provider_rulefiles = ();
+
+       # Array to store the used rulefiles.
+       my @used_rulesfiles = ();
+
+       # Get the filename which contains the used rulefiles for this provider.
+       my $used_rulesfiles_file = &get_provider_used_rulesfiles_file($provider);
+
+       # Read-in file, if it exists.
+       &General::readhash("$used_rulesfiles_file", \%provider_rulefiles) if (-f $used_rulesfiles_file);
+
+       # Loop through the hash of rulefiles which does the provider offer.
+       foreach my $rulefile (keys %provider_rulefiles) {
+               # Skip disabled rulefiles.
+               next unless($provider_rulefiles{$rulefile} eq "enabled");
+
+               # The General::readhash function does not allow dots as
+               # key value and limits the key "string" to the part before
+               # the dot, in case it contains one.
+               #
+               # So add the file extension for the rules file manually again.
+               $rulefile = "$rulefile.rules";
+
+               # Add the enabled rulefile to the array of enabled rulefiles.
+               push(@used_rulesfiles, $rulefile);
+       }
+
+       # Return the array of used rulesfiles.
+       return @used_rulesfiles;
+}
+
+#
+## Function to delete the stored etag data of a given provider.
+#
+sub remove_from_etags ($) {
+       my ($provider) = @_;
+
+       my %etags;
+
+       # Early exit function if the etags file does not exist.
+       return unless (-f $etags_file);
+
+       # Read-in etag file.
+       &General::readhash("$etags_file", \%etags);
+
+       # Check if the hash contains an entry for the given provider.
+       if ($etags{$provider}) {
+               # Drop the entry.
+               delete($etags{$provider});
+
+               # Write back the etags file.
+               &General::writehash("$etags_file", \%etags);
+       }
+}
+
 #
 ## Function to write the lock file for locking the WUI, while
 ## the autoupdate script runs.