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