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