]> git.ipfire.org Git - ipfire-2.x.git/blob - config/cfgroot/ids-functions.pl
ids-functions.pl: Use temporary file in downloader.
[ipfire-2.x.git] / config / cfgroot / ids-functions.pl
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
24 package IDS;
25
26 require '/var/ipfire/general-functions.pl';
27
28 # Location where all config and settings files are stored.
29 our $settingsdir = "${General::swroot}/suricata";
30
31 # Location and name of the tarball which contains the ruleset.
32 our $rulestarball = "/var/tmp/idsrules.tar.gz";
33
34 # File to store any errors, which also will be read and displayed by the wui.
35 our $storederrorfile = "/tmp/ids_storederror";
36
37 # Location where the rulefiles are stored.
38 our $rulespath = "/var/lib/suricata";
39
40 # File which contains a list of all supported ruleset sources.
41 # (Sourcefire, Emergingthreads, etc..)
42 our $rulesetsourcesfile = "$settingsdir/ruleset-sources";
43
44 # The pidfile of the IDS.
45 our $idspidfile = "/var/run/suricata.pid";
46
47 # Location of suricatactrl.
48 my $suricatactrl = "/usr/local/bin/suricatactrl";
49
50 # Array with allowed commands of suricatactrl.
51 my @suricatactrl_cmds = ( 'start', 'stop', 'restart', 'reload', 'fix-rules-dir', 'cron' );
52
53 # Array with supported cron intervals.
54 my @cron_intervals = ('off', 'daily', 'weekly' );
55
56 #
57 ## Function for checking if at least 300MB of free disk space are available
58 ## on the "/var" partition.
59 #
60 sub 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) {
77 # Log error to syslog.
78 &_log_to_syslog("Not enough free disk space on /var. Only $available MB from 300 MB available.");
79
80 # Exit function and return "1" - False.
81 return 1;
82 }
83 }
84 }
85
86 # Everything okay, return nothing.
87 return;
88 }
89
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 #
99 sub downloadruleset {
100 # Get snort settings.
101 my %snortsettings=();
102 &General::readhash("$settingsdir/settings", \%snortsettings);
103
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
113 # Get all available ruleset locations.
114 my %rulesetsources=();
115 &General::readhash($rulesetsourcesfile, \%rulesetsources);
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 {
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;
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) {
166 # Log error and abort.
167 &_log_to_syslog("Unable to gather a download URL for the selected ruleset.");
168 return 1;
169 }
170
171 # Pass the requrested url to the downloader.
172 my $request = HTTP::Request->new(HEAD => $url);
173
174 # Accept the html header.
175 $request->header('Accept' => 'text/html');
176
177 # Perform the request and fetch the html header.
178 my $response = $downloader->request($request);
179
180 # Check if there was any error.
181 unless ($response->is_success) {
182 # Obtain error.
183 my $error = $response->content;
184
185 # Log error message.
186 &_log_to_syslog("Unable to download the ruleset. \($error\)");
187
188 # Return "1" - false.
189 return 1;
190 }
191
192 # Assign the fetched header object.
193 my $header = $response->headers;
194
195 # Grab the remote file size from the object and store it in the
196 # variable.
197 my $remote_filesize = $header->content_length;
198
199 # Load perl module to deal with temporary files.
200 use File::Temp;
201
202 # Generate temporay file name, located in "/var/tmp" and with a suffix of ".tar.gz".
203 my $tmp = File::Temp->new( SUFFIX => ".tar.gz", DIR => "/var/tmp/", UNLINK => 0 );
204 my $tmpfile = $tmp->filename();
205
206 # Pass the requested url to the downloader.
207 my $request = HTTP::Request->new(GET => $url);
208
209 # Perform the request and save the output into the tmpfile.
210 my $response = $downloader->request($request, $tmpfile);
211
212 # Check if there was any error.
213 unless ($response->is_success) {
214 # Obtain error.
215 my $error = $response->content;
216
217 # Log error message.
218 &_log_to_syslog("Unable to download the ruleset. \($error\)");
219
220 # Return "1" - false.
221 return 1;
222 }
223
224 # Load perl stat module.
225 use File::stat;
226
227 # Perform stat on the tmpfile.
228 my $stat = stat($tmpfile);
229
230 # Grab the local filesize of the downloaded tarball.
231 my $local_filesize = $stat->size;
232
233 # Check if both file sizes match.
234 unless ($remote_filesize eq $local_filesize) {
235 # Log error message.
236 &_log_to_syslog("Unable to completely download the ruleset. ");
237 &_log_to_syslog("Only got $local_filesize Bytes instead of $remote_filesize Bytes. ");
238
239 # Delete temporary file.
240 unlink("$tmpfile");
241
242 # Return "1" - false.
243 return 1;
244 }
245
246 # Load file copy module, which contains the move() function.
247 use File::Copy;
248
249 # Overwrite existing rules tarball with the new downloaded one.
250 move("$tmpfile", "$rulestarball");
251
252 # If we got here, everything worked fine. Return nothing.
253 return;
254 }
255
256 #
257 ## A tiny wrapper function to call the oinkmaster script.
258 #
259 sub oinkmaster () {
260 # Check if the files in rulesdir have the correct permissions.
261 &_check_rulesdir_permissions();
262
263 # Cleanup the rules directory before filling it with the new rulest.
264 &_cleanup_rulesdir();
265
266 # Load perl module to talk to the kernel syslog.
267 use Sys::Syslog qw(:DEFAULT setlogsock);
268
269 # Establish the connection to the syslog service.
270 openlog('oinkmaster', 'cons,pid', 'user');
271
272 # Call oinkmaster to generate ruleset.
273 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";
274
275 # Log output of oinkmaster to syslog.
276 while(<OINKMASTER>) {
277 # The syslog function works best with an array based input,
278 # so generate one before passing the message details to syslog.
279 my @syslog = ("INFO", "$_");
280
281 # Send the log message.
282 syslog(@syslog);
283 }
284
285 # Close the pipe to oinkmaster process.
286 close(OINKMASTER);
287
288 # Close the log handle.
289 closelog();
290 }
291
292 #
293 ## Function to do all the logging stuff if the downloading or updating of the ruleset fails.
294 #
295 sub log_error ($) {
296 my ($error) = @_;
297
298 # Remove any newline.
299 chomp($error);
300
301 # Call private function to log the error message to syslog.
302 &_log_to_syslog($error);
303
304 # Call private function to write/store the error message in the storederrorfile.
305 &_store_error_message($error);
306 }
307
308 #
309 ## Function to log a given error message to the kernel syslog.
310 #
311 sub _log_to_syslog ($) {
312 my ($message) = @_;
313
314 # Load perl module to talk to the kernel syslog.
315 use Sys::Syslog qw(:DEFAULT setlogsock);
316
317 # The syslog function works best with an array based input,
318 # so generate one before passing the message details to syslog.
319 my @syslog = ("ERR", "<ERROR> $message");
320
321 # Establish the connection to the syslog service.
322 openlog('oinkmaster', 'cons,pid', 'user');
323
324 # Send the log message.
325 syslog(@syslog);
326
327 # Close the log handle.
328 closelog();
329 }
330
331 #
332 ## Private function to write a given error message to the storederror file.
333 #
334 sub _store_error_message ($) {
335 my ($message) = @_;
336
337 # Remove any newline.
338 chomp($message);
339
340 # Open file for writing.
341 open (ERRORFILE, ">$storederrorfile") or die "Could not write to $storederrorfile. $!\n";
342
343 # Write error to file.
344 print ERRORFILE "$message\n";
345
346 # Close file.
347 close (ERRORFILE);
348 }
349
350 #
351 ## Function to get a list of all available network zones.
352 #
353 sub get_available_network_zones () {
354 # Get netsettings.
355 my %netsettings = ();
356 &General::readhash("${General::swroot}/ethernet/settings", \%netsettings);
357
358 # Obtain the configuration type from the netsettings hash.
359 my $config_type = $netsettings{'CONFIG_TYPE'};
360
361 # Hash which contains the conversation from the config mode
362 # to the existing network interface names. They are stored like
363 # an array.
364 #
365 # Mode "0" red is a modem and green
366 # Mode "1" red is a netdev and green
367 # Mode "2" red, green and orange
368 # Mode "3" red, green and blue
369 # Mode "4" red, green, blue, orange
370 my %config_type_to_interfaces = (
371 "0" => [ "red", "green" ],
372 "1" => [ "red", "green" ],
373 "2" => [ "red", "green", "orange" ],
374 "3" => [ "red", "green", "blue" ],
375 "4" => [ "red", "green", "blue", "orange" ]
376 );
377
378 # Obtain and dereference the corresponding network interaces based on the read
379 # network config type.
380 my @network_zones = @{ $config_type_to_interfaces{$config_type} };
381
382 # Return them.
383 return @network_zones;
384 }
385
386 #
387 ## Function to check if the IDS is running.
388 #
389 sub ids_is_running () {
390 if(-f $idspidfile) {
391 # Open PID file for reading.
392 open(PIDFILE, "$idspidfile") or die "Could not open $idspidfile. $!\n";
393
394 # Grab the process-id.
395 my $pid = <PIDFILE>;
396
397 # Close filehandle.
398 close(PIDFILE);
399
400 # Remove any newline.
401 chomp($pid);
402
403 # Check if a directory for the process-id exists in proc.
404 if(-d "/proc/$pid") {
405 # The IDS daemon is running return the process id.
406 return $pid;
407 }
408 }
409
410 # Return nothing - IDS is not running.
411 return;
412 }
413
414 #
415 ## Function to call suricatactrl binary with a given command.
416 #
417 sub call_suricatactrl ($) {
418 # Get called option.
419 my ($option, $interval) = @_;
420
421 # Loop through the array of supported commands and check if
422 # the given one is part of it.
423 foreach my $cmd (@suricatactrl_cmds) {
424 # Skip current command unless the given one has been found.
425 next unless($cmd eq $option);
426
427 # Check if the given command is "cron".
428 if ($option eq "cron") {
429 # Check if an interval has been given.
430 if ($interval) {
431 # Check if the given interval is valid.
432 foreach my $element (@cron_intervals) {
433 # Skip current element until the given one has been found.
434 next unless($element eq $interval);
435
436 # Call the suricatactrl binary and pass the "cron" command
437 # with the requrested interval.
438 system("$suricatactrl $option $interval &>/dev/null");
439
440 # Return "1" - True.
441 return 1;
442 }
443 }
444
445 # If we got here, the given interval is not supported or none has been given. - Return nothing.
446 return;
447 } else {
448 # Call the suricatactrl binary and pass the requrested
449 # option to it.
450 system("$suricatactrl $option &>/dev/null");
451
452 # Return "1" - True.
453 return 1;
454 }
455 }
456
457 # Command not found - return nothing.
458 return;
459 }
460
461 #
462 ## Function to create a new empty file.
463 #
464 sub create_empty_file($) {
465 my ($file) = @_;
466
467 # Check if the given file exists.
468 if(-e $file) {
469 # Do nothing to prevent from overwriting existing files.
470 return;
471 }
472
473 # Open the file for writing.
474 open(FILE, ">$file") or die "Could not write to $file. $!\n";
475
476 # Close file handle.
477 close(FILE);
478
479 # Return true.
480 return 1;
481 }
482
483 #
484 ## Private function to check if the file permission of the rulespath are correct.
485 ## If not, call suricatactrl to fix them.
486 #
487 sub _check_rulesdir_permissions() {
488 # Check if the rulepath main directory is writable.
489 unless (-W $rulespath) {
490 # If not call suricatctrl to fix it.
491 &call_suricatactrl("fix-rules-dir");
492 }
493
494 # Open snort rules directory and do a directory listing.
495 opendir(DIR, $rulespath) or die $!;
496 # Loop through the direcory.
497 while (my $file = readdir(DIR)) {
498 # We only want files.
499 next unless (-f "$rulespath/$file");
500
501 # Check if the file is writable by the user.
502 if (-W "$rulespath/$file") {
503 # Everything is okay - go on to the next file.
504 next;
505 } else {
506 # There are wrong permissions, call suricatactrl to fix it.
507 &call_suricatactrl("fix-rules-dir");
508 }
509 }
510 }
511
512 #
513 ## Private function to cleanup the directory which contains
514 ## the IDS rules, before extracting and modifing the new ruleset.
515 #
516 sub _cleanup_rulesdir() {
517 # Open rules directory and do a directory listing.
518 opendir(DIR, $rulespath) or die $!;
519
520 # Loop through the direcory.
521 while (my $file = readdir(DIR)) {
522 # We only want files.
523 next unless (-f "$rulespath/$file");
524
525 # Skip element if it has config as file extension.
526 next if ($file =~ m/\.config$/);
527
528 # Delete the current processed file, if not, exit this function
529 # and return an error message.
530 unlink("$rulespath/$file") or return "Could not delete $rulespath/$file. $!\n";
531 }
532
533 # Return nothing;
534 return;
535 }
536
537 1;