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