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