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