]> git.ipfire.org Git - people/pmueller/ipfire-2.x.git/blob - config/cfgroot/ids-functions.pl
ids-functions.pl: Do not create an empty ignored settings file.
[people/pmueller/ipfire-2.x.git] / config / cfgroot / ids-functions.pl
1 #!/usr/bin/perl -w
2 ############################################################################
3 # #
4 # This file is part of the IPFire Firewall. #
5 # #
6 # IPFire is free software; you can redistribute it and/or modify #
7 # it under the terms of the GNU General Public License as published by #
8 # the Free Software Foundation; either version 2 of the License, or #
9 # (at your option) any later version. #
10 # #
11 # IPFire is distributed in the hope that it will be useful, #
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of #
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
14 # GNU General Public License for more details. #
15 # #
16 # You should have received a copy of the GNU General Public License #
17 # along with IPFire; if not, write to the Free Software #
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #
19 # #
20 # Copyright (C) 2018-2019 IPFire Team <info@ipfire.org> #
21 # #
22 ############################################################################
23
24 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 main file for providers ruleset inclusion exists.
36 our $suricata_used_providers_file = "$settingsdir/suricata-used-providers.yaml";
37
38 # File for static ruleset inclusions.
39 our $suricata_default_rulefiles_file = "$settingsdir/suricata-default-rules.yaml";
40
41 # File where the addresses of the homenet are stored.
42 our $homenet_file = "$settingsdir/suricata-homenet.yaml";
43
44 # File where the addresses of the used DNS servers are stored.
45 our $dns_servers_file = "$settingsdir/suricata-dns-servers.yaml";
46
47 # File where the HTTP ports definition is stored.
48 our $http_ports_file = "$settingsdir/suricata-http-ports.yaml";
49
50 # File which contains includes for provider specific rule modifications.
51 our $oinkmaster_provider_includes_file = "$settingsdir/oinkmaster-provider-includes.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 # File which stores the used and configured ruleset providers.
60 our $providers_settings_file = "$settingsdir/providers-settings";
61
62 # File which stores the configured settings for whitelisted addresses.
63 our $ignored_file = "$settingsdir/ignored";
64
65 # Location where the downloaded rulesets are stored.
66 our $dl_rules_path = "/var/tmp";
67
68 # File to store any errors, which also will be read and displayed by the wui.
69 our $storederrorfile = "/tmp/ids_storederror";
70
71 # File to lock the WUI, while the autoupdate script runs.
72 our $ids_page_lock_file = "/tmp/ids_page_locked";
73
74 # Location where the rulefiles are stored.
75 our $rulespath = "/var/lib/suricata";
76
77 # Location where the default rulefils are stored.
78 our $default_rulespath = "/usr/share/suricata/rules";
79
80 # Location where the addition config files are stored.
81 our $configspath = "/usr/share/suricata";
82
83 # Location of the classification file.
84 our $classification_file = "$configspath/classification.config";
85
86 # Location of the sid to msg mappings file.
87 our $sid_msg_file = "$rulespath/sid-msg.map";
88
89 # Location to store local rules. This file will not be touched.
90 our $local_rules_file = "$rulespath/local.rules";
91
92 # File which contains the rules to whitelist addresses on suricata.
93 our $whitelist_file = "$rulespath/whitelist.rules";
94
95 # File which contains a list of all supported ruleset sources.
96 # (Sourcefire, Emergingthreads, etc..)
97 our $rulesetsourcesfile = "$settingsdir/ruleset-sources";
98
99 # The pidfile of the IDS.
100 our $idspidfile = "/var/run/suricata.pid";
101
102 # Location of suricatactrl.
103 my $suricatactrl = "/usr/local/bin/suricatactrl";
104
105 # Prefix for each downloaded ruleset.
106 my $dl_rulesfile_prefix = "idsrules";
107
108 # Temporary directory where the rulesets will be extracted.
109 my $tmp_directory = "/tmp/ids_tmp";
110
111 # Temporary directory where the extracted rules files will be stored.
112 my $tmp_rules_directory = "$tmp_directory/rules";
113
114 # Temporary directory where the extracted additional config files will be stored.
115 my $tmp_conf_directory = "$tmp_directory/conf";
116
117 # Array with allowed commands of suricatactrl.
118 my @suricatactrl_cmds = ( 'start', 'stop', 'restart', 'reload', 'fix-rules-dir', 'cron' );
119
120 # Array with supported cron intervals.
121 my @cron_intervals = ('off', 'daily', 'weekly' );
122
123 # Array which contains the HTTP ports, which statically will be declared as HTTP_PORTS in the
124 # http_ports_file.
125 my @http_ports = ('80', '81');
126
127 # Array which contains a list of rulefiles which always will be included if they exist.
128 my @static_included_rulefiles = ('local.rules', 'whitelist.rules');
129
130 # Array which contains a list of allways enabled application layer protocols.
131 my @static_enabled_app_layer_protos = ('app-layer', 'decoder', 'files', 'stream');
132
133 # Hash which allows to convert the download type (dl_type) to a file suffix.
134 my %dl_type_to_suffix = (
135 "archive" => ".tar.gz",
136 "plain" => ".rules",
137 );
138
139 # Hash to translate an application layer protocol to the application name.
140 my %tr_app_layer_proto = (
141 "ikev2" => "ipsec",
142 "krb5" => "kerberos",
143 );
144
145 #
146 ## Function to check and create all IDS related files, if the does not exist.
147 #
148 sub check_and_create_filelayout() {
149 # Check if the files exist and if not, create them.
150 unless (-f "$oinkmaster_provider_includes_file") { &create_empty_file($oinkmaster_provider_includes_file); }
151 unless (-f "$modify_sids_file") { &create_empty_file($modify_sids_file); }
152 unless (-f "$suricata_used_providers_file") { &create_empty_file($suricata_used_providers_file); }
153 unless (-f "$suricata_default_rulefiles_file") { &create_empty_file($suricata_default_rulefiles_file); }
154 unless (-f "$ids_settings_file") { &create_empty_file($ids_settings_file); }
155 unless (-f "$providers_settings_file") { &create_empty_file($providers_settings_file); }
156 unless (-f "$whitelist_file" ) { &create_empty_file($whitelist_file); }
157 }
158
159 #
160 ## Function to get a list of all available ruleset providers.
161 ##
162 ## They will be returned as a sorted array.
163 #
164 sub get_ruleset_providers() {
165 my @providers;
166
167 # Loop through the hash of providers.
168 foreach my $provider ( keys %IDS::Ruleset::Providers ) {
169 # Add the provider to the array.
170 push(@providers, $provider);
171 }
172
173 # Sort and return the array.
174 return sort(@providers);
175 }
176
177 #
178 ## Function to get a list of all enabled ruleset providers.
179 ##
180 ## They will be returned as an array.
181 #
182 sub get_enabled_providers () {
183 my %used_providers = ();
184
185 # Array to store the enabled providers.
186 my @enabled_providers = ();
187
188 # Read-in the providers config file.
189 &General::readhasharray("$providers_settings_file", \%used_providers);
190
191 # Loop through the hash of used_providers.
192 foreach my $id (keys %used_providers) {
193 # Skip disabled providers.
194 next unless ($used_providers{$id}[3] eq "enabled");
195
196 # Grab the provider handle.
197 my $provider = "$used_providers{$id}[0]";
198
199 # Add the provider to the array of enabled providers.
200 push(@enabled_providers, $provider);
201 }
202
203 # Return the array.
204 return @enabled_providers;
205 }
206
207 #
208 ## Function for checking if at least 300MB of free disk space are available
209 ## on the "/var" partition.
210 #
211 sub checkdiskspace () {
212 # Call diskfree to gather the free disk space of /var.
213 my @df = &General::system_output("/bin/df", "-B", "M", "/var");
214
215 # Loop through the output.
216 foreach my $line (@df) {
217 # Ignore header line.
218 next if $line =~ m/^Filesystem/;
219
220 # Search for a line with the device information.
221 if ($line =~ m/dev/ ) {
222 # Split the line into single pieces.
223 my @values = split(' ', $line);
224 my ($filesystem, $blocks, $used, $available, $used_perenctage, $mounted_on) = @values;
225
226 # Check if the available disk space is more than 300MB.
227 if ($available < 300) {
228 # Log error to syslog.
229 &_log_to_syslog("Not enough free disk space on /var. Only $available MB from 300 MB available.");
230
231 # Exit function and return "1" - False.
232 return 1;
233 }
234 }
235 }
236
237 # Everything okay, return nothing.
238 return;
239 }
240
241 #
242 ## This function is responsible for downloading the configured IDS rulesets or if no one is specified
243 ## all configured rulesets will be downloaded.
244 ##
245 ## * At first it gathers all configured ruleset providers, initialize the downloader and sets an
246 ## upstream proxy if configured.
247 ## * After that, the given ruleset or in case all rulesets should be downloaded, it will determine wether it
248 ## is enabled or not.
249 ## * The next step will be to generate the final download url, by obtaining the URL for the desired
250 ## ruleset, add the settings for the upstream proxy.
251 ## * Finally the function will grab all the rules files or tarballs from the servers.
252 #
253 sub downloadruleset ($) {
254 my ($provider) = @_;
255
256 # If no provider is given default to "all".
257 $provider //= 'all';
258
259 # Hash to store the providers and access id's, for which rules should be downloaded.
260 my %sheduled_providers = ();
261
262 # Get used provider settings.
263 my %used_providers = ();
264 &General::readhasharray("$providers_settings_file", \%used_providers);
265
266 # Check if a ruleset has been configured.
267 unless(%used_providers) {
268 # Log that no ruleset has been configured and abort.
269 &_log_to_syslog("No ruleset provider has been configured.");
270
271 # Return "1".
272 return 1;
273 }
274
275 # Read proxysettings.
276 my %proxysettings=();
277 &General::readhash("${General::swroot}/proxy/settings", \%proxysettings);
278
279 # Load required perl module to handle the download.
280 use LWP::UserAgent;
281
282 # Init the download module.
283 my $downloader = LWP::UserAgent->new;
284
285 # Set timeout to 10 seconds.
286 $downloader->timeout(10);
287
288 # Check if an upstream proxy is configured.
289 if ($proxysettings{'UPSTREAM_PROXY'}) {
290 my $proxy_url;
291
292 $proxy_url = "http://";
293
294 # Check if the proxy requires authentication.
295 if (($proxysettings{'UPSTREAM_USER'}) && ($proxysettings{'UPSTREAM_PASSWORD'})) {
296 $proxy_url .= "$proxysettings{'UPSTREAM_USER'}\:$proxysettings{'UPSTREAM_PASSWORD'}\@";
297 }
298
299 # Add proxy server address and port.
300 $proxy_url .= $proxysettings{'UPSTREAM_PROXY'};
301
302 # Setup proxy settings.
303 $downloader->proxy(['http', 'https'], $proxy_url);
304 }
305
306 # Loop through the hash of configured providers.
307 foreach my $id ( keys %used_providers ) {
308 # Skip providers which are not enabled.
309 next if ($used_providers{$id}[3] ne "enabled");
310
311 # Obtain the provider handle.
312 my $provider_handle = $used_providers{$id}[0];
313
314 # Handle update off all providers.
315 if (($provider eq "all") || ($provider_handle eq "$provider")) {
316 # Add provider handle and it's id to the hash of sheduled providers.
317 $sheduled_providers{$provider_handle} = $id;
318 }
319 }
320
321 # Loop through the hash of sheduled providers.
322 foreach my $provider ( keys %sheduled_providers) {
323 # Log download/update of the ruleset.
324 &_log_to_syslog("Downloading ruleset for provider: $provider.");
325
326 # Grab the download url for the provider.
327 my $url = $IDS::Ruleset::Providers{$provider}{'dl_url'};
328
329 # Check if the provider requires a subscription.
330 if ($IDS::Ruleset::Providers{$provider}{'requires_subscription'} eq "True") {
331 # Grab the previously stored access id for the provider from hash.
332 my $id = $sheduled_providers{$provider};
333
334 # Grab the subscription code.
335 my $subscription_code = $used_providers{$id}[1];
336
337 # Add the subscription code to the download url.
338 $url =~ s/\<subscription_code\>/$subscription_code/g;
339
340 }
341
342 # Abort if no url could be determined for the provider.
343 unless ($url) {
344 # Log error and abort.
345 &_log_to_syslog("Unable to gather a download URL for the selected ruleset provider.");
346 return 1;
347 }
348
349 # Variable to store the filesize of the remote object.
350 my $remote_filesize;
351
352 # The sourcfire (snort rules) does not allow to send "HEAD" requests, so skip this check
353 # for this webserver.
354 #
355 # Check if the ruleset source contains "snort.org".
356 unless ($url =~ /\.snort\.org/) {
357 # Pass the requrested url to the downloader.
358 my $request = HTTP::Request->new(HEAD => $url);
359
360 # Accept the html header.
361 $request->header('Accept' => 'text/html');
362
363 # Perform the request and fetch the html header.
364 my $response = $downloader->request($request);
365
366 # Check if there was any error.
367 unless ($response->is_success) {
368 # Obtain error.
369 my $error = $response->status_line();
370
371 # Log error message.
372 &_log_to_syslog("Unable to download the ruleset. \($error\)");
373
374 # Return "1" - false.
375 return 1;
376 }
377
378 # Assign the fetched header object.
379 my $header = $response->headers();
380
381 # Grab the remote file size from the object and store it in the
382 # variable.
383 $remote_filesize = $header->content_length;
384 }
385
386 # Load perl module to deal with temporary files.
387 use File::Temp;
388
389 # Generate temporary file name, located in "/var/tmp" and with a suffix of ".tmp".
390 my $tmp = File::Temp->new( SUFFIX => ".tmp", DIR => "/var/tmp/", UNLINK => 0 );
391 my $tmpfile = $tmp->filename();
392
393 # Pass the requested url to the downloader.
394 my $request = HTTP::Request->new(GET => $url);
395
396 # Perform the request and save the output into the tmpfile.
397 my $response = $downloader->request($request, $tmpfile);
398
399 # Check if there was any error.
400 unless ($response->is_success) {
401 # Obtain error.
402 my $error = $response->content;
403
404 # Log error message.
405 &_log_to_syslog("Unable to download the ruleset. \($error\)");
406
407 # Return "1" - false.
408 return 1;
409 }
410
411 # Load perl stat module.
412 use File::stat;
413
414 # Perform stat on the tmpfile.
415 my $stat = stat($tmpfile);
416
417 # Grab the local filesize of the downloaded tarball.
418 my $local_filesize = $stat->size;
419
420 # Check if both file sizes match.
421 if (($remote_filesize) && ($remote_filesize ne $local_filesize)) {
422 # Log error message.
423 &_log_to_syslog("Unable to completely download the ruleset. ");
424 &_log_to_syslog("Only got $local_filesize Bytes instead of $remote_filesize Bytes. ");
425
426 # Delete temporary file.
427 unlink("$tmpfile");
428
429 # Return "1" - false.
430 return 1;
431 }
432
433 # Genarate and assign file name and path to store the downloaded rules file.
434 my $dl_rulesfile = &_get_dl_rulesfile($provider);
435
436 # Check if a file name could be obtained.
437 unless ($dl_rulesfile) {
438 # Log error message.
439 &_log_to_syslog("Unable to store the downloaded rules file. ");
440
441 # Delete downloaded temporary file.
442 unlink("$tmpfile");
443
444 # Return "1" - false.
445 return 1;
446 }
447
448 # Load file copy module, which contains the move() function.
449 use File::Copy;
450
451 # Overwrite the may existing rulefile or tarball with the downloaded one.
452 move("$tmpfile", "$dl_rulesfile");
453
454 # Delete temporary file.
455 unlink("$tmpfile");
456
457 # Set correct ownership for the tarball.
458 set_ownership("$dl_rulesfile");
459 }
460
461 # If we got here, everything worked fine. Return nothing.
462 return;
463 }
464
465 #
466 ## Function to extract a given ruleset.
467 ##
468 ## In case the ruleset provider offers a plain file, it simply will
469 ## be copied.
470 #
471 sub extractruleset ($) {
472 my ($provider) = @_;
473
474 # Load perl module to deal with archives.
475 use Archive::Tar;
476
477 # Disable chown functionality when uncompressing files.
478 $Archive::Tar::CHOWN = "0";
479
480 # Load perl module to deal with files and path.
481 use File::Basename;
482
483 # Load perl module for file copying.
484 use File::Copy;
485
486 # Get full path and downloaded rulesfile for the given provider.
487 my $tarball = &_get_dl_rulesfile($provider);
488
489 # Check if the file exists.
490 unless (-f $tarball) {
491 &_log_to_syslog("Could not find ruleset file: $tarball");
492
493 # Return nothing.
494 return;
495 }
496
497 # Check if the temporary directories exist, otherwise create them.
498 mkdir("$tmp_directory") unless (-d "$tmp_directory");
499 mkdir("$tmp_rules_directory") unless (-d "$tmp_rules_directory");
500 mkdir("$tmp_conf_directory") unless (-d "$tmp_conf_directory");
501
502 # Omit the type (dl_type) of the stored ruleset.
503 my $type = $IDS::Ruleset::Providers{$provider}{'dl_type'};
504
505 # Handle the different ruleset types.
506 if ($type eq "plain") {
507 # Generate destination filename an full path.
508 my $destination = "$tmp_rules_directory/$provider\-ruleset.rules";
509
510 # Copy the file into the temporary rules directory.
511 copy($tarball, $destination);
512
513 } elsif ( $type eq "archive") {
514 # Initialize the tar module.
515 my $tar = Archive::Tar->new($tarball);
516
517 # Get the filelist inside the tarball.
518 my @packed_files = $tar->list_files;
519
520 # Loop through the filelist.
521 foreach my $packed_file (@packed_files) {
522 my $destination;
523
524 # Splitt the packed file into chunks.
525 my $file = fileparse($packed_file);
526
527 # Handle msg-id.map file.
528 if ("$file" eq "sid-msg.map") {
529 # Set extract destination to temporary config_dir.
530 $destination = "$tmp_conf_directory/$provider\-sid-msg.map";
531
532 # Handle classification.conf
533 } elsif ("$file" eq "classification.config") {
534 # Set extract destination to temporary config_dir.
535 $destination = "$tmp_conf_directory/$provider\-classification.config";
536
537 # Handle rules files.
538 } elsif ($file =~ m/\.rules$/) {
539 my $rulesfilename;
540
541 # Splitt the filename into chunks.
542 my @filename = split("-", $file);
543
544 # Reverse the array.
545 @filename = reverse(@filename);
546
547 # Get the amount of elements in the array.
548 my $elements = @filename;
549
550 # Remove last element of the hash.
551 # It contains the vendor name, which will be replaced.
552 if ($elements >= 3) {
553 # Remove last element from hash.
554 pop(@filename);
555 }
556
557 # Check if the last element of the filename does not
558 # contain the providers name.
559 if ($filename[-1] ne "$provider") {
560 # Add provider name as last element.
561 push(@filename, $provider);
562 }
563
564 # Reverse the array back.
565 @filename = reverse(@filename);
566
567 # Generate the name for the rulesfile.
568 $rulesfilename = join("-", @filename);
569
570 # Set extract destination to temporaray rules_dir.
571 $destination = "$tmp_rules_directory/$rulesfilename";
572 } else {
573 # Skip all other files.
574 next;
575 }
576
577 # Check if the destination file exists.
578 unless(-e "$destination") {
579 # Extract the file to the temporary directory.
580 $tar->extract_file("$packed_file", "$destination");
581 } else {
582 # Load perl module to deal with temporary files.
583 use File::Temp;
584
585 # Generate temporary file name, located in the temporary rules directory and a suffix of ".tmp".
586 my $tmp = File::Temp->new( SUFFIX => ".tmp", DIR => "$tmp_rules_directory", UNLINK => 0 );
587 my $tmpfile = $tmp->filename();
588
589 # Extract the file to the new temporary file name.
590 $tar->extract_file("$packed_file", "$tmpfile");
591
592 # Open the the existing file.
593 open(DESTFILE, ">>", "$destination") or die "Could not open $destination. $!\n";
594 open(TMPFILE, "<", "$tmpfile") or die "Could not open $tmpfile. $!\n";
595
596 # Loop through the content of the temporary file.
597 while (<TMPFILE>) {
598 # Append the content line by line to the destination file.
599 print DESTFILE "$_";
600 }
601
602 # Close the file handles.
603 close(TMPFILE);
604 close(DESTFILE);
605
606 # Remove the temporary file.
607 unlink("$tmpfile");
608 }
609 }
610 }
611 }
612
613 #
614 ## A wrapper function to call the oinkmaster script, setup the rules structues and
615 ## call the functions to merge the additional config files. (classification, sid-msg, etc.).
616 #
617 sub oinkmaster () {
618 # Check if the files in rulesdir have the correct permissions.
619 &_check_rulesdir_permissions();
620
621 # Cleanup the rules directory before filling it with the new rulests.
622 &_cleanup_rulesdir();
623
624 # Get all enabled providers.
625 my @enabled_providers = &get_enabled_providers();
626
627 # Loop through the array of enabled providers.
628 foreach my $provider (@enabled_providers) {
629 # Call the extractruleset function.
630 &extractruleset($provider);
631 }
632
633 # Load perl module to talk to the kernel syslog.
634 use Sys::Syslog qw(:DEFAULT setlogsock);
635
636 # Establish the connection to the syslog service.
637 openlog('oinkmaster', 'cons,pid', 'user');
638
639 # Call oinkmaster to generate ruleset.
640 open(OINKMASTER, "/usr/local/bin/oinkmaster.pl -s -u dir://$tmp_rules_directory -C $settingsdir/oinkmaster.conf -o $rulespath 2>&1 |") or die "Could not execute oinkmaster $!\n";
641
642 # Log output of oinkmaster to syslog.
643 while(<OINKMASTER>) {
644 # The syslog function works best with an array based input,
645 # so generate one before passing the message details to syslog.
646 my @syslog = ("INFO", "$_");
647
648 # Send the log message.
649 syslog(@syslog);
650 }
651
652 # Close the pipe to oinkmaster process.
653 close(OINKMASTER);
654
655 # Close the log handle.
656 closelog();
657
658 # Call function to merge the classification files.
659 &merge_classifications(@enabled_providers);
660
661 # Call function to merge the sid to message mapping files.
662 &merge_sid_msg(@enabled_providers);
663
664 # Cleanup temporary directory.
665 &cleanup_tmp_directory();
666 }
667
668 #
669 ## Function to merge the classifications for a given amount of providers and write them
670 ## to the classifications file.
671 #
672 sub merge_classifications(@) {
673 my @providers = @_;
674
675 # Hash to store all collected classifications.
676 my %classifications = ();
677
678 # Loop through the given array of providers.
679 foreach my $provider (@providers) {
680 # Generate full path to classification file.
681 my $classification_file = "$tmp_conf_directory/$provider\-classification.config";
682
683 # Skip provider if no classification file exists.
684 next unless (-f "$classification_file");
685
686 # Open the classification file.
687 open(CLASSIFICATION, $classification_file) or die "Could not open file $classification_file. $!\n";
688
689 # Loop through the file content.
690 while(<CLASSIFICATION>) {
691 # Parse the file and grab the classification details.
692 if ($_ =~/.*config classification\: (.*)/) {
693 # Split the grabbed details.
694 my ($short_name, $short_desc, $priority) = split("\,", $1);
695
696 # Check if the grabbed classification is allready known and the priority value is greater
697 # than the stored one (which causes less priority in the IDS).
698 if (($classifications{$short_name}) && ($classifications{$short_name}[1] >= $priority)) {
699 #Change the priority value to the stricter one.
700 $classifications{$short_name} = [ "$classifications{$short_name}[0]", "$priority" ];
701 } else {
702 # Add the classification to the hash.
703 $classifications{$short_name} = [ "$short_desc", "$priority" ];
704 }
705 }
706 }
707
708 # Close the file.
709 close(CLASSIFICATION);
710 }
711
712 # Open classification file for writing.
713 open(FILE, ">", "$classification_file") or die "Could not write to $classification_file. $!\n";
714
715 # Print notice about autogenerated file.
716 print FILE "#Autogenerated file. Any custom changes will be overwritten!\n\n";
717
718 # Sort and loop through the hash of classifications.
719 foreach my $key (sort keys %classifications) {
720 # Assign some nice variable names for the items.
721 my $short_name = $key;
722 my $short_desc = $classifications{$key}[0];
723 my $priority = $classifications{$key}[1];
724
725 # Write the classification to the file.
726 print FILE "config classification: $short_name,$short_desc,$priority\n";
727 }
728
729 # Close file handle.
730 close(FILE);
731 }
732
733 #
734 ## Function to merge the "sid to message mapping" files of various given providers.
735 #
736 sub merge_sid_msg (@) {
737 my @providers = @_;
738
739 # Hash which contains all the sid to message mappings.
740 my %mappings = ();
741
742 # Loop through the array of given providers.
743 foreach my $provider (@providers) {
744 # Generate full path and filename.
745 my $sid_msg_file = "$tmp_conf_directory/$provider\-sid-msg.map";
746
747 # Skip provider if no sid to msg mapping file for this provider exists.
748 next unless (-f $sid_msg_file);
749
750 # Open the file.
751 open(MAPPING, $sid_msg_file) or die "Could not open $sid_msg_file. $!\n";
752
753 # Loop through the file content.
754 while (<MAPPING>) {
755 # Remove newlines.
756 chomp($_);
757
758 # Skip lines which do not start with a number,
759 next unless ($_ =~ /^\d+/);
760
761 # Split line content and assign it to an array.
762 my @line = split(/ \|\| /, $_);
763
764 # Grab the first element (and remove it) from the line array.
765 # It contains the sid.
766 my $sid = shift(@line);
767
768 # Store the grabbed sid and the remain array as hash value.
769 # It still contains the messages, references etc.
770 $mappings{$sid} = [@line];
771 }
772
773 # Close file handle.
774 close(MAPPING);
775 }
776
777 # Open mappings file for writing.
778 open(FILE, ">", $sid_msg_file) or die "Could not write $sid_msg_file. $!\n";
779
780 # Write notice about autogenerated file.
781 print FILE "#Autogenerated file. Any custom changes will be overwritten!\n\n";
782
783 # Loop through the hash of mappings.
784 foreach my $sid ( sort keys %mappings) {
785 # Grab data for the sid.
786 my @data = @{$mappings{$sid}};
787
788 # Add the sid to the data array.
789 unshift(@data, $sid);
790
791 # Generate line.
792 my $line = join(" \|\| ", @data);
793
794 print FILE "$line\n";
795
796 }
797
798 # Close file handle.
799 close(FILE);
800 }
801
802 #
803 ## A very tiny function to move an extracted ruleset from the temporary directory into
804 ## the rules directory.
805 #
806 sub move_tmp_ruleset() {
807 # Load perl module.
808 use File::Copy;
809
810 # Do a directory listing of the temporary directory.
811 opendir DH, $tmp_rules_directory;
812
813 # Loop over all files.
814 while(my $file = readdir DH) {
815 # Move them to the rules directory.
816 move "$tmp_rules_directory/$file" , "$rulespath/$file";
817 }
818
819 # Close directory handle.
820 closedir DH;
821 }
822
823 #
824 ## Function to cleanup the temporary IDS directroy.
825 #
826 sub cleanup_tmp_directory () {
827 # Load rmtree() function from file path perl module.
828 use File::Path 'rmtree';
829
830 # Delete temporary directory and all containing files.
831 rmtree([ "$tmp_directory" ]);
832 }
833
834 #
835 ## Function to do all the logging stuff if the downloading or updating of the ruleset fails.
836 #
837 sub log_error ($) {
838 my ($error) = @_;
839
840 # Remove any newline.
841 chomp($error);
842
843 # Call private function to log the error message to syslog.
844 &_log_to_syslog($error);
845
846 # Call private function to write/store the error message in the storederrorfile.
847 &_store_error_message($error);
848 }
849
850 #
851 ## Function to log a given error message to the kernel syslog.
852 #
853 sub _log_to_syslog ($) {
854 my ($message) = @_;
855
856 # Load perl module to talk to the kernel syslog.
857 use Sys::Syslog qw(:DEFAULT setlogsock);
858
859 # The syslog function works best with an array based input,
860 # so generate one before passing the message details to syslog.
861 my @syslog = ("ERR", "<ERROR> $message");
862
863 # Establish the connection to the syslog service.
864 openlog('oinkmaster', 'cons,pid', 'user');
865
866 # Send the log message.
867 syslog(@syslog);
868
869 # Close the log handle.
870 closelog();
871 }
872
873 #
874 ## Private function to write a given error message to the storederror file.
875 #
876 sub _store_error_message ($) {
877 my ($message) = @_;
878
879 # Remove any newline.
880 chomp($message);
881
882 # Open file for writing.
883 open (ERRORFILE, ">$storederrorfile") or die "Could not write to $storederrorfile. $!\n";
884
885 # Write error to file.
886 print ERRORFILE "$message\n";
887
888 # Close file.
889 close (ERRORFILE);
890
891 # Set correct ownership for the file.
892 &set_ownership("$storederrorfile");
893 }
894
895 #
896 ## Private function to get the path and filename for a downloaded ruleset by a given provider.
897 #
898 sub _get_dl_rulesfile($) {
899 my ($provider) = @_;
900
901 # Gather the download type for the given provider.
902 my $dl_type = $IDS::Ruleset::Providers{$provider}{'dl_type'};
903
904 # Obtain the file suffix for the download file type.
905 my $suffix = $dl_type_to_suffix{$dl_type};
906
907 # Check if a suffix has been found.
908 unless ($suffix) {
909 # Abort return - nothing.
910 return;
911 }
912
913 # Generate the full filename and path for the stored rules file.
914 my $rulesfile = "$dl_rules_path/$dl_rulesfile_prefix-$provider$suffix";
915
916 # Return the generated filename.
917 return $rulesfile;
918 }
919
920 #
921 ## Tiny function to delete the stored ruleset file or tarball for a given provider.
922 #
923 sub drop_dl_rulesfile ($) {
924 my ($provider) = @_;
925
926 # Gather the full path and name of the stored rulesfile.
927 my $rulesfile = &_get_dl_rulesfile($provider);
928
929 # Check if the given rulesfile exists.
930 if (-f $rulesfile) {
931 # Delete the stored rulesfile.
932 unlink($rulesfile) or die "Could not delete $rulesfile. $!\n";
933 }
934 }
935
936 #
937 ## Tiny function to get/generate the full path and filename for the providers oinkmaster
938 ## modified sids file.
939 #
940 sub get_oinkmaster_provider_modified_sids_file ($) {
941 my ($provider) = @_;
942
943 # Generate the filename.
944 my $filename = "$settingsdir/oinkmaster-$provider-modified-sids.conf";
945
946 # Return the filename.
947 return $filename;
948 }
949
950 #
951 ## Function to directly altering the oinkmaster provider includes file.
952 ##
953 ## Requires tha acition "remove" or "add" and a provider handle.
954 #
955 sub alter_oinkmaster_provider_includes_file ($$) {
956 my ($action, $provider) = @_;
957
958 # Call function to get the path and name for the given providers
959 # oinkmaster modified sids file.
960 my $provider_modified_sids_file = &get_oinkmaster_provider_modified_sids_file($provider);
961
962 # Open the file for reading..
963 open (FILE, $oinkmaster_provider_includes_file) or die "Could not read $oinkmaster_provider_includes_file. $!\n";
964
965 # Read-in file content.
966 my @lines = <FILE>;
967
968 # Close file after reading.
969 close(FILE);
970
971 # Re-open the file for writing.
972 open(FILE, ">", $oinkmaster_provider_includes_file) or die "Could not write to $oinkmaster_provider_includes_file. $!\n";
973
974 # Loop through the file content.
975 foreach my $line (@lines) {
976 # Remove newlines.
977 chomp($line);
978
979 # Skip line if we found our given provider and the action should be remove.
980 next if (($line =~ /$provider/) && ($action eq "remove"));
981
982 # Write the read-in line back to the file.
983 print FILE "$line\n";
984 }
985
986 # Check if the file exists and add the provider if requested.
987 if ((-f $provider_modified_sids_file) && ($action eq "add")) {
988 print FILE "include $provider_modified_sids_file\n";
989 }
990
991 # Close file handle.
992 close(FILE);
993 }
994
995 #
996 ## Function to read-in the given enabled or disables sids file.
997 #
998 sub read_enabled_disabled_sids_file($) {
999 my ($file) = @_;
1000
1001 # Temporary hash to store the sids and their state. It will be
1002 # returned at the end of this function.
1003 my %temphash;
1004
1005 # Open the given filename.
1006 open(FILE, "$file") or die "Could not open $file. $!\n";
1007
1008 # Loop through the file.
1009 while(<FILE>) {
1010 # Remove newlines.
1011 chomp $_;
1012
1013 # Skip blank lines.
1014 next if ($_ =~ /^\s*$/);
1015
1016 # Skip coments.
1017 next if ($_ =~ /^\#/);
1018
1019 # Splitt line into sid and state part.
1020 my ($state, $sid) = split(" ", $_);
1021
1022 # Skip line if the sid is not numeric.
1023 next unless ($sid =~ /\d+/ );
1024
1025 # Check if the sid was enabled.
1026 if ($state eq "enablesid") {
1027 # Add the sid and its state as enabled to the temporary hash.
1028 $temphash{$sid} = "enabled";
1029 # Check if the sid was disabled.
1030 } elsif ($state eq "disablesid") {
1031 # Add the sid and its state as disabled to the temporary hash.
1032 $temphash{$sid} = "disabled";
1033 # Invalid state - skip the current sid and state.
1034 } else {
1035 next;
1036 }
1037 }
1038
1039 # Close filehandle.
1040 close(FILE);
1041
1042 # Return the hash.
1043 return %temphash;
1044 }
1045
1046 #
1047 ## Function to check if the IDS is running.
1048 #
1049 sub ids_is_running () {
1050 if(-f $idspidfile) {
1051 # Open PID file for reading.
1052 open(PIDFILE, "$idspidfile") or die "Could not open $idspidfile. $!\n";
1053
1054 # Grab the process-id.
1055 my $pid = <PIDFILE>;
1056
1057 # Close filehandle.
1058 close(PIDFILE);
1059
1060 # Remove any newline.
1061 chomp($pid);
1062
1063 # Check if a directory for the process-id exists in proc.
1064 if(-d "/proc/$pid") {
1065 # The IDS daemon is running return the process id.
1066 return $pid;
1067 }
1068 }
1069
1070 # Return nothing - IDS is not running.
1071 return;
1072 }
1073
1074 #
1075 ## Function to call suricatactrl binary with a given command.
1076 #
1077 sub call_suricatactrl ($) {
1078 # Get called option.
1079 my ($option, $interval) = @_;
1080
1081 # Loop through the array of supported commands and check if
1082 # the given one is part of it.
1083 foreach my $cmd (@suricatactrl_cmds) {
1084 # Skip current command unless the given one has been found.
1085 next unless($cmd eq $option);
1086
1087 # Check if the given command is "cron".
1088 if ($option eq "cron") {
1089 # Check if an interval has been given.
1090 if ($interval) {
1091 # Check if the given interval is valid.
1092 foreach my $element (@cron_intervals) {
1093 # Skip current element until the given one has been found.
1094 next unless($element eq $interval);
1095
1096 # Call the suricatactrl binary and pass the "cron" command
1097 # with the requrested interval.
1098 &General::system("$suricatactrl", "$option", "$interval");
1099
1100 # Return "1" - True.
1101 return 1;
1102 }
1103 }
1104
1105 # If we got here, the given interval is not supported or none has been given. - Return nothing.
1106 return;
1107 } else {
1108 # Call the suricatactrl binary and pass the requrested
1109 # option to it.
1110 &General::system("$suricatactrl", "$option");
1111
1112 # Return "1" - True.
1113 return 1;
1114 }
1115 }
1116
1117 # Command not found - return nothing.
1118 return;
1119 }
1120
1121 #
1122 ## Function to create a new empty file.
1123 #
1124 sub create_empty_file($) {
1125 my ($file) = @_;
1126
1127 # Check if the given file exists.
1128 if(-e $file) {
1129 # Do nothing to prevent from overwriting existing files.
1130 return;
1131 }
1132
1133 # Open the file for writing.
1134 open(FILE, ">$file") or die "Could not write to $file. $!\n";
1135
1136 # Close file handle.
1137 close(FILE);
1138
1139 # Return true.
1140 return 1;
1141 }
1142
1143 #
1144 ## Private function to check if the file permission of the rulespath are correct.
1145 ## If not, call suricatactrl to fix them.
1146 #
1147 sub _check_rulesdir_permissions() {
1148 # Check if the rulepath main directory is writable.
1149 unless (-W $rulespath) {
1150 # If not call suricatctrl to fix it.
1151 &call_suricatactrl("fix-rules-dir");
1152 }
1153
1154 # Open snort rules directory and do a directory listing.
1155 opendir(DIR, $rulespath) or die $!;
1156 # Loop through the direcory.
1157 while (my $file = readdir(DIR)) {
1158 # We only want files.
1159 next unless (-f "$rulespath/$file");
1160
1161 # Check if the file is writable by the user.
1162 if (-W "$rulespath/$file") {
1163 # Everything is okay - go on to the next file.
1164 next;
1165 } else {
1166 # There are wrong permissions, call suricatactrl to fix it.
1167 &call_suricatactrl("fix-rules-dir");
1168 }
1169 }
1170 }
1171
1172 #
1173 ## Private function to cleanup the directory which contains
1174 ## the IDS rules, before extracting and modifing the new ruleset.
1175 #
1176 sub _cleanup_rulesdir() {
1177 # Open rules directory and do a directory listing.
1178 opendir(DIR, $rulespath) or die $!;
1179
1180 # Loop through the direcory.
1181 while (my $file = readdir(DIR)) {
1182 # We only want files.
1183 next unless (-f "$rulespath/$file");
1184
1185 # Skip rules file for whitelisted hosts.
1186 next if ("$rulespath/$file" eq $whitelist_file);
1187
1188 # Skip rules file with local rules.
1189 next if ("$rulespath/$file" eq $local_rules_file);
1190
1191 # Delete the current processed file, if not, exit this function
1192 # and return an error message.
1193 unlink("$rulespath/$file") or return "Could not delete $rulespath/$file. $!\n";
1194 }
1195
1196 # Return nothing;
1197 return;
1198 }
1199
1200 #
1201 ## Function to generate the file which contains the home net information.
1202 #
1203 sub generate_home_net_file() {
1204 my %netsettings;
1205
1206 # Read-in network settings.
1207 &General::readhash("${General::swroot}/ethernet/settings", \%netsettings);
1208
1209 # Get available network zones.
1210 my @network_zones = &Network::get_available_network_zones();
1211
1212 # Temporary array to store network address and prefix of the configured
1213 # networks.
1214 my @networks;
1215
1216 # Loop through the array of available network zones.
1217 foreach my $zone (@network_zones) {
1218 # Check if the current processed zone is red.
1219 if($zone eq "red") {
1220 # Grab the IP-address of the red interface.
1221 my $red_address = &get_red_address();
1222
1223 # Check if an address has been obtained.
1224 if ($red_address) {
1225 # Generate full network string.
1226 my $red_network = join("/", $red_address, "32");
1227
1228 # Add the red network to the array of networks.
1229 push(@networks, $red_network);
1230 }
1231
1232 # Check if the configured RED_TYPE is static.
1233 if ($netsettings{'RED_TYPE'} eq "STATIC") {
1234 # Get configured and enabled aliases.
1235 my @aliases = &get_aliases();
1236
1237 # Loop through the array.
1238 foreach my $alias (@aliases) {
1239 # Add "/32" prefix.
1240 my $network = join("/", $alias, "32");
1241
1242 # Add the generated network to the array of networks.
1243 push(@networks, $network);
1244 }
1245 }
1246 # Process remaining network zones.
1247 } else {
1248 # Convert current zone name into upper case.
1249 $zone = uc($zone);
1250
1251 # Generate key to access the required data from the netsettings hash.
1252 my $zone_netaddress = $zone . "_NETADDRESS";
1253 my $zone_netmask = $zone . "_NETMASK";
1254
1255 # Obtain the settings from the netsettings hash.
1256 my $netaddress = $netsettings{$zone_netaddress};
1257 my $netmask = $netsettings{$zone_netmask};
1258
1259 # Convert the subnetmask into prefix notation.
1260 my $prefix = &Network::convert_netmask2prefix($netmask);
1261
1262 # Generate full network string.
1263 my $network = join("/", $netaddress,$prefix);
1264
1265 # Check if the network is valid.
1266 if(&Network::check_subnet($network)) {
1267 # Add the generated network to the array of networks.
1268 push(@networks, $network);
1269 }
1270 }
1271 }
1272
1273 # Format home net declaration.
1274 my $line = "\"[" . join(',', @networks) . "]\"";
1275
1276 # Open file to store the addresses of the home net.
1277 open(FILE, ">$homenet_file") or die "Could not open $homenet_file. $!\n";
1278
1279 # Print yaml header.
1280 print FILE "%YAML 1.1\n";
1281 print FILE "---\n\n";
1282
1283 # Print notice about autogenerated file.
1284 print FILE "#Autogenerated file. Any custom changes will be overwritten!\n";
1285
1286 # Print the generated and required HOME_NET declaration to the file.
1287 print FILE "HOME_NET:\t$line\n";
1288
1289 # Close file handle.
1290 close(FILE);
1291 }
1292
1293 #
1294 # Function to generate and write the file which contains the configured and used DNS servers.
1295 #
1296 sub generate_dns_servers_file() {
1297 # Get the used DNS servers.
1298 my @nameservers = &General::get_nameservers();
1299
1300 # Get network settings.
1301 my %netsettings;
1302 &General::readhash("${General::swroot}/ethernet/settings", \%netsettings);
1303
1304 # Format dns servers declaration.
1305 my $line = "";
1306
1307 # Check if the system has configured nameservers.
1308 if (@nameservers) {
1309 # Add the GREEN address as DNS servers.
1310 push(@nameservers, $netsettings{'GREEN_ADDRESS'});
1311
1312 # Check if a BLUE zone exists.
1313 if ($netsettings{'BLUE_ADDRESS'}) {
1314 # Add the BLUE address to the array of nameservers.
1315 push(@nameservers, $netsettings{'BLUE_ADDRESS'});
1316 }
1317
1318 # Generate the line which will be written to the DNS servers file.
1319 $line = join(",", @nameservers);
1320 } else {
1321 # External net simply contains (any).
1322 $line = "\$EXTERNAL_NET";
1323 }
1324
1325 # Open file to store the used DNS server addresses.
1326 open(FILE, ">$dns_servers_file") or die "Could not open $dns_servers_file. $!\n";
1327
1328 # Print yaml header.
1329 print FILE "%YAML 1.1\n";
1330 print FILE "---\n\n";
1331
1332 # Print notice about autogenerated file.
1333 print FILE "#Autogenerated file. Any custom changes will be overwritten!\n";
1334
1335 # Print the generated DNS declaration to the file.
1336 print FILE "DNS_SERVERS:\t\"[$line]\"\n";
1337
1338 # Close file handle.
1339 close(FILE);
1340 }
1341
1342 #
1343 # Function to generate and write the file which contains the HTTP_PORTS definition.
1344 #
1345 sub generate_http_ports_file() {
1346 my %proxysettings;
1347
1348 # Read-in proxy settings
1349 &General::readhash("${General::swroot}/proxy/advanced/settings", \%proxysettings);
1350
1351 # Check if the proxy is enabled.
1352 if (( -e "${General::swroot}/proxy/enable") || (-e "${General::swroot}/proxy/enable_blue")) {
1353 # Add the proxy port to the array of HTTP ports.
1354 push(@http_ports, $proxysettings{'PROXY_PORT'});
1355 }
1356
1357 # Check if the transparent mode of the proxy is enabled.
1358 if ((-e "${General::swroot}/proxy/transparent") || (-e "${General::swroot}/proxy/transparent_blue")) {
1359 # Add the transparent proxy port to the array of HTTP ports.
1360 push(@http_ports, $proxysettings{'TRANSPARENT_PORT'});
1361 }
1362
1363 # Format HTTP_PORTS declaration.
1364 my $line = "";
1365
1366 # Generate line which will be written to the http ports file.
1367 $line = join(",", @http_ports);
1368
1369 # Open file to store the HTTP_PORTS.
1370 open(FILE, ">$http_ports_file") or die "Could not open $http_ports_file. $!\n";
1371
1372 # Print yaml header.
1373 print FILE "%YAML 1.1\n";
1374 print FILE "---\n\n";
1375
1376 # Print notice about autogenerated file.
1377 print FILE "#Autogenerated file. Any custom changes will be overwritten!\n";
1378
1379 # Print the generated HTTP_PORTS declaration to the file.
1380 print FILE "HTTP_PORTS:\t\"[$line]\"\n";
1381
1382 # Close file handle.
1383 close(FILE);
1384 }
1385
1386 #
1387 ## Function to generate and write the file for used rulefiles file for a given provider.
1388 ##
1389 ## The function requires as first argument a provider handle, and as second an array with files.
1390 #
1391 sub write_used_provider_rulefiles_file($@) {
1392 my ($provider, @files) = @_;
1393
1394 # Get the path and file for the provider specific used rulefiles file.
1395 my $used_provider_rulesfile_file = &get_used_provider_rulesfile_file($provider);
1396
1397 # Open file for used rulefiles.
1398 open (FILE, ">", "$used_provider_rulesfile_file") or die "Could not write to $used_provider_rulesfile_file. $!\n";
1399
1400 # Write yaml header to the file.
1401 print FILE "%YAML 1.1\n";
1402 print FILE "---\n\n";
1403
1404 # Write header to file.
1405 print FILE "#Autogenerated file. Any custom changes will be overwritten!\n";
1406
1407 # Loop through the array of given files.
1408 foreach my $file (@files) {
1409 # Check if the given filename exists and write it to the file of used rulefiles.
1410 if(-f "$rulespath/$file") {
1411 print FILE " - $file\n";
1412 }
1413 }
1414
1415 # Close file after writing.
1416 close(FILE);
1417 }
1418
1419 #
1420 ## Function to write the main file for provider rulesfiles inclusions.
1421 ##
1422 ## This function requires an array of provider handles.
1423 #
1424 sub write_main_used_rulefiles_file (@) {
1425 my (@providers) = @_;
1426
1427 # Call function to write the static rulefiles file.
1428 &_write_default_rulefiles_file();
1429
1430 # Open file for used rulefils inclusion.
1431 open (FILE, ">", "$suricata_used_providers_file") or die "Could not write to $suricata_used_providers_file. $!\n";
1432
1433 # Write yaml header to the file.
1434 print FILE "%YAML 1.1\n";
1435 print FILE "---\n\n";
1436
1437 # Write header to file.
1438 print FILE "#Autogenerated file. Any custom changes will be overwritten!\n";
1439
1440 # Loop through the list of given providers.
1441 foreach my $provider (@providers) {
1442 # Call function to get the providers used rulefiles file.
1443 my $filename = &get_used_provider_rulesfile_file($provider);
1444
1445 # Check if the file exists and write it into the used rulefiles file.
1446 if (-f $filename) {
1447 # Print the provider to the file.
1448 print FILE "include\: $filename\n";
1449 }
1450 }
1451
1452 # Close the filehandle after writing.
1453 close(FILE);
1454 }
1455
1456 sub _write_default_rulefiles_file () {
1457 # Get enabled application layer protocols.
1458 my @enabled_app_layer_protos = &get_suricata_enabled_app_layer_protos();
1459
1460 # Open file.
1461 open (FILE, ">", $suricata_default_rulefiles_file) or die "Could not write to $suricata_default_rulefiles_file. $!\n";
1462
1463 # Write yaml header to the file.
1464 print FILE "%YAML 1.1\n";
1465 print FILE "---\n\n";
1466
1467 # Write notice about autogenerated file.
1468 print FILE "#Autogenerated file. Any custom changes will be overwritten!\n";
1469
1470 # Loop through the array of static included rulesfiles.
1471 foreach my $file (@static_included_rulefiles) {
1472 # Check if the file exists.
1473 if (-f "$rulespath/$file") {
1474 # Write the rulesfile name to the file.
1475 print FILE " - $rulespath/$file\n";
1476 }
1477 }
1478
1479 print FILE "\n#Default rules for used application layer protocols.\n";
1480 foreach my $enabled_app_layer_proto (@enabled_app_layer_protos) {
1481 # Check if the current processed app layer proto needs to be translated
1482 # into an application name.
1483 if (exists($tr_app_layer_proto{$enabled_app_layer_proto})) {
1484 # Obtain the translated application name for this protocol.
1485 $enabled_app_layer_proto = $tr_app_layer_proto{$enabled_app_layer_proto};
1486 }
1487
1488 # Generate filename.
1489 my $rulesfile = "$default_rulespath/$enabled_app_layer_proto\.rules";
1490
1491 # Check if such a file exists.
1492 if (-f "$rulesfile") {
1493 # Write the rulesfile name to the file.
1494 print FILE " - $rulesfile\n";
1495 }
1496
1497 # Generate filename with "events" in filename.
1498 $rulesfile = "$default_rulespath/$enabled_app_layer_proto\-events.rules";
1499
1500 # Check if this file exists.
1501 if (-f "$rulesfile" ) {
1502 # Write the rulesfile name to the file.
1503 print FILE " - $rulesfile\n";
1504 }
1505 }
1506
1507 # Close the file handle
1508 close(FILE);
1509 }
1510
1511 #
1512 ## Tiny function to generate the full path and name for the used_provider_rulesfile file of a given provider.
1513 #
1514 sub get_used_provider_rulesfile_file ($) {
1515 my ($provider) = @_;
1516
1517 my $filename = "$settingsdir/suricata\-$provider\-used\-rulefiles.yaml";
1518
1519 # Return the gernerated file.
1520 return $filename;
1521 }
1522
1523 #
1524 ## Function to generate and write the file for modify the ruleset.
1525 #
1526 sub write_modify_sids_file() {
1527 # Get configured settings.
1528 my %idssettings=();
1529 &General::readhash("$ids_settings_file", \%idssettings);
1530
1531 # Open modify sid's file for writing.
1532 open(FILE, ">$modify_sids_file") or die "Could not write to $modify_sids_file. $!\n";
1533
1534 # Write file header.
1535 print FILE "#Autogenerated file. Any custom changes will be overwritten!\n";
1536
1537 # Check if the traffic only should be monitored.
1538 unless($idssettings{'MONITOR_TRAFFIC_ONLY'} eq 'on') {
1539 # Suricata is in IPS mode, which means that the rule actions have to be changed
1540 # from 'alert' to 'drop', however not all rules should be changed. Some rules
1541 # exist purely to set a flowbit which is used to convey other information, such
1542 # as a specific type of file being downloaded, to other rulewhich then check for
1543 # malware in that file. Rules which fall into the first category should stay as
1544 # alert since not all flows of that type contain malware.
1545
1546 # These types of rulesfiles contain meta-data which gives the action that should
1547 # be used when in IPS mode. Do the following:
1548 #
1549 # 1. Disable all rules and set the action to 'drop'
1550 # 2. Set the action back to 'alert' if the rule contains 'flowbits:noalert;'
1551 # This should give rules not in the policy a reasonable default if the user
1552 # manually enables them.
1553 # 3. Enable rules and set actions according to the meta-data strings.
1554
1555 my $policy = 'balanced'; # Placeholder to allow policy to be changed.
1556
1557 print FILE <<END;
1558 modifysid * "^#(?:alert|drop)(.+policy $policy-ips alert)" | "alert\${1}"
1559 modifysid * "^#(?:alert|drop)(.+policy $policy-ips drop)" | "drop\${1}"
1560 modifysid * "^(#?)(?:alert|drop)" | "\${1}drop"
1561 modifysid * "^(#?)drop(.+flowbits:noalert;)" | "\${1}alert\${2}"
1562 END
1563 }
1564
1565 # Close file handle.
1566 close(FILE);
1567 }
1568
1569 #
1570 ## Function to get the ruleset date for a given provider.
1571 ##
1572 ## The function simply return the creation date in a human read-able format
1573 ## of the stored providers rulesfile.
1574 #
1575 sub get_ruleset_date($) {
1576 my ($provider) = @_;
1577 my $date;
1578 my $mtime;
1579
1580 # Load neccessary perl modules for file stat and to format the timestamp.
1581 use File::stat;
1582 use POSIX qw( strftime );
1583
1584 # Get the stored rulesfile for this provider.
1585 my $stored_rulesfile = &_get_dl_rulesfile($provider);
1586
1587 # Check if we got a file.
1588 if (-f $stored_rulesfile) {
1589 # Call stat on the rulestarball.
1590 my $stat = stat("$stored_rulesfile");
1591
1592 # Get timestamp the file creation.
1593 $mtime = $stat->mtime;
1594 }
1595
1596 # Check if the timestamp has not been grabbed.
1597 unless ($mtime) {
1598 # Return N/A for Not available.
1599 return "N/A";
1600 }
1601
1602 # Convert into human read-able format.
1603 $date = strftime('%Y-%m-%d %H:%M:%S', localtime($mtime));
1604
1605 # Return the date.
1606 return $date;
1607 }
1608
1609 #
1610 ## Function to gather the version of suricata.
1611 #
1612 sub get_suricata_version($) {
1613 my ($format) = @_;
1614
1615 # Execute piped suricata command and return the version information.
1616 open(SURICATA, "suricata -V |") or die "Couldn't execute program: $!";
1617
1618 # Grab and store the output of the piped program.
1619 my $version_string = <SURICATA>;
1620
1621 # Close pipe.
1622 close(SURICATA);
1623
1624 # Remove newlines.
1625 chomp($version_string);
1626
1627 # Grab the version from the version string.
1628 $version_string =~ /([0-9]+([.][0-9]+)+)/;
1629
1630 # Splitt the version into single chunks.
1631 my ($major_ver, $minor_ver, $patchlevel) = split(/\./, $1);
1632
1633 # Check and return the requested version sheme.
1634 if ($format eq "major") {
1635 # Return the full version.
1636 return "$major_ver";
1637 } elsif ($format eq "minor") {
1638 # Return the major and minor part.
1639 return "$major_ver.$minor_ver";
1640 } else {
1641 # Return the full version string.
1642 return "$major_ver.$minor_ver.$patchlevel";
1643 }
1644 }
1645
1646 #
1647 ## Function to get the enabled application layer protocols.
1648 #
1649 sub get_suricata_enabled_app_layer_protos() {
1650 # Array to store and return the enabled app layer protos.
1651 my @enabled_app_layer_protos = ();
1652
1653 # Execute piped suricata command and return the list of
1654 # enabled application layer protocols.
1655 open(SURICATA, "suricata --list-app-layer-protos |") or die "Could not execute program: $!";
1656
1657 # Grab and store the list of enabled application layer protocols.
1658 my @output = <SURICATA>;
1659
1660 # Close pipe.
1661 close(SURICATA);
1662
1663 # Merge allways enabled static application layers protocols array.
1664 @enabled_app_layer_protos = @static_enabled_app_layer_protos;
1665
1666 # Loop through the array which contains the output of suricata.
1667 foreach my $line (@output) {
1668 # Skip header line which starts with "===".
1669 next if ($line =~ /^\s*=/);
1670
1671 # Skip info or warning lines.
1672 next if ($line =~ /\s*--/);
1673
1674 # Remove newlines.
1675 chomp($line);
1676
1677 # Add enabled app layer proto to the array.
1678 push(@enabled_app_layer_protos, $line);
1679 }
1680
1681 # Sort the array.
1682 @enabled_app_layer_protos = sort(@enabled_app_layer_protos);
1683
1684 # Return the array.
1685 return @enabled_app_layer_protos;
1686 }
1687
1688 #
1689 ## Function to generate the rules file with whitelisted addresses.
1690 #
1691 sub generate_ignore_file() {
1692 my %ignored = ();
1693
1694 # SID range 1000000-1999999 Reserved for Local Use
1695 # Put your custom rules in this range to avoid conflicts
1696 my $sid = 1500000;
1697
1698 # Read-in ignoredfile.
1699 &General::readhasharray($IDS::ignored_file, \%ignored);
1700
1701 # Open ignorefile for writing.
1702 open(FILE, ">$IDS::whitelist_file") or die "Could not write to $IDS::whitelist_file. $!\n";
1703
1704 # Config file header.
1705 print FILE "# Autogenerated file.\n";
1706 print FILE "# All user modifications will be overwritten.\n\n";
1707
1708 # Add all user defined addresses to the whitelist.
1709 #
1710 # Check if the hash contains any elements.
1711 if (keys (%ignored)) {
1712 # Loop through the entire hash and write the host/network
1713 # and remark to the ignore file.
1714 while ( (my $key) = each %ignored) {
1715 my $address = $ignored{$key}[0];
1716 my $remark = $ignored{$key}[1];
1717 my $status = $ignored{$key}[2];
1718
1719 # Check if the status of the entry is "enabled".
1720 if ($status eq "enabled") {
1721 # Check if the address/network is valid.
1722 if ((&General::validip($address)) || (&General::validipandmask($address))) {
1723 # Write rule line to the file to pass any traffic from this IP
1724 print FILE "pass ip $address any -> any any (msg:\"pass all traffic from/to $address\"\; bypass; sid:$sid\;)\n";
1725
1726 # Increment sid.
1727 $sid++;
1728 }
1729 }
1730 }
1731 }
1732
1733 close(FILE);
1734 }
1735
1736 #
1737 ## Function to set correct ownership for single files and directories.
1738 #
1739
1740 sub set_ownership($) {
1741 my ($target) = @_;
1742
1743 # User and group of the WUI.
1744 my $uname = "nobody";
1745 my $grname = "nobody";
1746
1747 # The chown function implemented in perl requies the user and group as nummeric id's.
1748 my $uid = getpwnam($uname);
1749 my $gid = getgrnam($grname);
1750
1751 # Check if the given target exists.
1752 unless ($target) {
1753 # Stop the script and print error message.
1754 die "The $target does not exist. Cannot change the ownership!\n";
1755 }
1756
1757 # Check weather the target is a file or directory.
1758 if (-f $target) {
1759 # Change ownership ot the single file.
1760 chown($uid, $gid, "$target");
1761 } elsif (-d $target) {
1762 # Do a directory listing.
1763 opendir(DIR, $target) or die $!;
1764 # Loop through the direcory.
1765 while (my $file = readdir(DIR)) {
1766
1767 # We only want files.
1768 next unless (-f "$target/$file");
1769
1770 # Set correct ownership for the files.
1771 chown($uid, $gid, "$target/$file");
1772 }
1773
1774 closedir(DIR);
1775
1776 # Change ownership of the directory.
1777 chown($uid, $gid, "$target");
1778 }
1779 }
1780
1781 #
1782 ## Function to read-in the aliases file and returns all configured and enabled aliases.
1783 #
1784 sub get_aliases() {
1785 # Location of the aliases file.
1786 my $aliases_file = "${General::swroot}/ethernet/aliases";
1787
1788 # Array to store the aliases.
1789 my @aliases;
1790
1791 # Check if the file is empty.
1792 if (-z $aliases_file) {
1793 # Abort nothing to do.
1794 return;
1795 }
1796
1797 # Open the aliases file.
1798 open(ALIASES, $aliases_file) or die "Could not open $aliases_file. $!\n";
1799
1800 # Loop through the file content.
1801 while (my $line = <ALIASES>) {
1802 # Remove newlines.
1803 chomp($line);
1804
1805 # Splitt line content into single chunks.
1806 my ($address, $state, $remark) = split(/\,/, $line);
1807
1808 # Check if the state of the current processed alias is "on".
1809 if ($state eq "on") {
1810 # Check if the address is valid.
1811 if(&Network::check_ip_address($address)) {
1812 # Add the alias to the array of aliases.
1813 push(@aliases, $address);
1814 }
1815 }
1816 }
1817
1818 # Close file handle.
1819 close(ALIASES);
1820
1821 # Return the array.
1822 return @aliases;
1823 }
1824
1825 #
1826 ## Function to grab the current assigned IP-address on red.
1827 #
1828 sub get_red_address() {
1829 # File, which contains the current IP-address of the red interface.
1830 my $file = "${General::swroot}/red/local-ipaddress";
1831
1832 # Check if the file exists.
1833 if (-e $file) {
1834 # Open the given file.
1835 open(FILE, "$file") or die "Could not open $file.";
1836
1837 # Obtain the address from the first line of the file.
1838 my $address = <FILE>;
1839
1840 # Close filehandle
1841 close(FILE);
1842
1843 # Remove newlines.
1844 chomp $address;
1845
1846 # Check if the grabbed address is valid.
1847 if (&General::validip($address)) {
1848 # Return the address.
1849 return $address;
1850 }
1851 }
1852
1853 # Return nothing.
1854 return;
1855 }
1856
1857 #
1858 ## Function to get the used rules files of a given provider.
1859 #
1860 sub read_used_provider_rulesfiles($) {
1861 my ($provider) = @_;
1862
1863 # Array to store the used rulefiles.
1864 my @used_rulesfiles = ();
1865
1866 # Get the used rulesefile file for the provider.
1867 my $rulesfile_file = &get_used_provider_rulesfile_file($provider);
1868
1869 # Check if the a used rulesfile exists for this provider.
1870 if (-f $rulesfile_file) {
1871 # Open the file or used rulefiles and read-in content.
1872 open(FILE, $rulesfile_file) or die "Could not open $rulesfile_file. $!\n";
1873
1874 while (<FILE>) {
1875 # Assign the current line to a nice variable.
1876 my $line = $_;
1877
1878 # Remove newlines.
1879 chomp($line);
1880
1881 # Skip comments.
1882 next if ($line =~ /\#/);
1883
1884 # Skip blank lines.
1885 next if ($line =~ /^\s*$/);
1886
1887 # Gather the rulefile.
1888 if ($line =~ /.*- (.*)/) {
1889 my $rulefile = $1;
1890
1891 # Add the rulefile to the array of used rulesfiles.
1892 push(@used_rulesfiles, $rulefile);
1893 }
1894 }
1895
1896 # Close the file.
1897 close(FILE);
1898 }
1899
1900 # Return the array of used rulesfiles.
1901 return @used_rulesfiles;
1902 }
1903
1904 #
1905 ## Function to write the lock file for locking the WUI, while
1906 ## the autoupdate script runs.
1907 #
1908 sub lock_ids_page() {
1909 # Call subfunction to create the file.
1910 &create_empty_file($ids_page_lock_file);
1911 }
1912
1913 #
1914 ## Function to release the lock of the WUI, again.
1915 #
1916 sub unlock_ids_page() {
1917 # Delete lock file.
1918 unlink($ids_page_lock_file);
1919 }
1920
1921 1;