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