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