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 of the classification file.
84 our $classification_file = "$rulespath/classification.config";
86 # Location to store local rules. This file will not be touched.
87 our $local_rules_file = "$rulespath/local.rules";
89 # File which contains the rules to whitelist addresses on suricata.
90 our $whitelist_file = "$rulespath/whitelist.rules";
92 # File which contains a list of all supported ruleset sources.
93 # (Sourcefire, Emergingthreads, etc..)
94 our $rulesetsourcesfile = "$settingsdir/ruleset-sources";
96 # The pidfile of the IDS.
97 our $idspidfile = "/var/run/suricata.pid";
99 # Location of suricatactrl.
100 my $suricatactrl = "/usr/local/bin/suricatactrl";
102 # Prefix for each downloaded ruleset.
103 my $dl_rulesfile_prefix = "idsrules";
105 # Temporary directory where the rulesets will be extracted.
106 my $tmp_directory = "/tmp/ids_tmp";
108 # Array with allowed commands of suricatactrl.
109 my @suricatactrl_cmds = ( 'start', 'stop', 'restart', 'reload', 'fix-rules-dir', 'cron' );
111 # Array with supported cron intervals.
112 my @cron_intervals = ('off', 'daily', 'weekly' );
114 # Array which contains the HTTP ports, which statically will be declared as HTTP_PORTS in the
116 my @http_ports = ('80', '81');
118 # Hash which allows to convert the download type (dl_type) to a file suffix.
119 my %dl_type_to_suffix = (
120 "archive" => ".tar.gz",
125 ## Function to check and create all IDS related files, if the does not exist.
127 sub check_and_create_filelayout
() {
128 # Check if the files exist and if not, create them.
129 unless (-f
"$enabled_sids_file") { &create_empty_file
($enabled_sids_file); }
130 unless (-f
"$disabled_sids_file") { &create_empty_file
($disabled_sids_file); }
131 unless (-f
"$modify_sids_file") { &create_empty_file
($modify_sids_file); }
132 unless (-f
"$used_rulefiles_file") { &create_empty_file
($used_rulefiles_file); }
133 unless (-f
"$ids_settings_file") { &create_empty_file
($ids_settings_file); }
134 unless (-f
"$providers_settings_file") { &create_empty_file
($providers_settings_file); }
135 unless (-f
"$ignored_file") { &create_empty_file
($ignored_file); }
136 unless (-f
"$whitelist_file" ) { &create_empty_file
($whitelist_file); }
140 ## Function to get a list of all available ruleset providers.
142 ## They will be returned as a sorted array.
144 sub get_ruleset_providers
() {
147 # Loop through the hash of providers.
148 foreach my $provider ( keys %IDS::Ruleset
::Providers
) {
149 # Add the provider to the array.
150 push(@providers, $provider);
153 # Sort and return the array.
154 return sort(@providers);
158 ## Function for checking if at least 300MB of free disk space are available
159 ## on the "/var" partition.
161 sub checkdiskspace
() {
162 # Call diskfree to gather the free disk space of /var.
163 my @df = &General
::system_output
("/bin/df", "-B", "M", "/var");
165 # Loop through the output.
166 foreach my $line (@df) {
167 # Ignore header line.
168 next if $line =~ m/^Filesystem/;
170 # Search for a line with the device information.
171 if ($line =~ m/dev/ ) {
172 # Split the line into single pieces.
173 my @values = split(' ', $line);
174 my ($filesystem, $blocks, $used, $available, $used_perenctage, $mounted_on) = @values;
176 # Check if the available disk space is more than 300MB.
177 if ($available < 300) {
178 # Log error to syslog.
179 &_log_to_syslog
("Not enough free disk space on /var. Only $available MB from 300 MB available.");
181 # Exit function and return "1" - False.
187 # Everything okay, return nothing.
192 ## This function is responsible for downloading the configured IDS rulesets or if no one is specified
193 ## all configured rulesets will be downloaded.
195 ## * At first it gathers all configured ruleset providers, initialize the downloader and sets an
196 ## upstream proxy if configured.
197 ## * After that, the given ruleset or in case all rulesets should be downloaded, it will determine wether it
198 ## is enabled or not.
199 ## * The next step will be to generate the final download url, by obtaining the URL for the desired
200 ## ruleset, add the settings for the upstream proxy.
201 ## * Finally the function will grab all the rules files or tarballs from the servers.
203 sub downloadruleset
($) {
206 # If no provider is given default to "all".
209 # Hash to store the providers and access id's, for which rules should be downloaded.
210 my %sheduled_providers = ();
212 # Get used provider settings.
213 my %used_providers = ();
214 &General
::readhasharray
("$providers_settings_file", \
%used_providers);
216 # Check if a ruleset has been configured.
217 unless(%used_providers) {
218 # Log that no ruleset has been configured and abort.
219 &_log_to_syslog
("No ruleset provider has been configured.");
225 # Read proxysettings.
226 my %proxysettings=();
227 &General
::readhash
("${General::swroot}/proxy/settings", \
%proxysettings);
229 # Load required perl module to handle the download.
232 # Init the download module.
233 my $downloader = LWP
::UserAgent
->new;
235 # Set timeout to 10 seconds.
236 $downloader->timeout(10);
238 # Check if an upstream proxy is configured.
239 if ($proxysettings{'UPSTREAM_PROXY'}) {
242 $proxy_url = "http://";
244 # Check if the proxy requires authentication.
245 if (($proxysettings{'UPSTREAM_USER'}) && ($proxysettings{'UPSTREAM_PASSWORD'})) {
246 $proxy_url .= "$proxysettings{'UPSTREAM_USER'}\:$proxysettings{'UPSTREAM_PASSWORD'}\@";
249 # Add proxy server address and port.
250 $proxy_url .= $proxysettings{'UPSTREAM_PROXY'};
252 # Setup proxy settings.
253 $downloader->proxy(['http', 'https'], $proxy_url);
256 # Loop through the hash of configured providers.
257 foreach my $id ( keys %used_providers ) {
258 # Skip providers which are not enabled.
259 next if ($used_providers{$id}[3] ne "enabled");
261 # Obtain the provider handle.
262 my $provider_handle = $used_providers{$id}[0];
264 # Handle update off all providers.
265 if (($provider eq "all") || ($provider_handle eq "$provider")) {
266 # Add provider handle and it's id to the hash of sheduled providers.
267 $sheduled_providers{$provider_handle} = $id;
271 # Loop through the hash of sheduled providers.
272 foreach my $provider ( keys %sheduled_providers) {
273 # Grab the download url for the provider.
274 my $url = $IDS::Ruleset
::Providers
{$provider}{'dl_url'};
276 # Check if the provider requires a subscription.
277 if ($IDS::Ruleset
::Providers
{$provider}{'requires_subscription'} eq "True") {
278 # Grab the previously stored access id for the provider from hash.
279 my $id = $sheduled_providers{$provider};
281 # Grab the subscription code.
282 my $subscription_code = $used_providers{$id}[1];
284 # Add the subscription code to the download url.
285 $url =~ s/\<subscription_code\>/$subscription_code/g;
289 # Abort if no url could be determined for the provider.
291 # Log error and abort.
292 &_log_to_syslog
("Unable to gather a download URL for the selected ruleset provider.");
296 # Variable to store the filesize of the remote object.
299 # The sourcfire (snort rules) does not allow to send "HEAD" requests, so skip this check
300 # for this webserver.
302 # Check if the ruleset source contains "snort.org".
303 unless ($url =~ /\.snort\.org/) {
304 # Pass the requrested url to the downloader.
305 my $request = HTTP
::Request
->new(HEAD
=> $url);
307 # Accept the html header.
308 $request->header('Accept' => 'text/html');
310 # Perform the request and fetch the html header.
311 my $response = $downloader->request($request);
313 # Check if there was any error.
314 unless ($response->is_success) {
316 my $error = $response->status_line();
319 &_log_to_syslog
("Unable to download the ruleset. \($error\)");
321 # Return "1" - false.
325 # Assign the fetched header object.
326 my $header = $response->headers();
328 # Grab the remote file size from the object and store it in the
330 $remote_filesize = $header->content_length;
333 # Load perl module to deal with temporary files.
336 # Generate temporary file name, located in "/var/tmp" and with a suffix of ".tmp".
337 my $tmp = File
::Temp
->new( SUFFIX
=> ".tmp", DIR
=> "/var/tmp/", UNLINK
=> 0 );
338 my $tmpfile = $tmp->filename();
340 # Pass the requested url to the downloader.
341 my $request = HTTP
::Request
->new(GET
=> $url);
343 # Perform the request and save the output into the tmpfile.
344 my $response = $downloader->request($request, $tmpfile);
346 # Check if there was any error.
347 unless ($response->is_success) {
349 my $error = $response->content;
352 &_log_to_syslog
("Unable to download the ruleset. \($error\)");
354 # Return "1" - false.
358 # Load perl stat module.
361 # Perform stat on the tmpfile.
362 my $stat = stat($tmpfile);
364 # Grab the local filesize of the downloaded tarball.
365 my $local_filesize = $stat->size;
367 # Check if both file sizes match.
368 if (($remote_filesize) && ($remote_filesize ne $local_filesize)) {
370 &_log_to_syslog
("Unable to completely download the ruleset. ");
371 &_log_to_syslog
("Only got $local_filesize Bytes instead of $remote_filesize Bytes. ");
373 # Delete temporary file.
376 # Return "1" - false.
380 # Genarate and assign file name and path to store the downloaded rules file.
381 my $dl_rulesfile = &_get_dl_rulesfile
($provider);
383 # Check if a file name could be obtained.
384 unless ($dl_rulesfile) {
386 &_log_to_syslog
("Unable to store the downloaded rules file. ");
388 # Delete downloaded temporary file.
391 # Return "1" - false.
394 # Load file copy module, which contains the move() function.
397 # Overwrite the may existing rulefile or tarball with the downloaded one.
398 move
("$tmpfile", "$dl_rulesfile");
400 # Delete temporary file.
403 # Set correct ownership for the tarball.
404 set_ownership
("$dl_rulesfile");
407 # If we got here, everything worked fine. Return nothing.
412 ## Function to extract a given ruleset.
414 sub extractruleset
($) {
417 # Load perl module to deal with archives.
420 # Load perl module to deal with files and path.
423 # Get full path and downloaded rulesfile for the given provider.
424 my $tarball = &_get_dl_rulesfile
($provider);
426 # Check if the file exists.
427 unless (-f
$tarball) {
428 &_log_to_syslog
("Could not extract ruleset file: $tarball");
434 # Destination directories, where the files will be extracted.
435 my $rules_destdir = "$tmp_directory/rules";
436 my $conf_destdir = "$tmp_directory/conf";
438 # Check if the temporary directories exist, otherwise create them.
439 mkdir("$tmp_directory") unless (-d
"$tmp_directory");
440 mkdir("$rules_destdir") unless (-d
"$rules_destdir");
441 mkdir("$conf_destdir") unless (-d
"$conf_destdir");
443 # Initialize the tar module.
444 my $tar = Archive
::Tar
->new($tarball);
446 # Get the filelist inside the tarball.
447 my @packed_files = $tar->list_files;
449 # Loop through the filelist.
450 foreach my $packed_file (@packed_files) {
453 # Splitt the packed file into chunks.
454 my $file = fileparse
($packed_file);
456 # Handle msg-id.map file.
457 if ("$file" eq "sid-msg.map") {
458 # Set extract destination to temporary config_dir.
459 $destination = "$conf_destdir/$provider\-sid-msg.map";
460 # Handle classification.conf
461 } elsif ("$file" eq "classification.config") {
462 # Set extract destination to temporary config_dir.
463 $destination = "$conf_destdir/$provider\-classification.config";
464 # Handle rules files.
465 } elsif ($file =~ m/\.rules$/) {
468 # Splitt the filename into chunks.
469 my @filename = split("-", $file);
472 @filename = reverse(@filename);
474 # Get the amount of elements in the array.
475 my $elements = @filename;
477 # Remove last element of the hash.
478 # It contains the vendor name, which will be replaced.
479 if ($elements >= 3) {
480 # Remove last element from hash.
484 # Check if the last element of the filename does not
485 # contain the providers name.
486 if (@filename[-1] ne "$provider") {
487 # Add provider name as last element.
488 push(@filename, $provider);
491 # Reverse the array back.
492 @filename = reverse(@filename);
494 # Generate the name for the rulesfile.
495 $rulesfilename = join("-", @filename);
497 # Set extract destination to temporaray rules_dir.
498 $destination = "$rules_destdir/$rulesfilename";
500 # Skip all other files.
504 # Extract the file to the temporary directory.
505 $tar->extract_file("$packed_file", "$destination");
510 ## A tiny wrapper function to call the oinkmaster script.
513 # Check if the files in rulesdir have the correct permissions.
514 &_check_rulesdir_permissions
();
516 # Cleanup the rules directory before filling it with the new rulest.
517 &_cleanup_rulesdir
();
519 # Load perl module to talk to the kernel syslog.
520 use Sys
::Syslog
qw(:DEFAULT setlogsock);
522 # Establish the connection to the syslog service.
523 openlog
('oinkmaster', 'cons,pid', 'user');
525 # Call oinkmaster to generate ruleset.
526 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";
528 # Log output of oinkmaster to syslog.
529 while(<OINKMASTER
>) {
530 # The syslog function works best with an array based input,
531 # so generate one before passing the message details to syslog.
532 my @syslog = ("INFO", "$_");
534 # Send the log message.
538 # Close the pipe to oinkmaster process.
541 # Close the log handle.
546 ## Function to merge the classifications for a given amount of providers and write them
547 ## to the classifications file.
549 sub merge_classifications
(@
) {
552 # Hash to store all collected classifications.
553 my %classifications = ();
555 # Loop through the given array of providers.
556 foreach my $provider (@providers) {
557 # Generate full path to classification file.
558 my $classification_file = "$tmp_directory/conf/$provider\-classification.config";
560 # Skip provider if no classification file exists.
561 next unless (-f
"$classification_file");
563 # Open the classification file.
564 open(CLASSIFICATION
, $classification_file) or die "Could not open file $classification_file. $!\n";
566 # Loop through the file content.
567 while(<CLASSIFICATION
>) {
568 # Parse the file and grab the classification details.
569 if ($_ =~/.*config classification\: (.*)/) {
570 # Split the grabbed details.
571 my ($short_name, $short_desc, $priority) = split("\,", $1);
573 # Check if the grabbed classification is allready known and the priority value is greater
574 # than the stored one (which causes less priority in the IDS).
575 if (($classifications{$short_name}) && ($classifications{$short_name}[1] >= $priority)) {
576 #Change the priority value to the stricter one.
577 $classifications{$short_name} = [ "$classifications{$short_name}[0]", "$priority" ];
579 # Add the classification to the hash.
580 $classifications{$short_name} = [ "$short_desc", "$priority" ];
586 close(CLASSIFICATION
);
589 # Open classification file for writing.
590 open(FILE
, ">", "$classification_file") or die "Could not write to $classification_file. $!\n";
592 # Print notice about autogenerated file.
593 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n\n";
595 # Sort and loop through the hash of classifications.
596 foreach my $key (sort keys %classifications) {
597 # Assign some nice variable names for the items.
598 my $short_name = $key;
599 my $short_desc = $classifications{$key}[0];
600 my $priority = $classifications{$key}[1];
602 # Write the classification to the file.
603 print FILE
"config classification: $short_name,$short_desc,$priority\n";
611 ## Function to do all the logging stuff if the downloading or updating of the ruleset fails.
616 # Remove any newline.
619 # Call private function to log the error message to syslog.
620 &_log_to_syslog
($error);
622 # Call private function to write/store the error message in the storederrorfile.
623 &_store_error_message
($error);
627 ## Function to log a given error message to the kernel syslog.
629 sub _log_to_syslog
($) {
632 # Load perl module to talk to the kernel syslog.
633 use Sys
::Syslog
qw(:DEFAULT setlogsock);
635 # The syslog function works best with an array based input,
636 # so generate one before passing the message details to syslog.
637 my @syslog = ("ERR", "<ERROR> $message");
639 # Establish the connection to the syslog service.
640 openlog
('oinkmaster', 'cons,pid', 'user');
642 # Send the log message.
645 # Close the log handle.
650 ## Private function to write a given error message to the storederror file.
652 sub _store_error_message
($) {
655 # Remove any newline.
658 # Open file for writing.
659 open (ERRORFILE
, ">$storederrorfile") or die "Could not write to $storederrorfile. $!\n";
661 # Write error to file.
662 print ERRORFILE
"$message\n";
667 # Set correct ownership for the file.
668 &set_ownership
("$storederrorfile");
672 ## Private function to get the path and filename for a downloaded ruleset by a given provider.
674 sub _get_dl_rulesfile
($) {
677 # Gather the download type for the given provider.
678 my $dl_type = $IDS::Ruleset
::Providers
{$provider}{'dl_type'};
680 # Obtain the file suffix for the download file type.
681 my $suffix = $dl_type_to_suffix{$dl_type};
683 # Check if a suffix has been found.
685 # Abort return - nothing.
689 # Generate the full filename and path for the stored rules file.
690 my $rulesfile = "$dl_rules_path/$dl_rulesfile_prefix-$provider$suffix";
692 # Return the generated filename.
697 ## Function to check if the IDS is running.
699 sub ids_is_running
() {
701 # Open PID file for reading.
702 open(PIDFILE
, "$idspidfile") or die "Could not open $idspidfile. $!\n";
704 # Grab the process-id.
710 # Remove any newline.
713 # Check if a directory for the process-id exists in proc.
714 if(-d
"/proc/$pid") {
715 # The IDS daemon is running return the process id.
720 # Return nothing - IDS is not running.
725 ## Function to call suricatactrl binary with a given command.
727 sub call_suricatactrl
($) {
729 my ($option, $interval) = @_;
731 # Loop through the array of supported commands and check if
732 # the given one is part of it.
733 foreach my $cmd (@suricatactrl_cmds) {
734 # Skip current command unless the given one has been found.
735 next unless($cmd eq $option);
737 # Check if the given command is "cron".
738 if ($option eq "cron") {
739 # Check if an interval has been given.
741 # Check if the given interval is valid.
742 foreach my $element (@cron_intervals) {
743 # Skip current element until the given one has been found.
744 next unless($element eq $interval);
746 # Call the suricatactrl binary and pass the "cron" command
747 # with the requrested interval.
748 &General
::system("$suricatactrl", "$option", "$interval");
755 # If we got here, the given interval is not supported or none has been given. - Return nothing.
758 # Call the suricatactrl binary and pass the requrested
760 &General
::system("$suricatactrl", "$option");
767 # Command not found - return nothing.
772 ## Function to create a new empty file.
774 sub create_empty_file
($) {
777 # Check if the given file exists.
779 # Do nothing to prevent from overwriting existing files.
783 # Open the file for writing.
784 open(FILE
, ">$file") or die "Could not write to $file. $!\n";
794 ## Private function to check if the file permission of the rulespath are correct.
795 ## If not, call suricatactrl to fix them.
797 sub _check_rulesdir_permissions
() {
798 # Check if the rulepath main directory is writable.
799 unless (-W
$rulespath) {
800 # If not call suricatctrl to fix it.
801 &call_suricatactrl
("fix-rules-dir");
804 # Open snort rules directory and do a directory listing.
805 opendir(DIR
, $rulespath) or die $!;
806 # Loop through the direcory.
807 while (my $file = readdir(DIR
)) {
808 # We only want files.
809 next unless (-f
"$rulespath/$file");
811 # Check if the file is writable by the user.
812 if (-W
"$rulespath/$file") {
813 # Everything is okay - go on to the next file.
816 # There are wrong permissions, call suricatactrl to fix it.
817 &call_suricatactrl
("fix-rules-dir");
823 ## Private function to cleanup the directory which contains
824 ## the IDS rules, before extracting and modifing the new ruleset.
826 sub _cleanup_rulesdir
() {
827 # Open rules directory and do a directory listing.
828 opendir(DIR
, $rulespath) or die $!;
830 # Loop through the direcory.
831 while (my $file = readdir(DIR
)) {
832 # We only want files.
833 next unless (-f
"$rulespath/$file");
835 # Skip element if it has config as file extension.
836 next if ($file =~ m/\.config$/);
838 # Skip rules file for whitelisted hosts.
839 next if ("$rulespath/$file" eq $whitelist_file);
841 # Skip rules file with local rules.
842 next if ("$rulespath/$file" eq $local_rules_file);
844 # Delete the current processed file, if not, exit this function
845 # and return an error message.
846 unlink("$rulespath/$file") or return "Could not delete $rulespath/$file. $!\n";
854 ## Function to generate the file which contains the home net information.
856 sub generate_home_net_file
() {
859 # Read-in network settings.
860 &General
::readhash
("${General::swroot}/ethernet/settings", \
%netsettings);
862 # Get available network zones.
863 my @network_zones = &Network
::get_available_network_zones
();
865 # Temporary array to store network address and prefix of the configured
869 # Loop through the array of available network zones.
870 foreach my $zone (@network_zones) {
871 # Check if the current processed zone is red.
873 # Grab the IP-address of the red interface.
874 my $red_address = &get_red_address
();
876 # Check if an address has been obtained.
878 # Generate full network string.
879 my $red_network = join("/", $red_address, "32");
881 # Add the red network to the array of networks.
882 push(@networks, $red_network);
885 # Check if the configured RED_TYPE is static.
886 if ($netsettings{'RED_TYPE'} eq "STATIC") {
887 # Get configured and enabled aliases.
888 my @aliases = &get_aliases
();
890 # Loop through the array.
891 foreach my $alias (@aliases) {
893 my $network = join("/", $alias, "32");
895 # Add the generated network to the array of networks.
896 push(@networks, $network);
899 # Process remaining network zones.
901 # Convert current zone name into upper case.
904 # Generate key to access the required data from the netsettings hash.
905 my $zone_netaddress = $zone . "_NETADDRESS";
906 my $zone_netmask = $zone . "_NETMASK";
908 # Obtain the settings from the netsettings hash.
909 my $netaddress = $netsettings{$zone_netaddress};
910 my $netmask = $netsettings{$zone_netmask};
912 # Convert the subnetmask into prefix notation.
913 my $prefix = &Network
::convert_netmask2prefix
($netmask);
915 # Generate full network string.
916 my $network = join("/", $netaddress,$prefix);
918 # Check if the network is valid.
919 if(&Network
::check_subnet
($network)) {
920 # Add the generated network to the array of networks.
921 push(@networks, $network);
926 # Format home net declaration.
927 my $line = "\"[" . join(',', @networks) . "]\"";
929 # Open file to store the addresses of the home net.
930 open(FILE
, ">$homenet_file") or die "Could not open $homenet_file. $!\n";
933 print FILE
"%YAML 1.1\n";
934 print FILE
"---\n\n";
936 # Print notice about autogenerated file.
937 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
939 # Print the generated and required HOME_NET declaration to the file.
940 print FILE
"HOME_NET:\t$line\n";
947 # Function to generate and write the file which contains the configured and used DNS servers.
949 sub generate_dns_servers_file
() {
950 # Get the used DNS servers.
951 my @nameservers = &General
::get_nameservers
();
953 # Get network settings.
955 &General
::readhash
("${General::swroot}/ethernet/settings", \
%netsettings);
957 # Format dns servers declaration.
960 # Check if the system has configured nameservers.
962 # Add the GREEN address as DNS servers.
963 push(@nameservers, $netsettings{'GREEN_ADDRESS'});
965 # Check if a BLUE zone exists.
966 if ($netsettings{'BLUE_ADDRESS'}) {
967 # Add the BLUE address to the array of nameservers.
968 push(@nameservers, $netsettings{'BLUE_ADDRESS'});
971 # Generate the line which will be written to the DNS servers file.
972 $line = join(",", @nameservers);
974 # External net simply contains (any).
975 $line = "\$EXTERNAL_NET";
978 # Open file to store the used DNS server addresses.
979 open(FILE
, ">$dns_servers_file") or die "Could not open $dns_servers_file. $!\n";
982 print FILE
"%YAML 1.1\n";
983 print FILE
"---\n\n";
985 # Print notice about autogenerated file.
986 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
988 # Print the generated DNS declaration to the file.
989 print FILE
"DNS_SERVERS:\t\"[$line]\"\n";
996 # Function to generate and write the file which contains the HTTP_PORTS definition.
998 sub generate_http_ports_file
() {
1001 # Read-in proxy settings
1002 &General
::readhash
("${General::swroot}/proxy/advanced/settings", \
%proxysettings);
1004 # Check if the proxy is enabled.
1005 if (( -e
"${General::swroot}/proxy/enable") || (-e
"${General::swroot}/proxy/enable_blue")) {
1006 # Add the proxy port to the array of HTTP ports.
1007 push(@http_ports, $proxysettings{'PROXY_PORT'});
1010 # Check if the transparent mode of the proxy is enabled.
1011 if ((-e
"${General::swroot}/proxy/transparent") || (-e
"${General::swroot}/proxy/transparent_blue")) {
1012 # Add the transparent proxy port to the array of HTTP ports.
1013 push(@http_ports, $proxysettings{'TRANSPARENT_PORT'});
1016 # Format HTTP_PORTS declaration.
1019 # Generate line which will be written to the http ports file.
1020 $line = join(",", @http_ports);
1022 # Open file to store the HTTP_PORTS.
1023 open(FILE
, ">$http_ports_file") or die "Could not open $http_ports_file. $!\n";
1025 # Print yaml header.
1026 print FILE
"%YAML 1.1\n";
1027 print FILE
"---\n\n";
1029 # Print notice about autogenerated file.
1030 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1032 # Print the generated HTTP_PORTS declaration to the file.
1033 print FILE
"HTTP_PORTS:\t\"[$line]\"\n";
1035 # Close file handle.
1040 ## Function to generate and write the file for used rulefiles.
1042 sub write_used_rulefiles_file
(@
) {
1045 # Open file for used rulefiles.
1046 open (FILE
, ">$used_rulefiles_file") or die "Could not write to $used_rulefiles_file. $!\n";
1048 # Write yaml header to the file.
1049 print FILE
"%YAML 1.1\n";
1050 print FILE
"---\n\n";
1052 # Write header to file.
1053 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1055 # Allways use the whitelist.
1056 print FILE
" - whitelist.rules\n";
1058 # Loop through the array of given files.
1059 foreach my $file (@files) {
1060 # Check if the given filename exists and write it to the file of used rulefiles.
1061 if(-f
"$rulespath/$file") {
1062 print FILE
" - $file\n";
1066 # Close file after writing.
1071 ## Function to generate and write the file for modify the ruleset.
1073 sub write_modify_sids_file
() {
1074 # Get configured settings.
1076 my %rulessettings=();
1077 &General
::readhash
("$ids_settings_file", \
%idssettings);
1078 &General
::readhash
("$rules_settings_file", \
%rulessettings);
1080 # Gather the configured ruleset.
1081 my $ruleset = $rulessettings{'RULES'};
1083 # Open modify sid's file for writing.
1084 open(FILE
, ">$modify_sids_file") or die "Could not write to $modify_sids_file. $!\n";
1086 # Write file header.
1087 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
1089 # Check if the traffic only should be monitored.
1090 unless($idssettings{'MONITOR_TRAFFIC_ONLY'} eq 'on') {
1091 # Suricata is in IPS mode, which means that the rule actions have to be changed
1092 # from 'alert' to 'drop', however not all rules should be changed. Some rules
1093 # exist purely to set a flowbit which is used to convey other information, such
1094 # as a specific type of file being downloaded, to other rulewhich then check for
1095 # malware in that file. Rules which fall into the first category should stay as
1096 # alert since not all flows of that type contain malware.
1098 if($ruleset eq 'registered' or $ruleset eq 'subscripted' or $ruleset eq 'community') {
1099 # These types of rulesfiles contain meta-data which gives the action that should
1100 # be used when in IPS mode. Do the following:
1102 # 1. Disable all rules and set the action to 'drop'
1103 # 2. Set the action back to 'alert' if the rule contains 'flowbits:noalert;'
1104 # This should give rules not in the policy a reasonable default if the user
1105 # manually enables them.
1106 # 3. Enable rules and set actions according to the meta-data strings.
1108 my $policy = 'balanced'; # Placeholder to allow policy to be changed.
1111 modifysid * "^#?(?:alert|drop)" | "#drop"
1112 modifysid * "^#drop(.+flowbits:noalert;)" | "#alert\${1}"
1113 modifysid * "^#(?:alert|drop)(.+policy $policy-ips alert)" | "alert\${1}"
1114 modifysid * "^#(?:alert|drop)(.+policy $policy-ips drop)" | "drop\${1}"
1117 # These rulefiles don't have the metadata, so set rules to 'drop' unless they
1118 # contain the string 'flowbits:noalert;'.
1120 modifysid * "^(#?)(?:alert|drop)" | "\${1}drop"
1121 modifysid * "^(#?)drop(.+flowbits:noalert;)" | "\${1}alert\${2}"
1126 # Close file handle.
1131 ## Function to gather the version of suricata.
1133 sub get_suricata_version
($) {
1136 # Execute piped suricata command and return the version information.
1137 open(SURICATA
, "suricata -V |") or die "Couldn't execute program: $!";
1139 # Grab and store the output of the piped program.
1140 my $version_string = <SURICATA
>;
1146 chomp($version_string);
1148 # Grab the version from the version string.
1149 $version_string =~ /([0-9]+([.][0-9]+)+)/;
1151 # Splitt the version into single chunks.
1152 my ($major_ver, $minor_ver, $patchlevel) = split(/\./, $1);
1154 # Check and return the requested version sheme.
1155 if ($format eq "major") {
1156 # Return the full version.
1157 return "$major_ver";
1158 } elsif ($format eq "minor") {
1159 # Return the major and minor part.
1160 return "$major_ver.$minor_ver";
1162 # Return the full version string.
1163 return "$major_ver.$minor_ver.$patchlevel";
1168 ## Function to generate the rules file with whitelisted addresses.
1170 sub generate_ignore_file
() {
1173 # SID range 1000000-1999999 Reserved for Local Use
1174 # Put your custom rules in this range to avoid conflicts
1177 # Read-in ignoredfile.
1178 &General
::readhasharray
($IDS::ignored_file
, \
%ignored);
1180 # Open ignorefile for writing.
1181 open(FILE
, ">$IDS::whitelist_file") or die "Could not write to $IDS::whitelist_file. $!\n";
1183 # Config file header.
1184 print FILE
"# Autogenerated file.\n";
1185 print FILE
"# All user modifications will be overwritten.\n\n";
1187 # Add all user defined addresses to the whitelist.
1189 # Check if the hash contains any elements.
1190 if (keys (%ignored)) {
1191 # Loop through the entire hash and write the host/network
1192 # and remark to the ignore file.
1193 while ( (my $key) = each %ignored) {
1194 my $address = $ignored{$key}[0];
1195 my $remark = $ignored{$key}[1];
1196 my $status = $ignored{$key}[2];
1198 # Check if the status of the entry is "enabled".
1199 if ($status eq "enabled") {
1200 # Check if the address/network is valid.
1201 if ((&General
::validip
($address)) || (&General
::validipandmask
($address))) {
1202 # Write rule line to the file to pass any traffic from this IP
1203 print FILE
"pass ip $address any -> any any (msg:\"pass all traffic from/to $address\"\; sid:$sid\;)\n";
1216 ## Function to set correct ownership for single files and directories.
1219 sub set_ownership
($) {
1222 # User and group of the WUI.
1223 my $uname = "nobody";
1224 my $grname = "nobody";
1226 # The chown function implemented in perl requies the user and group as nummeric id's.
1227 my $uid = getpwnam($uname);
1228 my $gid = getgrnam($grname);
1230 # Check if the given target exists.
1232 # Stop the script and print error message.
1233 die "The $target does not exist. Cannot change the ownership!\n";
1236 # Check weather the target is a file or directory.
1238 # Change ownership ot the single file.
1239 chown($uid, $gid, "$target");
1240 } elsif (-d
$target) {
1241 # Do a directory listing.
1242 opendir(DIR
, $target) or die $!;
1243 # Loop through the direcory.
1244 while (my $file = readdir(DIR
)) {
1246 # We only want files.
1247 next unless (-f
"$target/$file");
1249 # Set correct ownership for the files.
1250 chown($uid, $gid, "$target/$file");
1255 # Change ownership of the directory.
1256 chown($uid, $gid, "$target");
1261 ## Function to read-in the aliases file and returns all configured and enabled aliases.
1264 # Location of the aliases file.
1265 my $aliases_file = "${General::swroot}/ethernet/aliases";
1267 # Array to store the aliases.
1270 # Check if the file is empty.
1271 if (-z
$aliases_file) {
1272 # Abort nothing to do.
1276 # Open the aliases file.
1277 open(ALIASES
, $aliases_file) or die "Could not open $aliases_file. $!\n";
1279 # Loop through the file content.
1280 while (my $line = <ALIASES
>) {
1284 # Splitt line content into single chunks.
1285 my ($address, $state, $remark) = split(/\,/, $line);
1287 # Check if the state of the current processed alias is "on".
1288 if ($state eq "on") {
1289 # Check if the address is valid.
1290 if(&Network
::check_ip_address
($address)) {
1291 # Add the alias to the array of aliases.
1292 push(@aliases, $address);
1297 # Close file handle.
1305 ## Function to grab the current assigned IP-address on red.
1307 sub get_red_address
() {
1308 # File, which contains the current IP-address of the red interface.
1309 my $file = "${General::swroot}/red/local-ipaddress";
1311 # Check if the file exists.
1313 # Open the given file.
1314 open(FILE
, "$file") or die "Could not open $file.";
1316 # Obtain the address from the first line of the file.
1317 my $address = <FILE
>;
1325 # Check if the grabbed address is valid.
1326 if (&General
::validip
($address)) {
1327 # Return the address.
1337 ## Function to write the lock file for locking the WUI, while
1338 ## the autoupdate script runs.
1340 sub lock_ids_page
() {
1341 # Call subfunction to create the file.
1342 &create_empty_file
($ids_page_lock_file);
1346 ## Function to release the lock of the WUI, again.
1348 sub unlock_ids_page
() {
1350 unlink($ids_page_lock_file);