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