]> git.ipfire.org Git - people/pmueller/ipfire-2.x.git/blame - config/cfgroot/ids-functions.pl
logwatch: Update to 7.5.2
[people/pmueller/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
b02e30fd
SS
31# File where the used rulefiles are stored.
32our $used_rulefiles_file = "$settingsdir/suricata-used-rulefiles.yaml";
33
34# File where the addresses of the homenet are stored.
35our $homenet_file = "$settingsdir/suricata-homenet.yaml";
36
37# File which contains the enabled sids.
38our $enabled_sids_file = "$settingsdir/oinkmaster-enabled-sids.conf";
39
40# File which contains the disabled sids.
41our $disabled_sids_file = "$settingsdir/oinkmaster-disabled-sids.conf";
42
43# File which contains wheater the rules should be changed.
44our $modify_sids_file = "$settingsdir/oinkmaster-modify-sids.conf";
45
46# File which stores the configured IPS settings.
47our $ids_settings_file = "$settingsdir/settings";
48
49# File which stores the configured rules-settings.
50our $rules_settings_file = "$settingsdir/rules-settings";
51
52# File which stores the configured settings for whitelisted addresses.
53our $ignored_file = "$settingsdir/ignored";
54
eea2670b 55# Location and name of the tarball which contains the ruleset.
164eab66 56our $rulestarball = "/var/tmp/idsrules.tar.gz";
eea2670b 57
3983aebd 58# File to store any errors, which also will be read and displayed by the wui.
77910792 59our $storederrorfile = "/tmp/ids_storederror";
3983aebd 60
8076deba
SS
61# File to lock the WUI, while the autoupdate script runs.
62our $ids_page_lock_file = "/tmp/ids_page_locked";
63
298ef5ba 64# Location where the rulefiles are stored.
21cab141 65our $rulespath = "/var/lib/suricata";
298ef5ba 66
b02e30fd
SS
67# File which contains the rules to whitelist addresses on suricata.
68our $whitelist_file = "$rulespath/whitelist.rules";
69
bce84f39
SS
70# File which contains a list of all supported ruleset sources.
71# (Sourcefire, Emergingthreads, etc..)
72our $rulesetsourcesfile = "$settingsdir/ruleset-sources";
73
796eea21
SS
74# The pidfile of the IDS.
75our $idspidfile = "/var/run/suricata.pid";
76
5240a809
SS
77# Location of suricatactrl.
78my $suricatactrl = "/usr/local/bin/suricatactrl";
79
80# Array with allowed commands of suricatactrl.
ed06bc81
SS
81my @suricatactrl_cmds = ( 'start', 'stop', 'restart', 'reload', 'fix-rules-dir', 'cron' );
82
83# Array with supported cron intervals.
84my @cron_intervals = ('off', 'daily', 'weekly' );
5240a809 85
b02e30fd
SS
86#
87## Function to check and create all IDS related files, if the does not exist.
88#
89sub check_and_create_filelayout() {
90 # Check if the files exist and if not, create them.
91 unless (-f "$enabled_sids_file") { &create_empty_file($enabled_sids_file); }
92 unless (-f "$disabled_sids_file") { &create_empty_file($disabled_sids_file); }
93 unless (-f "$modify_sids_file") { &create_empty_file($modify_sids_file); }
94 unless (-f "$used_rulefiles_file") { &create_empty_file($used_rulefiles_file); }
95 unless (-f "$ids_settings_file") { &create_empty_file($ids_settings_file); }
96 unless (-f "$rules_settings_file") { &create_empty_file($rules_settings_file); }
97 unless (-f "$ignored_file") { &create_empty_file($ignored_file); }
98 unless (-f "$whitelist_file" ) { &create_empty_file($whitelist_file); }
99}
100
8dcebe53
SS
101#
102## Function for checking if at least 300MB of free disk space are available
103## on the "/var" partition.
104#
105sub checkdiskspace () {
106 # Call diskfree to gather the free disk space of /var.
107 my @df = `/bin/df -B M /var`;
108
109 # Loop through the output.
110 foreach my $line (@df) {
111 # Ignore header line.
112 next if $line =~ m/^Filesystem/;
113
114 # Search for a line with the device information.
115 if ($line =~ m/dev/ ) {
116 # Split the line into single pieces.
117 my @values = split(' ', $line);
118 my ($filesystem, $blocks, $used, $available, $used_perenctage, $mounted_on) = @values;
119
120 # Check if the available disk space is more than 300MB.
121 if ($available < 300) {
434001d0
SS
122 # Log error to syslog.
123 &_log_to_syslog("Not enough free disk space on /var. Only $available MB from 300 MB available.");
8dcebe53 124
434001d0
SS
125 # Exit function and return "1" - False.
126 return 1;
8dcebe53
SS
127 }
128 }
129 }
130
131 # Everything okay, return nothing.
132 return;
133}
134
eea2670b 135#
b749416a 136## This function is responsible for downloading the configured IDS ruleset.
eea2670b 137##
b749416a 138## * At first it obtains from the stored rules settings which ruleset should be downloaded.
eea2670b
SS
139## * The next step is to get the download locations for all available rulesets.
140## * After that, the function will check if an upstream proxy should be used and grab the settings.
141## * The last step will be to generate the final download url, by obtaining the URL for the desired
142## ruleset, add the settings for the upstream proxy and final grab the rules tarball from the server.
143#
144sub downloadruleset {
b749416a
SS
145 # Get rules settings.
146 my %rulessettings=();
147 &General::readhash("$rules_settings_file", \%rulessettings);
eea2670b 148
be52c68a 149 # Check if a ruleset has been configured.
b749416a 150 unless($rulessettings{'RULES'}) {
be52c68a
SS
151 # Log that no ruleset has been configured and abort.
152 &_log_to_syslog("No ruleset source has been configured.");
153
154 # Return "1".
155 return 1;
156 }
157
eea2670b
SS
158 # Get all available ruleset locations.
159 my %rulesetsources=();
bce84f39 160 &General::readhash($rulesetsourcesfile, \%rulesetsources);
eea2670b
SS
161
162 # Read proxysettings.
163 my %proxysettings=();
164 &General::readhash("${General::swroot}/proxy/settings", \%proxysettings);
165
166 # Load required perl module to handle the download.
167 use LWP::UserAgent;
168
169 # Init the download module.
170 my $downloader = LWP::UserAgent->new;
171
172 # Set timeout to 10 seconds.
173 $downloader->timeout(10);
174
175 # Check if an upstream proxy is configured.
176 if ($proxysettings{'UPSTREAM_PROXY'}) {
eea2670b
SS
177 my $proxy_url;
178
40407aee 179 $proxy_url = "http://";
eea2670b 180
40407aee
PM
181 # Check if the proxy requires authentication.
182 if (($proxysettings{'UPSTREAM_USER'}) && ($proxysettings{'UPSTREAM_PASSWORD'})) {
183 $proxy_url .= "$proxysettings{'UPSTREAM_USER'}\:$proxysettings{'UPSTREAM_PASSWORD'}\@";
eea2670b
SS
184 }
185
40407aee
PM
186 # Add proxy server address and port.
187 $proxy_url .= $proxysettings{'UPSTREAM_PROXY'};
188
eea2670b 189 # Setup proxy settings.
6994f001 190 $downloader->proxy(['http', 'https'], $proxy_url);
eea2670b
SS
191 }
192
193 # Grab the right url based on the configured vendor.
b749416a 194 my $url = $rulesetsources{$rulessettings{'RULES'}};
eea2670b
SS
195
196 # Check if the vendor requires an oinkcode and add it if needed.
b749416a 197 $url =~ s/\<oinkcode\>/$rulessettings{'OINKCODE'}/g;
eea2670b
SS
198
199 # Abort if no url could be determined for the vendor.
200 unless ($url) {
434001d0
SS
201 # Log error and abort.
202 &_log_to_syslog("Unable to gather a download URL for the selected ruleset.");
203 return 1;
eea2670b
SS
204 }
205
155b3b56
SS
206 # Variable to store the filesize of the remote object.
207 my $remote_filesize;
96da5803 208
155b3b56
SS
209 # The sourcfire (snort rules) does not allow to send "HEAD" requests, so skip this check
210 # for this webserver.
211 #
212 # Check if the ruleset source contains "snort.org".
213 unless ($url =~ /\.snort\.org/) {
214 # Pass the requrested url to the downloader.
215 my $request = HTTP::Request->new(HEAD => $url);
96da5803 216
155b3b56
SS
217 # Accept the html header.
218 $request->header('Accept' => 'text/html');
96da5803 219
155b3b56
SS
220 # Perform the request and fetch the html header.
221 my $response = $downloader->request($request);
96da5803 222
155b3b56
SS
223 # Check if there was any error.
224 unless ($response->is_success) {
225 # Obtain error.
226 my $error = $response->status_line();
96da5803 227
155b3b56
SS
228 # Log error message.
229 &_log_to_syslog("Unable to download the ruleset. \($error\)");
230
231 # Return "1" - false.
232 return 1;
233 }
96da5803 234
155b3b56
SS
235 # Assign the fetched header object.
236 my $header = $response->headers();
96da5803 237
155b3b56
SS
238 # Grab the remote file size from the object and store it in the
239 # variable.
240 $remote_filesize = $header->content_length;
241 }
96da5803 242
25b6545a
SS
243 # Load perl module to deal with temporary files.
244 use File::Temp;
245
a5ba473c 246 # Generate temporary file name, located in "/var/tmp" and with a suffix of ".tar.gz".
25b6545a
SS
247 my $tmp = File::Temp->new( SUFFIX => ".tar.gz", DIR => "/var/tmp/", UNLINK => 0 );
248 my $tmpfile = $tmp->filename();
249
eea2670b
SS
250 # Pass the requested url to the downloader.
251 my $request = HTTP::Request->new(GET => $url);
252
25b6545a
SS
253 # Perform the request and save the output into the tmpfile.
254 my $response = $downloader->request($request, $tmpfile);
eea2670b
SS
255
256 # Check if there was any error.
257 unless ($response->is_success) {
88daf7eb
SS
258 # Obtain error.
259 my $error = $response->content;
260
434001d0 261 # Log error message.
88daf7eb 262 &_log_to_syslog("Unable to download the ruleset. \($error\)");
434001d0
SS
263
264 # Return "1" - false.
265 return 1;
eea2670b
SS
266 }
267
96da5803
SS
268 # Load perl stat module.
269 use File::stat;
270
25b6545a
SS
271 # Perform stat on the tmpfile.
272 my $stat = stat($tmpfile);
96da5803
SS
273
274 # Grab the local filesize of the downloaded tarball.
275 my $local_filesize = $stat->size;
276
277 # Check if both file sizes match.
155b3b56 278 if (($remote_filesize) && ($remote_filesize ne $local_filesize)) {
96da5803
SS
279 # Log error message.
280 &_log_to_syslog("Unable to completely download the ruleset. ");
281 &_log_to_syslog("Only got $local_filesize Bytes instead of $remote_filesize Bytes. ");
282
25b6545a
SS
283 # Delete temporary file.
284 unlink("$tmpfile");
285
96da5803
SS
286 # Return "1" - false.
287 return 1;
288 }
289
25b6545a
SS
290 # Load file copy module, which contains the move() function.
291 use File::Copy;
292
293 # Overwrite existing rules tarball with the new downloaded one.
294 move("$tmpfile", "$rulestarball");
295
a5ba473c
TF
296 # Set correct ownership for the rulesdir and files.
297 set_ownership("$rulestarball");
298
eea2670b
SS
299 # If we got here, everything worked fine. Return nothing.
300 return;
301}
8dcebe53 302
25f5cb0d
SS
303#
304## A tiny wrapper function to call the oinkmaster script.
305#
306sub oinkmaster () {
330759d8
SS
307 # Check if the files in rulesdir have the correct permissions.
308 &_check_rulesdir_permissions();
309
883820bd
SS
310 # Cleanup the rules directory before filling it with the new rulest.
311 &_cleanup_rulesdir();
312
0e40e1e7
SS
313 # Load perl module to talk to the kernel syslog.
314 use Sys::Syslog qw(:DEFAULT setlogsock);
315
316 # Establish the connection to the syslog service.
317 openlog('oinkmaster', 'cons,pid', 'user');
318
25f5cb0d 319 # Call oinkmaster to generate ruleset.
26dc79a6 320 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
321
322 # Log output of oinkmaster to syslog.
323 while(<OINKMASTER>) {
324 # The syslog function works best with an array based input,
325 # so generate one before passing the message details to syslog.
326 my @syslog = ("INFO", "$_");
327
328 # Send the log message.
329 syslog(@syslog);
330 }
331
332 # Close the pipe to oinkmaster process.
333 close(OINKMASTER);
334
335 # Close the log handle.
336 closelog();
25f5cb0d
SS
337}
338
3983aebd
SS
339#
340## Function to do all the logging stuff if the downloading or updating of the ruleset fails.
341#
342sub log_error ($) {
343 my ($error) = @_;
344
345 # Remove any newline.
346 chomp($error);
347
eb5592c1
SS
348 # Call private function to log the error message to syslog.
349 &_log_to_syslog($error);
350
3983aebd
SS
351 # Call private function to write/store the error message in the storederrorfile.
352 &_store_error_message($error);
353}
354
eb5592c1
SS
355#
356## Function to log a given error message to the kernel syslog.
357#
358sub _log_to_syslog ($) {
359 my ($message) = @_;
360
361 # Load perl module to talk to the kernel syslog.
362 use Sys::Syslog qw(:DEFAULT setlogsock);
363
364 # The syslog function works best with an array based input,
365 # so generate one before passing the message details to syslog.
366 my @syslog = ("ERR", "<ERROR> $message");
367
368 # Establish the connection to the syslog service.
369 openlog('oinkmaster', 'cons,pid', 'user');
370
371 # Send the log message.
372 syslog(@syslog);
373
374 # Close the log handle.
375 closelog();
376}
377
3983aebd
SS
378#
379## Private function to write a given error message to the storederror file.
380#
381sub _store_error_message ($) {
382 my ($message) = @_;
383
384 # Remove any newline.
385 chomp($message);
386
387 # Open file for writing.
388 open (ERRORFILE, ">$storederrorfile") or die "Could not write to $storederrorfile. $!\n";
389
390 # Write error to file.
391 print ERRORFILE "$message\n";
392
393 # Close file.
394 close (ERRORFILE);
3c59b1fa
SS
395
396 # Set correct ownership for the file.
397 &set_ownership("$storederrorfile");
3983aebd
SS
398}
399
1cae702c
SS
400#
401## Function to get a list of all available network zones.
402#
403sub get_available_network_zones () {
404 # Get netsettings.
405 my %netsettings = ();
406 &General::readhash("${General::swroot}/ethernet/settings", \%netsettings);
407
408 # Obtain the configuration type from the netsettings hash.
409 my $config_type = $netsettings{'CONFIG_TYPE'};
410
411 # Hash which contains the conversation from the config mode
412 # to the existing network interface names. They are stored like
413 # an array.
414 #
415 # Mode "0" red is a modem and green
416 # Mode "1" red is a netdev and green
417 # Mode "2" red, green and orange
418 # Mode "3" red, green and blue
419 # Mode "4" red, green, blue, orange
420 my %config_type_to_interfaces = (
421 "0" => [ "red", "green" ],
422 "1" => [ "red", "green" ],
423 "2" => [ "red", "green", "orange" ],
424 "3" => [ "red", "green", "blue" ],
425 "4" => [ "red", "green", "blue", "orange" ]
426 );
427
428 # Obtain and dereference the corresponding network interaces based on the read
429 # network config type.
430 my @network_zones = @{ $config_type_to_interfaces{$config_type} };
431
432 # Return them.
433 return @network_zones;
434}
435
796eea21
SS
436#
437## Function to check if the IDS is running.
438#
439sub ids_is_running () {
440 if(-f $idspidfile) {
441 # Open PID file for reading.
442 open(PIDFILE, "$idspidfile") or die "Could not open $idspidfile. $!\n";
443
444 # Grab the process-id.
445 my $pid = <PIDFILE>;
446
447 # Close filehandle.
448 close(PIDFILE);
449
450 # Remove any newline.
451 chomp($pid);
452
453 # Check if a directory for the process-id exists in proc.
454 if(-d "/proc/$pid") {
455 # The IDS daemon is running return the process id.
456 return $pid;
457 }
458 }
459
460 # Return nothing - IDS is not running.
461 return;
462}
463
5240a809
SS
464#
465## Function to call suricatactrl binary with a given command.
466#
467sub call_suricatactrl ($) {
468 # Get called option.
ed06bc81 469 my ($option, $interval) = @_;
5240a809
SS
470
471 # Loop through the array of supported commands and check if
472 # the given one is part of it.
473 foreach my $cmd (@suricatactrl_cmds) {
474 # Skip current command unless the given one has been found.
475 next unless($cmd eq $option);
476
ed06bc81
SS
477 # Check if the given command is "cron".
478 if ($option eq "cron") {
479 # Check if an interval has been given.
480 if ($interval) {
481 # Check if the given interval is valid.
482 foreach my $element (@cron_intervals) {
483 # Skip current element until the given one has been found.
484 next unless($element eq $interval);
485
486 # Call the suricatactrl binary and pass the "cron" command
487 # with the requrested interval.
488 system("$suricatactrl $option $interval &>/dev/null");
489
490 # Return "1" - True.
491 return 1;
492 }
493 }
5240a809 494
ed06bc81
SS
495 # If we got here, the given interval is not supported or none has been given. - Return nothing.
496 return;
497 } else {
498 # Call the suricatactrl binary and pass the requrested
499 # option to it.
500 system("$suricatactrl $option &>/dev/null");
501
502 # Return "1" - True.
503 return 1;
504 }
5240a809
SS
505 }
506
507 # Command not found - return nothing.
508 return;
509}
510
308ba5e7
SS
511#
512## Function to create a new empty file.
513#
514sub create_empty_file($) {
515 my ($file) = @_;
516
517 # Check if the given file exists.
518 if(-e $file) {
519 # Do nothing to prevent from overwriting existing files.
520 return;
521 }
522
523 # Open the file for writing.
524 open(FILE, ">$file") or die "Could not write to $file. $!\n";
525
526 # Close file handle.
527 close(FILE);
528
529 # Return true.
530 return 1;
531}
532
330759d8
SS
533#
534## Private function to check if the file permission of the rulespath are correct.
535## If not, call suricatactrl to fix them.
536#
537sub _check_rulesdir_permissions() {
e568796b
SS
538 # Check if the rulepath main directory is writable.
539 unless (-W $rulespath) {
540 # If not call suricatctrl to fix it.
541 &call_suricatactrl("fix-rules-dir");
542 }
543
330759d8
SS
544 # Open snort rules directory and do a directory listing.
545 opendir(DIR, $rulespath) or die $!;
546 # Loop through the direcory.
547 while (my $file = readdir(DIR)) {
548 # We only want files.
549 next unless (-f "$rulespath/$file");
550
551 # Check if the file is writable by the user.
552 if (-W "$rulespath/$file") {
553 # Everything is okay - go on to the next file.
554 next;
555 } else {
556 # There are wrong permissions, call suricatactrl to fix it.
557 &call_suricatactrl("fix-rules-dir");
558 }
559 }
560}
561
b59cdbee
SS
562#
563## Private function to cleanup the directory which contains
564## the IDS rules, before extracting and modifing the new ruleset.
565#
566sub _cleanup_rulesdir() {
8cf04a16
SS
567 # Open rules directory and do a directory listing.
568 opendir(DIR, $rulespath) or die $!;
569
570 # Loop through the direcory.
571 while (my $file = readdir(DIR)) {
572 # We only want files.
573 next unless (-f "$rulespath/$file");
574
575 # Skip element if it has config as file extension.
576 next if ($file =~ m/\.config$/);
b59cdbee 577
fefb5173
SS
578 # Skip rules file for whitelisted hosts.
579 next if ("$rulespath/$file" eq $whitelist_file);
580
8cf04a16 581 # Delete the current processed file, if not, exit this function
b59cdbee 582 # and return an error message.
1201c1e7 583 unlink("$rulespath/$file") or return "Could not delete $rulespath/$file. $!\n";
b59cdbee
SS
584 }
585
4ce42488 586 # Return nothing;
b59cdbee
SS
587 return;
588}
589
b02e30fd
SS
590#
591## Function to generate the file which contains the home net information.
592#
593sub generate_home_net_file() {
594 my %netsettings;
595
596 # Read-in network settings.
597 &General::readhash("${General::swroot}/ethernet/settings", \%netsettings);
598
599 # Get available network zones.
600 my @network_zones = &get_available_network_zones();
601
602 # Temporary array to store network address and prefix of the configured
603 # networks.
604 my @networks;
605
606 # Loop through the array of available network zones.
607 foreach my $zone (@network_zones) {
bcbc9897
SS
608 # Check if the current processed zone is red.
609 if($zone eq "red") {
610 # Grab the IP-address of the red interface.
611 my $red_address = &get_red_address();
b02e30fd 612
bcbc9897
SS
613 # Check if an address has been obtained.
614 if ($red_address) {
615 # Generate full network string.
616 my $red_network = join("/", $red_address, "32");
b02e30fd 617
bcbc9897
SS
618 # Add the red network to the array of networks.
619 push(@networks, $red_network);
620 }
23c0347a 621
23c0347a
SS
622 # Check if the configured RED_TYPE is static.
623 if ($netsettings{'RED_TYPE'} eq "STATIC") {
624 # Get configured and enabled aliases.
625 my @aliases = &get_aliases();
626
627 # Loop through the array.
628 foreach my $alias (@aliases) {
629 # Add "/32" prefix.
630 my $network = join("/", $alias, "32");
631
632 # Add the generated network to the array of networks.
633 push(@networks, $network);
634 }
635 }
bcbc9897
SS
636 # Process remaining network zones.
637 } else {
638 # Convert current zone name into upper case.
639 $zone = uc($zone);
640
641 # Generate key to access the required data from the netsettings hash.
642 my $zone_netaddress = $zone . "_NETADDRESS";
643 my $zone_netmask = $zone . "_NETMASK";
644
645 # Obtain the settings from the netsettings hash.
646 my $netaddress = $netsettings{$zone_netaddress};
647 my $netmask = $netsettings{$zone_netmask};
648
649 # Convert the subnetmask into prefix notation.
650 my $prefix = &Network::convert_netmask2prefix($netmask);
651
652 # Generate full network string.
653 my $network = join("/", $netaddress,$prefix);
654
655 # Check if the network is valid.
656 if(&Network::check_subnet($network)) {
657 # Add the generated network to the array of networks.
658 push(@networks, $network);
659 }
23c0347a 660 }
b02e30fd
SS
661 }
662
663 # Format home net declaration.
664 my $line = "\"\[";
665
666 # Loop through the array of networks.
667 foreach my $network (@networks) {
668 # Add the network to the line.
669 $line = "$line" . "$network";
670
671 # Check if the current network was the last in the array.
672 if ($network eq $networks[-1]) {
673 # Close the line.
674 $line = "$line" . "\]\"";
675 } else {
676 # Add "," for the next network.
677 $line = "$line" . "\,";
678 }
679 }
680
681 # Open file to store the addresses of the home net.
682 open(FILE, ">$homenet_file") or die "Could not open $homenet_file. $!\n";
683
684 # Print yaml header.
685 print FILE "%YAML 1.1\n";
686 print FILE "---\n\n";
687
688 # Print notice about autogenerated file.
689 print FILE "#Autogenerated file. Any custom changes will be overwritten!\n";
690
691 # Print the generated and required HOME_NET declaration to the file.
692 print FILE "HOME_NET:\t$line\n";
693
694 # Close file handle.
695 close(FILE);
696}
697
698#
699## Function to generate and write the file for used rulefiles.
700#
701sub write_used_rulefiles_file(@) {
702 my @files = @_;
703
704 # Open file for used rulefiles.
705 open (FILE, ">$used_rulefiles_file") or die "Could not write to $used_rulefiles_file. $!\n";
706
707 # Write yaml header to the file.
708 print FILE "%YAML 1.1\n";
709 print FILE "---\n\n";
710
711 # Write header to file.
712 print FILE "#Autogenerated file. Any custom changes will be overwritten!\n";
713
714 # Allways use the whitelist.
715 print FILE " - whitelist.rules\n";
716
717 # Loop through the array of given files.
718 foreach my $file (@files) {
719 # Check if the given filename exists and write it to the file of used rulefiles.
720 if(-f "$rulespath/$file") {
721 print FILE " - $file\n";
722 }
723 }
724
725 # Close file after writing.
726 close(FILE);
727}
728
74cc8f5a
SS
729#
730## Function to generate and write the file for modify the ruleset.
731#
81bae51f
SS
732sub write_modify_sids_file() {
733 # Get configured settings.
734 my %idssettings=();
735 my %rulessettings=();
736 &General::readhash("$ids_settings_file", \%idssettings);
737 &General::readhash("$rules_settings_file", \%rulessettings);
738
739 # Gather the configured ruleset.
740 my $ruleset = $rulessettings{'RULES'};
74cc8f5a
SS
741
742 # Open modify sid's file for writing.
2ee51088 743 open(FILE, ">$modify_sids_file") or die "Could not write to $modify_sids_file. $!\n";
74cc8f5a
SS
744
745 # Write file header.
746 print FILE "#Autogenerated file. Any custom changes will be overwritten!\n";
747
748 # Check if the traffic only should be monitored.
81bae51f 749 unless($idssettings{'MONITOR_TRAFFIC_ONLY'} eq 'on') {
a5ba473c
TF
750 # Suricata is in IPS mode, which means that the rule actions have to be changed
751 # from 'alert' to 'drop', however not all rules should be changed. Some rules
752 # exist purely to set a flowbit which is used to convey other information, such
753 # as a specific type of file being downloaded, to other rulewhich then check for
754 # malware in that file. Rules which fall into the first category should stay as
755 # alert since not all flows of that type contain malware.
756
81bae51f 757 if($ruleset eq 'registered' or $ruleset eq 'subscripted' or $ruleset eq 'community') {
a5ba473c
TF
758 # These types of rulesfiles contain meta-data which gives the action that should
759 # be used when in IPS mode. Do the following:
760 #
761 # 1. Disable all rules and set the action to 'drop'
762 # 2. Set the action back to 'alert' if the rule contains 'flowbits:noalert;'
763 # This should give rules not in the policy a reasonable default if the user
764 # manually enables them.
765 # 3. Enable rules and set actions according to the meta-data strings.
766
767 my $policy = 'balanced'; # Placeholder to allow policy to be changed.
768
769 print FILE <<END;
770modifysid * "^#?(?:alert|drop)" | "#drop"
771modifysid * "^#drop(.+flowbits:noalert;)" | "#alert\${1}"
772modifysid * "^#(?:alert|drop)(.+policy $policy-ips alert)" | "alert\${1}"
773modifysid * "^#(?:alert|drop)(.+policy $policy-ips drop)" | "drop\${1}"
774END
775 } else {
776 # These rulefiles don't have the metadata, so set rules to 'drop' unless they
777 # contain the string 'flowbits:noalert;'.
778 print FILE <<END;
779modifysid * "^(#?)(?:alert|drop)" | "\${1}drop"
780modifysid * "^(#?)drop(.+flowbits:noalert;)" | "\${1}alert\${2}"
781END
782 }
74cc8f5a
SS
783 }
784
785 # Close file handle.
786 close(FILE);
787}
788
04a0d07c
SS
789#
790## Function to gather the version of suricata.
791#
792sub get_suricata_version($) {
793 my ($format) = @_;
794
795 # Execute piped suricata command and return the version information.
796 open(SURICATA, "suricata -V |") or die "Couldn't execute program: $!";
797
798 # Grab and store the output of the piped program.
799 my $version_string = <SURICATA>;
800
801 # Close pipe.
802 close(SURICATA);
803
804 # Remove newlines.
805 chomp($version_string);
806
807 # Grab the version from the version string.
808 $version_string =~ /([0-9]+([.][0-9]+)+)/;
809
810 # Splitt the version into single chunks.
811 my ($major_ver, $minor_ver, $patchlevel) = split(/\./, $1);
812
813 # Check and return the requested version sheme.
814 if ($format eq "major") {
815 # Return the full version.
816 return "$major_ver";
817 } elsif ($format eq "minor") {
818 # Return the major and minor part.
819 return "$major_ver.$minor_ver";
820 } else {
821 # Return the full version string.
822 return "$major_ver.$minor_ver.$patchlevel";
823 }
824}
825
9283e9b9
SS
826#
827## Function to generate the rules file with whitelisted addresses.
828#
829sub generate_ignore_file() {
830 my %ignored = ();
831
832 # SID range 1000000-1999999 Reserved for Local Use
833 # Put your custom rules in this range to avoid conflicts
834 my $sid = 1500000;
835
836 # Read-in ignoredfile.
837 &General::readhasharray($IDS::ignored_file, \%ignored);
838
839 # Open ignorefile for writing.
840 open(FILE, ">$IDS::whitelist_file") or die "Could not write to $IDS::whitelist_file. $!\n";
841
842 # Config file header.
843 print FILE "# Autogenerated file.\n";
844 print FILE "# All user modifications will be overwritten.\n\n";
845
846 # Add all user defined addresses to the whitelist.
847 #
848 # Check if the hash contains any elements.
849 if (keys (%ignored)) {
850 # Loop through the entire hash and write the host/network
851 # and remark to the ignore file.
852 while ( (my $key) = each %ignored) {
853 my $address = $ignored{$key}[0];
854 my $remark = $ignored{$key}[1];
855 my $status = $ignored{$key}[2];
856
857 # Check if the status of the entry is "enabled".
858 if ($status eq "enabled") {
859 # Check if the address/network is valid.
860 if ((&General::validip($address)) || (&General::validipandmask($address))) {
861 # Write rule line to the file to pass any traffic from this IP
862 print FILE "pass ip $address any -> any any (msg:\"pass all traffic from/to $address\"\; sid:$sid\;)\n";
863
864 # Increment sid.
865 $sid++;
866 }
867 }
868 }
869 }
870
871 close(FILE);
872}
873
1fedede6
SS
874#
875## Function to set correct ownership for single files and directories.
876#
877
878sub set_ownership($) {
879 my ($target) = @_;
880
881 # User and group of the WUI.
882 my $uname = "nobody";
883 my $grname = "nobody";
884
885 # The chown function implemented in perl requies the user and group as nummeric id's.
886 my $uid = getpwnam($uname);
887 my $gid = getgrnam($grname);
888
889 # Check if the given target exists.
890 unless ($target) {
891 # Stop the script and print error message.
892 die "The $target does not exist. Cannot change the ownership!\n";
893 }
894
895 # Check weather the target is a file or directory.
896 if (-f $target) {
897 # Change ownership ot the single file.
898 chown($uid, $gid, "$target");
899 } elsif (-d $target) {
900 # Do a directory listing.
901 opendir(DIR, $target) or die $!;
902 # Loop through the direcory.
903 while (my $file = readdir(DIR)) {
904
905 # We only want files.
906 next unless (-f "$target/$file");
907
908 # Set correct ownership for the files.
909 chown($uid, $gid, "$target/$file");
910 }
911
912 closedir(DIR);
913
914 # Change ownership of the directory.
915 chown($uid, $gid, "$target");
916 }
917}
77c31301
SS
918
919#
920## Function to read-in the aliases file and returns all configured and enabled aliases.
921#
922sub get_aliases() {
923 # Location of the aliases file.
924 my $aliases_file = "${General::swroot}/ethernet/aliases";
925
926 # Array to store the aliases.
927 my @aliases;
928
929 # Check if the file is empty.
930 if (-z $aliases_file) {
931 # Abort nothing to do.
932 return;
933 }
934
935 # Open the aliases file.
936 open(ALIASES, $aliases_file) or die "Could not open $aliases_file. $!\n";
937
938 # Loop through the file content.
939 while (my $line = <ALIASES>) {
940 # Remove newlines.
941 chomp($line);
942
943 # Splitt line content into single chunks.
944 my ($address, $state, $remark) = split(/\,/, $line);
945
946 # Check if the state of the current processed alias is "on".
947 if ($state eq "on") {
948 # Check if the address is valid.
949 if(&Network::check_ip_address($address)) {
950 # Add the alias to the array of aliases.
951 push(@aliases, $address);
952 }
953 }
954 }
955
956 # Close file handle.
957 close(ALIASES);
958
959 # Return the array.
960 return @aliases;
961}
962
de8e1e5b
SS
963#
964## Function to grab the current assigned IP-address on red.
965#
966sub get_red_address() {
967 # File, which contains the current IP-address of the red interface.
968 my $file = "${General::swroot}/red/local-ipaddress";
969
970 # Check if the file exists.
971 if (-e $file) {
972 # Open the given file.
973 open(FILE, "$file") or die "Could not open $file.";
974
975 # Obtain the address from the first line of the file.
976 my $address = <FILE>;
977
978 # Close filehandle
979 close(FILE);
980
981 # Remove newlines.
982 chomp $address;
983
984 # Check if the grabbed address is valid.
985 if (&General::validip($address)) {
986 # Return the address.
987 return $address;
988 }
989 }
990
991 # Return nothing.
992 return;
993}
77c31301 994
8076deba
SS
995#
996## Function to write the lock file for locking the WUI, while
997## the autoupdate script runs.
998#
999sub lock_ids_page() {
1000 # Call subfunction to create the file.
1001 &create_empty_file($ids_page_lock_file);
1002}
1003
1004#
1005## Function to release the lock of the WUI, again.
1006#
1007sub unlock_ids_page() {
1008 # Delete lock file.
1009 unlink($ids_page_lock_file);
1010}
1011
8dcebe53 10121;