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 rulesets or if no one is specified
187 ## all configured rulesets will be downloaded.
189 ## * At first it gathers all configured ruleset providers, initialize the downloader and sets an
190 ## upstream proxy if configured.
191 ## * After that, the given ruleset or in case all rulesets should be downloaded, it will determine wether it
192 ## is enabled or not.
193 ## * The next step will be to generate the final download url, by obtaining the URL for the desired
194 ## ruleset, add the settings for the upstream proxy.
195 ## * Finally the function will grab all the rules files or tarballs from the servers.
197 sub downloadruleset
($) {
200 # If no provider is given default to "all".
203 # Hash to store the providers and access id's, for which rules should be downloaded.
204 my %sheduled_providers = ();
206 # Get used provider settings.
207 my %used_providers = ();
208 &General
::readhasharray
("$providers_settings_file", \
%used_providers);
210 # Check if a ruleset has been configured.
211 unless(%used_providers) {
212 # Log that no ruleset has been configured and abort.
213 &_log_to_syslog
("No ruleset provider has been configured.");
219 # Read proxysettings.
220 my %proxysettings=();
221 &General
::readhash
("${General::swroot}/proxy/settings", \
%proxysettings);
223 # Load required perl module to handle the download.
226 # Init the download module.
227 my $downloader = LWP
::UserAgent
->new;
229 # Set timeout to 10 seconds.
230 $downloader->timeout(10);
232 # Check if an upstream proxy is configured.
233 if ($proxysettings{'UPSTREAM_PROXY'}) {
236 $proxy_url = "http://";
238 # Check if the proxy requires authentication.
239 if (($proxysettings{'UPSTREAM_USER'}) && ($proxysettings{'UPSTREAM_PASSWORD'})) {
240 $proxy_url .= "$proxysettings{'UPSTREAM_USER'}\:$proxysettings{'UPSTREAM_PASSWORD'}\@";
243 # Add proxy server address and port.
244 $proxy_url .= $proxysettings{'UPSTREAM_PROXY'};
246 # Setup proxy settings.
247 $downloader->proxy(['http', 'https'], $proxy_url);
250 # Loop through the hash of configured providers.
251 foreach my $id ( keys %used_providers ) {
252 # Skip providers which are not enabled.
253 next if ($used_providers{$id}[3] ne "enabled");
255 # Obtain the provider handle.
256 my $provider_handle = $used_providers{$id}[0];
258 # Handle update off all providers.
259 if (($provider eq "all") || ($provider_handle eq "$provider")) {
260 # Add provider handle and it's id to the hash of sheduled providers.
261 $sheduled_providers{$provider_handle} = $id;
265 # Loop through the hash of sheduled providers.
266 foreach my $provider ( keys %sheduled_providers) {
267 # Grab the download url for the provider.
268 my $url = $IDS::Ruleset
::Providers
{$provider}{'dl_url'};
270 # Check if the provider requires a subscription.
271 if ($IDS::Ruleset
::Providers
{$provider}{'requires_subscription'} eq "True") {
272 # Grab the previously stored access id for the provider from hash.
273 my $id = $sheduled_providers{$provider};
275 # Grab the subscription code.
276 my $subscription_code = $used_providers{$id}[1];
278 # Add the subscription code to the download url.
279 $url =~ s/\<subscription_code\>/$subscription_code/g;
283 # Abort if no url could be determined for the provider.
285 # Log error and abort.
286 &_log_to_syslog
("Unable to gather a download URL for the selected ruleset provider.");
290 # Variable to store the filesize of the remote object.
293 # The sourcfire (snort rules) does not allow to send "HEAD" requests, so skip this check
294 # for this webserver.
296 # Check if the ruleset source contains "snort.org".
297 unless ($url =~ /\.snort\.org/) {
298 # Pass the requrested url to the downloader.
299 my $request = HTTP
::Request
->new(HEAD
=> $url);
301 # Accept the html header.
302 $request->header('Accept' => 'text/html');
304 # Perform the request and fetch the html header.
305 my $response = $downloader->request($request);
307 # Check if there was any error.
308 unless ($response->is_success) {
310 my $error = $response->status_line();
313 &_log_to_syslog
("Unable to download the ruleset. \($error\)");
315 # Return "1" - false.
319 # Assign the fetched header object.
320 my $header = $response->headers();
322 # Grab the remote file size from the object and store it in the
324 $remote_filesize = $header->content_length;
327 # Load perl module to deal with temporary files.
330 # Generate temporary file name, located in "/var/tmp" and with a suffix of ".tmp".
331 my $tmp = File
::Temp
->new( SUFFIX
=> ".tmp", DIR
=> "/var/tmp/", UNLINK
=> 0 );
332 my $tmpfile = $tmp->filename();
334 # Pass the requested url to the downloader.
335 my $request = HTTP
::Request
->new(GET
=> $url);
337 # Perform the request and save the output into the tmpfile.
338 my $response = $downloader->request($request, $tmpfile);
340 # Check if there was any error.
341 unless ($response->is_success) {
343 my $error = $response->content;
346 &_log_to_syslog
("Unable to download the ruleset. \($error\)");
348 # Return "1" - false.
352 # Load perl stat module.
355 # Perform stat on the tmpfile.
356 my $stat = stat($tmpfile);
358 # Grab the local filesize of the downloaded tarball.
359 my $local_filesize = $stat->size;
361 # Check if both file sizes match.
362 if (($remote_filesize) && ($remote_filesize ne $local_filesize)) {
364 &_log_to_syslog
("Unable to completely download the ruleset. ");
365 &_log_to_syslog
("Only got $local_filesize Bytes instead of $remote_filesize Bytes. ");
367 # Delete temporary file.
370 # Return "1" - false.
374 # Genarate and assign file name and path to store the downloaded rules file.
375 my $dl_rulesfile = &_get_dl_rulesfile
($provider);
377 # Check if a file name could be obtained.
378 unless ($dl_rulesfile) {
380 &_log_to_syslog
("Unable to store the downloaded rules file. ");
382 # Delete downloaded temporary file.
385 # Return "1" - false.
388 # Load file copy module, which contains the move() function.
391 # Overwrite the may existing rulefile or tarball with the downloaded one.
392 move
("$tmpfile", "$dl_rulesfile");
394 # Delete temporary file.
397 # Set correct ownership for the tarball.
398 set_ownership
("$dl_rulesfile");
401 # If we got here, everything worked fine. Return nothing.
406 ## A tiny wrapper function to call the oinkmaster script.
409 # Check if the files in rulesdir have the correct permissions.
410 &_check_rulesdir_permissions
();
412 # Cleanup the rules directory before filling it with the new rulest.
413 &_cleanup_rulesdir
();
415 # Load perl module to talk to the kernel syslog.
416 use Sys
::Syslog
qw(:DEFAULT setlogsock);
418 # Establish the connection to the syslog service.
419 openlog
('oinkmaster', 'cons,pid', 'user');
421 # Call oinkmaster to generate ruleset.
422 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";
424 # Log output of oinkmaster to syslog.
425 while(<OINKMASTER
>) {
426 # The syslog function works best with an array based input,
427 # so generate one before passing the message details to syslog.
428 my @syslog = ("INFO", "$_");
430 # Send the log message.
434 # Close the pipe to oinkmaster process.
437 # Close the log handle.
442 ## Function to do all the logging stuff if the downloading or updating of the ruleset fails.
447 # Remove any newline.
450 # Call private function to log the error message to syslog.
451 &_log_to_syslog
($error);
453 # Call private function to write/store the error message in the storederrorfile.
454 &_store_error_message
($error);
458 ## Function to log a given error message to the kernel syslog.
460 sub _log_to_syslog
($) {
463 # Load perl module to talk to the kernel syslog.
464 use Sys
::Syslog
qw(:DEFAULT setlogsock);
466 # The syslog function works best with an array based input,
467 # so generate one before passing the message details to syslog.
468 my @syslog = ("ERR", "<ERROR> $message");
470 # Establish the connection to the syslog service.
471 openlog
('oinkmaster', 'cons,pid', 'user');
473 # Send the log message.
476 # Close the log handle.
481 ## Private function to write a given error message to the storederror file.
483 sub _store_error_message
($) {
486 # Remove any newline.
489 # Open file for writing.
490 open (ERRORFILE
, ">$storederrorfile") or die "Could not write to $storederrorfile. $!\n";
492 # Write error to file.
493 print ERRORFILE
"$message\n";
498 # Set correct ownership for the file.
499 &set_ownership
("$storederrorfile");
503 ## Private function to get the path and filename for a downloaded ruleset by a given provider.
505 sub _get_dl_rulesfile
($) {
508 # Gather the download type for the given provider.
509 my $dl_type = $IDS::Ruleset
::Providers
{$provider}{'dl_type'};
511 # Obtain the file suffix for the download file type.
512 my $suffix = $dl_type_to_suffix{$dl_type};
514 # Check if a suffix has been found.
516 # Abort return - nothing.
520 # Generate the full filename and path for the stored rules file.
521 my $rulesfile = "$dl_rules_path/$dl_rulesfile_prefix-$provider$suffix";
523 # Return the generated filename.
528 ## Function to check if the IDS is running.
530 sub ids_is_running
() {
532 # Open PID file for reading.
533 open(PIDFILE
, "$idspidfile") or die "Could not open $idspidfile. $!\n";
535 # Grab the process-id.
541 # Remove any newline.
544 # Check if a directory for the process-id exists in proc.
545 if(-d
"/proc/$pid") {
546 # The IDS daemon is running return the process id.
551 # Return nothing - IDS is not running.
556 ## Function to call suricatactrl binary with a given command.
558 sub call_suricatactrl
($) {
560 my ($option, $interval) = @_;
562 # Loop through the array of supported commands and check if
563 # the given one is part of it.
564 foreach my $cmd (@suricatactrl_cmds) {
565 # Skip current command unless the given one has been found.
566 next unless($cmd eq $option);
568 # Check if the given command is "cron".
569 if ($option eq "cron") {
570 # Check if an interval has been given.
572 # Check if the given interval is valid.
573 foreach my $element (@cron_intervals) {
574 # Skip current element until the given one has been found.
575 next unless($element eq $interval);
577 # Call the suricatactrl binary and pass the "cron" command
578 # with the requrested interval.
579 &General
::system("$suricatactrl", "$option", "$interval");
586 # If we got here, the given interval is not supported or none has been given. - Return nothing.
589 # Call the suricatactrl binary and pass the requrested
591 &General
::system("$suricatactrl", "$option");
598 # Command not found - return nothing.
603 ## Function to create a new empty file.
605 sub create_empty_file
($) {
608 # Check if the given file exists.
610 # Do nothing to prevent from overwriting existing files.
614 # Open the file for writing.
615 open(FILE
, ">$file") or die "Could not write to $file. $!\n";
625 ## Private function to check if the file permission of the rulespath are correct.
626 ## If not, call suricatactrl to fix them.
628 sub _check_rulesdir_permissions
() {
629 # Check if the rulepath main directory is writable.
630 unless (-W
$rulespath) {
631 # If not call suricatctrl to fix it.
632 &call_suricatactrl
("fix-rules-dir");
635 # Open snort rules directory and do a directory listing.
636 opendir(DIR
, $rulespath) or die $!;
637 # Loop through the direcory.
638 while (my $file = readdir(DIR
)) {
639 # We only want files.
640 next unless (-f
"$rulespath/$file");
642 # Check if the file is writable by the user.
643 if (-W
"$rulespath/$file") {
644 # Everything is okay - go on to the next file.
647 # There are wrong permissions, call suricatactrl to fix it.
648 &call_suricatactrl
("fix-rules-dir");
654 ## Private function to cleanup the directory which contains
655 ## the IDS rules, before extracting and modifing the new ruleset.
657 sub _cleanup_rulesdir
() {
658 # Open rules directory and do a directory listing.
659 opendir(DIR
, $rulespath) or die $!;
661 # Loop through the direcory.
662 while (my $file = readdir(DIR
)) {
663 # We only want files.
664 next unless (-f
"$rulespath/$file");
666 # Skip element if it has config as file extension.
667 next if ($file =~ m/\.config$/);
669 # Skip rules file for whitelisted hosts.
670 next if ("$rulespath/$file" eq $whitelist_file);
672 # Skip rules file with local rules.
673 next if ("$rulespath/$file" eq $local_rules_file);
675 # Delete the current processed file, if not, exit this function
676 # and return an error message.
677 unlink("$rulespath/$file") or return "Could not delete $rulespath/$file. $!\n";
685 ## Function to generate the file which contains the home net information.
687 sub generate_home_net_file
() {
690 # Read-in network settings.
691 &General
::readhash
("${General::swroot}/ethernet/settings", \
%netsettings);
693 # Get available network zones.
694 my @network_zones = &Network
::get_available_network_zones
();
696 # Temporary array to store network address and prefix of the configured
700 # Loop through the array of available network zones.
701 foreach my $zone (@network_zones) {
702 # Check if the current processed zone is red.
704 # Grab the IP-address of the red interface.
705 my $red_address = &get_red_address
();
707 # Check if an address has been obtained.
709 # Generate full network string.
710 my $red_network = join("/", $red_address, "32");
712 # Add the red network to the array of networks.
713 push(@networks, $red_network);
716 # Check if the configured RED_TYPE is static.
717 if ($netsettings{'RED_TYPE'} eq "STATIC") {
718 # Get configured and enabled aliases.
719 my @aliases = &get_aliases
();
721 # Loop through the array.
722 foreach my $alias (@aliases) {
724 my $network = join("/", $alias, "32");
726 # Add the generated network to the array of networks.
727 push(@networks, $network);
730 # Process remaining network zones.
732 # Convert current zone name into upper case.
735 # Generate key to access the required data from the netsettings hash.
736 my $zone_netaddress = $zone . "_NETADDRESS";
737 my $zone_netmask = $zone . "_NETMASK";
739 # Obtain the settings from the netsettings hash.
740 my $netaddress = $netsettings{$zone_netaddress};
741 my $netmask = $netsettings{$zone_netmask};
743 # Convert the subnetmask into prefix notation.
744 my $prefix = &Network
::convert_netmask2prefix
($netmask);
746 # Generate full network string.
747 my $network = join("/", $netaddress,$prefix);
749 # Check if the network is valid.
750 if(&Network
::check_subnet
($network)) {
751 # Add the generated network to the array of networks.
752 push(@networks, $network);
757 # Format home net declaration.
758 my $line = "\"[" . join(',', @networks) . "]\"";
760 # Open file to store the addresses of the home net.
761 open(FILE
, ">$homenet_file") or die "Could not open $homenet_file. $!\n";
764 print FILE
"%YAML 1.1\n";
765 print FILE
"---\n\n";
767 # Print notice about autogenerated file.
768 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
770 # Print the generated and required HOME_NET declaration to the file.
771 print FILE
"HOME_NET:\t$line\n";
778 # Function to generate and write the file which contains the configured and used DNS servers.
780 sub generate_dns_servers_file
() {
781 # Get the used DNS servers.
782 my @nameservers = &General
::get_nameservers
();
784 # Get network settings.
786 &General
::readhash
("${General::swroot}/ethernet/settings", \
%netsettings);
788 # Format dns servers declaration.
791 # Check if the system has configured nameservers.
793 # Add the GREEN address as DNS servers.
794 push(@nameservers, $netsettings{'GREEN_ADDRESS'});
796 # Check if a BLUE zone exists.
797 if ($netsettings{'BLUE_ADDRESS'}) {
798 # Add the BLUE address to the array of nameservers.
799 push(@nameservers, $netsettings{'BLUE_ADDRESS'});
802 # Generate the line which will be written to the DNS servers file.
803 $line = join(",", @nameservers);
805 # External net simply contains (any).
806 $line = "\$EXTERNAL_NET";
809 # Open file to store the used DNS server addresses.
810 open(FILE
, ">$dns_servers_file") or die "Could not open $dns_servers_file. $!\n";
813 print FILE
"%YAML 1.1\n";
814 print FILE
"---\n\n";
816 # Print notice about autogenerated file.
817 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
819 # Print the generated DNS declaration to the file.
820 print FILE
"DNS_SERVERS:\t\"[$line]\"\n";
827 # Function to generate and write the file which contains the HTTP_PORTS definition.
829 sub generate_http_ports_file
() {
832 # Read-in proxy settings
833 &General
::readhash
("${General::swroot}/proxy/advanced/settings", \
%proxysettings);
835 # Check if the proxy is enabled.
836 if (( -e
"${General::swroot}/proxy/enable") || (-e
"${General::swroot}/proxy/enable_blue")) {
837 # Add the proxy port to the array of HTTP ports.
838 push(@http_ports, $proxysettings{'PROXY_PORT'});
841 # Check if the transparent mode of the proxy is enabled.
842 if ((-e
"${General::swroot}/proxy/transparent") || (-e
"${General::swroot}/proxy/transparent_blue")) {
843 # Add the transparent proxy port to the array of HTTP ports.
844 push(@http_ports, $proxysettings{'TRANSPARENT_PORT'});
847 # Format HTTP_PORTS declaration.
850 # Generate line which will be written to the http ports file.
851 $line = join(",", @http_ports);
853 # Open file to store the HTTP_PORTS.
854 open(FILE
, ">$http_ports_file") or die "Could not open $http_ports_file. $!\n";
857 print FILE
"%YAML 1.1\n";
858 print FILE
"---\n\n";
860 # Print notice about autogenerated file.
861 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
863 # Print the generated HTTP_PORTS declaration to the file.
864 print FILE
"HTTP_PORTS:\t\"[$line]\"\n";
871 ## Function to generate and write the file for used rulefiles.
873 sub write_used_rulefiles_file
(@
) {
876 # Open file for used rulefiles.
877 open (FILE
, ">$used_rulefiles_file") or die "Could not write to $used_rulefiles_file. $!\n";
879 # Write yaml header to the file.
880 print FILE
"%YAML 1.1\n";
881 print FILE
"---\n\n";
883 # Write header to file.
884 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
886 # Allways use the whitelist.
887 print FILE
" - whitelist.rules\n";
889 # Loop through the array of given files.
890 foreach my $file (@files) {
891 # Check if the given filename exists and write it to the file of used rulefiles.
892 if(-f
"$rulespath/$file") {
893 print FILE
" - $file\n";
897 # Close file after writing.
902 ## Function to generate and write the file for modify the ruleset.
904 sub write_modify_sids_file
() {
905 # Get configured settings.
907 my %rulessettings=();
908 &General
::readhash
("$ids_settings_file", \
%idssettings);
909 &General
::readhash
("$rules_settings_file", \
%rulessettings);
911 # Gather the configured ruleset.
912 my $ruleset = $rulessettings{'RULES'};
914 # Open modify sid's file for writing.
915 open(FILE
, ">$modify_sids_file") or die "Could not write to $modify_sids_file. $!\n";
918 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
920 # Check if the traffic only should be monitored.
921 unless($idssettings{'MONITOR_TRAFFIC_ONLY'} eq 'on') {
922 # Suricata is in IPS mode, which means that the rule actions have to be changed
923 # from 'alert' to 'drop', however not all rules should be changed. Some rules
924 # exist purely to set a flowbit which is used to convey other information, such
925 # as a specific type of file being downloaded, to other rulewhich then check for
926 # malware in that file. Rules which fall into the first category should stay as
927 # alert since not all flows of that type contain malware.
929 if($ruleset eq 'registered' or $ruleset eq 'subscripted' or $ruleset eq 'community') {
930 # These types of rulesfiles contain meta-data which gives the action that should
931 # be used when in IPS mode. Do the following:
933 # 1. Disable all rules and set the action to 'drop'
934 # 2. Set the action back to 'alert' if the rule contains 'flowbits:noalert;'
935 # This should give rules not in the policy a reasonable default if the user
936 # manually enables them.
937 # 3. Enable rules and set actions according to the meta-data strings.
939 my $policy = 'balanced'; # Placeholder to allow policy to be changed.
942 modifysid * "^#?(?:alert|drop)" | "#drop"
943 modifysid * "^#drop(.+flowbits:noalert;)" | "#alert\${1}"
944 modifysid * "^#(?:alert|drop)(.+policy $policy-ips alert)" | "alert\${1}"
945 modifysid * "^#(?:alert|drop)(.+policy $policy-ips drop)" | "drop\${1}"
948 # These rulefiles don't have the metadata, so set rules to 'drop' unless they
949 # contain the string 'flowbits:noalert;'.
951 modifysid * "^(#?)(?:alert|drop)" | "\${1}drop"
952 modifysid * "^(#?)drop(.+flowbits:noalert;)" | "\${1}alert\${2}"
962 ## Function to gather the version of suricata.
964 sub get_suricata_version
($) {
967 # Execute piped suricata command and return the version information.
968 open(SURICATA
, "suricata -V |") or die "Couldn't execute program: $!";
970 # Grab and store the output of the piped program.
971 my $version_string = <SURICATA
>;
977 chomp($version_string);
979 # Grab the version from the version string.
980 $version_string =~ /([0-9]+([.][0-9]+)+)/;
982 # Splitt the version into single chunks.
983 my ($major_ver, $minor_ver, $patchlevel) = split(/\./, $1);
985 # Check and return the requested version sheme.
986 if ($format eq "major") {
987 # Return the full version.
989 } elsif ($format eq "minor") {
990 # Return the major and minor part.
991 return "$major_ver.$minor_ver";
993 # Return the full version string.
994 return "$major_ver.$minor_ver.$patchlevel";
999 ## Function to generate the rules file with whitelisted addresses.
1001 sub generate_ignore_file
() {
1004 # SID range 1000000-1999999 Reserved for Local Use
1005 # Put your custom rules in this range to avoid conflicts
1008 # Read-in ignoredfile.
1009 &General
::readhasharray
($IDS::ignored_file
, \
%ignored);
1011 # Open ignorefile for writing.
1012 open(FILE
, ">$IDS::whitelist_file") or die "Could not write to $IDS::whitelist_file. $!\n";
1014 # Config file header.
1015 print FILE
"# Autogenerated file.\n";
1016 print FILE
"# All user modifications will be overwritten.\n\n";
1018 # Add all user defined addresses to the whitelist.
1020 # Check if the hash contains any elements.
1021 if (keys (%ignored)) {
1022 # Loop through the entire hash and write the host/network
1023 # and remark to the ignore file.
1024 while ( (my $key) = each %ignored) {
1025 my $address = $ignored{$key}[0];
1026 my $remark = $ignored{$key}[1];
1027 my $status = $ignored{$key}[2];
1029 # Check if the status of the entry is "enabled".
1030 if ($status eq "enabled") {
1031 # Check if the address/network is valid.
1032 if ((&General
::validip
($address)) || (&General
::validipandmask
($address))) {
1033 # Write rule line to the file to pass any traffic from this IP
1034 print FILE
"pass ip $address any -> any any (msg:\"pass all traffic from/to $address\"\; sid:$sid\;)\n";
1047 ## Function to set correct ownership for single files and directories.
1050 sub set_ownership
($) {
1053 # User and group of the WUI.
1054 my $uname = "nobody";
1055 my $grname = "nobody";
1057 # The chown function implemented in perl requies the user and group as nummeric id's.
1058 my $uid = getpwnam($uname);
1059 my $gid = getgrnam($grname);
1061 # Check if the given target exists.
1063 # Stop the script and print error message.
1064 die "The $target does not exist. Cannot change the ownership!\n";
1067 # Check weather the target is a file or directory.
1069 # Change ownership ot the single file.
1070 chown($uid, $gid, "$target");
1071 } elsif (-d
$target) {
1072 # Do a directory listing.
1073 opendir(DIR
, $target) or die $!;
1074 # Loop through the direcory.
1075 while (my $file = readdir(DIR
)) {
1077 # We only want files.
1078 next unless (-f
"$target/$file");
1080 # Set correct ownership for the files.
1081 chown($uid, $gid, "$target/$file");
1086 # Change ownership of the directory.
1087 chown($uid, $gid, "$target");
1092 ## Function to read-in the aliases file and returns all configured and enabled aliases.
1095 # Location of the aliases file.
1096 my $aliases_file = "${General::swroot}/ethernet/aliases";
1098 # Array to store the aliases.
1101 # Check if the file is empty.
1102 if (-z
$aliases_file) {
1103 # Abort nothing to do.
1107 # Open the aliases file.
1108 open(ALIASES
, $aliases_file) or die "Could not open $aliases_file. $!\n";
1110 # Loop through the file content.
1111 while (my $line = <ALIASES
>) {
1115 # Splitt line content into single chunks.
1116 my ($address, $state, $remark) = split(/\,/, $line);
1118 # Check if the state of the current processed alias is "on".
1119 if ($state eq "on") {
1120 # Check if the address is valid.
1121 if(&Network
::check_ip_address
($address)) {
1122 # Add the alias to the array of aliases.
1123 push(@aliases, $address);
1128 # Close file handle.
1136 ## Function to grab the current assigned IP-address on red.
1138 sub get_red_address
() {
1139 # File, which contains the current IP-address of the red interface.
1140 my $file = "${General::swroot}/red/local-ipaddress";
1142 # Check if the file exists.
1144 # Open the given file.
1145 open(FILE
, "$file") or die "Could not open $file.";
1147 # Obtain the address from the first line of the file.
1148 my $address = <FILE
>;
1156 # Check if the grabbed address is valid.
1157 if (&General
::validip
($address)) {
1158 # Return the address.
1168 ## Function to write the lock file for locking the WUI, while
1169 ## the autoupdate script runs.
1171 sub lock_ids_page
() {
1172 # Call subfunction to create the file.
1173 &create_empty_file
($ids_page_lock_file);
1177 ## Function to release the lock of the WUI, again.
1179 sub unlock_ids_page
() {
1181 unlink($ids_page_lock_file);