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 = "/etc/suricata/rules";
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' );
54 ## Function for checking if at least 300MB of free disk space are available
55 ## on the "/var" partition.
57 sub checkdiskspace
() {
58 # Call diskfree to gather the free disk space of /var.
59 my @df = `/bin/df -B M /var`;
61 # Loop through the output.
62 foreach my $line (@df) {
64 next if $line =~ m/^Filesystem/;
66 # Search for a line with the device information.
67 if ($line =~ m/dev/ ) {
68 # Split the line into single pieces.
69 my @values = split(' ', $line);
70 my ($filesystem, $blocks, $used, $available, $used_perenctage, $mounted_on) = @values;
72 # Check if the available disk space is more than 300MB.
73 if ($available < 300) {
74 # Log error to syslog.
75 &_log_to_syslog
("Not enough free disk space on /var. Only $available MB from 300 MB available.");
77 # Exit function and return "1" - False.
83 # Everything okay, return nothing.
88 ## This function is responsible for downloading the configured snort ruleset.
90 ## * At first it obtains from the stored snortsettings which ruleset should be downloaded.
91 ## * The next step is to get the download locations for all available rulesets.
92 ## * After that, the function will check if an upstream proxy should be used and grab the settings.
93 ## * The last step will be to generate the final download url, by obtaining the URL for the desired
94 ## ruleset, add the settings for the upstream proxy and final grab the rules tarball from the server.
99 &General
::readhash
("$settingsdir/settings", \
%snortsettings);
101 # Check if a ruleset has been configured.
102 unless($snortsettings{'RULES'}) {
103 # Log that no ruleset has been configured and abort.
104 &_log_to_syslog
("No ruleset source has been configured.");
110 # Get all available ruleset locations.
111 my %rulesetsources=();
112 &General
::readhash
($rulesetsourcesfile, \
%rulesetsources);
114 # Read proxysettings.
115 my %proxysettings=();
116 &General
::readhash
("${General::swroot}/proxy/settings", \
%proxysettings);
118 # Load required perl module to handle the download.
121 # Init the download module.
122 my $downloader = LWP
::UserAgent
->new;
124 # Set timeout to 10 seconds.
125 $downloader->timeout(10);
127 # Check if an upstream proxy is configured.
128 if ($proxysettings{'UPSTREAM_PROXY'}) {
129 my ($peer, $peerport) = (/^(?:[a-zA-Z ]+\:\/\
/)?(?:[A-Za-z0-9\_\.\-]*?(?:\:[A-Za-z0-9\_\.\-]*?)?\@)?([a-zA-Z0-9\.\_\-]*?)(?:\:([0-9]{1,5}))?(?:\/.*?
)?
$/);
132 # Check if we got a peer.
134 $proxy_url = "http://";
136 # Check if the proxy requires authentication.
137 if (($proxysettings{'UPSTREAM_USER'}) && ($proxysettings{'UPSTREAM_PASSWORD'})) {
138 $proxy_url .= "$proxysettings{'UPSTREAM_USER'}\:$proxysettings{'UPSTREAM_PASSWORD'}\@";
141 # Add proxy server address and port.
142 $proxy_url .= "$peer\:$peerport";
144 # Log error message and break.
145 &_log_to_syslog
("Could not proper configure the proxy server access.");
147 # Return "1" - false.
151 # Setup proxy settings.
152 $downloader->proxy('http', $proxy_url);
155 # Grab the right url based on the configured vendor.
156 my $url = $rulesetsources{$snortsettings{'RULES'}};
158 # Check if the vendor requires an oinkcode and add it if needed.
159 $url =~ s/\<oinkcode\>/$snortsettings{'OINKCODE'}/g;
161 # Abort if no url could be determined for the vendor.
163 # Log error and abort.
164 &_log_to_syslog
("Unable to gather a download URL for the selected ruleset.");
168 # Pass the requested url to the downloader.
169 my $request = HTTP
::Request
->new(GET
=> $url);
171 # Perform the request and save the output into the "$rulestarball" file.
172 my $response = $downloader->request($request, $rulestarball);
174 # Check if there was any error.
175 unless ($response->is_success) {
177 my $error = $response->content;
180 &_log_to_syslog
("Unable to download the ruleset. \($error\)");
182 # Return "1" - false.
186 # If we got here, everything worked fine. Return nothing.
191 ## A tiny wrapper function to call the oinkmaster script.
194 # Check if the files in rulesdir have the correct permissions.
195 &_check_rulesdir_permissions
();
197 # Load perl module to talk to the kernel syslog.
198 use Sys
::Syslog
qw(:DEFAULT setlogsock);
200 # Establish the connection to the syslog service.
201 openlog
('oinkmaster', 'cons,pid', 'user');
203 # Call oinkmaster to generate ruleset.
204 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";
206 # Log output of oinkmaster to syslog.
207 while(<OINKMASTER
>) {
208 # The syslog function works best with an array based input,
209 # so generate one before passing the message details to syslog.
210 my @syslog = ("INFO", "$_");
212 # Send the log message.
216 # Close the pipe to oinkmaster process.
219 # Close the log handle.
224 ## Function to do all the logging stuff if the downloading or updating of the ruleset fails.
229 # Remove any newline.
232 # Call private function to log the error message to syslog.
233 &_log_to_syslog
($error);
235 # Call private function to write/store the error message in the storederrorfile.
236 &_store_error_message
($error);
240 ## Function to log a given error message to the kernel syslog.
242 sub _log_to_syslog
($) {
245 # Load perl module to talk to the kernel syslog.
246 use Sys
::Syslog
qw(:DEFAULT setlogsock);
248 # The syslog function works best with an array based input,
249 # so generate one before passing the message details to syslog.
250 my @syslog = ("ERR", "<ERROR> $message");
252 # Establish the connection to the syslog service.
253 openlog
('oinkmaster', 'cons,pid', 'user');
255 # Send the log message.
258 # Close the log handle.
263 ## Private function to write a given error message to the storederror file.
265 sub _store_error_message
($) {
268 # Remove any newline.
271 # Open file for writing.
272 open (ERRORFILE
, ">$storederrorfile") or die "Could not write to $storederrorfile. $!\n";
274 # Write error to file.
275 print ERRORFILE
"$message\n";
282 ## Function to get a list of all available network zones.
284 sub get_available_network_zones
() {
286 my %netsettings = ();
287 &General
::readhash
("${General::swroot}/ethernet/settings", \
%netsettings);
289 # Obtain the configuration type from the netsettings hash.
290 my $config_type = $netsettings{'CONFIG_TYPE'};
292 # Hash which contains the conversation from the config mode
293 # to the existing network interface names. They are stored like
296 # Mode "0" red is a modem and green
297 # Mode "1" red is a netdev and green
298 # Mode "2" red, green and orange
299 # Mode "3" red, green and blue
300 # Mode "4" red, green, blue, orange
301 my %config_type_to_interfaces = (
302 "0" => [ "red", "green" ],
303 "1" => [ "red", "green" ],
304 "2" => [ "red", "green", "orange" ],
305 "3" => [ "red", "green", "blue" ],
306 "4" => [ "red", "green", "blue", "orange" ]
309 # Obtain and dereference the corresponding network interaces based on the read
310 # network config type.
311 my @network_zones = @
{ $config_type_to_interfaces{$config_type} };
314 return @network_zones;
318 ## Function to check if the IDS is running.
320 sub ids_is_running
() {
322 # Open PID file for reading.
323 open(PIDFILE
, "$idspidfile") or die "Could not open $idspidfile. $!\n";
325 # Grab the process-id.
331 # Remove any newline.
334 # Check if a directory for the process-id exists in proc.
335 if(-d
"/proc/$pid") {
336 # The IDS daemon is running return the process id.
341 # Return nothing - IDS is not running.
346 ## Function to call suricatactrl binary with a given command.
348 sub call_suricatactrl
($) {
352 # Loop through the array of supported commands and check if
353 # the given one is part of it.
354 foreach my $cmd (@suricatactrl_cmds) {
355 # Skip current command unless the given one has been found.
356 next unless($cmd eq $option);
358 # Call the suricatactrl binary and pass the requrested
360 system("$suricatactrl $option &>/dev/null");
366 # Command not found - return nothing.
371 ## Function to create a new empty file.
373 sub create_empty_file
($) {
376 # Check if the given file exists.
378 # Do nothing to prevent from overwriting existing files.
382 # Open the file for writing.
383 open(FILE
, ">$file") or die "Could not write to $file. $!\n";
393 ## Private function to check if the file permission of the rulespath are correct.
394 ## If not, call suricatactrl to fix them.
396 sub _check_rulesdir_permissions
() {
397 # Check if the rulepath main directory is writable.
398 unless (-W
$rulespath) {
399 # If not call suricatctrl to fix it.
400 &call_suricatactrl
("fix-rules-dir");
403 # Open snort rules directory and do a directory listing.
404 opendir(DIR
, $rulespath) or die $!;
405 # Loop through the direcory.
406 while (my $file = readdir(DIR
)) {
407 # We only want files.
408 next unless (-f
"$rulespath/$file");
410 # Check if the file is writable by the user.
411 if (-W
"$rulespath/$file") {
412 # Everything is okay - go on to the next file.
415 # There are wrong permissions, call suricatactrl to fix it.
416 &call_suricatactrl
("fix-rules-dir");