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 ############################################################################
26 require '/var/ipfire/general-functions.pl';
27 require "${General::swroot}/network-functions.pl";
29 # Location where all config and settings files are stored.
30 our $settingsdir = "${General::swroot}/suricata";
32 # File where the used rulefiles are stored.
33 our $used_rulefiles_file = "$settingsdir/suricata-used-rulefiles.yaml";
35 # File where the addresses of the homenet are stored.
36 our $homenet_file = "$settingsdir/suricata-homenet.yaml";
38 # File where the addresses of the used DNS servers are stored.
39 our $dns_servers_file = "$settingsdir/suricata-dns-servers.yaml";
41 # File where the HTTP ports definition is stored.
42 our $http_ports_file = "$settingsdir/suricata-http-ports.yaml";
44 # File which contains the enabled sids.
45 our $enabled_sids_file = "$settingsdir/oinkmaster-enabled-sids.conf";
47 # File which contains the disabled sids.
48 our $disabled_sids_file = "$settingsdir/oinkmaster-disabled-sids.conf";
50 # File which contains wheater the rules should be changed.
51 our $modify_sids_file = "$settingsdir/oinkmaster-modify-sids.conf";
53 # File which stores the configured IPS settings.
54 our $ids_settings_file = "$settingsdir/settings";
56 # File which stores the configured rules-settings.
57 our $rules_settings_file = "$settingsdir/rules-settings";
59 # File which stores the configured settings for whitelisted addresses.
60 our $ignored_file = "$settingsdir/ignored";
62 # Location and name of the tarball which contains the ruleset.
63 our $rulestarball = "/var/tmp/idsrules.tar.gz";
65 # File to store any errors, which also will be read and displayed by the wui.
66 our $storederrorfile = "/tmp/ids_storederror";
68 # File to lock the WUI, while the autoupdate script runs.
69 our $ids_page_lock_file = "/tmp/ids_page_locked";
71 # Location where the rulefiles are stored.
72 our $rulespath = "/var/lib/suricata";
74 # Location to store local rules. This file will not be touched.
75 our $local_rules_file = "$rulespath/local.rules";
77 # File which contains the rules to whitelist addresses on suricata.
78 our $whitelist_file = "$rulespath/whitelist.rules";
80 # File which contains a list of all supported ruleset sources.
81 # (Sourcefire, Emergingthreads, etc..)
82 our $rulesetsourcesfile = "$settingsdir/ruleset-sources";
84 # The pidfile of the IDS.
85 our $idspidfile = "/var/run/suricata.pid";
87 # Location of suricatactrl.
88 my $suricatactrl = "/usr/local/bin/suricatactrl";
90 # Array with allowed commands of suricatactrl.
91 my @suricatactrl_cmds = ( 'start', 'stop', 'restart', 'reload', 'fix-rules-dir', 'cron' );
93 # Array with supported cron intervals.
94 my @cron_intervals = ('off', 'daily', 'weekly' );
96 # Array which contains the HTTP ports, which statically will be declared as HTTP_PORTS in the
98 my @http_ports = ('80', '81');
101 ## Function to check and create all IDS related files, if the does not exist.
103 sub check_and_create_filelayout
() {
104 # Check if the files exist and if not, create them.
105 unless (-f
"$enabled_sids_file") { &create_empty_file
($enabled_sids_file); }
106 unless (-f
"$disabled_sids_file") { &create_empty_file
($disabled_sids_file); }
107 unless (-f
"$modify_sids_file") { &create_empty_file
($modify_sids_file); }
108 unless (-f
"$used_rulefiles_file") { &create_empty_file
($used_rulefiles_file); }
109 unless (-f
"$ids_settings_file") { &create_empty_file
($ids_settings_file); }
110 unless (-f
"$rules_settings_file") { &create_empty_file
($rules_settings_file); }
111 unless (-f
"$ignored_file") { &create_empty_file
($ignored_file); }
112 unless (-f
"$whitelist_file" ) { &create_empty_file
($whitelist_file); }
116 ## Function for checking if at least 300MB of free disk space are available
117 ## on the "/var" partition.
119 sub checkdiskspace
() {
120 # Call diskfree to gather the free disk space of /var.
121 my @df = &General
::system_output
("/bin/df", "-B", "M", "/var");
123 # Loop through the output.
124 foreach my $line (@df) {
125 # Ignore header line.
126 next if $line =~ m/^Filesystem/;
128 # Search for a line with the device information.
129 if ($line =~ m/dev/ ) {
130 # Split the line into single pieces.
131 my @values = split(' ', $line);
132 my ($filesystem, $blocks, $used, $available, $used_perenctage, $mounted_on) = @values;
134 # Check if the available disk space is more than 300MB.
135 if ($available < 300) {
136 # Log error to syslog.
137 &_log_to_syslog
("Not enough free disk space on /var. Only $available MB from 300 MB available.");
139 # Exit function and return "1" - False.
145 # Everything okay, return nothing.
150 ## This function is responsible for downloading the configured IDS ruleset.
152 ## * At first it obtains from the stored rules settings which ruleset should be downloaded.
153 ## * The next step is to get the download locations for all available rulesets.
154 ## * After that, the function will check if an upstream proxy should be used and grab the settings.
155 ## * The last step will be to generate the final download url, by obtaining the URL for the desired
156 ## ruleset, add the settings for the upstream proxy and final grab the rules tarball from the server.
158 sub downloadruleset
{
159 # Get rules settings.
160 my %rulessettings=();
161 &General
::readhash
("$rules_settings_file", \
%rulessettings);
163 # Check if a ruleset has been configured.
164 unless($rulessettings{'RULES'}) {
165 # Log that no ruleset has been configured and abort.
166 &_log_to_syslog
("No ruleset source has been configured.");
172 # Get all available ruleset locations.
173 my %rulesetsources=();
174 &General
::readhash
($rulesetsourcesfile, \
%rulesetsources);
176 # Read proxysettings.
177 my %proxysettings=();
178 &General
::readhash
("${General::swroot}/proxy/settings", \
%proxysettings);
180 # Load required perl module to handle the download.
183 # Init the download module.
184 my $downloader = LWP
::UserAgent
->new;
186 # Set timeout to 10 seconds.
187 $downloader->timeout(10);
189 # Check if an upstream proxy is configured.
190 if ($proxysettings{'UPSTREAM_PROXY'}) {
193 $proxy_url = "http://";
195 # Check if the proxy requires authentication.
196 if (($proxysettings{'UPSTREAM_USER'}) && ($proxysettings{'UPSTREAM_PASSWORD'})) {
197 $proxy_url .= "$proxysettings{'UPSTREAM_USER'}\:$proxysettings{'UPSTREAM_PASSWORD'}\@";
200 # Add proxy server address and port.
201 $proxy_url .= $proxysettings{'UPSTREAM_PROXY'};
203 # Setup proxy settings.
204 $downloader->proxy(['http', 'https'], $proxy_url);
207 # Grab the right url based on the configured vendor.
208 my $url = $rulesetsources{$rulessettings{'RULES'}};
210 # Check if the vendor requires an oinkcode and add it if needed.
211 $url =~ s/\<oinkcode\>/$rulessettings{'OINKCODE'}/g;
213 # Abort if no url could be determined for the vendor.
215 # Log error and abort.
216 &_log_to_syslog
("Unable to gather a download URL for the selected ruleset.");
220 # Variable to store the filesize of the remote object.
223 # The sourcfire (snort rules) does not allow to send "HEAD" requests, so skip this check
224 # for this webserver.
226 # Check if the ruleset source contains "snort.org".
227 unless ($url =~ /\.snort\.org/) {
228 # Pass the requrested url to the downloader.
229 my $request = HTTP
::Request
->new(HEAD
=> $url);
231 # Accept the html header.
232 $request->header('Accept' => 'text/html');
234 # Perform the request and fetch the html header.
235 my $response = $downloader->request($request);
237 # Check if there was any error.
238 unless ($response->is_success) {
240 my $error = $response->status_line();
243 &_log_to_syslog
("Unable to download the ruleset. \($error\)");
245 # Return "1" - false.
249 # Assign the fetched header object.
250 my $header = $response->headers();
252 # Grab the remote file size from the object and store it in the
254 $remote_filesize = $header->content_length;
257 # Load perl module to deal with temporary files.
260 # Generate temporary file name, located in "/var/tmp" and with a suffix of ".tar.gz".
261 my $tmp = File
::Temp
->new( SUFFIX
=> ".tar.gz", DIR
=> "/var/tmp/", UNLINK
=> 0 );
262 my $tmpfile = $tmp->filename();
264 # Pass the requested url to the downloader.
265 my $request = HTTP
::Request
->new(GET
=> $url);
267 # Perform the request and save the output into the tmpfile.
268 my $response = $downloader->request($request, $tmpfile);
270 # Check if there was any error.
271 unless ($response->is_success) {
273 my $error = $response->content;
276 &_log_to_syslog
("Unable to download the ruleset. \($error\)");
278 # Return "1" - false.
282 # Load perl stat module.
285 # Perform stat on the tmpfile.
286 my $stat = stat($tmpfile);
288 # Grab the local filesize of the downloaded tarball.
289 my $local_filesize = $stat->size;
291 # Check if both file sizes match.
292 if (($remote_filesize) && ($remote_filesize ne $local_filesize)) {
294 &_log_to_syslog
("Unable to completely download the ruleset. ");
295 &_log_to_syslog
("Only got $local_filesize Bytes instead of $remote_filesize Bytes. ");
297 # Delete temporary file.
300 # Return "1" - false.
304 # Load file copy module, which contains the move() function.
307 # Overwrite existing rules tarball with the new downloaded one.
308 move
("$tmpfile", "$rulestarball");
310 # Set correct ownership for the rulesdir and files.
311 set_ownership
("$rulestarball");
313 # If we got here, everything worked fine. Return nothing.
318 ## A tiny wrapper function to call the oinkmaster script.
321 # Check if the files in rulesdir have the correct permissions.
322 &_check_rulesdir_permissions
();
324 # Cleanup the rules directory before filling it with the new rulest.
325 &_cleanup_rulesdir
();
327 # Load perl module to talk to the kernel syslog.
328 use Sys
::Syslog
qw(:DEFAULT setlogsock);
330 # Establish the connection to the syslog service.
331 openlog
('oinkmaster', 'cons,pid', 'user');
333 # Call oinkmaster to generate ruleset.
334 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";
336 # Log output of oinkmaster to syslog.
337 while(<OINKMASTER
>) {
338 # The syslog function works best with an array based input,
339 # so generate one before passing the message details to syslog.
340 my @syslog = ("INFO", "$_");
342 # Send the log message.
346 # Close the pipe to oinkmaster process.
349 # Close the log handle.
354 ## Function to do all the logging stuff if the downloading or updating of the ruleset fails.
359 # Remove any newline.
362 # Call private function to log the error message to syslog.
363 &_log_to_syslog
($error);
365 # Call private function to write/store the error message in the storederrorfile.
366 &_store_error_message
($error);
370 ## Function to log a given error message to the kernel syslog.
372 sub _log_to_syslog
($) {
375 # Load perl module to talk to the kernel syslog.
376 use Sys
::Syslog
qw(:DEFAULT setlogsock);
378 # The syslog function works best with an array based input,
379 # so generate one before passing the message details to syslog.
380 my @syslog = ("ERR", "<ERROR> $message");
382 # Establish the connection to the syslog service.
383 openlog
('oinkmaster', 'cons,pid', 'user');
385 # Send the log message.
388 # Close the log handle.
393 ## Private function to write a given error message to the storederror file.
395 sub _store_error_message
($) {
398 # Remove any newline.
401 # Open file for writing.
402 open (ERRORFILE
, ">$storederrorfile") or die "Could not write to $storederrorfile. $!\n";
404 # Write error to file.
405 print ERRORFILE
"$message\n";
410 # Set correct ownership for the file.
411 &set_ownership
("$storederrorfile");
415 ## Function to check if the IDS is running.
417 sub ids_is_running
() {
419 # Open PID file for reading.
420 open(PIDFILE
, "$idspidfile") or die "Could not open $idspidfile. $!\n";
422 # Grab the process-id.
428 # Remove any newline.
431 # Check if a directory for the process-id exists in proc.
432 if(-d
"/proc/$pid") {
433 # The IDS daemon is running return the process id.
438 # Return nothing - IDS is not running.
443 ## Function to call suricatactrl binary with a given command.
445 sub call_suricatactrl
($) {
447 my ($option, $interval) = @_;
449 # Loop through the array of supported commands and check if
450 # the given one is part of it.
451 foreach my $cmd (@suricatactrl_cmds) {
452 # Skip current command unless the given one has been found.
453 next unless($cmd eq $option);
455 # Check if the given command is "cron".
456 if ($option eq "cron") {
457 # Check if an interval has been given.
459 # Check if the given interval is valid.
460 foreach my $element (@cron_intervals) {
461 # Skip current element until the given one has been found.
462 next unless($element eq $interval);
464 # Call the suricatactrl binary and pass the "cron" command
465 # with the requrested interval.
466 &General
::system("$suricatactrl", "$option", "$interval");
473 # If we got here, the given interval is not supported or none has been given. - Return nothing.
476 # Call the suricatactrl binary and pass the requrested
478 &General
::system("$suricatactrl", "$option");
485 # Command not found - return nothing.
490 ## Function to create a new empty file.
492 sub create_empty_file
($) {
495 # Check if the given file exists.
497 # Do nothing to prevent from overwriting existing files.
501 # Open the file for writing.
502 open(FILE
, ">$file") or die "Could not write to $file. $!\n";
512 ## Private function to check if the file permission of the rulespath are correct.
513 ## If not, call suricatactrl to fix them.
515 sub _check_rulesdir_permissions
() {
516 # Check if the rulepath main directory is writable.
517 unless (-W
$rulespath) {
518 # If not call suricatctrl to fix it.
519 &call_suricatactrl
("fix-rules-dir");
522 # Open snort rules directory and do a directory listing.
523 opendir(DIR
, $rulespath) or die $!;
524 # Loop through the direcory.
525 while (my $file = readdir(DIR
)) {
526 # We only want files.
527 next unless (-f
"$rulespath/$file");
529 # Check if the file is writable by the user.
530 if (-W
"$rulespath/$file") {
531 # Everything is okay - go on to the next file.
534 # There are wrong permissions, call suricatactrl to fix it.
535 &call_suricatactrl
("fix-rules-dir");
541 ## Private function to cleanup the directory which contains
542 ## the IDS rules, before extracting and modifing the new ruleset.
544 sub _cleanup_rulesdir
() {
545 # Open rules directory and do a directory listing.
546 opendir(DIR
, $rulespath) or die $!;
548 # Loop through the direcory.
549 while (my $file = readdir(DIR
)) {
550 # We only want files.
551 next unless (-f
"$rulespath/$file");
553 # Skip element if it has config as file extension.
554 next if ($file =~ m/\.config$/);
556 # Skip rules file for whitelisted hosts.
557 next if ("$rulespath/$file" eq $whitelist_file);
559 # Skip rules file with local rules.
560 next if ("$rulespath/$file" eq $local_rules_file);
562 # Delete the current processed file, if not, exit this function
563 # and return an error message.
564 unlink("$rulespath/$file") or return "Could not delete $rulespath/$file. $!\n";
572 ## Function to generate the file which contains the home net information.
574 sub generate_home_net_file
() {
577 # Read-in network settings.
578 &General
::readhash
("${General::swroot}/ethernet/settings", \
%netsettings);
580 # Get available network zones.
581 my @network_zones = &Network
::get_available_network_zones
();
583 # Temporary array to store network address and prefix of the configured
587 # Loop through the array of available network zones.
588 foreach my $zone (@network_zones) {
589 # Check if the current processed zone is red.
591 # Grab the IP-address of the red interface.
592 my $red_address = &get_red_address
();
594 # Check if an address has been obtained.
596 # Generate full network string.
597 my $red_network = join("/", $red_address, "32");
599 # Add the red network to the array of networks.
600 push(@networks, $red_network);
603 # Check if the configured RED_TYPE is static.
604 if ($netsettings{'RED_TYPE'} eq "STATIC") {
605 # Get configured and enabled aliases.
606 my @aliases = &get_aliases
();
608 # Loop through the array.
609 foreach my $alias (@aliases) {
611 my $network = join("/", $alias, "32");
613 # Add the generated network to the array of networks.
614 push(@networks, $network);
617 # Process remaining network zones.
619 # Convert current zone name into upper case.
622 # Generate key to access the required data from the netsettings hash.
623 my $zone_netaddress = $zone . "_NETADDRESS";
624 my $zone_netmask = $zone . "_NETMASK";
626 # Obtain the settings from the netsettings hash.
627 my $netaddress = $netsettings{$zone_netaddress};
628 my $netmask = $netsettings{$zone_netmask};
630 # Convert the subnetmask into prefix notation.
631 my $prefix = &Network
::convert_netmask2prefix
($netmask);
633 # Generate full network string.
634 my $network = join("/", $netaddress,$prefix);
636 # Check if the network is valid.
637 if(&Network
::check_subnet
($network)) {
638 # Add the generated network to the array of networks.
639 push(@networks, $network);
644 # Format home net declaration.
645 my $line = "\"[" . join(',', @networks) . "]\"";
647 # Open file to store the addresses of the home net.
648 open(FILE
, ">$homenet_file") or die "Could not open $homenet_file. $!\n";
651 print FILE
"%YAML 1.1\n";
652 print FILE
"---\n\n";
654 # Print notice about autogenerated file.
655 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
657 # Print the generated and required HOME_NET declaration to the file.
658 print FILE
"HOME_NET:\t$line\n";
665 # Function to generate and write the file which contains the configured and used DNS servers.
667 sub generate_dns_servers_file
() {
668 # Get the used DNS servers.
669 my @nameservers = &General
::get_nameservers
();
671 # Get network settings.
673 &General
::readhash
("${General::swroot}/ethernet/settings", \
%netsettings);
675 # Format dns servers declaration.
678 # Check if the system has configured nameservers.
680 # Add the GREEN address as DNS servers.
681 push(@nameservers, $netsettings{'GREEN_ADDRESS'});
683 # Check if a BLUE zone exists.
684 if ($netsettings{'BLUE_ADDRESS'}) {
685 # Add the BLUE address to the array of nameservers.
686 push(@nameservers, $netsettings{'BLUE_ADDRESS'});
689 # Generate the line which will be written to the DNS servers file.
690 $line = join(",", @nameservers);
692 # External net simply contains (any).
693 $line = "\$EXTERNAL_NET";
696 # Open file to store the used DNS server addresses.
697 open(FILE
, ">$dns_servers_file") or die "Could not open $dns_servers_file. $!\n";
700 print FILE
"%YAML 1.1\n";
701 print FILE
"---\n\n";
703 # Print notice about autogenerated file.
704 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
706 # Print the generated DNS declaration to the file.
707 print FILE
"DNS_SERVERS:\t\"[$line]\"\n";
714 # Function to generate and write the file which contains the HTTP_PORTS definition.
716 sub generate_http_ports_file
() {
719 # Read-in proxy settings
720 &General
::readhash
("${General::swroot}/proxy/advanced/settings", \
%proxysettings);
722 # Check if the proxy is enabled.
723 if (( -e
"${General::swroot}/proxy/enable") || (-e
"${General::swroot}/proxy/enable_blue")) {
724 # Add the proxy port to the array of HTTP ports.
725 push(@http_ports, $proxysettings{'PROXY_PORT'});
728 # Check if the transparent mode of the proxy is enabled.
729 if ((-e
"${General::swroot}/proxy/transparent") || (-e
"${General::swroot}/proxy/transparent_blue")) {
730 # Add the transparent proxy port to the array of HTTP ports.
731 push(@http_ports, $proxysettings{'TRANSPARENT_PORT'});
734 # Format HTTP_PORTS declaration.
737 # Generate line which will be written to the http ports file.
738 $line = join(",", @http_ports);
740 # Open file to store the HTTP_PORTS.
741 open(FILE
, ">$http_ports_file") or die "Could not open $http_ports_file. $!\n";
744 print FILE
"%YAML 1.1\n";
745 print FILE
"---\n\n";
747 # Print notice about autogenerated file.
748 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
750 # Print the generated HTTP_PORTS declaration to the file.
751 print FILE
"HTTP_PORTS:\t\"[$line]\"\n";
758 ## Function to generate and write the file for used rulefiles.
760 sub write_used_rulefiles_file
(@
) {
763 # Open file for used rulefiles.
764 open (FILE
, ">$used_rulefiles_file") or die "Could not write to $used_rulefiles_file. $!\n";
766 # Write yaml header to the file.
767 print FILE
"%YAML 1.1\n";
768 print FILE
"---\n\n";
770 # Write header to file.
771 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
773 # Allways use the whitelist.
774 print FILE
" - whitelist.rules\n";
776 # Loop through the array of given files.
777 foreach my $file (@files) {
778 # Check if the given filename exists and write it to the file of used rulefiles.
779 if(-f
"$rulespath/$file") {
780 print FILE
" - $file\n";
784 # Close file after writing.
789 ## Function to generate and write the file for modify the ruleset.
791 sub write_modify_sids_file
() {
792 # Get configured settings.
794 my %rulessettings=();
795 &General
::readhash
("$ids_settings_file", \
%idssettings);
796 &General
::readhash
("$rules_settings_file", \
%rulessettings);
798 # Gather the configured ruleset.
799 my $ruleset = $rulessettings{'RULES'};
801 # Open modify sid's file for writing.
802 open(FILE
, ">$modify_sids_file") or die "Could not write to $modify_sids_file. $!\n";
805 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
807 # Check if the traffic only should be monitored.
808 unless($idssettings{'MONITOR_TRAFFIC_ONLY'} eq 'on') {
809 # Suricata is in IPS mode, which means that the rule actions have to be changed
810 # from 'alert' to 'drop', however not all rules should be changed. Some rules
811 # exist purely to set a flowbit which is used to convey other information, such
812 # as a specific type of file being downloaded, to other rulewhich then check for
813 # malware in that file. Rules which fall into the first category should stay as
814 # alert since not all flows of that type contain malware.
816 if($ruleset eq 'registered' or $ruleset eq 'subscripted' or $ruleset eq 'community') {
817 # These types of rulesfiles contain meta-data which gives the action that should
818 # be used when in IPS mode. Do the following:
820 # 1. Disable all rules and set the action to 'drop'
821 # 2. Set the action back to 'alert' if the rule contains 'flowbits:noalert;'
822 # This should give rules not in the policy a reasonable default if the user
823 # manually enables them.
824 # 3. Enable rules and set actions according to the meta-data strings.
826 my $policy = 'balanced'; # Placeholder to allow policy to be changed.
829 modifysid * "^#?(?:alert|drop)" | "#drop"
830 modifysid * "^#drop(.+flowbits:noalert;)" | "#alert\${1}"
831 modifysid * "^#(?:alert|drop)(.+policy $policy-ips alert)" | "alert\${1}"
832 modifysid * "^#(?:alert|drop)(.+policy $policy-ips drop)" | "drop\${1}"
835 # These rulefiles don't have the metadata, so set rules to 'drop' unless they
836 # contain the string 'flowbits:noalert;'.
838 modifysid * "^(#?)(?:alert|drop)" | "\${1}drop"
839 modifysid * "^(#?)drop(.+flowbits:noalert;)" | "\${1}alert\${2}"
849 ## Function to gather the version of suricata.
851 sub get_suricata_version
($) {
854 # Execute piped suricata command and return the version information.
855 open(SURICATA
, "suricata -V |") or die "Couldn't execute program: $!";
857 # Grab and store the output of the piped program.
858 my $version_string = <SURICATA
>;
864 chomp($version_string);
866 # Grab the version from the version string.
867 $version_string =~ /([0-9]+([.][0-9]+)+)/;
869 # Splitt the version into single chunks.
870 my ($major_ver, $minor_ver, $patchlevel) = split(/\./, $1);
872 # Check and return the requested version sheme.
873 if ($format eq "major") {
874 # Return the full version.
876 } elsif ($format eq "minor") {
877 # Return the major and minor part.
878 return "$major_ver.$minor_ver";
880 # Return the full version string.
881 return "$major_ver.$minor_ver.$patchlevel";
886 ## Function to generate the rules file with whitelisted addresses.
888 sub generate_ignore_file
() {
891 # SID range 1000000-1999999 Reserved for Local Use
892 # Put your custom rules in this range to avoid conflicts
895 # Read-in ignoredfile.
896 &General
::readhasharray
($IDS::ignored_file
, \
%ignored);
898 # Open ignorefile for writing.
899 open(FILE
, ">$IDS::whitelist_file") or die "Could not write to $IDS::whitelist_file. $!\n";
901 # Config file header.
902 print FILE
"# Autogenerated file.\n";
903 print FILE
"# All user modifications will be overwritten.\n\n";
905 # Add all user defined addresses to the whitelist.
907 # Check if the hash contains any elements.
908 if (keys (%ignored)) {
909 # Loop through the entire hash and write the host/network
910 # and remark to the ignore file.
911 while ( (my $key) = each %ignored) {
912 my $address = $ignored{$key}[0];
913 my $remark = $ignored{$key}[1];
914 my $status = $ignored{$key}[2];
916 # Check if the status of the entry is "enabled".
917 if ($status eq "enabled") {
918 # Check if the address/network is valid.
919 if ((&General
::validip
($address)) || (&General
::validipandmask
($address))) {
920 # Write rule line to the file to pass any traffic from this IP
921 print FILE
"pass ip $address any -> any any (msg:\"pass all traffic from/to $address\"\; sid:$sid\;)\n";
934 ## Function to set correct ownership for single files and directories.
937 sub set_ownership
($) {
940 # User and group of the WUI.
941 my $uname = "nobody";
942 my $grname = "nobody";
944 # The chown function implemented in perl requies the user and group as nummeric id's.
945 my $uid = getpwnam($uname);
946 my $gid = getgrnam($grname);
948 # Check if the given target exists.
950 # Stop the script and print error message.
951 die "The $target does not exist. Cannot change the ownership!\n";
954 # Check weather the target is a file or directory.
956 # Change ownership ot the single file.
957 chown($uid, $gid, "$target");
958 } elsif (-d
$target) {
959 # Do a directory listing.
960 opendir(DIR
, $target) or die $!;
961 # Loop through the direcory.
962 while (my $file = readdir(DIR
)) {
964 # We only want files.
965 next unless (-f
"$target/$file");
967 # Set correct ownership for the files.
968 chown($uid, $gid, "$target/$file");
973 # Change ownership of the directory.
974 chown($uid, $gid, "$target");
979 ## Function to read-in the aliases file and returns all configured and enabled aliases.
982 # Location of the aliases file.
983 my $aliases_file = "${General::swroot}/ethernet/aliases";
985 # Array to store the aliases.
988 # Check if the file is empty.
989 if (-z
$aliases_file) {
990 # Abort nothing to do.
994 # Open the aliases file.
995 open(ALIASES
, $aliases_file) or die "Could not open $aliases_file. $!\n";
997 # Loop through the file content.
998 while (my $line = <ALIASES
>) {
1002 # Splitt line content into single chunks.
1003 my ($address, $state, $remark) = split(/\,/, $line);
1005 # Check if the state of the current processed alias is "on".
1006 if ($state eq "on") {
1007 # Check if the address is valid.
1008 if(&Network
::check_ip_address
($address)) {
1009 # Add the alias to the array of aliases.
1010 push(@aliases, $address);
1015 # Close file handle.
1023 ## Function to grab the current assigned IP-address on red.
1025 sub get_red_address
() {
1026 # File, which contains the current IP-address of the red interface.
1027 my $file = "${General::swroot}/red/local-ipaddress";
1029 # Check if the file exists.
1031 # Open the given file.
1032 open(FILE
, "$file") or die "Could not open $file.";
1034 # Obtain the address from the first line of the file.
1035 my $address = <FILE
>;
1043 # Check if the grabbed address is valid.
1044 if (&General
::validip
($address)) {
1045 # Return the address.
1055 ## Function to write the lock file for locking the WUI, while
1056 ## the autoupdate script runs.
1058 sub lock_ids_page
() {
1059 # Call subfunction to create the file.
1060 &create_empty_file
($ids_page_lock_file);
1064 ## Function to release the lock of the WUI, again.
1066 sub unlock_ids_page
() {
1068 unlink($ids_page_lock_file);