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