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