]> git.ipfire.org Git - people/pmueller/ipfire-2.x.git/blame - config/cfgroot/ids-functions.pl
ids-functions.pl: Fix another typo.
[people/pmueller/ipfire-2.x.git] / config / cfgroot / ids-functions.pl
CommitLineData
8dcebe53
SS
1#!/usr/bin/perl -w
2############################################################################
3# #
4# This file is part of the IPFire Firewall. #
5# #
6# IPFire is free software; you can redistribute it and/or modify #
7# it under the terms of the GNU General Public License as published by #
8# the Free Software Foundation; either version 2 of the License, or #
9# (at your option) any later version. #
10# #
11# IPFire is distributed in the hope that it will be useful, #
12# but WITHOUT ANY WARRANTY; without even the implied warranty of #
13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
14# GNU General Public License for more details. #
15# #
16# You should have received a copy of the GNU General Public License #
17# along with IPFire; if not, write to the Free Software #
18# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #
19# #
fd2dccaa 20# Copyright (C) 2018-2019 IPFire Team <info@ipfire.org> #
8dcebe53
SS
21# #
22############################################################################
23
e55fa2f7
SS
24use strict;
25
8dcebe53
SS
26package IDS;
27
28require '/var/ipfire/general-functions.pl';
abffcc99 29require "${General::swroot}/network-functions.pl";
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
16b2d281
SS
754#
755## Function to cleanup the temporary IDS directroy.
756#
757sub cleanup_tmp_directory () {
758 # Load rmtree() function from file path perl module.
759 use File::Path 'rmtree';
760
761 # Delete temporary directory and all containing files.
762 rmtree([ "$tmp_directory" ]);
763}
764
3983aebd
SS
765#
766## Function to do all the logging stuff if the downloading or updating of the ruleset fails.
767#
768sub log_error ($) {
769 my ($error) = @_;
770
771 # Remove any newline.
772 chomp($error);
773
eb5592c1
SS
774 # Call private function to log the error message to syslog.
775 &_log_to_syslog($error);
776
3983aebd
SS
777 # Call private function to write/store the error message in the storederrorfile.
778 &_store_error_message($error);
779}
780
eb5592c1
SS
781#
782## Function to log a given error message to the kernel syslog.
783#
784sub _log_to_syslog ($) {
785 my ($message) = @_;
786
787 # Load perl module to talk to the kernel syslog.
788 use Sys::Syslog qw(:DEFAULT setlogsock);
789
790 # The syslog function works best with an array based input,
791 # so generate one before passing the message details to syslog.
792 my @syslog = ("ERR", "<ERROR> $message");
793
794 # Establish the connection to the syslog service.
795 openlog('oinkmaster', 'cons,pid', 'user');
796
797 # Send the log message.
798 syslog(@syslog);
799
800 # Close the log handle.
801 closelog();
802}
803
3983aebd
SS
804#
805## Private function to write a given error message to the storederror file.
806#
807sub _store_error_message ($) {
808 my ($message) = @_;
809
810 # Remove any newline.
811 chomp($message);
812
813 # Open file for writing.
814 open (ERRORFILE, ">$storederrorfile") or die "Could not write to $storederrorfile. $!\n";
815
816 # Write error to file.
817 print ERRORFILE "$message\n";
818
819 # Close file.
820 close (ERRORFILE);
3c59b1fa
SS
821
822 # Set correct ownership for the file.
823 &set_ownership("$storederrorfile");
3983aebd
SS
824}
825
788a71f5
SS
826#
827## Private function to get the path and filename for a downloaded ruleset by a given provider.
828#
829sub _get_dl_rulesfile($) {
830 my ($provider) = @_;
831
832 # Gather the download type for the given provider.
833 my $dl_type = $IDS::Ruleset::Providers{$provider}{'dl_type'};
834
835 # Obtain the file suffix for the download file type.
836 my $suffix = $dl_type_to_suffix{$dl_type};
837
838 # Check if a suffix has been found.
839 unless ($suffix) {
840 # Abort return - nothing.
841 return;
842 }
843
844 # Generate the full filename and path for the stored rules file.
845 my $rulesfile = "$dl_rules_path/$dl_rulesfile_prefix-$provider$suffix";
846
847 # Return the generated filename.
848 return $rulesfile;
849}
850
61b92664
SS
851#
852## Tiny function to delete the stored ruleset file or tarball for a given provider.
853#
854sub drop_dl_rulesfile ($) {
855 my ($provider) = @_;
856
857 # Gather the full path and name of the stored rulesfile.
858 my $rulesfile = &_get_dl_rulesfile($provider);
859
860 # Check if the given rulesfile exists.
861 if (-f $rulesfile) {
862 # Delete the stored rulesfile.
863 unlink($rulesfile) or die "Could not delete $rulesfile. $!\n";
864 }
865}
866
796eea21
SS
867#
868## Function to check if the IDS is running.
869#
870sub ids_is_running () {
871 if(-f $idspidfile) {
872 # Open PID file for reading.
873 open(PIDFILE, "$idspidfile") or die "Could not open $idspidfile. $!\n";
874
875 # Grab the process-id.
876 my $pid = <PIDFILE>;
877
878 # Close filehandle.
879 close(PIDFILE);
880
881 # Remove any newline.
882 chomp($pid);
883
884 # Check if a directory for the process-id exists in proc.
885 if(-d "/proc/$pid") {
886 # The IDS daemon is running return the process id.
887 return $pid;
888 }
889 }
890
891 # Return nothing - IDS is not running.
892 return;
893}
894
5240a809
SS
895#
896## Function to call suricatactrl binary with a given command.
897#
898sub call_suricatactrl ($) {
899 # Get called option.
ed06bc81 900 my ($option, $interval) = @_;
5240a809
SS
901
902 # Loop through the array of supported commands and check if
903 # the given one is part of it.
904 foreach my $cmd (@suricatactrl_cmds) {
905 # Skip current command unless the given one has been found.
906 next unless($cmd eq $option);
907
ed06bc81
SS
908 # Check if the given command is "cron".
909 if ($option eq "cron") {
910 # Check if an interval has been given.
911 if ($interval) {
912 # Check if the given interval is valid.
913 foreach my $element (@cron_intervals) {
914 # Skip current element until the given one has been found.
915 next unless($element eq $interval);
916
917 # Call the suricatactrl binary and pass the "cron" command
918 # with the requrested interval.
81631920 919 &General::system("$suricatactrl", "$option", "$interval");
ed06bc81
SS
920
921 # Return "1" - True.
922 return 1;
923 }
924 }
5240a809 925
ed06bc81
SS
926 # If we got here, the given interval is not supported or none has been given. - Return nothing.
927 return;
928 } else {
929 # Call the suricatactrl binary and pass the requrested
930 # option to it.
81631920 931 &General::system("$suricatactrl", "$option");
ed06bc81
SS
932
933 # Return "1" - True.
934 return 1;
935 }
5240a809
SS
936 }
937
938 # Command not found - return nothing.
939 return;
940}
941
308ba5e7
SS
942#
943## Function to create a new empty file.
944#
945sub create_empty_file($) {
946 my ($file) = @_;
947
948 # Check if the given file exists.
949 if(-e $file) {
950 # Do nothing to prevent from overwriting existing files.
951 return;
952 }
953
954 # Open the file for writing.
955 open(FILE, ">$file") or die "Could not write to $file. $!\n";
956
957 # Close file handle.
958 close(FILE);
959
960 # Return true.
961 return 1;
962}
963
330759d8
SS
964#
965## Private function to check if the file permission of the rulespath are correct.
966## If not, call suricatactrl to fix them.
967#
968sub _check_rulesdir_permissions() {
e568796b
SS
969 # Check if the rulepath main directory is writable.
970 unless (-W $rulespath) {
971 # If not call suricatctrl to fix it.
972 &call_suricatactrl("fix-rules-dir");
973 }
974
330759d8
SS
975 # Open snort rules directory and do a directory listing.
976 opendir(DIR, $rulespath) or die $!;
977 # Loop through the direcory.
978 while (my $file = readdir(DIR)) {
979 # We only want files.
980 next unless (-f "$rulespath/$file");
981
982 # Check if the file is writable by the user.
983 if (-W "$rulespath/$file") {
984 # Everything is okay - go on to the next file.
985 next;
986 } else {
987 # There are wrong permissions, call suricatactrl to fix it.
988 &call_suricatactrl("fix-rules-dir");
989 }
990 }
991}
992
b59cdbee
SS
993#
994## Private function to cleanup the directory which contains
995## the IDS rules, before extracting and modifing the new ruleset.
996#
997sub _cleanup_rulesdir() {
8cf04a16
SS
998 # Open rules directory and do a directory listing.
999 opendir(DIR, $rulespath) or die $!;
1000
1001 # Loop through the direcory.
1002 while (my $file = readdir(DIR)) {
1003 # We only want files.
1004 next unless (-f "$rulespath/$file");
1005
fefb5173
SS
1006 # Skip rules file for whitelisted hosts.
1007 next if ("$rulespath/$file" eq $whitelist_file);
1008
612bb2df
SS
1009 # Skip rules file with local rules.
1010 next if ("$rulespath/$file" eq $local_rules_file);
1011
8cf04a16 1012 # Delete the current processed file, if not, exit this function
b59cdbee 1013 # and return an error message.
1201c1e7 1014 unlink("$rulespath/$file") or return "Could not delete $rulespath/$file. $!\n";
b59cdbee
SS
1015 }
1016
4ce42488 1017 # Return nothing;
b59cdbee
SS
1018 return;
1019}
1020
b02e30fd
SS
1021#
1022## Function to generate the file which contains the home net information.
1023#
1024sub generate_home_net_file() {
1025 my %netsettings;
1026
1027 # Read-in network settings.
1028 &General::readhash("${General::swroot}/ethernet/settings", \%netsettings);
1029
1030 # Get available network zones.
abffcc99 1031 my @network_zones = &Network::get_available_network_zones();
b02e30fd
SS
1032
1033 # Temporary array to store network address and prefix of the configured
1034 # networks.
1035 my @networks;
1036
1037 # Loop through the array of available network zones.
1038 foreach my $zone (@network_zones) {
bcbc9897
SS
1039 # Check if the current processed zone is red.
1040 if($zone eq "red") {
1041 # Grab the IP-address of the red interface.
1042 my $red_address = &get_red_address();
b02e30fd 1043
bcbc9897
SS
1044 # Check if an address has been obtained.
1045 if ($red_address) {
1046 # Generate full network string.
1047 my $red_network = join("/", $red_address, "32");
b02e30fd 1048
bcbc9897
SS
1049 # Add the red network to the array of networks.
1050 push(@networks, $red_network);
1051 }
23c0347a 1052
23c0347a
SS
1053 # Check if the configured RED_TYPE is static.
1054 if ($netsettings{'RED_TYPE'} eq "STATIC") {
1055 # Get configured and enabled aliases.
1056 my @aliases = &get_aliases();
1057
1058 # Loop through the array.
1059 foreach my $alias (@aliases) {
1060 # Add "/32" prefix.
1061 my $network = join("/", $alias, "32");
1062
1063 # Add the generated network to the array of networks.
1064 push(@networks, $network);
1065 }
1066 }
bcbc9897
SS
1067 # Process remaining network zones.
1068 } else {
1069 # Convert current zone name into upper case.
1070 $zone = uc($zone);
1071
1072 # Generate key to access the required data from the netsettings hash.
1073 my $zone_netaddress = $zone . "_NETADDRESS";
1074 my $zone_netmask = $zone . "_NETMASK";
1075
1076 # Obtain the settings from the netsettings hash.
1077 my $netaddress = $netsettings{$zone_netaddress};
1078 my $netmask = $netsettings{$zone_netmask};
1079
1080 # Convert the subnetmask into prefix notation.
1081 my $prefix = &Network::convert_netmask2prefix($netmask);
1082
1083 # Generate full network string.
1084 my $network = join("/", $netaddress,$prefix);
1085
1086 # Check if the network is valid.
1087 if(&Network::check_subnet($network)) {
1088 # Add the generated network to the array of networks.
1089 push(@networks, $network);
1090 }
23c0347a 1091 }
b02e30fd
SS
1092 }
1093
1094 # Format home net declaration.
7479c993 1095 my $line = "\"[" . join(',', @networks) . "]\"";
b02e30fd
SS
1096
1097 # Open file to store the addresses of the home net.
1098 open(FILE, ">$homenet_file") or die "Could not open $homenet_file. $!\n";
1099
1100 # Print yaml header.
1101 print FILE "%YAML 1.1\n";
1102 print FILE "---\n\n";
1103
1104 # Print notice about autogenerated file.
1105 print FILE "#Autogenerated file. Any custom changes will be overwritten!\n";
1106
1107 # Print the generated and required HOME_NET declaration to the file.
1108 print FILE "HOME_NET:\t$line\n";
1109
1110 # Close file handle.
1111 close(FILE);
1112}
1113
30ee98e9
SS
1114#
1115# Function to generate and write the file which contains the configured and used DNS servers.
1116#
1117sub generate_dns_servers_file() {
12c49915
SS
1118 # Get the used DNS servers.
1119 my @nameservers = &General::get_nameservers();
30ee98e9 1120
7b97359b
SS
1121 # Get network settings.
1122 my %netsettings;
1123 &General::readhash("${General::swroot}/ethernet/settings", \%netsettings);
1124
30ee98e9 1125 # Format dns servers declaration.
b76118c3 1126 my $line = "";
30ee98e9 1127
12c49915
SS
1128 # Check if the system has configured nameservers.
1129 if (@nameservers) {
7b97359b
SS
1130 # Add the GREEN address as DNS servers.
1131 push(@nameservers, $netsettings{'GREEN_ADDRESS'});
1132
1133 # Check if a BLUE zone exists.
1134 if ($netsettings{'BLUE_ADDRESS'}) {
1135 # Add the BLUE address to the array of nameservers.
1136 push(@nameservers, $netsettings{'BLUE_ADDRESS'});
1137 }
1138
1139 # Generate the line which will be written to the DNS servers file.
b76118c3 1140 $line = join(",", @nameservers);
12c49915 1141 } else {
7b97359b 1142 # External net simply contains (any).
99cadb74 1143 $line = "\$EXTERNAL_NET";
fd2dccaa 1144 }
30ee98e9 1145
30ee98e9
SS
1146 # Open file to store the used DNS server addresses.
1147 open(FILE, ">$dns_servers_file") or die "Could not open $dns_servers_file. $!\n";
1148
1149 # Print yaml header.
1150 print FILE "%YAML 1.1\n";
1151 print FILE "---\n\n";
1152
1153 # Print notice about autogenerated file.
1154 print FILE "#Autogenerated file. Any custom changes will be overwritten!\n";
1155
1156 # Print the generated DNS declaration to the file.
b76118c3 1157 print FILE "DNS_SERVERS:\t\"[$line]\"\n";
30ee98e9
SS
1158
1159 # Close file handle.
1160 close(FILE);
1161}
1162
e698090e
SS
1163#
1164# Function to generate and write the file which contains the HTTP_PORTS definition.
1165#
1166sub generate_http_ports_file() {
1167 my %proxysettings;
1168
1169 # Read-in proxy settings
1170 &General::readhash("${General::swroot}/proxy/advanced/settings", \%proxysettings);
1171
1172 # Check if the proxy is enabled.
1173 if (( -e "${General::swroot}/proxy/enable") || (-e "${General::swroot}/proxy/enable_blue")) {
1174 # Add the proxy port to the array of HTTP ports.
1175 push(@http_ports, $proxysettings{'PROXY_PORT'});
1176 }
1177
1178 # Check if the transparent mode of the proxy is enabled.
1179 if ((-e "${General::swroot}/proxy/transparent") || (-e "${General::swroot}/proxy/transparent_blue")) {
1180 # Add the transparent proxy port to the array of HTTP ports.
1181 push(@http_ports, $proxysettings{'TRANSPARENT_PORT'});
1182 }
1183
1184 # Format HTTP_PORTS declaration.
1185 my $line = "";
1186
1187 # Generate line which will be written to the http ports file.
1188 $line = join(",", @http_ports);
1189
1190 # Open file to store the HTTP_PORTS.
1191 open(FILE, ">$http_ports_file") or die "Could not open $http_ports_file. $!\n";
1192
1193 # Print yaml header.
1194 print FILE "%YAML 1.1\n";
1195 print FILE "---\n\n";
1196
1197 # Print notice about autogenerated file.
1198 print FILE "#Autogenerated file. Any custom changes will be overwritten!\n";
1199
1200 # Print the generated HTTP_PORTS declaration to the file.
1201 print FILE "HTTP_PORTS:\t\"[$line]\"\n";
1202
1203 # Close file handle.
1204 close(FILE);
1205}
1206
b02e30fd
SS
1207#
1208## Function to generate and write the file for used rulefiles.
1209#
1210sub write_used_rulefiles_file(@) {
1211 my @files = @_;
1212
1213 # Open file for used rulefiles.
1214 open (FILE, ">$used_rulefiles_file") or die "Could not write to $used_rulefiles_file. $!\n";
1215
1216 # Write yaml header to the file.
1217 print FILE "%YAML 1.1\n";
1218 print FILE "---\n\n";
1219
1220 # Write header to file.
1221 print FILE "#Autogenerated file. Any custom changes will be overwritten!\n";
1222
1223 # Allways use the whitelist.
1224 print FILE " - whitelist.rules\n";
1225
1226 # Loop through the array of given files.
1227 foreach my $file (@files) {
1228 # Check if the given filename exists and write it to the file of used rulefiles.
1229 if(-f "$rulespath/$file") {
1230 print FILE " - $file\n";
1231 }
1232 }
1233
1234 # Close file after writing.
1235 close(FILE);
1236}
1237
74cc8f5a
SS
1238#
1239## Function to generate and write the file for modify the ruleset.
1240#
81bae51f
SS
1241sub write_modify_sids_file() {
1242 # Get configured settings.
1243 my %idssettings=();
81bae51f 1244 &General::readhash("$ids_settings_file", \%idssettings);
74cc8f5a
SS
1245
1246 # Open modify sid's file for writing.
2ee51088 1247 open(FILE, ">$modify_sids_file") or die "Could not write to $modify_sids_file. $!\n";
74cc8f5a
SS
1248
1249 # Write file header.
1250 print FILE "#Autogenerated file. Any custom changes will be overwritten!\n";
1251
1252 # Check if the traffic only should be monitored.
81bae51f 1253 unless($idssettings{'MONITOR_TRAFFIC_ONLY'} eq 'on') {
a5ba473c
TF
1254 # Suricata is in IPS mode, which means that the rule actions have to be changed
1255 # from 'alert' to 'drop', however not all rules should be changed. Some rules
1256 # exist purely to set a flowbit which is used to convey other information, such
1257 # as a specific type of file being downloaded, to other rulewhich then check for
1258 # malware in that file. Rules which fall into the first category should stay as
1259 # alert since not all flows of that type contain malware.
1260
aac869c4
SS
1261 # These types of rulesfiles contain meta-data which gives the action that should
1262 # be used when in IPS mode. Do the following:
1263 #
1264 # 1. Disable all rules and set the action to 'drop'
1265 # 2. Set the action back to 'alert' if the rule contains 'flowbits:noalert;'
1266 # This should give rules not in the policy a reasonable default if the user
1267 # manually enables them.
1268 # 3. Enable rules and set actions according to the meta-data strings.
a5ba473c 1269
aac869c4 1270 my $policy = 'balanced'; # Placeholder to allow policy to be changed.
a5ba473c
TF
1271
1272 print FILE <<END;
a5ba473c
TF
1273modifysid * "^#(?:alert|drop)(.+policy $policy-ips alert)" | "alert\${1}"
1274modifysid * "^#(?:alert|drop)(.+policy $policy-ips drop)" | "drop\${1}"
a5ba473c
TF
1275modifysid * "^(#?)(?:alert|drop)" | "\${1}drop"
1276modifysid * "^(#?)drop(.+flowbits:noalert;)" | "\${1}alert\${2}"
1277END
1278 }
74cc8f5a
SS
1279
1280 # Close file handle.
1281 close(FILE);
1282}
1283
04a0d07c
SS
1284#
1285## Function to gather the version of suricata.
1286#
1287sub get_suricata_version($) {
1288 my ($format) = @_;
1289
1290 # Execute piped suricata command and return the version information.
1291 open(SURICATA, "suricata -V |") or die "Couldn't execute program: $!";
1292
1293 # Grab and store the output of the piped program.
1294 my $version_string = <SURICATA>;
1295
1296 # Close pipe.
1297 close(SURICATA);
1298
1299 # Remove newlines.
1300 chomp($version_string);
1301
fd2dccaa 1302 # Grab the version from the version string.
04a0d07c
SS
1303 $version_string =~ /([0-9]+([.][0-9]+)+)/;
1304
1305 # Splitt the version into single chunks.
1306 my ($major_ver, $minor_ver, $patchlevel) = split(/\./, $1);
1307
1308 # Check and return the requested version sheme.
1309 if ($format eq "major") {
1310 # Return the full version.
1311 return "$major_ver";
1312 } elsif ($format eq "minor") {
1313 # Return the major and minor part.
1314 return "$major_ver.$minor_ver";
1315 } else {
1316 # Return the full version string.
1317 return "$major_ver.$minor_ver.$patchlevel";
fd2dccaa 1318 }
04a0d07c
SS
1319}
1320
9283e9b9
SS
1321#
1322## Function to generate the rules file with whitelisted addresses.
1323#
1324sub generate_ignore_file() {
1325 my %ignored = ();
1326
1327 # SID range 1000000-1999999 Reserved for Local Use
1328 # Put your custom rules in this range to avoid conflicts
1329 my $sid = 1500000;
1330
1331 # Read-in ignoredfile.
1332 &General::readhasharray($IDS::ignored_file, \%ignored);
1333
1334 # Open ignorefile for writing.
1335 open(FILE, ">$IDS::whitelist_file") or die "Could not write to $IDS::whitelist_file. $!\n";
1336
1337 # Config file header.
1338 print FILE "# Autogenerated file.\n";
1339 print FILE "# All user modifications will be overwritten.\n\n";
1340
1341 # Add all user defined addresses to the whitelist.
1342 #
1343 # Check if the hash contains any elements.
1344 if (keys (%ignored)) {
1345 # Loop through the entire hash and write the host/network
1346 # and remark to the ignore file.
1347 while ( (my $key) = each %ignored) {
1348 my $address = $ignored{$key}[0];
1349 my $remark = $ignored{$key}[1];
1350 my $status = $ignored{$key}[2];
1351
1352 # Check if the status of the entry is "enabled".
1353 if ($status eq "enabled") {
1354 # Check if the address/network is valid.
1355 if ((&General::validip($address)) || (&General::validipandmask($address))) {
1356 # Write rule line to the file to pass any traffic from this IP
1357 print FILE "pass ip $address any -> any any (msg:\"pass all traffic from/to $address\"\; sid:$sid\;)\n";
1358
1359 # Increment sid.
1360 $sid++;
1361 }
1362 }
1363 }
1364 }
1365
1366 close(FILE);
1367}
1368
1fedede6
SS
1369#
1370## Function to set correct ownership for single files and directories.
1371#
1372
1373sub set_ownership($) {
1374 my ($target) = @_;
1375
1376 # User and group of the WUI.
1377 my $uname = "nobody";
1378 my $grname = "nobody";
1379
1380 # The chown function implemented in perl requies the user and group as nummeric id's.
1381 my $uid = getpwnam($uname);
1382 my $gid = getgrnam($grname);
1383
1384 # Check if the given target exists.
1385 unless ($target) {
1386 # Stop the script and print error message.
1387 die "The $target does not exist. Cannot change the ownership!\n";
1388 }
1389
1390 # Check weather the target is a file or directory.
1391 if (-f $target) {
1392 # Change ownership ot the single file.
1393 chown($uid, $gid, "$target");
1394 } elsif (-d $target) {
1395 # Do a directory listing.
1396 opendir(DIR, $target) or die $!;
1397 # Loop through the direcory.
1398 while (my $file = readdir(DIR)) {
1399
1400 # We only want files.
1401 next unless (-f "$target/$file");
1402
1403 # Set correct ownership for the files.
1404 chown($uid, $gid, "$target/$file");
1405 }
1406
1407 closedir(DIR);
1408
1409 # Change ownership of the directory.
1410 chown($uid, $gid, "$target");
1411 }
1412}
77c31301
SS
1413
1414#
1415## Function to read-in the aliases file and returns all configured and enabled aliases.
1416#
1417sub get_aliases() {
1418 # Location of the aliases file.
1419 my $aliases_file = "${General::swroot}/ethernet/aliases";
1420
1421 # Array to store the aliases.
1422 my @aliases;
1423
1424 # Check if the file is empty.
1425 if (-z $aliases_file) {
1426 # Abort nothing to do.
1427 return;
1428 }
1429
1430 # Open the aliases file.
1431 open(ALIASES, $aliases_file) or die "Could not open $aliases_file. $!\n";
1432
1433 # Loop through the file content.
1434 while (my $line = <ALIASES>) {
1435 # Remove newlines.
1436 chomp($line);
1437
1438 # Splitt line content into single chunks.
1439 my ($address, $state, $remark) = split(/\,/, $line);
1440
1441 # Check if the state of the current processed alias is "on".
1442 if ($state eq "on") {
1443 # Check if the address is valid.
1444 if(&Network::check_ip_address($address)) {
1445 # Add the alias to the array of aliases.
1446 push(@aliases, $address);
1447 }
1448 }
1449 }
1450
1451 # Close file handle.
1452 close(ALIASES);
1453
1454 # Return the array.
1455 return @aliases;
1456}
1457
de8e1e5b
SS
1458#
1459## Function to grab the current assigned IP-address on red.
1460#
1461sub get_red_address() {
1462 # File, which contains the current IP-address of the red interface.
1463 my $file = "${General::swroot}/red/local-ipaddress";
1464
1465 # Check if the file exists.
1466 if (-e $file) {
1467 # Open the given file.
1468 open(FILE, "$file") or die "Could not open $file.";
1469
1470 # Obtain the address from the first line of the file.
1471 my $address = <FILE>;
1472
1473 # Close filehandle
1474 close(FILE);
1475
1476 # Remove newlines.
1477 chomp $address;
1478
1479 # Check if the grabbed address is valid.
1480 if (&General::validip($address)) {
1481 # Return the address.
1482 return $address;
1483 }
1484 }
1485
1486 # Return nothing.
1487 return;
1488}
77c31301 1489
6563d449
SS
1490#
1491## Function to get all used rulesfiles files.
1492#
1493sub get_used_rulesfiles() {
1494 # Array to store the used rulefiles.
1495 my @used_rulesfiles = ();
1496
1497 # Check if the used rulesfile is empty.
dae33250 1498 unless (-z $used_rulefiles_file) {
6563d449
SS
1499 # Open the file or used rulefiles and read-in content.
1500 open(FILE, $used_rulefiles_file) or die "Could not open $used_rulefiles_file. $!\n";
1501
1502 while (<FILE>) {
1503 # Assign the current line to a nice variable.
1504 my $line = $_;
1505
1506 # Remove newlines.
1507 chomp($line);
1508
1509 # Skip comments.
1510 next if ($line =~ /\#/);
1511
1512 # Skip blank lines.
1513 next if ($line =~ /^\s*$/);
1514
1515 # Gather the rulefile.
1516 if ($line =~ /.*- (.*)/) {
1517 my $rulefile = $1;
1518
1519 # Add the rulefile to the array of used rulesfiles.
1520 push(@used_rulesfiles, $rulefile);
1521 }
1522 }
1523
1524 # Close the file.
1525 close(FILE);
1526 }
1527
1528 # Return the array of used rulesfiles.
1529 return @used_rulesfiles;
1530}
1531
8076deba
SS
1532#
1533## Function to write the lock file for locking the WUI, while
1534## the autoupdate script runs.
1535#
1536sub lock_ids_page() {
1537 # Call subfunction to create the file.
1538 &create_empty_file($ids_page_lock_file);
1539}
1540
1541#
1542## Function to release the lock of the WUI, again.
1543#
1544sub unlock_ids_page() {
1545 # Delete lock file.
1546 unlink($ids_page_lock_file);
1547}
1548
8dcebe53 15491;