]> git.ipfire.org Git - ipfire-2.x.git/blame - config/cfgroot/ids-functions.pl
suricata: Rootfile update
[ipfire-2.x.git] / config / cfgroot / ids-functions.pl
CommitLineData
8dcebe53
SS
1#!/usr/bin/perl -w
2############################################################################
3# #
4# This file is part of the IPFire Firewall. #
5# #
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. #
10# #
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. #
15# #
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 #
19# #
20# Copyright (C) 2018 IPFire Team <info@ipfire.org>. #
21# #
22############################################################################
23
24package IDS;
25
26require '/var/ipfire/general-functions.pl';
8dcebe53 27
02844177 28# Location where all config and settings files are stored.
164eab66 29our $settingsdir = "${General::swroot}/suricata";
02844177 30
eea2670b 31# Location and name of the tarball which contains the ruleset.
164eab66 32our $rulestarball = "/var/tmp/idsrules.tar.gz";
eea2670b 33
3983aebd 34# File to store any errors, which also will be read and displayed by the wui.
77910792 35our $storederrorfile = "/tmp/ids_storederror";
3983aebd 36
298ef5ba 37# Location where the rulefiles are stored.
21cab141 38our $rulespath = "/var/lib/suricata";
298ef5ba 39
bce84f39
SS
40# File which contains a list of all supported ruleset sources.
41# (Sourcefire, Emergingthreads, etc..)
42our $rulesetsourcesfile = "$settingsdir/ruleset-sources";
43
796eea21
SS
44# The pidfile of the IDS.
45our $idspidfile = "/var/run/suricata.pid";
46
5240a809
SS
47# Location of suricatactrl.
48my $suricatactrl = "/usr/local/bin/suricatactrl";
49
50# Array with allowed commands of suricatactrl.
ed06bc81
SS
51my @suricatactrl_cmds = ( 'start', 'stop', 'restart', 'reload', 'fix-rules-dir', 'cron' );
52
53# Array with supported cron intervals.
54my @cron_intervals = ('off', 'daily', 'weekly' );
5240a809 55
8dcebe53
SS
56#
57## Function for checking if at least 300MB of free disk space are available
58## on the "/var" partition.
59#
60sub checkdiskspace () {
61 # Call diskfree to gather the free disk space of /var.
62 my @df = `/bin/df -B M /var`;
63
64 # Loop through the output.
65 foreach my $line (@df) {
66 # Ignore header line.
67 next if $line =~ m/^Filesystem/;
68
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;
74
75 # Check if the available disk space is more than 300MB.
76 if ($available < 300) {
434001d0
SS
77 # Log error to syslog.
78 &_log_to_syslog("Not enough free disk space on /var. Only $available MB from 300 MB available.");
8dcebe53 79
434001d0
SS
80 # Exit function and return "1" - False.
81 return 1;
8dcebe53
SS
82 }
83 }
84 }
85
86 # Everything okay, return nothing.
87 return;
88}
89
eea2670b
SS
90#
91## This function is responsible for downloading the configured snort ruleset.
92##
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.
98#
99sub downloadruleset {
100 # Get snort settings.
101 my %snortsettings=();
02844177 102 &General::readhash("$settingsdir/settings", \%snortsettings);
eea2670b 103
be52c68a
SS
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.");
108
109 # Return "1".
110 return 1;
111 }
112
eea2670b
SS
113 # Get all available ruleset locations.
114 my %rulesetsources=();
bce84f39 115 &General::readhash($rulesetsourcesfile, \%rulesetsources);
eea2670b
SS
116
117 # Read proxysettings.
118 my %proxysettings=();
119 &General::readhash("${General::swroot}/proxy/settings", \%proxysettings);
120
121 # Load required perl module to handle the download.
122 use LWP::UserAgent;
123
124 # Init the download module.
125 my $downloader = LWP::UserAgent->new;
126
127 # Set timeout to 10 seconds.
128 $downloader->timeout(10);
129
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}))?(?:\/.*?)?$/);
133 my $proxy_url;
134
135 # Check if we got a peer.
136 if ($peer) {
137 $proxy_url = "http://";
138
139 # Check if the proxy requires authentication.
140 if (($proxysettings{'UPSTREAM_USER'}) && ($proxysettings{'UPSTREAM_PASSWORD'})) {
141 $proxy_url .= "$proxysettings{'UPSTREAM_USER'}\:$proxysettings{'UPSTREAM_PASSWORD'}\@";
142 }
143
144 # Add proxy server address and port.
145 $proxy_url .= "$peer\:$peerport";
146 } else {
434001d0
SS
147 # Log error message and break.
148 &_log_to_syslog("Could not proper configure the proxy server access.");
149
150 # Return "1" - false.
151 return 1;
eea2670b
SS
152 }
153
154 # Setup proxy settings.
155 $downloader->proxy('http', $proxy_url);
156 }
157
158 # Grab the right url based on the configured vendor.
159 my $url = $rulesetsources{$snortsettings{'RULES'}};
160
161 # Check if the vendor requires an oinkcode and add it if needed.
162 $url =~ s/\<oinkcode\>/$snortsettings{'OINKCODE'}/g;
163
164 # Abort if no url could be determined for the vendor.
165 unless ($url) {
434001d0
SS
166 # Log error and abort.
167 &_log_to_syslog("Unable to gather a download URL for the selected ruleset.");
168 return 1;
eea2670b
SS
169 }
170
171 # Pass the requested url to the downloader.
172 my $request = HTTP::Request->new(GET => $url);
173
174 # Perform the request and save the output into the "$rulestarball" file.
175 my $response = $downloader->request($request, $rulestarball);
176
177 # Check if there was any error.
178 unless ($response->is_success) {
88daf7eb
SS
179 # Obtain error.
180 my $error = $response->content;
181
434001d0 182 # Log error message.
88daf7eb 183 &_log_to_syslog("Unable to download the ruleset. \($error\)");
434001d0
SS
184
185 # Return "1" - false.
186 return 1;
eea2670b
SS
187 }
188
189 # If we got here, everything worked fine. Return nothing.
190 return;
191}
8dcebe53 192
25f5cb0d
SS
193#
194## A tiny wrapper function to call the oinkmaster script.
195#
196sub oinkmaster () {
330759d8
SS
197 # Check if the files in rulesdir have the correct permissions.
198 &_check_rulesdir_permissions();
199
0e40e1e7
SS
200 # Load perl module to talk to the kernel syslog.
201 use Sys::Syslog qw(:DEFAULT setlogsock);
202
203 # Establish the connection to the syslog service.
204 openlog('oinkmaster', 'cons,pid', 'user');
205
25f5cb0d 206 # Call oinkmaster to generate ruleset.
d9711d91 207 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";
0e40e1e7
SS
208
209 # Log output of oinkmaster to syslog.
210 while(<OINKMASTER>) {
211 # The syslog function works best with an array based input,
212 # so generate one before passing the message details to syslog.
213 my @syslog = ("INFO", "$_");
214
215 # Send the log message.
216 syslog(@syslog);
217 }
218
219 # Close the pipe to oinkmaster process.
220 close(OINKMASTER);
221
222 # Close the log handle.
223 closelog();
25f5cb0d
SS
224}
225
3983aebd
SS
226#
227## Function to do all the logging stuff if the downloading or updating of the ruleset fails.
228#
229sub log_error ($) {
230 my ($error) = @_;
231
232 # Remove any newline.
233 chomp($error);
234
eb5592c1
SS
235 # Call private function to log the error message to syslog.
236 &_log_to_syslog($error);
237
3983aebd
SS
238 # Call private function to write/store the error message in the storederrorfile.
239 &_store_error_message($error);
240}
241
eb5592c1
SS
242#
243## Function to log a given error message to the kernel syslog.
244#
245sub _log_to_syslog ($) {
246 my ($message) = @_;
247
248 # Load perl module to talk to the kernel syslog.
249 use Sys::Syslog qw(:DEFAULT setlogsock);
250
251 # The syslog function works best with an array based input,
252 # so generate one before passing the message details to syslog.
253 my @syslog = ("ERR", "<ERROR> $message");
254
255 # Establish the connection to the syslog service.
256 openlog('oinkmaster', 'cons,pid', 'user');
257
258 # Send the log message.
259 syslog(@syslog);
260
261 # Close the log handle.
262 closelog();
263}
264
3983aebd
SS
265#
266## Private function to write a given error message to the storederror file.
267#
268sub _store_error_message ($) {
269 my ($message) = @_;
270
271 # Remove any newline.
272 chomp($message);
273
274 # Open file for writing.
275 open (ERRORFILE, ">$storederrorfile") or die "Could not write to $storederrorfile. $!\n";
276
277 # Write error to file.
278 print ERRORFILE "$message\n";
279
280 # Close file.
281 close (ERRORFILE);
282}
283
1cae702c
SS
284#
285## Function to get a list of all available network zones.
286#
287sub get_available_network_zones () {
288 # Get netsettings.
289 my %netsettings = ();
290 &General::readhash("${General::swroot}/ethernet/settings", \%netsettings);
291
292 # Obtain the configuration type from the netsettings hash.
293 my $config_type = $netsettings{'CONFIG_TYPE'};
294
295 # Hash which contains the conversation from the config mode
296 # to the existing network interface names. They are stored like
297 # an array.
298 #
299 # Mode "0" red is a modem and green
300 # Mode "1" red is a netdev and green
301 # Mode "2" red, green and orange
302 # Mode "3" red, green and blue
303 # Mode "4" red, green, blue, orange
304 my %config_type_to_interfaces = (
305 "0" => [ "red", "green" ],
306 "1" => [ "red", "green" ],
307 "2" => [ "red", "green", "orange" ],
308 "3" => [ "red", "green", "blue" ],
309 "4" => [ "red", "green", "blue", "orange" ]
310 );
311
312 # Obtain and dereference the corresponding network interaces based on the read
313 # network config type.
314 my @network_zones = @{ $config_type_to_interfaces{$config_type} };
315
316 # Return them.
317 return @network_zones;
318}
319
796eea21
SS
320#
321## Function to check if the IDS is running.
322#
323sub ids_is_running () {
324 if(-f $idspidfile) {
325 # Open PID file for reading.
326 open(PIDFILE, "$idspidfile") or die "Could not open $idspidfile. $!\n";
327
328 # Grab the process-id.
329 my $pid = <PIDFILE>;
330
331 # Close filehandle.
332 close(PIDFILE);
333
334 # Remove any newline.
335 chomp($pid);
336
337 # Check if a directory for the process-id exists in proc.
338 if(-d "/proc/$pid") {
339 # The IDS daemon is running return the process id.
340 return $pid;
341 }
342 }
343
344 # Return nothing - IDS is not running.
345 return;
346}
347
5240a809
SS
348#
349## Function to call suricatactrl binary with a given command.
350#
351sub call_suricatactrl ($) {
352 # Get called option.
ed06bc81 353 my ($option, $interval) = @_;
5240a809
SS
354
355 # Loop through the array of supported commands and check if
356 # the given one is part of it.
357 foreach my $cmd (@suricatactrl_cmds) {
358 # Skip current command unless the given one has been found.
359 next unless($cmd eq $option);
360
ed06bc81
SS
361 # Check if the given command is "cron".
362 if ($option eq "cron") {
363 # Check if an interval has been given.
364 if ($interval) {
365 # Check if the given interval is valid.
366 foreach my $element (@cron_intervals) {
367 # Skip current element until the given one has been found.
368 next unless($element eq $interval);
369
370 # Call the suricatactrl binary and pass the "cron" command
371 # with the requrested interval.
372 system("$suricatactrl $option $interval &>/dev/null");
373
374 # Return "1" - True.
375 return 1;
376 }
377 }
5240a809 378
ed06bc81
SS
379 # If we got here, the given interval is not supported or none has been given. - Return nothing.
380 return;
381 } else {
382 # Call the suricatactrl binary and pass the requrested
383 # option to it.
384 system("$suricatactrl $option &>/dev/null");
385
386 # Return "1" - True.
387 return 1;
388 }
5240a809
SS
389 }
390
391 # Command not found - return nothing.
392 return;
393}
394
308ba5e7
SS
395#
396## Function to create a new empty file.
397#
398sub create_empty_file($) {
399 my ($file) = @_;
400
401 # Check if the given file exists.
402 if(-e $file) {
403 # Do nothing to prevent from overwriting existing files.
404 return;
405 }
406
407 # Open the file for writing.
408 open(FILE, ">$file") or die "Could not write to $file. $!\n";
409
410 # Close file handle.
411 close(FILE);
412
413 # Return true.
414 return 1;
415}
416
330759d8
SS
417#
418## Private function to check if the file permission of the rulespath are correct.
419## If not, call suricatactrl to fix them.
420#
421sub _check_rulesdir_permissions() {
e568796b
SS
422 # Check if the rulepath main directory is writable.
423 unless (-W $rulespath) {
424 # If not call suricatctrl to fix it.
425 &call_suricatactrl("fix-rules-dir");
426 }
427
330759d8
SS
428 # Open snort rules directory and do a directory listing.
429 opendir(DIR, $rulespath) or die $!;
430 # Loop through the direcory.
431 while (my $file = readdir(DIR)) {
432 # We only want files.
433 next unless (-f "$rulespath/$file");
434
435 # Check if the file is writable by the user.
436 if (-W "$rulespath/$file") {
437 # Everything is okay - go on to the next file.
438 next;
439 } else {
440 # There are wrong permissions, call suricatactrl to fix it.
441 &call_suricatactrl("fix-rules-dir");
442 }
443 }
444}
445
8dcebe53 4461;