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