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