]> git.ipfire.org Git - ipfire-2.x.git/blame - config/cfgroot/ids-functions.pl
ids-functions.pl: Introduce extraceruleset() function.
[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# #
fd2dccaa 20# Copyright (C) 2018-2019 IPFire Team <info@ipfire.org> #
8dcebe53
SS
21# #
22############################################################################
23
e55fa2f7
SS
24use strict;
25
8dcebe53
SS
26package IDS;
27
28require '/var/ipfire/general-functions.pl';
abffcc99 29require "${General::swroot}/network-functions.pl";
4e4c3f14 30require "${General::swroot}/suricata/ruleset-sources";
8dcebe53 31
02844177 32# Location where all config and settings files are stored.
164eab66 33our $settingsdir = "${General::swroot}/suricata";
02844177 34
b02e30fd
SS
35# File where the used rulefiles are stored.
36our $used_rulefiles_file = "$settingsdir/suricata-used-rulefiles.yaml";
37
38# File where the addresses of the homenet are stored.
39our $homenet_file = "$settingsdir/suricata-homenet.yaml";
40
30ee98e9
SS
41# File where the addresses of the used DNS servers are stored.
42our $dns_servers_file = "$settingsdir/suricata-dns-servers.yaml";
43
e698090e
SS
44# File where the HTTP ports definition is stored.
45our $http_ports_file = "$settingsdir/suricata-http-ports.yaml";
46
b02e30fd
SS
47# File which contains the enabled sids.
48our $enabled_sids_file = "$settingsdir/oinkmaster-enabled-sids.conf";
49
50# File which contains the disabled sids.
51our $disabled_sids_file = "$settingsdir/oinkmaster-disabled-sids.conf";
52
53# File which contains wheater the rules should be changed.
54our $modify_sids_file = "$settingsdir/oinkmaster-modify-sids.conf";
55
56# File which stores the configured IPS settings.
57our $ids_settings_file = "$settingsdir/settings";
58
a8d36d3e 59# DEPRECATED - File which stores the configured rules-settings.
b02e30fd
SS
60our $rules_settings_file = "$settingsdir/rules-settings";
61
a8d36d3e
SS
62# File which stores the used and configured ruleset providers.
63our $providers_settings_file = "$settingsdir/providers-settings";
64
b02e30fd
SS
65# File which stores the configured settings for whitelisted addresses.
66our $ignored_file = "$settingsdir/ignored";
67
788a71f5 68# DEPRECATED - Location and name of the tarball which contains the ruleset.
164eab66 69our $rulestarball = "/var/tmp/idsrules.tar.gz";
eea2670b 70
788a71f5
SS
71# Location where the downloaded rulesets are stored.
72our $dl_rules_path = "/var/tmp";
73
3983aebd 74# File to store any errors, which also will be read and displayed by the wui.
77910792 75our $storederrorfile = "/tmp/ids_storederror";
3983aebd 76
8076deba
SS
77# File to lock the WUI, while the autoupdate script runs.
78our $ids_page_lock_file = "/tmp/ids_page_locked";
79
298ef5ba 80# Location where the rulefiles are stored.
21cab141 81our $rulespath = "/var/lib/suricata";
298ef5ba 82
612bb2df
SS
83# Location to store local rules. This file will not be touched.
84our $local_rules_file = "$rulespath/local.rules";
85
b02e30fd
SS
86# File which contains the rules to whitelist addresses on suricata.
87our $whitelist_file = "$rulespath/whitelist.rules";
88
bce84f39
SS
89# File which contains a list of all supported ruleset sources.
90# (Sourcefire, Emergingthreads, etc..)
91our $rulesetsourcesfile = "$settingsdir/ruleset-sources";
92
796eea21
SS
93# The pidfile of the IDS.
94our $idspidfile = "/var/run/suricata.pid";
95
5240a809
SS
96# Location of suricatactrl.
97my $suricatactrl = "/usr/local/bin/suricatactrl";
98
788a71f5
SS
99# Prefix for each downloaded ruleset.
100my $dl_rulesfile_prefix = "idsrules";
101
0fbfffea
SS
102# Temporary directory where the rulesets will be extracted.
103my $tmp_directory = "/tmp/ids_tmp";
104
5240a809 105# Array with allowed commands of suricatactrl.
ed06bc81
SS
106my @suricatactrl_cmds = ( 'start', 'stop', 'restart', 'reload', 'fix-rules-dir', 'cron' );
107
108# Array with supported cron intervals.
109my @cron_intervals = ('off', 'daily', 'weekly' );
5240a809 110
e698090e
SS
111# Array which contains the HTTP ports, which statically will be declared as HTTP_PORTS in the
112# http_ports_file.
113my @http_ports = ('80', '81');
114
788a71f5
SS
115# Hash which allows to convert the download type (dl_type) to a file suffix.
116my %dl_type_to_suffix = (
117 "archive" => ".tar.gz",
118 "plain" => ".rules",
119);
120
b02e30fd
SS
121#
122## Function to check and create all IDS related files, if the does not exist.
123#
124sub check_and_create_filelayout() {
125 # Check if the files exist and if not, create them.
126 unless (-f "$enabled_sids_file") { &create_empty_file($enabled_sids_file); }
127 unless (-f "$disabled_sids_file") { &create_empty_file($disabled_sids_file); }
128 unless (-f "$modify_sids_file") { &create_empty_file($modify_sids_file); }
129 unless (-f "$used_rulefiles_file") { &create_empty_file($used_rulefiles_file); }
130 unless (-f "$ids_settings_file") { &create_empty_file($ids_settings_file); }
a8d36d3e 131 unless (-f "$providers_settings_file") { &create_empty_file($providers_settings_file); }
b02e30fd
SS
132 unless (-f "$ignored_file") { &create_empty_file($ignored_file); }
133 unless (-f "$whitelist_file" ) { &create_empty_file($whitelist_file); }
134}
135
70cc1315
SS
136#
137## Function to get a list of all available ruleset providers.
138##
139## They will be returned as a sorted array.
140#
141sub get_ruleset_providers() {
142 my @providers;
143
144 # Loop through the hash of providers.
145 foreach my $provider ( keys %IDS::Ruleset::Providers ) {
146 # Add the provider to the array.
147 push(@providers, $provider);
148 }
149
150 # Sort and return the array.
151 return sort(@providers);
152}
153
8dcebe53
SS
154#
155## Function for checking if at least 300MB of free disk space are available
156## on the "/var" partition.
157#
158sub checkdiskspace () {
159 # Call diskfree to gather the free disk space of /var.
81631920 160 my @df = &General::system_output("/bin/df", "-B", "M", "/var");
8dcebe53
SS
161
162 # Loop through the output.
163 foreach my $line (@df) {
164 # Ignore header line.
165 next if $line =~ m/^Filesystem/;
166
167 # Search for a line with the device information.
168 if ($line =~ m/dev/ ) {
169 # Split the line into single pieces.
170 my @values = split(' ', $line);
171 my ($filesystem, $blocks, $used, $available, $used_perenctage, $mounted_on) = @values;
172
173 # Check if the available disk space is more than 300MB.
174 if ($available < 300) {
434001d0
SS
175 # Log error to syslog.
176 &_log_to_syslog("Not enough free disk space on /var. Only $available MB from 300 MB available.");
8dcebe53 177
434001d0
SS
178 # Exit function and return "1" - False.
179 return 1;
8dcebe53
SS
180 }
181 }
182 }
183
184 # Everything okay, return nothing.
185 return;
186}
187
eea2670b 188#
b3c2c336
SS
189## This function is responsible for downloading the configured IDS rulesets or if no one is specified
190## all configured rulesets will be downloaded.
eea2670b 191##
b3c2c336
SS
192## * At first it gathers all configured ruleset providers, initialize the downloader and sets an
193## upstream proxy if configured.
194## * After that, the given ruleset or in case all rulesets should be downloaded, it will determine wether it
195## is enabled or not.
196## * The next step will be to generate the final download url, by obtaining the URL for the desired
197## ruleset, add the settings for the upstream proxy.
198## * Finally the function will grab all the rules files or tarballs from the servers.
eea2670b 199#
b3c2c336
SS
200sub downloadruleset ($) {
201 my ($provider) = @_;
202
203 # If no provider is given default to "all".
204 $provider //= 'all';
205
206 # Hash to store the providers and access id's, for which rules should be downloaded.
207 my %sheduled_providers = ();
208
209 # Get used provider settings.
210 my %used_providers = ();
211 &General::readhasharray("$providers_settings_file", \%used_providers);
eea2670b 212
be52c68a 213 # Check if a ruleset has been configured.
b3c2c336 214 unless(%used_providers) {
be52c68a 215 # Log that no ruleset has been configured and abort.
b3c2c336 216 &_log_to_syslog("No ruleset provider has been configured.");
be52c68a
SS
217
218 # Return "1".
219 return 1;
220 }
221
eea2670b
SS
222 # Read proxysettings.
223 my %proxysettings=();
224 &General::readhash("${General::swroot}/proxy/settings", \%proxysettings);
225
226 # Load required perl module to handle the download.
227 use LWP::UserAgent;
228
229 # Init the download module.
230 my $downloader = LWP::UserAgent->new;
231
232 # Set timeout to 10 seconds.
233 $downloader->timeout(10);
234
235 # Check if an upstream proxy is configured.
236 if ($proxysettings{'UPSTREAM_PROXY'}) {
eea2670b
SS
237 my $proxy_url;
238
40407aee 239 $proxy_url = "http://";
eea2670b 240
40407aee
PM
241 # Check if the proxy requires authentication.
242 if (($proxysettings{'UPSTREAM_USER'}) && ($proxysettings{'UPSTREAM_PASSWORD'})) {
243 $proxy_url .= "$proxysettings{'UPSTREAM_USER'}\:$proxysettings{'UPSTREAM_PASSWORD'}\@";
eea2670b
SS
244 }
245
40407aee
PM
246 # Add proxy server address and port.
247 $proxy_url .= $proxysettings{'UPSTREAM_PROXY'};
248
eea2670b 249 # Setup proxy settings.
6994f001 250 $downloader->proxy(['http', 'https'], $proxy_url);
eea2670b
SS
251 }
252
b3c2c336
SS
253 # Loop through the hash of configured providers.
254 foreach my $id ( keys %used_providers ) {
255 # Skip providers which are not enabled.
256 next if ($used_providers{$id}[3] ne "enabled");
eea2670b 257
b3c2c336
SS
258 # Obtain the provider handle.
259 my $provider_handle = $used_providers{$id}[0];
eea2670b 260
b3c2c336
SS
261 # Handle update off all providers.
262 if (($provider eq "all") || ($provider_handle eq "$provider")) {
263 # Add provider handle and it's id to the hash of sheduled providers.
2c02c936 264 $sheduled_providers{$provider_handle} = $id;
b3c2c336 265 }
eea2670b
SS
266 }
267
b3c2c336
SS
268 # Loop through the hash of sheduled providers.
269 foreach my $provider ( keys %sheduled_providers) {
270 # Grab the download url for the provider.
271 my $url = $IDS::Ruleset::Providers{$provider}{'dl_url'};
272
273 # Check if the provider requires a subscription.
274 if ($IDS::Ruleset::Providers{$provider}{'requires_subscription'} eq "True") {
275 # Grab the previously stored access id for the provider from hash.
276 my $id = $sheduled_providers{$provider};
277
278 # Grab the subscription code.
279 my $subscription_code = $used_providers{$id}[1];
280
281 # Add the subscription code to the download url.
282 $url =~ s/\<subscription_code\>/$subscription_code/g;
283
284 }
285
286 # Abort if no url could be determined for the provider.
287 unless ($url) {
288 # Log error and abort.
289 &_log_to_syslog("Unable to gather a download URL for the selected ruleset provider.");
290 return 1;
291 }
292
293 # Variable to store the filesize of the remote object.
294 my $remote_filesize;
295
296 # The sourcfire (snort rules) does not allow to send "HEAD" requests, so skip this check
297 # for this webserver.
298 #
299 # Check if the ruleset source contains "snort.org".
300 unless ($url =~ /\.snort\.org/) {
301 # Pass the requrested url to the downloader.
302 my $request = HTTP::Request->new(HEAD => $url);
303
304 # Accept the html header.
305 $request->header('Accept' => 'text/html');
306
307 # Perform the request and fetch the html header.
308 my $response = $downloader->request($request);
309
310 # Check if there was any error.
311 unless ($response->is_success) {
312 # Obtain error.
313 my $error = $response->status_line();
314
315 # Log error message.
316 &_log_to_syslog("Unable to download the ruleset. \($error\)");
317
318 # Return "1" - false.
319 return 1;
320 }
321
322 # Assign the fetched header object.
323 my $header = $response->headers();
324
325 # Grab the remote file size from the object and store it in the
326 # variable.
327 $remote_filesize = $header->content_length;
328 }
329
330 # Load perl module to deal with temporary files.
331 use File::Temp;
96da5803 332
b3c2c336
SS
333 # Generate temporary file name, located in "/var/tmp" and with a suffix of ".tmp".
334 my $tmp = File::Temp->new( SUFFIX => ".tmp", DIR => "/var/tmp/", UNLINK => 0 );
335 my $tmpfile = $tmp->filename();
96da5803 336
b3c2c336
SS
337 # Pass the requested url to the downloader.
338 my $request = HTTP::Request->new(GET => $url);
96da5803 339
b3c2c336
SS
340 # Perform the request and save the output into the tmpfile.
341 my $response = $downloader->request($request, $tmpfile);
96da5803 342
155b3b56
SS
343 # Check if there was any error.
344 unless ($response->is_success) {
345 # Obtain error.
b3c2c336 346 my $error = $response->content;
96da5803 347
155b3b56
SS
348 # Log error message.
349 &_log_to_syslog("Unable to download the ruleset. \($error\)");
350
351 # Return "1" - false.
352 return 1;
353 }
96da5803 354
b3c2c336
SS
355 # Load perl stat module.
356 use File::stat;
96da5803 357
b3c2c336
SS
358 # Perform stat on the tmpfile.
359 my $stat = stat($tmpfile);
96da5803 360
b3c2c336
SS
361 # Grab the local filesize of the downloaded tarball.
362 my $local_filesize = $stat->size;
25b6545a 363
b3c2c336
SS
364 # Check if both file sizes match.
365 if (($remote_filesize) && ($remote_filesize ne $local_filesize)) {
366 # Log error message.
367 &_log_to_syslog("Unable to completely download the ruleset. ");
368 &_log_to_syslog("Only got $local_filesize Bytes instead of $remote_filesize Bytes. ");
eea2670b 369
b3c2c336
SS
370 # Delete temporary file.
371 unlink("$tmpfile");
88daf7eb 372
b3c2c336
SS
373 # Return "1" - false.
374 return 1;
375 }
434001d0 376
b3c2c336
SS
377 # Genarate and assign file name and path to store the downloaded rules file.
378 my $dl_rulesfile = &_get_dl_rulesfile($provider);
eea2670b 379
b3c2c336
SS
380 # Check if a file name could be obtained.
381 unless ($dl_rulesfile) {
382 # Log error message.
383 &_log_to_syslog("Unable to store the downloaded rules file. ");
96da5803 384
b3c2c336
SS
385 # Delete downloaded temporary file.
386 unlink("$tmpfile");
96da5803 387
b3c2c336
SS
388 # Return "1" - false.
389 }
96da5803 390
b3c2c336
SS
391 # Load file copy module, which contains the move() function.
392 use File::Copy;
96da5803 393
b3c2c336
SS
394 # Overwrite the may existing rulefile or tarball with the downloaded one.
395 move("$tmpfile", "$dl_rulesfile");
25b6545a 396
ae226132
SS
397 # Delete temporary file.
398 unlink("$tmpfile");
399
b3c2c336
SS
400 # Set correct ownership for the tarball.
401 set_ownership("$dl_rulesfile");
96da5803
SS
402 }
403
eea2670b
SS
404 # If we got here, everything worked fine. Return nothing.
405 return;
406}
8dcebe53 407
0fbfffea
SS
408#
409## Function to extract a given ruleset.
410#
411sub extractruleset ($) {
412 my ($provider) = @_;
413
414 # Load perl module to deal with archives.
415 use Archive::Tar;
416
417 # Load perl module to deal with files and path.
418 use File::Basename;
419
420 # Get full path and downloaded rulesfile for the given provider.
421 my $tarball = &_get_dl_rulesfile($provider);
422
423 # Check if the file exists.
424 unless (-f $tarball) {
425 &_log_to_syslog("Could not extract ruleset file: $tarball");
426
427 # Return nothing.
428 return;
429 }
430
431 # Destination directories, where the files will be extracted.
432 my $rules_destdir = "$tmp_directory/rules";
433 my $conf_destdir = "$tmp_directory/conf";
434
435 # Check if the temporary directories exist, otherwise create them.
436 mkdir("$tmp_directory") unless (-d "$tmp_directory");
437 mkdir("$rules_destdir") unless (-d "$rules_destdir");
438 mkdir("$conf_destdir") unless (-d "$conf_destdir");
439
440 # Initialize the tar module.
441 my $tar = Archive::Tar->new($tarball);
442
443 # Get the filelist inside the tarball.
444 my @packed_files = $tar->list_files;
445
446 # Loop through the filelist.
447 foreach my $packed_file (@packed_files) {
448 my $destination;
449
450 # Splitt the packed file into chunks.
451 my $file = fileparse($packed_file);
452
453 # Handle msg-id.map file.
454 if ("$file" eq "sid-msg.map") {
455 # Set extract destination to temporary config_dir.
456 $destination = "$conf_destdir/$provider\-sid-msg.map";
457 # Handle classification.conf
458 } elsif ("$file" eq "classification.config") {
459 # Set extract destination to temporary config_dir.
460 $destination = "$conf_destdir/$provider\-classification.config";
461 # Handle rules files.
462 } elsif ($file =~ m/\.rules$/) {
463 my $rulesfilename;
464
465 # Splitt the filename into chunks.
466 my @filename = split("-", $file);
467
468 # Reverse the array.
469 @filename = reverse(@filename);
470
471 # Get the amount of elements in the array.
472 my $elements = @filename;
473
474 # Remove last element of the hash.
475 # It contains the vendor name, which will be replaced.
476 if ($elements >= 3) {
477 # Remove last element from hash.
478 pop(@filename);
479 }
480
481 # Check if the last element of the filename does not
482 # contain the providers name.
483 if (@filename[-1] ne "$provider") {
484 # Add provider name as last element.
485 push(@filename, $provider);
486 }
487
488 # Reverse the array back.
489 @filename = reverse(@filename);
490
491 # Generate the name for the rulesfile.
492 $rulesfilename = join("-", @filename);
493
494 # Set extract destination to temporaray rules_dir.
495 $destination = "$rules_destdir/$rulesfilename";
496 } else {
497 # Skip all other files.
498 next;
499 }
500
501 # Extract the file to the temporary directory.
502 $tar->extract_file("$packed_file", "$destination");
503 }
504}
505
25f5cb0d
SS
506#
507## A tiny wrapper function to call the oinkmaster script.
508#
509sub oinkmaster () {
330759d8
SS
510 # Check if the files in rulesdir have the correct permissions.
511 &_check_rulesdir_permissions();
512
883820bd
SS
513 # Cleanup the rules directory before filling it with the new rulest.
514 &_cleanup_rulesdir();
515
0e40e1e7
SS
516 # Load perl module to talk to the kernel syslog.
517 use Sys::Syslog qw(:DEFAULT setlogsock);
518
519 # Establish the connection to the syslog service.
520 openlog('oinkmaster', 'cons,pid', 'user');
521
25f5cb0d 522 # Call oinkmaster to generate ruleset.
26dc79a6 523 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";
0e40e1e7
SS
524
525 # Log output of oinkmaster to syslog.
526 while(<OINKMASTER>) {
527 # The syslog function works best with an array based input,
528 # so generate one before passing the message details to syslog.
529 my @syslog = ("INFO", "$_");
530
531 # Send the log message.
532 syslog(@syslog);
533 }
534
535 # Close the pipe to oinkmaster process.
536 close(OINKMASTER);
537
538 # Close the log handle.
539 closelog();
25f5cb0d
SS
540}
541
3983aebd
SS
542#
543## Function to do all the logging stuff if the downloading or updating of the ruleset fails.
544#
545sub log_error ($) {
546 my ($error) = @_;
547
548 # Remove any newline.
549 chomp($error);
550
eb5592c1
SS
551 # Call private function to log the error message to syslog.
552 &_log_to_syslog($error);
553
3983aebd
SS
554 # Call private function to write/store the error message in the storederrorfile.
555 &_store_error_message($error);
556}
557
eb5592c1
SS
558#
559## Function to log a given error message to the kernel syslog.
560#
561sub _log_to_syslog ($) {
562 my ($message) = @_;
563
564 # Load perl module to talk to the kernel syslog.
565 use Sys::Syslog qw(:DEFAULT setlogsock);
566
567 # The syslog function works best with an array based input,
568 # so generate one before passing the message details to syslog.
569 my @syslog = ("ERR", "<ERROR> $message");
570
571 # Establish the connection to the syslog service.
572 openlog('oinkmaster', 'cons,pid', 'user');
573
574 # Send the log message.
575 syslog(@syslog);
576
577 # Close the log handle.
578 closelog();
579}
580
3983aebd
SS
581#
582## Private function to write a given error message to the storederror file.
583#
584sub _store_error_message ($) {
585 my ($message) = @_;
586
587 # Remove any newline.
588 chomp($message);
589
590 # Open file for writing.
591 open (ERRORFILE, ">$storederrorfile") or die "Could not write to $storederrorfile. $!\n";
592
593 # Write error to file.
594 print ERRORFILE "$message\n";
595
596 # Close file.
597 close (ERRORFILE);
3c59b1fa
SS
598
599 # Set correct ownership for the file.
600 &set_ownership("$storederrorfile");
3983aebd
SS
601}
602
788a71f5
SS
603#
604## Private function to get the path and filename for a downloaded ruleset by a given provider.
605#
606sub _get_dl_rulesfile($) {
607 my ($provider) = @_;
608
609 # Gather the download type for the given provider.
610 my $dl_type = $IDS::Ruleset::Providers{$provider}{'dl_type'};
611
612 # Obtain the file suffix for the download file type.
613 my $suffix = $dl_type_to_suffix{$dl_type};
614
615 # Check if a suffix has been found.
616 unless ($suffix) {
617 # Abort return - nothing.
618 return;
619 }
620
621 # Generate the full filename and path for the stored rules file.
622 my $rulesfile = "$dl_rules_path/$dl_rulesfile_prefix-$provider$suffix";
623
624 # Return the generated filename.
625 return $rulesfile;
626}
627
796eea21
SS
628#
629## Function to check if the IDS is running.
630#
631sub ids_is_running () {
632 if(-f $idspidfile) {
633 # Open PID file for reading.
634 open(PIDFILE, "$idspidfile") or die "Could not open $idspidfile. $!\n";
635
636 # Grab the process-id.
637 my $pid = <PIDFILE>;
638
639 # Close filehandle.
640 close(PIDFILE);
641
642 # Remove any newline.
643 chomp($pid);
644
645 # Check if a directory for the process-id exists in proc.
646 if(-d "/proc/$pid") {
647 # The IDS daemon is running return the process id.
648 return $pid;
649 }
650 }
651
652 # Return nothing - IDS is not running.
653 return;
654}
655
5240a809
SS
656#
657## Function to call suricatactrl binary with a given command.
658#
659sub call_suricatactrl ($) {
660 # Get called option.
ed06bc81 661 my ($option, $interval) = @_;
5240a809
SS
662
663 # Loop through the array of supported commands and check if
664 # the given one is part of it.
665 foreach my $cmd (@suricatactrl_cmds) {
666 # Skip current command unless the given one has been found.
667 next unless($cmd eq $option);
668
ed06bc81
SS
669 # Check if the given command is "cron".
670 if ($option eq "cron") {
671 # Check if an interval has been given.
672 if ($interval) {
673 # Check if the given interval is valid.
674 foreach my $element (@cron_intervals) {
675 # Skip current element until the given one has been found.
676 next unless($element eq $interval);
677
678 # Call the suricatactrl binary and pass the "cron" command
679 # with the requrested interval.
81631920 680 &General::system("$suricatactrl", "$option", "$interval");
ed06bc81
SS
681
682 # Return "1" - True.
683 return 1;
684 }
685 }
5240a809 686
ed06bc81
SS
687 # If we got here, the given interval is not supported or none has been given. - Return nothing.
688 return;
689 } else {
690 # Call the suricatactrl binary and pass the requrested
691 # option to it.
81631920 692 &General::system("$suricatactrl", "$option");
ed06bc81
SS
693
694 # Return "1" - True.
695 return 1;
696 }
5240a809
SS
697 }
698
699 # Command not found - return nothing.
700 return;
701}
702
308ba5e7
SS
703#
704## Function to create a new empty file.
705#
706sub create_empty_file($) {
707 my ($file) = @_;
708
709 # Check if the given file exists.
710 if(-e $file) {
711 # Do nothing to prevent from overwriting existing files.
712 return;
713 }
714
715 # Open the file for writing.
716 open(FILE, ">$file") or die "Could not write to $file. $!\n";
717
718 # Close file handle.
719 close(FILE);
720
721 # Return true.
722 return 1;
723}
724
330759d8
SS
725#
726## Private function to check if the file permission of the rulespath are correct.
727## If not, call suricatactrl to fix them.
728#
729sub _check_rulesdir_permissions() {
e568796b
SS
730 # Check if the rulepath main directory is writable.
731 unless (-W $rulespath) {
732 # If not call suricatctrl to fix it.
733 &call_suricatactrl("fix-rules-dir");
734 }
735
330759d8
SS
736 # Open snort rules directory and do a directory listing.
737 opendir(DIR, $rulespath) or die $!;
738 # Loop through the direcory.
739 while (my $file = readdir(DIR)) {
740 # We only want files.
741 next unless (-f "$rulespath/$file");
742
743 # Check if the file is writable by the user.
744 if (-W "$rulespath/$file") {
745 # Everything is okay - go on to the next file.
746 next;
747 } else {
748 # There are wrong permissions, call suricatactrl to fix it.
749 &call_suricatactrl("fix-rules-dir");
750 }
751 }
752}
753
b59cdbee
SS
754#
755## Private function to cleanup the directory which contains
756## the IDS rules, before extracting and modifing the new ruleset.
757#
758sub _cleanup_rulesdir() {
8cf04a16
SS
759 # Open rules directory and do a directory listing.
760 opendir(DIR, $rulespath) or die $!;
761
762 # Loop through the direcory.
763 while (my $file = readdir(DIR)) {
764 # We only want files.
765 next unless (-f "$rulespath/$file");
766
767 # Skip element if it has config as file extension.
768 next if ($file =~ m/\.config$/);
b59cdbee 769
fefb5173
SS
770 # Skip rules file for whitelisted hosts.
771 next if ("$rulespath/$file" eq $whitelist_file);
772
612bb2df
SS
773 # Skip rules file with local rules.
774 next if ("$rulespath/$file" eq $local_rules_file);
775
8cf04a16 776 # Delete the current processed file, if not, exit this function
b59cdbee 777 # and return an error message.
1201c1e7 778 unlink("$rulespath/$file") or return "Could not delete $rulespath/$file. $!\n";
b59cdbee
SS
779 }
780
4ce42488 781 # Return nothing;
b59cdbee
SS
782 return;
783}
784
b02e30fd
SS
785#
786## Function to generate the file which contains the home net information.
787#
788sub generate_home_net_file() {
789 my %netsettings;
790
791 # Read-in network settings.
792 &General::readhash("${General::swroot}/ethernet/settings", \%netsettings);
793
794 # Get available network zones.
abffcc99 795 my @network_zones = &Network::get_available_network_zones();
b02e30fd
SS
796
797 # Temporary array to store network address and prefix of the configured
798 # networks.
799 my @networks;
800
801 # Loop through the array of available network zones.
802 foreach my $zone (@network_zones) {
bcbc9897
SS
803 # Check if the current processed zone is red.
804 if($zone eq "red") {
805 # Grab the IP-address of the red interface.
806 my $red_address = &get_red_address();
b02e30fd 807
bcbc9897
SS
808 # Check if an address has been obtained.
809 if ($red_address) {
810 # Generate full network string.
811 my $red_network = join("/", $red_address, "32");
b02e30fd 812
bcbc9897
SS
813 # Add the red network to the array of networks.
814 push(@networks, $red_network);
815 }
23c0347a 816
23c0347a
SS
817 # Check if the configured RED_TYPE is static.
818 if ($netsettings{'RED_TYPE'} eq "STATIC") {
819 # Get configured and enabled aliases.
820 my @aliases = &get_aliases();
821
822 # Loop through the array.
823 foreach my $alias (@aliases) {
824 # Add "/32" prefix.
825 my $network = join("/", $alias, "32");
826
827 # Add the generated network to the array of networks.
828 push(@networks, $network);
829 }
830 }
bcbc9897
SS
831 # Process remaining network zones.
832 } else {
833 # Convert current zone name into upper case.
834 $zone = uc($zone);
835
836 # Generate key to access the required data from the netsettings hash.
837 my $zone_netaddress = $zone . "_NETADDRESS";
838 my $zone_netmask = $zone . "_NETMASK";
839
840 # Obtain the settings from the netsettings hash.
841 my $netaddress = $netsettings{$zone_netaddress};
842 my $netmask = $netsettings{$zone_netmask};
843
844 # Convert the subnetmask into prefix notation.
845 my $prefix = &Network::convert_netmask2prefix($netmask);
846
847 # Generate full network string.
848 my $network = join("/", $netaddress,$prefix);
849
850 # Check if the network is valid.
851 if(&Network::check_subnet($network)) {
852 # Add the generated network to the array of networks.
853 push(@networks, $network);
854 }
23c0347a 855 }
b02e30fd
SS
856 }
857
858 # Format home net declaration.
7479c993 859 my $line = "\"[" . join(',', @networks) . "]\"";
b02e30fd
SS
860
861 # Open file to store the addresses of the home net.
862 open(FILE, ">$homenet_file") or die "Could not open $homenet_file. $!\n";
863
864 # Print yaml header.
865 print FILE "%YAML 1.1\n";
866 print FILE "---\n\n";
867
868 # Print notice about autogenerated file.
869 print FILE "#Autogenerated file. Any custom changes will be overwritten!\n";
870
871 # Print the generated and required HOME_NET declaration to the file.
872 print FILE "HOME_NET:\t$line\n";
873
874 # Close file handle.
875 close(FILE);
876}
877
30ee98e9
SS
878#
879# Function to generate and write the file which contains the configured and used DNS servers.
880#
881sub generate_dns_servers_file() {
12c49915
SS
882 # Get the used DNS servers.
883 my @nameservers = &General::get_nameservers();
30ee98e9 884
7b97359b
SS
885 # Get network settings.
886 my %netsettings;
887 &General::readhash("${General::swroot}/ethernet/settings", \%netsettings);
888
30ee98e9 889 # Format dns servers declaration.
b76118c3 890 my $line = "";
30ee98e9 891
12c49915
SS
892 # Check if the system has configured nameservers.
893 if (@nameservers) {
7b97359b
SS
894 # Add the GREEN address as DNS servers.
895 push(@nameservers, $netsettings{'GREEN_ADDRESS'});
896
897 # Check if a BLUE zone exists.
898 if ($netsettings{'BLUE_ADDRESS'}) {
899 # Add the BLUE address to the array of nameservers.
900 push(@nameservers, $netsettings{'BLUE_ADDRESS'});
901 }
902
903 # Generate the line which will be written to the DNS servers file.
b76118c3 904 $line = join(",", @nameservers);
12c49915 905 } else {
7b97359b 906 # External net simply contains (any).
99cadb74 907 $line = "\$EXTERNAL_NET";
fd2dccaa 908 }
30ee98e9 909
30ee98e9
SS
910 # Open file to store the used DNS server addresses.
911 open(FILE, ">$dns_servers_file") or die "Could not open $dns_servers_file. $!\n";
912
913 # Print yaml header.
914 print FILE "%YAML 1.1\n";
915 print FILE "---\n\n";
916
917 # Print notice about autogenerated file.
918 print FILE "#Autogenerated file. Any custom changes will be overwritten!\n";
919
920 # Print the generated DNS declaration to the file.
b76118c3 921 print FILE "DNS_SERVERS:\t\"[$line]\"\n";
30ee98e9
SS
922
923 # Close file handle.
924 close(FILE);
925}
926
e698090e
SS
927#
928# Function to generate and write the file which contains the HTTP_PORTS definition.
929#
930sub generate_http_ports_file() {
931 my %proxysettings;
932
933 # Read-in proxy settings
934 &General::readhash("${General::swroot}/proxy/advanced/settings", \%proxysettings);
935
936 # Check if the proxy is enabled.
937 if (( -e "${General::swroot}/proxy/enable") || (-e "${General::swroot}/proxy/enable_blue")) {
938 # Add the proxy port to the array of HTTP ports.
939 push(@http_ports, $proxysettings{'PROXY_PORT'});
940 }
941
942 # Check if the transparent mode of the proxy is enabled.
943 if ((-e "${General::swroot}/proxy/transparent") || (-e "${General::swroot}/proxy/transparent_blue")) {
944 # Add the transparent proxy port to the array of HTTP ports.
945 push(@http_ports, $proxysettings{'TRANSPARENT_PORT'});
946 }
947
948 # Format HTTP_PORTS declaration.
949 my $line = "";
950
951 # Generate line which will be written to the http ports file.
952 $line = join(",", @http_ports);
953
954 # Open file to store the HTTP_PORTS.
955 open(FILE, ">$http_ports_file") or die "Could not open $http_ports_file. $!\n";
956
957 # Print yaml header.
958 print FILE "%YAML 1.1\n";
959 print FILE "---\n\n";
960
961 # Print notice about autogenerated file.
962 print FILE "#Autogenerated file. Any custom changes will be overwritten!\n";
963
964 # Print the generated HTTP_PORTS declaration to the file.
965 print FILE "HTTP_PORTS:\t\"[$line]\"\n";
966
967 # Close file handle.
968 close(FILE);
969}
970
b02e30fd
SS
971#
972## Function to generate and write the file for used rulefiles.
973#
974sub write_used_rulefiles_file(@) {
975 my @files = @_;
976
977 # Open file for used rulefiles.
978 open (FILE, ">$used_rulefiles_file") or die "Could not write to $used_rulefiles_file. $!\n";
979
980 # Write yaml header to the file.
981 print FILE "%YAML 1.1\n";
982 print FILE "---\n\n";
983
984 # Write header to file.
985 print FILE "#Autogenerated file. Any custom changes will be overwritten!\n";
986
987 # Allways use the whitelist.
988 print FILE " - whitelist.rules\n";
989
990 # Loop through the array of given files.
991 foreach my $file (@files) {
992 # Check if the given filename exists and write it to the file of used rulefiles.
993 if(-f "$rulespath/$file") {
994 print FILE " - $file\n";
995 }
996 }
997
998 # Close file after writing.
999 close(FILE);
1000}
1001
74cc8f5a
SS
1002#
1003## Function to generate and write the file for modify the ruleset.
1004#
81bae51f
SS
1005sub write_modify_sids_file() {
1006 # Get configured settings.
1007 my %idssettings=();
1008 my %rulessettings=();
1009 &General::readhash("$ids_settings_file", \%idssettings);
1010 &General::readhash("$rules_settings_file", \%rulessettings);
1011
1012 # Gather the configured ruleset.
1013 my $ruleset = $rulessettings{'RULES'};
74cc8f5a
SS
1014
1015 # Open modify sid's file for writing.
2ee51088 1016 open(FILE, ">$modify_sids_file") or die "Could not write to $modify_sids_file. $!\n";
74cc8f5a
SS
1017
1018 # Write file header.
1019 print FILE "#Autogenerated file. Any custom changes will be overwritten!\n";
1020
1021 # Check if the traffic only should be monitored.
81bae51f 1022 unless($idssettings{'MONITOR_TRAFFIC_ONLY'} eq 'on') {
a5ba473c
TF
1023 # Suricata is in IPS mode, which means that the rule actions have to be changed
1024 # from 'alert' to 'drop', however not all rules should be changed. Some rules
1025 # exist purely to set a flowbit which is used to convey other information, such
1026 # as a specific type of file being downloaded, to other rulewhich then check for
1027 # malware in that file. Rules which fall into the first category should stay as
1028 # alert since not all flows of that type contain malware.
1029
81bae51f 1030 if($ruleset eq 'registered' or $ruleset eq 'subscripted' or $ruleset eq 'community') {
a5ba473c
TF
1031 # These types of rulesfiles contain meta-data which gives the action that should
1032 # be used when in IPS mode. Do the following:
1033 #
1034 # 1. Disable all rules and set the action to 'drop'
1035 # 2. Set the action back to 'alert' if the rule contains 'flowbits:noalert;'
1036 # This should give rules not in the policy a reasonable default if the user
1037 # manually enables them.
1038 # 3. Enable rules and set actions according to the meta-data strings.
1039
1040 my $policy = 'balanced'; # Placeholder to allow policy to be changed.
1041
1042 print FILE <<END;
1043modifysid * "^#?(?:alert|drop)" | "#drop"
1044modifysid * "^#drop(.+flowbits:noalert;)" | "#alert\${1}"
1045modifysid * "^#(?:alert|drop)(.+policy $policy-ips alert)" | "alert\${1}"
1046modifysid * "^#(?:alert|drop)(.+policy $policy-ips drop)" | "drop\${1}"
1047END
1048 } else {
1049 # These rulefiles don't have the metadata, so set rules to 'drop' unless they
1050 # contain the string 'flowbits:noalert;'.
1051 print FILE <<END;
1052modifysid * "^(#?)(?:alert|drop)" | "\${1}drop"
1053modifysid * "^(#?)drop(.+flowbits:noalert;)" | "\${1}alert\${2}"
1054END
1055 }
74cc8f5a
SS
1056 }
1057
1058 # Close file handle.
1059 close(FILE);
1060}
1061
04a0d07c
SS
1062#
1063## Function to gather the version of suricata.
1064#
1065sub get_suricata_version($) {
1066 my ($format) = @_;
1067
1068 # Execute piped suricata command and return the version information.
1069 open(SURICATA, "suricata -V |") or die "Couldn't execute program: $!";
1070
1071 # Grab and store the output of the piped program.
1072 my $version_string = <SURICATA>;
1073
1074 # Close pipe.
1075 close(SURICATA);
1076
1077 # Remove newlines.
1078 chomp($version_string);
1079
fd2dccaa 1080 # Grab the version from the version string.
04a0d07c
SS
1081 $version_string =~ /([0-9]+([.][0-9]+)+)/;
1082
1083 # Splitt the version into single chunks.
1084 my ($major_ver, $minor_ver, $patchlevel) = split(/\./, $1);
1085
1086 # Check and return the requested version sheme.
1087 if ($format eq "major") {
1088 # Return the full version.
1089 return "$major_ver";
1090 } elsif ($format eq "minor") {
1091 # Return the major and minor part.
1092 return "$major_ver.$minor_ver";
1093 } else {
1094 # Return the full version string.
1095 return "$major_ver.$minor_ver.$patchlevel";
fd2dccaa 1096 }
04a0d07c
SS
1097}
1098
9283e9b9
SS
1099#
1100## Function to generate the rules file with whitelisted addresses.
1101#
1102sub generate_ignore_file() {
1103 my %ignored = ();
1104
1105 # SID range 1000000-1999999 Reserved for Local Use
1106 # Put your custom rules in this range to avoid conflicts
1107 my $sid = 1500000;
1108
1109 # Read-in ignoredfile.
1110 &General::readhasharray($IDS::ignored_file, \%ignored);
1111
1112 # Open ignorefile for writing.
1113 open(FILE, ">$IDS::whitelist_file") or die "Could not write to $IDS::whitelist_file. $!\n";
1114
1115 # Config file header.
1116 print FILE "# Autogenerated file.\n";
1117 print FILE "# All user modifications will be overwritten.\n\n";
1118
1119 # Add all user defined addresses to the whitelist.
1120 #
1121 # Check if the hash contains any elements.
1122 if (keys (%ignored)) {
1123 # Loop through the entire hash and write the host/network
1124 # and remark to the ignore file.
1125 while ( (my $key) = each %ignored) {
1126 my $address = $ignored{$key}[0];
1127 my $remark = $ignored{$key}[1];
1128 my $status = $ignored{$key}[2];
1129
1130 # Check if the status of the entry is "enabled".
1131 if ($status eq "enabled") {
1132 # Check if the address/network is valid.
1133 if ((&General::validip($address)) || (&General::validipandmask($address))) {
1134 # Write rule line to the file to pass any traffic from this IP
1135 print FILE "pass ip $address any -> any any (msg:\"pass all traffic from/to $address\"\; sid:$sid\;)\n";
1136
1137 # Increment sid.
1138 $sid++;
1139 }
1140 }
1141 }
1142 }
1143
1144 close(FILE);
1145}
1146
1fedede6
SS
1147#
1148## Function to set correct ownership for single files and directories.
1149#
1150
1151sub set_ownership($) {
1152 my ($target) = @_;
1153
1154 # User and group of the WUI.
1155 my $uname = "nobody";
1156 my $grname = "nobody";
1157
1158 # The chown function implemented in perl requies the user and group as nummeric id's.
1159 my $uid = getpwnam($uname);
1160 my $gid = getgrnam($grname);
1161
1162 # Check if the given target exists.
1163 unless ($target) {
1164 # Stop the script and print error message.
1165 die "The $target does not exist. Cannot change the ownership!\n";
1166 }
1167
1168 # Check weather the target is a file or directory.
1169 if (-f $target) {
1170 # Change ownership ot the single file.
1171 chown($uid, $gid, "$target");
1172 } elsif (-d $target) {
1173 # Do a directory listing.
1174 opendir(DIR, $target) or die $!;
1175 # Loop through the direcory.
1176 while (my $file = readdir(DIR)) {
1177
1178 # We only want files.
1179 next unless (-f "$target/$file");
1180
1181 # Set correct ownership for the files.
1182 chown($uid, $gid, "$target/$file");
1183 }
1184
1185 closedir(DIR);
1186
1187 # Change ownership of the directory.
1188 chown($uid, $gid, "$target");
1189 }
1190}
77c31301
SS
1191
1192#
1193## Function to read-in the aliases file and returns all configured and enabled aliases.
1194#
1195sub get_aliases() {
1196 # Location of the aliases file.
1197 my $aliases_file = "${General::swroot}/ethernet/aliases";
1198
1199 # Array to store the aliases.
1200 my @aliases;
1201
1202 # Check if the file is empty.
1203 if (-z $aliases_file) {
1204 # Abort nothing to do.
1205 return;
1206 }
1207
1208 # Open the aliases file.
1209 open(ALIASES, $aliases_file) or die "Could not open $aliases_file. $!\n";
1210
1211 # Loop through the file content.
1212 while (my $line = <ALIASES>) {
1213 # Remove newlines.
1214 chomp($line);
1215
1216 # Splitt line content into single chunks.
1217 my ($address, $state, $remark) = split(/\,/, $line);
1218
1219 # Check if the state of the current processed alias is "on".
1220 if ($state eq "on") {
1221 # Check if the address is valid.
1222 if(&Network::check_ip_address($address)) {
1223 # Add the alias to the array of aliases.
1224 push(@aliases, $address);
1225 }
1226 }
1227 }
1228
1229 # Close file handle.
1230 close(ALIASES);
1231
1232 # Return the array.
1233 return @aliases;
1234}
1235
de8e1e5b
SS
1236#
1237## Function to grab the current assigned IP-address on red.
1238#
1239sub get_red_address() {
1240 # File, which contains the current IP-address of the red interface.
1241 my $file = "${General::swroot}/red/local-ipaddress";
1242
1243 # Check if the file exists.
1244 if (-e $file) {
1245 # Open the given file.
1246 open(FILE, "$file") or die "Could not open $file.";
1247
1248 # Obtain the address from the first line of the file.
1249 my $address = <FILE>;
1250
1251 # Close filehandle
1252 close(FILE);
1253
1254 # Remove newlines.
1255 chomp $address;
1256
1257 # Check if the grabbed address is valid.
1258 if (&General::validip($address)) {
1259 # Return the address.
1260 return $address;
1261 }
1262 }
1263
1264 # Return nothing.
1265 return;
1266}
77c31301 1267
8076deba
SS
1268#
1269## Function to write the lock file for locking the WUI, while
1270## the autoupdate script runs.
1271#
1272sub lock_ids_page() {
1273 # Call subfunction to create the file.
1274 &create_empty_file($ids_page_lock_file);
1275}
1276
1277#
1278## Function to release the lock of the WUI, again.
1279#
1280sub unlock_ids_page() {
1281 # Delete lock file.
1282 unlink($ids_page_lock_file);
1283}
1284
8dcebe53 12851;