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