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