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