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