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