2 ############################################################################
4 # This file is part of the IPFire Firewall. #
6 # IPFire is free software; you can redistribute it and/or modify #
7 # it under the terms of the GNU General Public License as published by #
8 # the Free Software Foundation; either version 2 of the License, or #
9 # (at your option) any later version. #
11 # IPFire is distributed in the hope that it will be useful, #
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of #
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
14 # GNU General Public License for more details. #
16 # You should have received a copy of the GNU General Public License #
17 # along with IPFire; if not, write to the Free Software #
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #
20 # Copyright (C) 2018-2019 IPFire Team <info@ipfire.org> #
22 ############################################################################
28 require '/var/ipfire/general-functions.pl';
29 require "${General::swroot}/network-functions.pl";
30 require "${General::swroot}/suricata/ruleset-sources";
32 # Location where all config and settings files are stored.
33 our $settingsdir = "${General::swroot}/suricata";
35 # File where the used rulefiles are stored.
36 our $used_rulefiles_file = "$settingsdir/suricata-used-rulefiles.yaml";
38 # File where the addresses of the homenet are stored.
39 our $homenet_file = "$settingsdir/suricata-homenet.yaml";
41 # File where the addresses of the used DNS servers are stored.
42 our $dns_servers_file = "$settingsdir/suricata-dns-servers.yaml";
44 # File where the HTTP ports definition is stored.
45 our $http_ports_file = "$settingsdir/suricata-http-ports.yaml";
47 # File which contains the enabled sids.
48 our $enabled_sids_file = "$settingsdir/oinkmaster-enabled-sids.conf";
50 # File which contains the disabled sids.
51 our $disabled_sids_file = "$settingsdir/oinkmaster-disabled-sids.conf";
53 # File which contains wheater the rules should be changed.
54 our $modify_sids_file = "$settingsdir/oinkmaster-modify-sids.conf";
56 # File which stores the configured IPS settings.
57 our $ids_settings_file = "$settingsdir/settings";
59 # DEPRECATED - File which stores the configured rules-settings.
60 our $rules_settings_file = "$settingsdir/rules-settings";
62 # File which stores the used and configured ruleset providers.
63 our $providers_settings_file = "$settingsdir/providers-settings";
65 # File which stores the configured settings for whitelisted addresses.
66 our $ignored_file = "$settingsdir/ignored";
68 # DEPRECATED - Location and name of the tarball which contains the ruleset.
69 our $rulestarball = "/var/tmp/idsrules.tar.gz";
71 # Location where the downloaded rulesets are stored.
72 our $dl_rules_path = "/var/tmp";
74 # File to store any errors, which also will be read and displayed by the wui.
75 our $storederrorfile = "/tmp/ids_storederror";
77 # File to lock the WUI, while the autoupdate script runs.
78 our $ids_page_lock_file = "/tmp/ids_page_locked";
80 # Location where the rulefiles are stored.
81 our $rulespath = "/var/lib/suricata";
83 # Location to store local rules. This file will not be touched.
84 our $local_rules_file = "$rulespath/local.rules";
86 # File which contains the rules to whitelist addresses on suricata.
87 our $whitelist_file = "$rulespath/whitelist.rules";
89 # File which contains a list of all supported ruleset sources.
90 # (Sourcefire, Emergingthreads, etc..)
91 our $rulesetsourcesfile = "$settingsdir/ruleset-sources";
93 # The pidfile of the IDS.
94 our $idspidfile = "/var/run/suricata.pid";
96 # Location of suricatactrl.
97 my $suricatactrl = "/usr/local/bin/suricatactrl";
99 # Prefix for each downloaded ruleset.
100 my $dl_rulesfile_prefix = "idsrules";
102 # Array with allowed commands of suricatactrl.
103 my @suricatactrl_cmds = ( 'start', 'stop', 'restart', 'reload', 'fix-rules-dir', 'cron' );
105 # Array with supported cron intervals.
106 my @cron_intervals = ('off', 'daily', 'weekly' );
108 # Array which contains the HTTP ports, which statically will be declared as HTTP_PORTS in the
110 my @http_ports = ('80', '81');
112 # Hash which allows to convert the download type (dl_type) to a file suffix.
113 my %dl_type_to_suffix = (
114 "archive" => ".tar.gz",
119 ## Function to check and create all IDS related files, if the does not exist.
121 sub check_and_create_filelayout
() {
122 # Check if the files exist and if not, create them.
123 unless (-f
"$enabled_sids_file") { &create_empty_file
($enabled_sids_file); }
124 unless (-f
"$disabled_sids_file") { &create_empty_file
($disabled_sids_file); }
125 unless (-f
"$modify_sids_file") { &create_empty_file
($modify_sids_file); }
126 unless (-f
"$used_rulefiles_file") { &create_empty_file
($used_rulefiles_file); }
127 unless (-f
"$ids_settings_file") { &create_empty_file
($ids_settings_file); }
128 unless (-f
"$providers_settings_file") { &create_empty_file
($providers_settings_file); }
129 unless (-f
"$ignored_file") { &create_empty_file
($ignored_file); }
130 unless (-f
"$whitelist_file" ) { &create_empty_file
($whitelist_file); }
134 ## Function to get a list of all available ruleset providers.
136 ## They will be returned as a sorted array.
138 sub get_ruleset_providers
() {
141 # Loop through the hash of providers.
142 foreach my $provider ( keys %IDS::Ruleset
::Providers
) {
143 # Add the provider to the array.
144 push(@providers, $provider);
147 # Sort and return the array.
148 return sort(@providers);
152 ## Function for checking if at least 300MB of free disk space are available
153 ## on the "/var" partition.
155 sub checkdiskspace
() {
156 # Call diskfree to gather the free disk space of /var.
157 my @df = &General
::system_output
("/bin/df", "-B", "M", "/var");
159 # Loop through the output.
160 foreach my $line (@df) {
161 # Ignore header line.
162 next if $line =~ m/^Filesystem/;
164 # Search for a line with the device information.
165 if ($line =~ m/dev/ ) {
166 # Split the line into single pieces.
167 my @values = split(' ', $line);
168 my ($filesystem, $blocks, $used, $available, $used_perenctage, $mounted_on) = @values;
170 # Check if the available disk space is more than 300MB.
171 if ($available < 300) {
172 # Log error to syslog.
173 &_log_to_syslog
("Not enough free disk space on /var. Only $available MB from 300 MB available.");
175 # Exit function and return "1" - False.
181 # Everything okay, return nothing.
186 ## This function is responsible for downloading the configured IDS ruleset.
188 ## * At first it obtains from the stored rules settings which ruleset should be downloaded.
189 ## * The next step is to get the download locations for all available rulesets.
190 ## * After that, the function will check if an upstream proxy should be used and grab the settings.
191 ## * The last step will be to generate the final download url, by obtaining the URL for the desired
192 ## ruleset, add the settings for the upstream proxy and final grab the rules tarball from the server.
194 sub downloadruleset
{
195 # Get rules settings.
196 my %rulessettings=();
197 &General
::readhash
("$rules_settings_file", \
%rulessettings);
199 # Check if a ruleset has been configured.
200 unless($rulessettings{'RULES'}) {
201 # Log that no ruleset has been configured and abort.
202 &_log_to_syslog
("No ruleset source has been configured.");
208 # Read proxysettings.
209 my %proxysettings=();
210 &General
::readhash
("${General::swroot}/proxy/settings", \
%proxysettings);
212 # Load required perl module to handle the download.
215 # Init the download module.
216 my $downloader = LWP
::UserAgent
->new;
218 # Set timeout to 10 seconds.
219 $downloader->timeout(10);
221 # Check if an upstream proxy is configured.
222 if ($proxysettings{'UPSTREAM_PROXY'}) {
225 $proxy_url = "http://";
227 # Check if the proxy requires authentication.
228 if (($proxysettings{'UPSTREAM_USER'}) && ($proxysettings{'UPSTREAM_PASSWORD'})) {
229 $proxy_url .= "$proxysettings{'UPSTREAM_USER'}\:$proxysettings{'UPSTREAM_PASSWORD'}\@";
232 # Add proxy server address and port.
233 $proxy_url .= $proxysettings{'UPSTREAM_PROXY'};
235 # Setup proxy settings.
236 $downloader->proxy(['http', 'https'], $proxy_url);
239 # Grab the right url based on the configured vendor.
240 my $url = $IDS::Ruleset
::Providers
{$rulessettings{'RULES'}}{'dl_url'};
242 # Check if the vendor requires an oinkcode and add it if needed.
243 $url =~ s/\<oinkcode\>/$rulessettings{'OINKCODE'}/g;
245 # Abort if no url could be determined for the vendor.
247 # Log error and abort.
248 &_log_to_syslog
("Unable to gather a download URL for the selected ruleset.");
252 # Variable to store the filesize of the remote object.
255 # The sourcfire (snort rules) does not allow to send "HEAD" requests, so skip this check
256 # for this webserver.
258 # Check if the ruleset source contains "snort.org".
259 unless ($url =~ /\.snort\.org/) {
260 # Pass the requrested url to the downloader.
261 my $request = HTTP
::Request
->new(HEAD
=> $url);
263 # Accept the html header.
264 $request->header('Accept' => 'text/html');
266 # Perform the request and fetch the html header.
267 my $response = $downloader->request($request);
269 # Check if there was any error.
270 unless ($response->is_success) {
272 my $error = $response->status_line();
275 &_log_to_syslog
("Unable to download the ruleset. \($error\)");
277 # Return "1" - false.
281 # Assign the fetched header object.
282 my $header = $response->headers();
284 # Grab the remote file size from the object and store it in the
286 $remote_filesize = $header->content_length;
289 # Load perl module to deal with temporary files.
292 # Generate temporary file name, located in "/var/tmp" and with a suffix of ".tar.gz".
293 my $tmp = File
::Temp
->new( SUFFIX
=> ".tar.gz", DIR
=> "/var/tmp/", UNLINK
=> 0 );
294 my $tmpfile = $tmp->filename();
296 # Pass the requested url to the downloader.
297 my $request = HTTP
::Request
->new(GET
=> $url);
299 # Perform the request and save the output into the tmpfile.
300 my $response = $downloader->request($request, $tmpfile);
302 # Check if there was any error.
303 unless ($response->is_success) {
305 my $error = $response->content;
308 &_log_to_syslog
("Unable to download the ruleset. \($error\)");
310 # Return "1" - false.
314 # Load perl stat module.
317 # Perform stat on the tmpfile.
318 my $stat = stat($tmpfile);
320 # Grab the local filesize of the downloaded tarball.
321 my $local_filesize = $stat->size;
323 # Check if both file sizes match.
324 if (($remote_filesize) && ($remote_filesize ne $local_filesize)) {
326 &_log_to_syslog
("Unable to completely download the ruleset. ");
327 &_log_to_syslog
("Only got $local_filesize Bytes instead of $remote_filesize Bytes. ");
329 # Delete temporary file.
332 # Return "1" - false.
336 # Load file copy module, which contains the move() function.
339 # Overwrite existing rules tarball with the new downloaded one.
340 move
("$tmpfile", "$rulestarball");
342 # Set correct ownership for the rulesdir and files.
343 set_ownership
("$rulestarball");
345 # If we got here, everything worked fine. Return nothing.
350 ## A tiny wrapper function to call the oinkmaster script.
353 # Check if the files in rulesdir have the correct permissions.
354 &_check_rulesdir_permissions
();
356 # Cleanup the rules directory before filling it with the new rulest.
357 &_cleanup_rulesdir
();
359 # Load perl module to talk to the kernel syslog.
360 use Sys
::Syslog
qw(:DEFAULT setlogsock);
362 # Establish the connection to the syslog service.
363 openlog
('oinkmaster', 'cons,pid', 'user');
365 # Call oinkmaster to generate ruleset.
366 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";
368 # Log output of oinkmaster to syslog.
369 while(<OINKMASTER
>) {
370 # The syslog function works best with an array based input,
371 # so generate one before passing the message details to syslog.
372 my @syslog = ("INFO", "$_");
374 # Send the log message.
378 # Close the pipe to oinkmaster process.
381 # Close the log handle.
386 ## Function to do all the logging stuff if the downloading or updating of the ruleset fails.
391 # Remove any newline.
394 # Call private function to log the error message to syslog.
395 &_log_to_syslog
($error);
397 # Call private function to write/store the error message in the storederrorfile.
398 &_store_error_message
($error);
402 ## Function to log a given error message to the kernel syslog.
404 sub _log_to_syslog
($) {
407 # Load perl module to talk to the kernel syslog.
408 use Sys
::Syslog
qw(:DEFAULT setlogsock);
410 # The syslog function works best with an array based input,
411 # so generate one before passing the message details to syslog.
412 my @syslog = ("ERR", "<ERROR> $message");
414 # Establish the connection to the syslog service.
415 openlog
('oinkmaster', 'cons,pid', 'user');
417 # Send the log message.
420 # Close the log handle.
425 ## Private function to write a given error message to the storederror file.
427 sub _store_error_message
($) {
430 # Remove any newline.
433 # Open file for writing.
434 open (ERRORFILE
, ">$storederrorfile") or die "Could not write to $storederrorfile. $!\n";
436 # Write error to file.
437 print ERRORFILE
"$message\n";
442 # Set correct ownership for the file.
443 &set_ownership
("$storederrorfile");
447 ## Private function to get the path and filename for a downloaded ruleset by a given provider.
449 sub _get_dl_rulesfile
($) {
452 # Gather the download type for the given provider.
453 my $dl_type = $IDS::Ruleset
::Providers
{$provider}{'dl_type'};
455 # Obtain the file suffix for the download file type.
456 my $suffix = $dl_type_to_suffix{$dl_type};
458 # Check if a suffix has been found.
460 # Abort return - nothing.
464 # Generate the full filename and path for the stored rules file.
465 my $rulesfile = "$dl_rules_path/$dl_rulesfile_prefix-$provider$suffix";
467 # Return the generated filename.
472 ## Function to check if the IDS is running.
474 sub ids_is_running
() {
476 # Open PID file for reading.
477 open(PIDFILE
, "$idspidfile") or die "Could not open $idspidfile. $!\n";
479 # Grab the process-id.
485 # Remove any newline.
488 # Check if a directory for the process-id exists in proc.
489 if(-d
"/proc/$pid") {
490 # The IDS daemon is running return the process id.
495 # Return nothing - IDS is not running.
500 ## Function to call suricatactrl binary with a given command.
502 sub call_suricatactrl
($) {
504 my ($option, $interval) = @_;
506 # Loop through the array of supported commands and check if
507 # the given one is part of it.
508 foreach my $cmd (@suricatactrl_cmds) {
509 # Skip current command unless the given one has been found.
510 next unless($cmd eq $option);
512 # Check if the given command is "cron".
513 if ($option eq "cron") {
514 # Check if an interval has been given.
516 # Check if the given interval is valid.
517 foreach my $element (@cron_intervals) {
518 # Skip current element until the given one has been found.
519 next unless($element eq $interval);
521 # Call the suricatactrl binary and pass the "cron" command
522 # with the requrested interval.
523 &General
::system("$suricatactrl", "$option", "$interval");
530 # If we got here, the given interval is not supported or none has been given. - Return nothing.
533 # Call the suricatactrl binary and pass the requrested
535 &General
::system("$suricatactrl", "$option");
542 # Command not found - return nothing.
547 ## Function to create a new empty file.
549 sub create_empty_file
($) {
552 # Check if the given file exists.
554 # Do nothing to prevent from overwriting existing files.
558 # Open the file for writing.
559 open(FILE
, ">$file") or die "Could not write to $file. $!\n";
569 ## Private function to check if the file permission of the rulespath are correct.
570 ## If not, call suricatactrl to fix them.
572 sub _check_rulesdir_permissions
() {
573 # Check if the rulepath main directory is writable.
574 unless (-W
$rulespath) {
575 # If not call suricatctrl to fix it.
576 &call_suricatactrl
("fix-rules-dir");
579 # Open snort rules directory and do a directory listing.
580 opendir(DIR
, $rulespath) or die $!;
581 # Loop through the direcory.
582 while (my $file = readdir(DIR
)) {
583 # We only want files.
584 next unless (-f
"$rulespath/$file");
586 # Check if the file is writable by the user.
587 if (-W
"$rulespath/$file") {
588 # Everything is okay - go on to the next file.
591 # There are wrong permissions, call suricatactrl to fix it.
592 &call_suricatactrl
("fix-rules-dir");
598 ## Private function to cleanup the directory which contains
599 ## the IDS rules, before extracting and modifing the new ruleset.
601 sub _cleanup_rulesdir
() {
602 # Open rules directory and do a directory listing.
603 opendir(DIR
, $rulespath) or die $!;
605 # Loop through the direcory.
606 while (my $file = readdir(DIR
)) {
607 # We only want files.
608 next unless (-f
"$rulespath/$file");
610 # Skip element if it has config as file extension.
611 next if ($file =~ m/\.config$/);
613 # Skip rules file for whitelisted hosts.
614 next if ("$rulespath/$file" eq $whitelist_file);
616 # Skip rules file with local rules.
617 next if ("$rulespath/$file" eq $local_rules_file);
619 # Delete the current processed file, if not, exit this function
620 # and return an error message.
621 unlink("$rulespath/$file") or return "Could not delete $rulespath/$file. $!\n";
629 ## Function to generate the file which contains the home net information.
631 sub generate_home_net_file
() {
634 # Read-in network settings.
635 &General
::readhash
("${General::swroot}/ethernet/settings", \
%netsettings);
637 # Get available network zones.
638 my @network_zones = &Network
::get_available_network_zones
();
640 # Temporary array to store network address and prefix of the configured
644 # Loop through the array of available network zones.
645 foreach my $zone (@network_zones) {
646 # Check if the current processed zone is red.
648 # Grab the IP-address of the red interface.
649 my $red_address = &get_red_address
();
651 # Check if an address has been obtained.
653 # Generate full network string.
654 my $red_network = join("/", $red_address, "32");
656 # Add the red network to the array of networks.
657 push(@networks, $red_network);
660 # Check if the configured RED_TYPE is static.
661 if ($netsettings{'RED_TYPE'} eq "STATIC") {
662 # Get configured and enabled aliases.
663 my @aliases = &get_aliases
();
665 # Loop through the array.
666 foreach my $alias (@aliases) {
668 my $network = join("/", $alias, "32");
670 # Add the generated network to the array of networks.
671 push(@networks, $network);
674 # Process remaining network zones.
676 # Convert current zone name into upper case.
679 # Generate key to access the required data from the netsettings hash.
680 my $zone_netaddress = $zone . "_NETADDRESS";
681 my $zone_netmask = $zone . "_NETMASK";
683 # Obtain the settings from the netsettings hash.
684 my $netaddress = $netsettings{$zone_netaddress};
685 my $netmask = $netsettings{$zone_netmask};
687 # Convert the subnetmask into prefix notation.
688 my $prefix = &Network
::convert_netmask2prefix
($netmask);
690 # Generate full network string.
691 my $network = join("/", $netaddress,$prefix);
693 # Check if the network is valid.
694 if(&Network
::check_subnet
($network)) {
695 # Add the generated network to the array of networks.
696 push(@networks, $network);
701 # Format home net declaration.
702 my $line = "\"[" . join(',', @networks) . "]\"";
704 # Open file to store the addresses of the home net.
705 open(FILE
, ">$homenet_file") or die "Could not open $homenet_file. $!\n";
708 print FILE
"%YAML 1.1\n";
709 print FILE
"---\n\n";
711 # Print notice about autogenerated file.
712 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
714 # Print the generated and required HOME_NET declaration to the file.
715 print FILE
"HOME_NET:\t$line\n";
722 # Function to generate and write the file which contains the configured and used DNS servers.
724 sub generate_dns_servers_file
() {
725 # Get the used DNS servers.
726 my @nameservers = &General
::get_nameservers
();
728 # Get network settings.
730 &General
::readhash
("${General::swroot}/ethernet/settings", \
%netsettings);
732 # Format dns servers declaration.
735 # Check if the system has configured nameservers.
737 # Add the GREEN address as DNS servers.
738 push(@nameservers, $netsettings{'GREEN_ADDRESS'});
740 # Check if a BLUE zone exists.
741 if ($netsettings{'BLUE_ADDRESS'}) {
742 # Add the BLUE address to the array of nameservers.
743 push(@nameservers, $netsettings{'BLUE_ADDRESS'});
746 # Generate the line which will be written to the DNS servers file.
747 $line = join(",", @nameservers);
749 # External net simply contains (any).
750 $line = "\$EXTERNAL_NET";
753 # Open file to store the used DNS server addresses.
754 open(FILE
, ">$dns_servers_file") or die "Could not open $dns_servers_file. $!\n";
757 print FILE
"%YAML 1.1\n";
758 print FILE
"---\n\n";
760 # Print notice about autogenerated file.
761 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
763 # Print the generated DNS declaration to the file.
764 print FILE
"DNS_SERVERS:\t\"[$line]\"\n";
771 # Function to generate and write the file which contains the HTTP_PORTS definition.
773 sub generate_http_ports_file
() {
776 # Read-in proxy settings
777 &General
::readhash
("${General::swroot}/proxy/advanced/settings", \
%proxysettings);
779 # Check if the proxy is enabled.
780 if (( -e
"${General::swroot}/proxy/enable") || (-e
"${General::swroot}/proxy/enable_blue")) {
781 # Add the proxy port to the array of HTTP ports.
782 push(@http_ports, $proxysettings{'PROXY_PORT'});
785 # Check if the transparent mode of the proxy is enabled.
786 if ((-e
"${General::swroot}/proxy/transparent") || (-e
"${General::swroot}/proxy/transparent_blue")) {
787 # Add the transparent proxy port to the array of HTTP ports.
788 push(@http_ports, $proxysettings{'TRANSPARENT_PORT'});
791 # Format HTTP_PORTS declaration.
794 # Generate line which will be written to the http ports file.
795 $line = join(",", @http_ports);
797 # Open file to store the HTTP_PORTS.
798 open(FILE
, ">$http_ports_file") or die "Could not open $http_ports_file. $!\n";
801 print FILE
"%YAML 1.1\n";
802 print FILE
"---\n\n";
804 # Print notice about autogenerated file.
805 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
807 # Print the generated HTTP_PORTS declaration to the file.
808 print FILE
"HTTP_PORTS:\t\"[$line]\"\n";
815 ## Function to generate and write the file for used rulefiles.
817 sub write_used_rulefiles_file
(@
) {
820 # Open file for used rulefiles.
821 open (FILE
, ">$used_rulefiles_file") or die "Could not write to $used_rulefiles_file. $!\n";
823 # Write yaml header to the file.
824 print FILE
"%YAML 1.1\n";
825 print FILE
"---\n\n";
827 # Write header to file.
828 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
830 # Allways use the whitelist.
831 print FILE
" - whitelist.rules\n";
833 # Loop through the array of given files.
834 foreach my $file (@files) {
835 # Check if the given filename exists and write it to the file of used rulefiles.
836 if(-f
"$rulespath/$file") {
837 print FILE
" - $file\n";
841 # Close file after writing.
846 ## Function to generate and write the file for modify the ruleset.
848 sub write_modify_sids_file
() {
849 # Get configured settings.
851 my %rulessettings=();
852 &General
::readhash
("$ids_settings_file", \
%idssettings);
853 &General
::readhash
("$rules_settings_file", \
%rulessettings);
855 # Gather the configured ruleset.
856 my $ruleset = $rulessettings{'RULES'};
858 # Open modify sid's file for writing.
859 open(FILE
, ">$modify_sids_file") or die "Could not write to $modify_sids_file. $!\n";
862 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
864 # Check if the traffic only should be monitored.
865 unless($idssettings{'MONITOR_TRAFFIC_ONLY'} eq 'on') {
866 # Suricata is in IPS mode, which means that the rule actions have to be changed
867 # from 'alert' to 'drop', however not all rules should be changed. Some rules
868 # exist purely to set a flowbit which is used to convey other information, such
869 # as a specific type of file being downloaded, to other rulewhich then check for
870 # malware in that file. Rules which fall into the first category should stay as
871 # alert since not all flows of that type contain malware.
873 if($ruleset eq 'registered' or $ruleset eq 'subscripted' or $ruleset eq 'community') {
874 # These types of rulesfiles contain meta-data which gives the action that should
875 # be used when in IPS mode. Do the following:
877 # 1. Disable all rules and set the action to 'drop'
878 # 2. Set the action back to 'alert' if the rule contains 'flowbits:noalert;'
879 # This should give rules not in the policy a reasonable default if the user
880 # manually enables them.
881 # 3. Enable rules and set actions according to the meta-data strings.
883 my $policy = 'balanced'; # Placeholder to allow policy to be changed.
886 modifysid * "^#?(?:alert|drop)" | "#drop"
887 modifysid * "^#drop(.+flowbits:noalert;)" | "#alert\${1}"
888 modifysid * "^#(?:alert|drop)(.+policy $policy-ips alert)" | "alert\${1}"
889 modifysid * "^#(?:alert|drop)(.+policy $policy-ips drop)" | "drop\${1}"
892 # These rulefiles don't have the metadata, so set rules to 'drop' unless they
893 # contain the string 'flowbits:noalert;'.
895 modifysid * "^(#?)(?:alert|drop)" | "\${1}drop"
896 modifysid * "^(#?)drop(.+flowbits:noalert;)" | "\${1}alert\${2}"
906 ## Function to gather the version of suricata.
908 sub get_suricata_version
($) {
911 # Execute piped suricata command and return the version information.
912 open(SURICATA
, "suricata -V |") or die "Couldn't execute program: $!";
914 # Grab and store the output of the piped program.
915 my $version_string = <SURICATA
>;
921 chomp($version_string);
923 # Grab the version from the version string.
924 $version_string =~ /([0-9]+([.][0-9]+)+)/;
926 # Splitt the version into single chunks.
927 my ($major_ver, $minor_ver, $patchlevel) = split(/\./, $1);
929 # Check and return the requested version sheme.
930 if ($format eq "major") {
931 # Return the full version.
933 } elsif ($format eq "minor") {
934 # Return the major and minor part.
935 return "$major_ver.$minor_ver";
937 # Return the full version string.
938 return "$major_ver.$minor_ver.$patchlevel";
943 ## Function to generate the rules file with whitelisted addresses.
945 sub generate_ignore_file
() {
948 # SID range 1000000-1999999 Reserved for Local Use
949 # Put your custom rules in this range to avoid conflicts
952 # Read-in ignoredfile.
953 &General
::readhasharray
($IDS::ignored_file
, \
%ignored);
955 # Open ignorefile for writing.
956 open(FILE
, ">$IDS::whitelist_file") or die "Could not write to $IDS::whitelist_file. $!\n";
958 # Config file header.
959 print FILE
"# Autogenerated file.\n";
960 print FILE
"# All user modifications will be overwritten.\n\n";
962 # Add all user defined addresses to the whitelist.
964 # Check if the hash contains any elements.
965 if (keys (%ignored)) {
966 # Loop through the entire hash and write the host/network
967 # and remark to the ignore file.
968 while ( (my $key) = each %ignored) {
969 my $address = $ignored{$key}[0];
970 my $remark = $ignored{$key}[1];
971 my $status = $ignored{$key}[2];
973 # Check if the status of the entry is "enabled".
974 if ($status eq "enabled") {
975 # Check if the address/network is valid.
976 if ((&General
::validip
($address)) || (&General
::validipandmask
($address))) {
977 # Write rule line to the file to pass any traffic from this IP
978 print FILE
"pass ip $address any -> any any (msg:\"pass all traffic from/to $address\"\; sid:$sid\;)\n";
991 ## Function to set correct ownership for single files and directories.
994 sub set_ownership
($) {
997 # User and group of the WUI.
998 my $uname = "nobody";
999 my $grname = "nobody";
1001 # The chown function implemented in perl requies the user and group as nummeric id's.
1002 my $uid = getpwnam($uname);
1003 my $gid = getgrnam($grname);
1005 # Check if the given target exists.
1007 # Stop the script and print error message.
1008 die "The $target does not exist. Cannot change the ownership!\n";
1011 # Check weather the target is a file or directory.
1013 # Change ownership ot the single file.
1014 chown($uid, $gid, "$target");
1015 } elsif (-d
$target) {
1016 # Do a directory listing.
1017 opendir(DIR
, $target) or die $!;
1018 # Loop through the direcory.
1019 while (my $file = readdir(DIR
)) {
1021 # We only want files.
1022 next unless (-f
"$target/$file");
1024 # Set correct ownership for the files.
1025 chown($uid, $gid, "$target/$file");
1030 # Change ownership of the directory.
1031 chown($uid, $gid, "$target");
1036 ## Function to read-in the aliases file and returns all configured and enabled aliases.
1039 # Location of the aliases file.
1040 my $aliases_file = "${General::swroot}/ethernet/aliases";
1042 # Array to store the aliases.
1045 # Check if the file is empty.
1046 if (-z
$aliases_file) {
1047 # Abort nothing to do.
1051 # Open the aliases file.
1052 open(ALIASES
, $aliases_file) or die "Could not open $aliases_file. $!\n";
1054 # Loop through the file content.
1055 while (my $line = <ALIASES
>) {
1059 # Splitt line content into single chunks.
1060 my ($address, $state, $remark) = split(/\,/, $line);
1062 # Check if the state of the current processed alias is "on".
1063 if ($state eq "on") {
1064 # Check if the address is valid.
1065 if(&Network
::check_ip_address
($address)) {
1066 # Add the alias to the array of aliases.
1067 push(@aliases, $address);
1072 # Close file handle.
1080 ## Function to grab the current assigned IP-address on red.
1082 sub get_red_address
() {
1083 # File, which contains the current IP-address of the red interface.
1084 my $file = "${General::swroot}/red/local-ipaddress";
1086 # Check if the file exists.
1088 # Open the given file.
1089 open(FILE
, "$file") or die "Could not open $file.";
1091 # Obtain the address from the first line of the file.
1092 my $address = <FILE
>;
1100 # Check if the grabbed address is valid.
1101 if (&General
::validip
($address)) {
1102 # Return the address.
1112 ## Function to write the lock file for locking the WUI, while
1113 ## the autoupdate script runs.
1115 sub lock_ids_page
() {
1116 # Call subfunction to create the file.
1117 &create_empty_file
($ids_page_lock_file);
1121 ## Function to release the lock of the WUI, again.
1123 sub unlock_ids_page
() {
1125 unlink($ids_page_lock_file);