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