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