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