]> git.ipfire.org Git - people/pmueller/ipfire-2.x.git/blame - config/cfgroot/ids-functions.pl
ids-functions.pl: Fall back to $EXTERNAL_NET for DNS servers
[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
SS
713
714 # Format dns servers declaration.
b76118c3 715 my $line = "";
30ee98e9 716
12c49915
SS
717 # Check if the system has configured nameservers.
718 if (@nameservers) {
b76118c3 719 $line = join(",", @nameservers);
12c49915 720 } else {
99cadb74 721 $line = "\$EXTERNAL_NET";
fd2dccaa 722 }
30ee98e9 723
30ee98e9
SS
724 # Open file to store the used DNS server addresses.
725 open(FILE, ">$dns_servers_file") or die "Could not open $dns_servers_file. $!\n";
726
727 # Print yaml header.
728 print FILE "%YAML 1.1\n";
729 print FILE "---\n\n";
730
731 # Print notice about autogenerated file.
732 print FILE "#Autogenerated file. Any custom changes will be overwritten!\n";
733
734 # Print the generated DNS declaration to the file.
b76118c3 735 print FILE "DNS_SERVERS:\t\"[$line]\"\n";
30ee98e9
SS
736
737 # Close file handle.
738 close(FILE);
739}
740
b02e30fd
SS
741#
742## Function to generate and write the file for used rulefiles.
743#
744sub write_used_rulefiles_file(@) {
745 my @files = @_;
746
747 # Open file for used rulefiles.
748 open (FILE, ">$used_rulefiles_file") or die "Could not write to $used_rulefiles_file. $!\n";
749
750 # Write yaml header to the file.
751 print FILE "%YAML 1.1\n";
752 print FILE "---\n\n";
753
754 # Write header to file.
755 print FILE "#Autogenerated file. Any custom changes will be overwritten!\n";
756
757 # Allways use the whitelist.
758 print FILE " - whitelist.rules\n";
759
760 # Loop through the array of given files.
761 foreach my $file (@files) {
762 # Check if the given filename exists and write it to the file of used rulefiles.
763 if(-f "$rulespath/$file") {
764 print FILE " - $file\n";
765 }
766 }
767
768 # Close file after writing.
769 close(FILE);
770}
771
74cc8f5a
SS
772#
773## Function to generate and write the file for modify the ruleset.
774#
81bae51f
SS
775sub write_modify_sids_file() {
776 # Get configured settings.
777 my %idssettings=();
778 my %rulessettings=();
779 &General::readhash("$ids_settings_file", \%idssettings);
780 &General::readhash("$rules_settings_file", \%rulessettings);
781
782 # Gather the configured ruleset.
783 my $ruleset = $rulessettings{'RULES'};
74cc8f5a
SS
784
785 # Open modify sid's file for writing.
2ee51088 786 open(FILE, ">$modify_sids_file") or die "Could not write to $modify_sids_file. $!\n";
74cc8f5a
SS
787
788 # Write file header.
789 print FILE "#Autogenerated file. Any custom changes will be overwritten!\n";
790
791 # Check if the traffic only should be monitored.
81bae51f 792 unless($idssettings{'MONITOR_TRAFFIC_ONLY'} eq 'on') {
a5ba473c
TF
793 # Suricata is in IPS mode, which means that the rule actions have to be changed
794 # from 'alert' to 'drop', however not all rules should be changed. Some rules
795 # exist purely to set a flowbit which is used to convey other information, such
796 # as a specific type of file being downloaded, to other rulewhich then check for
797 # malware in that file. Rules which fall into the first category should stay as
798 # alert since not all flows of that type contain malware.
799
81bae51f 800 if($ruleset eq 'registered' or $ruleset eq 'subscripted' or $ruleset eq 'community') {
a5ba473c
TF
801 # These types of rulesfiles contain meta-data which gives the action that should
802 # be used when in IPS mode. Do the following:
803 #
804 # 1. Disable all rules and set the action to 'drop'
805 # 2. Set the action back to 'alert' if the rule contains 'flowbits:noalert;'
806 # This should give rules not in the policy a reasonable default if the user
807 # manually enables them.
808 # 3. Enable rules and set actions according to the meta-data strings.
809
810 my $policy = 'balanced'; # Placeholder to allow policy to be changed.
811
812 print FILE <<END;
813modifysid * "^#?(?:alert|drop)" | "#drop"
814modifysid * "^#drop(.+flowbits:noalert;)" | "#alert\${1}"
815modifysid * "^#(?:alert|drop)(.+policy $policy-ips alert)" | "alert\${1}"
816modifysid * "^#(?:alert|drop)(.+policy $policy-ips drop)" | "drop\${1}"
817END
818 } else {
819 # These rulefiles don't have the metadata, so set rules to 'drop' unless they
820 # contain the string 'flowbits:noalert;'.
821 print FILE <<END;
822modifysid * "^(#?)(?:alert|drop)" | "\${1}drop"
823modifysid * "^(#?)drop(.+flowbits:noalert;)" | "\${1}alert\${2}"
824END
825 }
74cc8f5a
SS
826 }
827
828 # Close file handle.
829 close(FILE);
830}
831
04a0d07c
SS
832#
833## Function to gather the version of suricata.
834#
835sub get_suricata_version($) {
836 my ($format) = @_;
837
838 # Execute piped suricata command and return the version information.
839 open(SURICATA, "suricata -V |") or die "Couldn't execute program: $!";
840
841 # Grab and store the output of the piped program.
842 my $version_string = <SURICATA>;
843
844 # Close pipe.
845 close(SURICATA);
846
847 # Remove newlines.
848 chomp($version_string);
849
fd2dccaa 850 # Grab the version from the version string.
04a0d07c
SS
851 $version_string =~ /([0-9]+([.][0-9]+)+)/;
852
853 # Splitt the version into single chunks.
854 my ($major_ver, $minor_ver, $patchlevel) = split(/\./, $1);
855
856 # Check and return the requested version sheme.
857 if ($format eq "major") {
858 # Return the full version.
859 return "$major_ver";
860 } elsif ($format eq "minor") {
861 # Return the major and minor part.
862 return "$major_ver.$minor_ver";
863 } else {
864 # Return the full version string.
865 return "$major_ver.$minor_ver.$patchlevel";
fd2dccaa 866 }
04a0d07c
SS
867}
868
9283e9b9
SS
869#
870## Function to generate the rules file with whitelisted addresses.
871#
872sub generate_ignore_file() {
873 my %ignored = ();
874
875 # SID range 1000000-1999999 Reserved for Local Use
876 # Put your custom rules in this range to avoid conflicts
877 my $sid = 1500000;
878
879 # Read-in ignoredfile.
880 &General::readhasharray($IDS::ignored_file, \%ignored);
881
882 # Open ignorefile for writing.
883 open(FILE, ">$IDS::whitelist_file") or die "Could not write to $IDS::whitelist_file. $!\n";
884
885 # Config file header.
886 print FILE "# Autogenerated file.\n";
887 print FILE "# All user modifications will be overwritten.\n\n";
888
889 # Add all user defined addresses to the whitelist.
890 #
891 # Check if the hash contains any elements.
892 if (keys (%ignored)) {
893 # Loop through the entire hash and write the host/network
894 # and remark to the ignore file.
895 while ( (my $key) = each %ignored) {
896 my $address = $ignored{$key}[0];
897 my $remark = $ignored{$key}[1];
898 my $status = $ignored{$key}[2];
899
900 # Check if the status of the entry is "enabled".
901 if ($status eq "enabled") {
902 # Check if the address/network is valid.
903 if ((&General::validip($address)) || (&General::validipandmask($address))) {
904 # Write rule line to the file to pass any traffic from this IP
905 print FILE "pass ip $address any -> any any (msg:\"pass all traffic from/to $address\"\; sid:$sid\;)\n";
906
907 # Increment sid.
908 $sid++;
909 }
910 }
911 }
912 }
913
914 close(FILE);
915}
916
1fedede6
SS
917#
918## Function to set correct ownership for single files and directories.
919#
920
921sub set_ownership($) {
922 my ($target) = @_;
923
924 # User and group of the WUI.
925 my $uname = "nobody";
926 my $grname = "nobody";
927
928 # The chown function implemented in perl requies the user and group as nummeric id's.
929 my $uid = getpwnam($uname);
930 my $gid = getgrnam($grname);
931
932 # Check if the given target exists.
933 unless ($target) {
934 # Stop the script and print error message.
935 die "The $target does not exist. Cannot change the ownership!\n";
936 }
937
938 # Check weather the target is a file or directory.
939 if (-f $target) {
940 # Change ownership ot the single file.
941 chown($uid, $gid, "$target");
942 } elsif (-d $target) {
943 # Do a directory listing.
944 opendir(DIR, $target) or die $!;
945 # Loop through the direcory.
946 while (my $file = readdir(DIR)) {
947
948 # We only want files.
949 next unless (-f "$target/$file");
950
951 # Set correct ownership for the files.
952 chown($uid, $gid, "$target/$file");
953 }
954
955 closedir(DIR);
956
957 # Change ownership of the directory.
958 chown($uid, $gid, "$target");
959 }
960}
77c31301
SS
961
962#
963## Function to read-in the aliases file and returns all configured and enabled aliases.
964#
965sub get_aliases() {
966 # Location of the aliases file.
967 my $aliases_file = "${General::swroot}/ethernet/aliases";
968
969 # Array to store the aliases.
970 my @aliases;
971
972 # Check if the file is empty.
973 if (-z $aliases_file) {
974 # Abort nothing to do.
975 return;
976 }
977
978 # Open the aliases file.
979 open(ALIASES, $aliases_file) or die "Could not open $aliases_file. $!\n";
980
981 # Loop through the file content.
982 while (my $line = <ALIASES>) {
983 # Remove newlines.
984 chomp($line);
985
986 # Splitt line content into single chunks.
987 my ($address, $state, $remark) = split(/\,/, $line);
988
989 # Check if the state of the current processed alias is "on".
990 if ($state eq "on") {
991 # Check if the address is valid.
992 if(&Network::check_ip_address($address)) {
993 # Add the alias to the array of aliases.
994 push(@aliases, $address);
995 }
996 }
997 }
998
999 # Close file handle.
1000 close(ALIASES);
1001
1002 # Return the array.
1003 return @aliases;
1004}
1005
de8e1e5b
SS
1006#
1007## Function to grab the current assigned IP-address on red.
1008#
1009sub get_red_address() {
1010 # File, which contains the current IP-address of the red interface.
1011 my $file = "${General::swroot}/red/local-ipaddress";
1012
1013 # Check if the file exists.
1014 if (-e $file) {
1015 # Open the given file.
1016 open(FILE, "$file") or die "Could not open $file.";
1017
1018 # Obtain the address from the first line of the file.
1019 my $address = <FILE>;
1020
1021 # Close filehandle
1022 close(FILE);
1023
1024 # Remove newlines.
1025 chomp $address;
1026
1027 # Check if the grabbed address is valid.
1028 if (&General::validip($address)) {
1029 # Return the address.
1030 return $address;
1031 }
1032 }
1033
1034 # Return nothing.
1035 return;
1036}
77c31301 1037
8076deba
SS
1038#
1039## Function to write the lock file for locking the WUI, while
1040## the autoupdate script runs.
1041#
1042sub lock_ids_page() {
1043 # Call subfunction to create the file.
1044 &create_empty_file($ids_page_lock_file);
1045}
1046
1047#
1048## Function to release the lock of the WUI, again.
1049#
1050sub unlock_ids_page() {
1051 # Delete lock file.
1052 unlink($ids_page_lock_file);
1053}
1054
8dcebe53 10551;