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