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