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