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 IPFire Team <info@ipfire.org>. #
22 ############################################################################
26 require '/var/ipfire/general-functions.pl';
28 # Location where all config and settings files are stored.
29 our $settingsdir = "${General::swroot}/suricata";
31 # Location and name of the tarball which contains the ruleset.
32 our $rulestarball = "/var/tmp/idsrules.tar.gz";
34 # File to store any errors, which also will be read and displayed by the wui.
35 our $storederrorfile = "/tmp/ids_storederror";
37 # Location where the rulefiles are stored.
38 our $rulespath = "/var/lib/suricata";
40 # File which contains a list of all supported ruleset sources.
41 # (Sourcefire, Emergingthreads, etc..)
42 our $rulesetsourcesfile = "$settingsdir/ruleset-sources";
44 # The pidfile of the IDS.
45 our $idspidfile = "/var/run/suricata.pid";
47 # Location of suricatactrl.
48 my $suricatactrl = "/usr/local/bin/suricatactrl";
50 # Array with allowed commands of suricatactrl.
51 my @suricatactrl_cmds = ( 'start', 'stop', 'restart', 'reload', 'fix-rules-dir', 'cron' );
53 # Array with supported cron intervals.
54 my @cron_intervals = ('off', 'daily', 'weekly' );
57 ## Function for checking if at least 300MB of free disk space are available
58 ## on the "/var" partition.
60 sub checkdiskspace
() {
61 # Call diskfree to gather the free disk space of /var.
62 my @df = `/bin/df -B M /var`;
64 # Loop through the output.
65 foreach my $line (@df) {
67 next if $line =~ m/^Filesystem/;
69 # Search for a line with the device information.
70 if ($line =~ m/dev/ ) {
71 # Split the line into single pieces.
72 my @values = split(' ', $line);
73 my ($filesystem, $blocks, $used, $available, $used_perenctage, $mounted_on) = @values;
75 # Check if the available disk space is more than 300MB.
76 if ($available < 300) {
77 # Log error to syslog.
78 &_log_to_syslog
("Not enough free disk space on /var. Only $available MB from 300 MB available.");
80 # Exit function and return "1" - False.
86 # Everything okay, return nothing.
91 ## This function is responsible for downloading the configured snort ruleset.
93 ## * At first it obtains from the stored snortsettings which ruleset should be downloaded.
94 ## * The next step is to get the download locations for all available rulesets.
95 ## * After that, the function will check if an upstream proxy should be used and grab the settings.
96 ## * The last step will be to generate the final download url, by obtaining the URL for the desired
97 ## ruleset, add the settings for the upstream proxy and final grab the rules tarball from the server.
100 # Get snort settings.
101 my %snortsettings=();
102 &General
::readhash
("$settingsdir/settings", \
%snortsettings);
104 # Check if a ruleset has been configured.
105 unless($snortsettings{'RULES'}) {
106 # Log that no ruleset has been configured and abort.
107 &_log_to_syslog
("No ruleset source has been configured.");
113 # Get all available ruleset locations.
114 my %rulesetsources=();
115 &General
::readhash
($rulesetsourcesfile, \
%rulesetsources);
117 # Read proxysettings.
118 my %proxysettings=();
119 &General
::readhash
("${General::swroot}/proxy/settings", \
%proxysettings);
121 # Load required perl module to handle the download.
124 # Init the download module.
125 my $downloader = LWP
::UserAgent
->new;
127 # Set timeout to 10 seconds.
128 $downloader->timeout(10);
130 # Check if an upstream proxy is configured.
131 if ($proxysettings{'UPSTREAM_PROXY'}) {
132 my ($peer, $peerport) = (/^(?:[a-zA-Z ]+\:\/\
/)?(?:[A-Za-z0-9\_\.\-]*?(?:\:[A-Za-z0-9\_\.\-]*?)?\@)?([a-zA-Z0-9\.\_\-]*?)(?:\:([0-9]{1,5}))?(?:\/.*?
)?
$/);
135 # Check if we got a peer.
137 $proxy_url = "http://";
139 # Check if the proxy requires authentication.
140 if (($proxysettings{'UPSTREAM_USER'}) && ($proxysettings{'UPSTREAM_PASSWORD'})) {
141 $proxy_url .= "$proxysettings{'UPSTREAM_USER'}\:$proxysettings{'UPSTREAM_PASSWORD'}\@";
144 # Add proxy server address and port.
145 $proxy_url .= "$peer\:$peerport";
147 # Log error message and break.
148 &_log_to_syslog
("Could not proper configure the proxy server access.");
150 # Return "1" - false.
154 # Setup proxy settings.
155 $downloader->proxy('http', $proxy_url);
158 # Grab the right url based on the configured vendor.
159 my $url = $rulesetsources{$snortsettings{'RULES'}};
161 # Check if the vendor requires an oinkcode and add it if needed.
162 $url =~ s/\<oinkcode\>/$snortsettings{'OINKCODE'}/g;
164 # Abort if no url could be determined for the vendor.
166 # Log error and abort.
167 &_log_to_syslog
("Unable to gather a download URL for the selected ruleset.");
171 # Pass the requrested url to the downloader.
172 my $request = HTTP
::Request
->new(HEAD
=> $url);
174 # Accept the html header.
175 $request->header('Accept' => 'text/html');
177 # Perform the request and fetch the html header.
178 my $response = $downloader->request($request);
180 # Check if there was any error.
181 unless ($response->is_success) {
183 my $error = $response->content;
186 &_log_to_syslog
("Unable to download the ruleset. \($error\)");
188 # Return "1" - false.
192 # Assign the fetched header object.
193 my $header = $response->headers;
195 # Grab the remote file size from the object and store it in the
197 my $remote_filesize = $header->content_length;
199 # Pass the requested url to the downloader.
200 my $request = HTTP
::Request
->new(GET
=> $url);
202 # Perform the request and save the output into the "$rulestarball" file.
203 my $response = $downloader->request($request, $rulestarball);
205 # Check if there was any error.
206 unless ($response->is_success) {
208 my $error = $response->content;
211 &_log_to_syslog
("Unable to download the ruleset. \($error\)");
213 # Return "1" - false.
217 # Load perl stat module.
220 # Perform stat on the rulestarball.
221 my $stat = stat($rulestarball);
223 # Grab the local filesize of the downloaded tarball.
224 my $local_filesize = $stat->size;
226 # Check if both file sizes match.
227 unless ($remote_filesize eq $local_filesize) {
229 &_log_to_syslog
("Unable to completely download the ruleset. ");
230 &_log_to_syslog
("Only got $local_filesize Bytes instead of $remote_filesize Bytes. ");
232 # Return "1" - false.
236 # If we got here, everything worked fine. Return nothing.
241 ## A tiny wrapper function to call the oinkmaster script.
244 # Check if the files in rulesdir have the correct permissions.
245 &_check_rulesdir_permissions
();
247 # Cleanup the rules directory before filling it with the new rulest.
248 &_cleanup_rulesdir
();
250 # Load perl module to talk to the kernel syslog.
251 use Sys
::Syslog
qw(:DEFAULT setlogsock);
253 # Establish the connection to the syslog service.
254 openlog
('oinkmaster', 'cons,pid', 'user');
256 # Call oinkmaster to generate ruleset.
257 open(OINKMASTER
, "/usr/local/bin/oinkmaster.pl -v -s -u file://$rulestarball -C $settingsdir/oinkmaster.conf -o $rulespath|") or die "Could not execute oinkmaster $!\n";
259 # Log output of oinkmaster to syslog.
260 while(<OINKMASTER
>) {
261 # The syslog function works best with an array based input,
262 # so generate one before passing the message details to syslog.
263 my @syslog = ("INFO", "$_");
265 # Send the log message.
269 # Close the pipe to oinkmaster process.
272 # Close the log handle.
277 ## Function to do all the logging stuff if the downloading or updating of the ruleset fails.
282 # Remove any newline.
285 # Call private function to log the error message to syslog.
286 &_log_to_syslog
($error);
288 # Call private function to write/store the error message in the storederrorfile.
289 &_store_error_message
($error);
293 ## Function to log a given error message to the kernel syslog.
295 sub _log_to_syslog
($) {
298 # Load perl module to talk to the kernel syslog.
299 use Sys
::Syslog
qw(:DEFAULT setlogsock);
301 # The syslog function works best with an array based input,
302 # so generate one before passing the message details to syslog.
303 my @syslog = ("ERR", "<ERROR> $message");
305 # Establish the connection to the syslog service.
306 openlog
('oinkmaster', 'cons,pid', 'user');
308 # Send the log message.
311 # Close the log handle.
316 ## Private function to write a given error message to the storederror file.
318 sub _store_error_message
($) {
321 # Remove any newline.
324 # Open file for writing.
325 open (ERRORFILE
, ">$storederrorfile") or die "Could not write to $storederrorfile. $!\n";
327 # Write error to file.
328 print ERRORFILE
"$message\n";
335 ## Function to get a list of all available network zones.
337 sub get_available_network_zones
() {
339 my %netsettings = ();
340 &General
::readhash
("${General::swroot}/ethernet/settings", \
%netsettings);
342 # Obtain the configuration type from the netsettings hash.
343 my $config_type = $netsettings{'CONFIG_TYPE'};
345 # Hash which contains the conversation from the config mode
346 # to the existing network interface names. They are stored like
349 # Mode "0" red is a modem and green
350 # Mode "1" red is a netdev and green
351 # Mode "2" red, green and orange
352 # Mode "3" red, green and blue
353 # Mode "4" red, green, blue, orange
354 my %config_type_to_interfaces = (
355 "0" => [ "red", "green" ],
356 "1" => [ "red", "green" ],
357 "2" => [ "red", "green", "orange" ],
358 "3" => [ "red", "green", "blue" ],
359 "4" => [ "red", "green", "blue", "orange" ]
362 # Obtain and dereference the corresponding network interaces based on the read
363 # network config type.
364 my @network_zones = @
{ $config_type_to_interfaces{$config_type} };
367 return @network_zones;
371 ## Function to check if the IDS is running.
373 sub ids_is_running
() {
375 # Open PID file for reading.
376 open(PIDFILE
, "$idspidfile") or die "Could not open $idspidfile. $!\n";
378 # Grab the process-id.
384 # Remove any newline.
387 # Check if a directory for the process-id exists in proc.
388 if(-d
"/proc/$pid") {
389 # The IDS daemon is running return the process id.
394 # Return nothing - IDS is not running.
399 ## Function to call suricatactrl binary with a given command.
401 sub call_suricatactrl
($) {
403 my ($option, $interval) = @_;
405 # Loop through the array of supported commands and check if
406 # the given one is part of it.
407 foreach my $cmd (@suricatactrl_cmds) {
408 # Skip current command unless the given one has been found.
409 next unless($cmd eq $option);
411 # Check if the given command is "cron".
412 if ($option eq "cron") {
413 # Check if an interval has been given.
415 # Check if the given interval is valid.
416 foreach my $element (@cron_intervals) {
417 # Skip current element until the given one has been found.
418 next unless($element eq $interval);
420 # Call the suricatactrl binary and pass the "cron" command
421 # with the requrested interval.
422 system("$suricatactrl $option $interval &>/dev/null");
429 # If we got here, the given interval is not supported or none has been given. - Return nothing.
432 # Call the suricatactrl binary and pass the requrested
434 system("$suricatactrl $option &>/dev/null");
441 # Command not found - return nothing.
446 ## Function to create a new empty file.
448 sub create_empty_file
($) {
451 # Check if the given file exists.
453 # Do nothing to prevent from overwriting existing files.
457 # Open the file for writing.
458 open(FILE
, ">$file") or die "Could not write to $file. $!\n";
468 ## Private function to check if the file permission of the rulespath are correct.
469 ## If not, call suricatactrl to fix them.
471 sub _check_rulesdir_permissions
() {
472 # Check if the rulepath main directory is writable.
473 unless (-W
$rulespath) {
474 # If not call suricatctrl to fix it.
475 &call_suricatactrl
("fix-rules-dir");
478 # Open snort rules directory and do a directory listing.
479 opendir(DIR
, $rulespath) or die $!;
480 # Loop through the direcory.
481 while (my $file = readdir(DIR
)) {
482 # We only want files.
483 next unless (-f
"$rulespath/$file");
485 # Check if the file is writable by the user.
486 if (-W
"$rulespath/$file") {
487 # Everything is okay - go on to the next file.
490 # There are wrong permissions, call suricatactrl to fix it.
491 &call_suricatactrl
("fix-rules-dir");
497 ## Private function to cleanup the directory which contains
498 ## the IDS rules, before extracting and modifing the new ruleset.
500 sub _cleanup_rulesdir
() {
501 # Open rules directory and do a directory listing.
502 opendir(DIR
, $rulespath) or die $!;
504 # Loop through the direcory.
505 while (my $file = readdir(DIR
)) {
506 # We only want files.
507 next unless (-f
"$rulespath/$file");
509 # Skip element if it has config as file extension.
510 next if ($file =~ m/\.config$/);
512 # Delete the current processed file, if not, exit this function
513 # and return an error message.
514 unlink("$rulespath/$file") or return "Could not delete $rulespath/$file. $!\n";