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