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