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