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