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