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 # Read proxysettings.
173 my %proxysettings=();
174 &General
::readhash
("${General::swroot}/proxy/settings", \
%proxysettings);
176 # Load required perl module to handle the download.
179 # Init the download module.
180 my $downloader = LWP
::UserAgent
->new;
182 # Set timeout to 10 seconds.
183 $downloader->timeout(10);
185 # Check if an upstream proxy is configured.
186 if ($proxysettings{'UPSTREAM_PROXY'}) {
189 $proxy_url = "http://";
191 # Check if the proxy requires authentication.
192 if (($proxysettings{'UPSTREAM_USER'}) && ($proxysettings{'UPSTREAM_PASSWORD'})) {
193 $proxy_url .= "$proxysettings{'UPSTREAM_USER'}\:$proxysettings{'UPSTREAM_PASSWORD'}\@";
196 # Add proxy server address and port.
197 $proxy_url .= $proxysettings{'UPSTREAM_PROXY'};
199 # Setup proxy settings.
200 $downloader->proxy(['http', 'https'], $proxy_url);
203 # Grab the right url based on the configured vendor.
204 my $url = $IDS::Ruleset
::Providers
{$rulessettings{'RULES'}}{'dl_url'};
206 # Check if the vendor requires an oinkcode and add it if needed.
207 $url =~ s/\<oinkcode\>/$rulessettings{'OINKCODE'}/g;
209 # Abort if no url could be determined for the vendor.
211 # Log error and abort.
212 &_log_to_syslog
("Unable to gather a download URL for the selected ruleset.");
216 # Variable to store the filesize of the remote object.
219 # The sourcfire (snort rules) does not allow to send "HEAD" requests, so skip this check
220 # for this webserver.
222 # Check if the ruleset source contains "snort.org".
223 unless ($url =~ /\.snort\.org/) {
224 # Pass the requrested url to the downloader.
225 my $request = HTTP
::Request
->new(HEAD
=> $url);
227 # Accept the html header.
228 $request->header('Accept' => 'text/html');
230 # Perform the request and fetch the html header.
231 my $response = $downloader->request($request);
233 # Check if there was any error.
234 unless ($response->is_success) {
236 my $error = $response->status_line();
239 &_log_to_syslog
("Unable to download the ruleset. \($error\)");
241 # Return "1" - false.
245 # Assign the fetched header object.
246 my $header = $response->headers();
248 # Grab the remote file size from the object and store it in the
250 $remote_filesize = $header->content_length;
253 # Load perl module to deal with temporary files.
256 # Generate temporary file name, located in "/var/tmp" and with a suffix of ".tar.gz".
257 my $tmp = File
::Temp
->new( SUFFIX
=> ".tar.gz", DIR
=> "/var/tmp/", UNLINK
=> 0 );
258 my $tmpfile = $tmp->filename();
260 # Pass the requested url to the downloader.
261 my $request = HTTP
::Request
->new(GET
=> $url);
263 # Perform the request and save the output into the tmpfile.
264 my $response = $downloader->request($request, $tmpfile);
266 # Check if there was any error.
267 unless ($response->is_success) {
269 my $error = $response->content;
272 &_log_to_syslog
("Unable to download the ruleset. \($error\)");
274 # Return "1" - false.
278 # Load perl stat module.
281 # Perform stat on the tmpfile.
282 my $stat = stat($tmpfile);
284 # Grab the local filesize of the downloaded tarball.
285 my $local_filesize = $stat->size;
287 # Check if both file sizes match.
288 if (($remote_filesize) && ($remote_filesize ne $local_filesize)) {
290 &_log_to_syslog
("Unable to completely download the ruleset. ");
291 &_log_to_syslog
("Only got $local_filesize Bytes instead of $remote_filesize Bytes. ");
293 # Delete temporary file.
296 # Return "1" - false.
300 # Load file copy module, which contains the move() function.
303 # Overwrite existing rules tarball with the new downloaded one.
304 move
("$tmpfile", "$rulestarball");
306 # Set correct ownership for the rulesdir and files.
307 set_ownership
("$rulestarball");
309 # If we got here, everything worked fine. Return nothing.
314 ## A tiny wrapper function to call the oinkmaster script.
317 # Check if the files in rulesdir have the correct permissions.
318 &_check_rulesdir_permissions
();
320 # Cleanup the rules directory before filling it with the new rulest.
321 &_cleanup_rulesdir
();
323 # Load perl module to talk to the kernel syslog.
324 use Sys
::Syslog
qw(:DEFAULT setlogsock);
326 # Establish the connection to the syslog service.
327 openlog
('oinkmaster', 'cons,pid', 'user');
329 # Call oinkmaster to generate ruleset.
330 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";
332 # Log output of oinkmaster to syslog.
333 while(<OINKMASTER
>) {
334 # The syslog function works best with an array based input,
335 # so generate one before passing the message details to syslog.
336 my @syslog = ("INFO", "$_");
338 # Send the log message.
342 # Close the pipe to oinkmaster process.
345 # Close the log handle.
350 ## Function to do all the logging stuff if the downloading or updating of the ruleset fails.
355 # Remove any newline.
358 # Call private function to log the error message to syslog.
359 &_log_to_syslog
($error);
361 # Call private function to write/store the error message in the storederrorfile.
362 &_store_error_message
($error);
366 ## Function to log a given error message to the kernel syslog.
368 sub _log_to_syslog
($) {
371 # Load perl module to talk to the kernel syslog.
372 use Sys
::Syslog
qw(:DEFAULT setlogsock);
374 # The syslog function works best with an array based input,
375 # so generate one before passing the message details to syslog.
376 my @syslog = ("ERR", "<ERROR> $message");
378 # Establish the connection to the syslog service.
379 openlog
('oinkmaster', 'cons,pid', 'user');
381 # Send the log message.
384 # Close the log handle.
389 ## Private function to write a given error message to the storederror file.
391 sub _store_error_message
($) {
394 # Remove any newline.
397 # Open file for writing.
398 open (ERRORFILE
, ">$storederrorfile") or die "Could not write to $storederrorfile. $!\n";
400 # Write error to file.
401 print ERRORFILE
"$message\n";
406 # Set correct ownership for the file.
407 &set_ownership
("$storederrorfile");
411 ## Function to check if the IDS is running.
413 sub ids_is_running
() {
415 # Open PID file for reading.
416 open(PIDFILE
, "$idspidfile") or die "Could not open $idspidfile. $!\n";
418 # Grab the process-id.
424 # Remove any newline.
427 # Check if a directory for the process-id exists in proc.
428 if(-d
"/proc/$pid") {
429 # The IDS daemon is running return the process id.
434 # Return nothing - IDS is not running.
439 ## Function to call suricatactrl binary with a given command.
441 sub call_suricatactrl
($) {
443 my ($option, $interval) = @_;
445 # Loop through the array of supported commands and check if
446 # the given one is part of it.
447 foreach my $cmd (@suricatactrl_cmds) {
448 # Skip current command unless the given one has been found.
449 next unless($cmd eq $option);
451 # Check if the given command is "cron".
452 if ($option eq "cron") {
453 # Check if an interval has been given.
455 # Check if the given interval is valid.
456 foreach my $element (@cron_intervals) {
457 # Skip current element until the given one has been found.
458 next unless($element eq $interval);
460 # Call the suricatactrl binary and pass the "cron" command
461 # with the requrested interval.
462 &General
::system("$suricatactrl", "$option", "$interval");
469 # If we got here, the given interval is not supported or none has been given. - Return nothing.
472 # Call the suricatactrl binary and pass the requrested
474 &General
::system("$suricatactrl", "$option");
481 # Command not found - return nothing.
486 ## Function to create a new empty file.
488 sub create_empty_file
($) {
491 # Check if the given file exists.
493 # Do nothing to prevent from overwriting existing files.
497 # Open the file for writing.
498 open(FILE
, ">$file") or die "Could not write to $file. $!\n";
508 ## Private function to check if the file permission of the rulespath are correct.
509 ## If not, call suricatactrl to fix them.
511 sub _check_rulesdir_permissions
() {
512 # Check if the rulepath main directory is writable.
513 unless (-W
$rulespath) {
514 # If not call suricatctrl to fix it.
515 &call_suricatactrl
("fix-rules-dir");
518 # Open snort rules directory and do a directory listing.
519 opendir(DIR
, $rulespath) or die $!;
520 # Loop through the direcory.
521 while (my $file = readdir(DIR
)) {
522 # We only want files.
523 next unless (-f
"$rulespath/$file");
525 # Check if the file is writable by the user.
526 if (-W
"$rulespath/$file") {
527 # Everything is okay - go on to the next file.
530 # There are wrong permissions, call suricatactrl to fix it.
531 &call_suricatactrl
("fix-rules-dir");
537 ## Private function to cleanup the directory which contains
538 ## the IDS rules, before extracting and modifing the new ruleset.
540 sub _cleanup_rulesdir
() {
541 # Open rules directory and do a directory listing.
542 opendir(DIR
, $rulespath) or die $!;
544 # Loop through the direcory.
545 while (my $file = readdir(DIR
)) {
546 # We only want files.
547 next unless (-f
"$rulespath/$file");
549 # Skip element if it has config as file extension.
550 next if ($file =~ m/\.config$/);
552 # Skip rules file for whitelisted hosts.
553 next if ("$rulespath/$file" eq $whitelist_file);
555 # Skip rules file with local rules.
556 next if ("$rulespath/$file" eq $local_rules_file);
558 # Delete the current processed file, if not, exit this function
559 # and return an error message.
560 unlink("$rulespath/$file") or return "Could not delete $rulespath/$file. $!\n";
568 ## Function to generate the file which contains the home net information.
570 sub generate_home_net_file
() {
573 # Read-in network settings.
574 &General
::readhash
("${General::swroot}/ethernet/settings", \
%netsettings);
576 # Get available network zones.
577 my @network_zones = &Network
::get_available_network_zones
();
579 # Temporary array to store network address and prefix of the configured
583 # Loop through the array of available network zones.
584 foreach my $zone (@network_zones) {
585 # Check if the current processed zone is red.
587 # Grab the IP-address of the red interface.
588 my $red_address = &get_red_address
();
590 # Check if an address has been obtained.
592 # Generate full network string.
593 my $red_network = join("/", $red_address, "32");
595 # Add the red network to the array of networks.
596 push(@networks, $red_network);
599 # Check if the configured RED_TYPE is static.
600 if ($netsettings{'RED_TYPE'} eq "STATIC") {
601 # Get configured and enabled aliases.
602 my @aliases = &get_aliases
();
604 # Loop through the array.
605 foreach my $alias (@aliases) {
607 my $network = join("/", $alias, "32");
609 # Add the generated network to the array of networks.
610 push(@networks, $network);
613 # Process remaining network zones.
615 # Convert current zone name into upper case.
618 # Generate key to access the required data from the netsettings hash.
619 my $zone_netaddress = $zone . "_NETADDRESS";
620 my $zone_netmask = $zone . "_NETMASK";
622 # Obtain the settings from the netsettings hash.
623 my $netaddress = $netsettings{$zone_netaddress};
624 my $netmask = $netsettings{$zone_netmask};
626 # Convert the subnetmask into prefix notation.
627 my $prefix = &Network
::convert_netmask2prefix
($netmask);
629 # Generate full network string.
630 my $network = join("/", $netaddress,$prefix);
632 # Check if the network is valid.
633 if(&Network
::check_subnet
($network)) {
634 # Add the generated network to the array of networks.
635 push(@networks, $network);
640 # Format home net declaration.
641 my $line = "\"[" . join(',', @networks) . "]\"";
643 # Open file to store the addresses of the home net.
644 open(FILE
, ">$homenet_file") or die "Could not open $homenet_file. $!\n";
647 print FILE
"%YAML 1.1\n";
648 print FILE
"---\n\n";
650 # Print notice about autogenerated file.
651 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
653 # Print the generated and required HOME_NET declaration to the file.
654 print FILE
"HOME_NET:\t$line\n";
661 # Function to generate and write the file which contains the configured and used DNS servers.
663 sub generate_dns_servers_file
() {
664 # Get the used DNS servers.
665 my @nameservers = &General
::get_nameservers
();
667 # Get network settings.
669 &General
::readhash
("${General::swroot}/ethernet/settings", \
%netsettings);
671 # Format dns servers declaration.
674 # Check if the system has configured nameservers.
676 # Add the GREEN address as DNS servers.
677 push(@nameservers, $netsettings{'GREEN_ADDRESS'});
679 # Check if a BLUE zone exists.
680 if ($netsettings{'BLUE_ADDRESS'}) {
681 # Add the BLUE address to the array of nameservers.
682 push(@nameservers, $netsettings{'BLUE_ADDRESS'});
685 # Generate the line which will be written to the DNS servers file.
686 $line = join(",", @nameservers);
688 # External net simply contains (any).
689 $line = "\$EXTERNAL_NET";
692 # Open file to store the used DNS server addresses.
693 open(FILE
, ">$dns_servers_file") or die "Could not open $dns_servers_file. $!\n";
696 print FILE
"%YAML 1.1\n";
697 print FILE
"---\n\n";
699 # Print notice about autogenerated file.
700 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
702 # Print the generated DNS declaration to the file.
703 print FILE
"DNS_SERVERS:\t\"[$line]\"\n";
710 # Function to generate and write the file which contains the HTTP_PORTS definition.
712 sub generate_http_ports_file
() {
715 # Read-in proxy settings
716 &General
::readhash
("${General::swroot}/proxy/advanced/settings", \
%proxysettings);
718 # Check if the proxy is enabled.
719 if (( -e
"${General::swroot}/proxy/enable") || (-e
"${General::swroot}/proxy/enable_blue")) {
720 # Add the proxy port to the array of HTTP ports.
721 push(@http_ports, $proxysettings{'PROXY_PORT'});
724 # Check if the transparent mode of the proxy is enabled.
725 if ((-e
"${General::swroot}/proxy/transparent") || (-e
"${General::swroot}/proxy/transparent_blue")) {
726 # Add the transparent proxy port to the array of HTTP ports.
727 push(@http_ports, $proxysettings{'TRANSPARENT_PORT'});
730 # Format HTTP_PORTS declaration.
733 # Generate line which will be written to the http ports file.
734 $line = join(",", @http_ports);
736 # Open file to store the HTTP_PORTS.
737 open(FILE
, ">$http_ports_file") or die "Could not open $http_ports_file. $!\n";
740 print FILE
"%YAML 1.1\n";
741 print FILE
"---\n\n";
743 # Print notice about autogenerated file.
744 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
746 # Print the generated HTTP_PORTS declaration to the file.
747 print FILE
"HTTP_PORTS:\t\"[$line]\"\n";
754 ## Function to generate and write the file for used rulefiles.
756 sub write_used_rulefiles_file
(@
) {
759 # Open file for used rulefiles.
760 open (FILE
, ">$used_rulefiles_file") or die "Could not write to $used_rulefiles_file. $!\n";
762 # Write yaml header to the file.
763 print FILE
"%YAML 1.1\n";
764 print FILE
"---\n\n";
766 # Write header to file.
767 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
769 # Allways use the whitelist.
770 print FILE
" - whitelist.rules\n";
772 # Loop through the array of given files.
773 foreach my $file (@files) {
774 # Check if the given filename exists and write it to the file of used rulefiles.
775 if(-f
"$rulespath/$file") {
776 print FILE
" - $file\n";
780 # Close file after writing.
785 ## Function to generate and write the file for modify the ruleset.
787 sub write_modify_sids_file
() {
788 # Get configured settings.
790 my %rulessettings=();
791 &General
::readhash
("$ids_settings_file", \
%idssettings);
792 &General
::readhash
("$rules_settings_file", \
%rulessettings);
794 # Gather the configured ruleset.
795 my $ruleset = $rulessettings{'RULES'};
797 # Open modify sid's file for writing.
798 open(FILE
, ">$modify_sids_file") or die "Could not write to $modify_sids_file. $!\n";
801 print FILE
"#Autogenerated file. Any custom changes will be overwritten!\n";
803 # Check if the traffic only should be monitored.
804 unless($idssettings{'MONITOR_TRAFFIC_ONLY'} eq 'on') {
805 # Suricata is in IPS mode, which means that the rule actions have to be changed
806 # from 'alert' to 'drop', however not all rules should be changed. Some rules
807 # exist purely to set a flowbit which is used to convey other information, such
808 # as a specific type of file being downloaded, to other rulewhich then check for
809 # malware in that file. Rules which fall into the first category should stay as
810 # alert since not all flows of that type contain malware.
812 if($ruleset eq 'registered' or $ruleset eq 'subscripted' or $ruleset eq 'community') {
813 # These types of rulesfiles contain meta-data which gives the action that should
814 # be used when in IPS mode. Do the following:
816 # 1. Disable all rules and set the action to 'drop'
817 # 2. Set the action back to 'alert' if the rule contains 'flowbits:noalert;'
818 # This should give rules not in the policy a reasonable default if the user
819 # manually enables them.
820 # 3. Enable rules and set actions according to the meta-data strings.
822 my $policy = 'balanced'; # Placeholder to allow policy to be changed.
825 modifysid * "^#?(?:alert|drop)" | "#drop"
826 modifysid * "^#drop(.+flowbits:noalert;)" | "#alert\${1}"
827 modifysid * "^#(?:alert|drop)(.+policy $policy-ips alert)" | "alert\${1}"
828 modifysid * "^#(?:alert|drop)(.+policy $policy-ips drop)" | "drop\${1}"
831 # These rulefiles don't have the metadata, so set rules to 'drop' unless they
832 # contain the string 'flowbits:noalert;'.
834 modifysid * "^(#?)(?:alert|drop)" | "\${1}drop"
835 modifysid * "^(#?)drop(.+flowbits:noalert;)" | "\${1}alert\${2}"
845 ## Function to gather the version of suricata.
847 sub get_suricata_version
($) {
850 # Execute piped suricata command and return the version information.
851 open(SURICATA
, "suricata -V |") or die "Couldn't execute program: $!";
853 # Grab and store the output of the piped program.
854 my $version_string = <SURICATA
>;
860 chomp($version_string);
862 # Grab the version from the version string.
863 $version_string =~ /([0-9]+([.][0-9]+)+)/;
865 # Splitt the version into single chunks.
866 my ($major_ver, $minor_ver, $patchlevel) = split(/\./, $1);
868 # Check and return the requested version sheme.
869 if ($format eq "major") {
870 # Return the full version.
872 } elsif ($format eq "minor") {
873 # Return the major and minor part.
874 return "$major_ver.$minor_ver";
876 # Return the full version string.
877 return "$major_ver.$minor_ver.$patchlevel";
882 ## Function to generate the rules file with whitelisted addresses.
884 sub generate_ignore_file
() {
887 # SID range 1000000-1999999 Reserved for Local Use
888 # Put your custom rules in this range to avoid conflicts
891 # Read-in ignoredfile.
892 &General
::readhasharray
($IDS::ignored_file
, \
%ignored);
894 # Open ignorefile for writing.
895 open(FILE
, ">$IDS::whitelist_file") or die "Could not write to $IDS::whitelist_file. $!\n";
897 # Config file header.
898 print FILE
"# Autogenerated file.\n";
899 print FILE
"# All user modifications will be overwritten.\n\n";
901 # Add all user defined addresses to the whitelist.
903 # Check if the hash contains any elements.
904 if (keys (%ignored)) {
905 # Loop through the entire hash and write the host/network
906 # and remark to the ignore file.
907 while ( (my $key) = each %ignored) {
908 my $address = $ignored{$key}[0];
909 my $remark = $ignored{$key}[1];
910 my $status = $ignored{$key}[2];
912 # Check if the status of the entry is "enabled".
913 if ($status eq "enabled") {
914 # Check if the address/network is valid.
915 if ((&General
::validip
($address)) || (&General
::validipandmask
($address))) {
916 # Write rule line to the file to pass any traffic from this IP
917 print FILE
"pass ip $address any -> any any (msg:\"pass all traffic from/to $address\"\; sid:$sid\;)\n";
930 ## Function to set correct ownership for single files and directories.
933 sub set_ownership
($) {
936 # User and group of the WUI.
937 my $uname = "nobody";
938 my $grname = "nobody";
940 # The chown function implemented in perl requies the user and group as nummeric id's.
941 my $uid = getpwnam($uname);
942 my $gid = getgrnam($grname);
944 # Check if the given target exists.
946 # Stop the script and print error message.
947 die "The $target does not exist. Cannot change the ownership!\n";
950 # Check weather the target is a file or directory.
952 # Change ownership ot the single file.
953 chown($uid, $gid, "$target");
954 } elsif (-d
$target) {
955 # Do a directory listing.
956 opendir(DIR
, $target) or die $!;
957 # Loop through the direcory.
958 while (my $file = readdir(DIR
)) {
960 # We only want files.
961 next unless (-f
"$target/$file");
963 # Set correct ownership for the files.
964 chown($uid, $gid, "$target/$file");
969 # Change ownership of the directory.
970 chown($uid, $gid, "$target");
975 ## Function to read-in the aliases file and returns all configured and enabled aliases.
978 # Location of the aliases file.
979 my $aliases_file = "${General::swroot}/ethernet/aliases";
981 # Array to store the aliases.
984 # Check if the file is empty.
985 if (-z
$aliases_file) {
986 # Abort nothing to do.
990 # Open the aliases file.
991 open(ALIASES
, $aliases_file) or die "Could not open $aliases_file. $!\n";
993 # Loop through the file content.
994 while (my $line = <ALIASES
>) {
998 # Splitt line content into single chunks.
999 my ($address, $state, $remark) = split(/\,/, $line);
1001 # Check if the state of the current processed alias is "on".
1002 if ($state eq "on") {
1003 # Check if the address is valid.
1004 if(&Network
::check_ip_address
($address)) {
1005 # Add the alias to the array of aliases.
1006 push(@aliases, $address);
1011 # Close file handle.
1019 ## Function to grab the current assigned IP-address on red.
1021 sub get_red_address
() {
1022 # File, which contains the current IP-address of the red interface.
1023 my $file = "${General::swroot}/red/local-ipaddress";
1025 # Check if the file exists.
1027 # Open the given file.
1028 open(FILE
, "$file") or die "Could not open $file.";
1030 # Obtain the address from the first line of the file.
1031 my $address = <FILE
>;
1039 # Check if the grabbed address is valid.
1040 if (&General
::validip
($address)) {
1041 # Return the address.
1051 ## Function to write the lock file for locking the WUI, while
1052 ## the autoupdate script runs.
1054 sub lock_ids_page
() {
1055 # Call subfunction to create the file.
1056 &create_empty_file
($ids_page_lock_file);
1060 ## Function to release the lock of the WUI, again.
1062 sub unlock_ids_page
() {
1064 unlink($ids_page_lock_file);