]> git.ipfire.org Git - people/pmueller/ipfire-2.x.git/blob - config/cfgroot/ids-functions.pl
ids-functions.pl: Do not delete the whitelist file on rulesdir cleanup.
[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 IPFire Team <info@ipfire.org>. #
21 # #
22 ############################################################################
23
24 package IDS;
25
26 require '/var/ipfire/general-functions.pl';
27
28 # Location where all config and settings files are stored.
29 our $settingsdir = "${General::swroot}/suricata";
30
31 # File where the used rulefiles are stored.
32 our $used_rulefiles_file = "$settingsdir/suricata-used-rulefiles.yaml";
33
34 # File where the addresses of the homenet are stored.
35 our $homenet_file = "$settingsdir/suricata-homenet.yaml";
36
37 # File which contains the enabled sids.
38 our $enabled_sids_file = "$settingsdir/oinkmaster-enabled-sids.conf";
39
40 # File which contains the disabled sids.
41 our $disabled_sids_file = "$settingsdir/oinkmaster-disabled-sids.conf";
42
43 # File which contains wheater the rules should be changed.
44 our $modify_sids_file = "$settingsdir/oinkmaster-modify-sids.conf";
45
46 # File which stores the configured IPS settings.
47 our $ids_settings_file = "$settingsdir/settings";
48
49 # File which stores the configured rules-settings.
50 our $rules_settings_file = "$settingsdir/rules-settings";
51
52 # File which stores the configured settings for whitelisted addresses.
53 our $ignored_file = "$settingsdir/ignored";
54
55 # Location and name of the tarball which contains the ruleset.
56 our $rulestarball = "/var/tmp/idsrules.tar.gz";
57
58 # File to store any errors, which also will be read and displayed by the wui.
59 our $storederrorfile = "/tmp/ids_storederror";
60
61 # File to lock the WUI, while the autoupdate script runs.
62 our $ids_page_lock_file = "/tmp/ids_page_locked";
63
64 # Location where the rulefiles are stored.
65 our $rulespath = "/var/lib/suricata";
66
67 # File which contains the rules to whitelist addresses on suricata.
68 our $whitelist_file = "$rulespath/whitelist.rules";
69
70 # File which contains a list of all supported ruleset sources.
71 # (Sourcefire, Emergingthreads, etc..)
72 our $rulesetsourcesfile = "$settingsdir/ruleset-sources";
73
74 # The pidfile of the IDS.
75 our $idspidfile = "/var/run/suricata.pid";
76
77 # Location of suricatactrl.
78 my $suricatactrl = "/usr/local/bin/suricatactrl";
79
80 # Array with allowed commands of suricatactrl.
81 my @suricatactrl_cmds = ( 'start', 'stop', 'restart', 'reload', 'fix-rules-dir', 'cron' );
82
83 # Array with supported cron intervals.
84 my @cron_intervals = ('off', 'daily', 'weekly' );
85
86 #
87 ## Function to check and create all IDS related files, if the does not exist.
88 #
89 sub check_and_create_filelayout() {
90 # Check if the files exist and if not, create them.
91 unless (-f "$enabled_sids_file") { &create_empty_file($enabled_sids_file); }
92 unless (-f "$disabled_sids_file") { &create_empty_file($disabled_sids_file); }
93 unless (-f "$modify_sids_file") { &create_empty_file($modify_sids_file); }
94 unless (-f "$used_rulefiles_file") { &create_empty_file($used_rulefiles_file); }
95 unless (-f "$ids_settings_file") { &create_empty_file($ids_settings_file); }
96 unless (-f "$rules_settings_file") { &create_empty_file($rules_settings_file); }
97 unless (-f "$ignored_file") { &create_empty_file($ignored_file); }
98 unless (-f "$whitelist_file" ) { &create_empty_file($whitelist_file); }
99 }
100
101 #
102 ## Function for checking if at least 300MB of free disk space are available
103 ## on the "/var" partition.
104 #
105 sub checkdiskspace () {
106 # Call diskfree to gather the free disk space of /var.
107 my @df = `/bin/df -B M /var`;
108
109 # Loop through the output.
110 foreach my $line (@df) {
111 # Ignore header line.
112 next if $line =~ m/^Filesystem/;
113
114 # Search for a line with the device information.
115 if ($line =~ m/dev/ ) {
116 # Split the line into single pieces.
117 my @values = split(' ', $line);
118 my ($filesystem, $blocks, $used, $available, $used_perenctage, $mounted_on) = @values;
119
120 # Check if the available disk space is more than 300MB.
121 if ($available < 300) {
122 # Log error to syslog.
123 &_log_to_syslog("Not enough free disk space on /var. Only $available MB from 300 MB available.");
124
125 # Exit function and return "1" - False.
126 return 1;
127 }
128 }
129 }
130
131 # Everything okay, return nothing.
132 return;
133 }
134
135 #
136 ## This function is responsible for downloading the configured IDS ruleset.
137 ##
138 ## * At first it obtains from the stored rules settings which ruleset should be downloaded.
139 ## * The next step is to get the download locations for all available rulesets.
140 ## * After that, the function will check if an upstream proxy should be used and grab the settings.
141 ## * The last step will be to generate the final download url, by obtaining the URL for the desired
142 ## ruleset, add the settings for the upstream proxy and final grab the rules tarball from the server.
143 #
144 sub downloadruleset {
145 # Get rules settings.
146 my %rulessettings=();
147 &General::readhash("$rules_settings_file", \%rulessettings);
148
149 # Check if a ruleset has been configured.
150 unless($rulessettings{'RULES'}) {
151 # Log that no ruleset has been configured and abort.
152 &_log_to_syslog("No ruleset source has been configured.");
153
154 # Return "1".
155 return 1;
156 }
157
158 # Get all available ruleset locations.
159 my %rulesetsources=();
160 &General::readhash($rulesetsourcesfile, \%rulesetsources);
161
162 # Read proxysettings.
163 my %proxysettings=();
164 &General::readhash("${General::swroot}/proxy/settings", \%proxysettings);
165
166 # Load required perl module to handle the download.
167 use LWP::UserAgent;
168
169 # Init the download module.
170 my $downloader = LWP::UserAgent->new;
171
172 # Set timeout to 10 seconds.
173 $downloader->timeout(10);
174
175 # Check if an upstream proxy is configured.
176 if ($proxysettings{'UPSTREAM_PROXY'}) {
177 my $proxy_url;
178
179 $proxy_url = "http://";
180
181 # Check if the proxy requires authentication.
182 if (($proxysettings{'UPSTREAM_USER'}) && ($proxysettings{'UPSTREAM_PASSWORD'})) {
183 $proxy_url .= "$proxysettings{'UPSTREAM_USER'}\:$proxysettings{'UPSTREAM_PASSWORD'}\@";
184 }
185
186 # Add proxy server address and port.
187 $proxy_url .= $proxysettings{'UPSTREAM_PROXY'};
188
189 # Setup proxy settings.
190 $downloader->proxy(['http', 'https'], $proxy_url);
191 }
192
193 # Grab the right url based on the configured vendor.
194 my $url = $rulesetsources{$rulessettings{'RULES'}};
195
196 # Check if the vendor requires an oinkcode and add it if needed.
197 $url =~ s/\<oinkcode\>/$rulessettings{'OINKCODE'}/g;
198
199 # Abort if no url could be determined for the vendor.
200 unless ($url) {
201 # Log error and abort.
202 &_log_to_syslog("Unable to gather a download URL for the selected ruleset.");
203 return 1;
204 }
205
206 # Variable to store the filesize of the remote object.
207 my $remote_filesize;
208
209 # The sourcfire (snort rules) does not allow to send "HEAD" requests, so skip this check
210 # for this webserver.
211 #
212 # Check if the ruleset source contains "snort.org".
213 unless ($url =~ /\.snort\.org/) {
214 # Pass the requrested url to the downloader.
215 my $request = HTTP::Request->new(HEAD => $url);
216
217 # Accept the html header.
218 $request->header('Accept' => 'text/html');
219
220 # Perform the request and fetch the html header.
221 my $response = $downloader->request($request);
222
223 # Check if there was any error.
224 unless ($response->is_success) {
225 # Obtain error.
226 my $error = $response->status_line();
227
228 # Log error message.
229 &_log_to_syslog("Unable to download the ruleset. \($error\)");
230
231 # Return "1" - false.
232 return 1;
233 }
234
235 # Assign the fetched header object.
236 my $header = $response->headers();
237
238 # Grab the remote file size from the object and store it in the
239 # variable.
240 $remote_filesize = $header->content_length;
241 }
242
243 # Load perl module to deal with temporary files.
244 use File::Temp;
245
246 # Generate temporay file name, located in "/var/tmp" and with a suffix of ".tar.gz".
247 my $tmp = File::Temp->new( SUFFIX => ".tar.gz", DIR => "/var/tmp/", UNLINK => 0 );
248 my $tmpfile = $tmp->filename();
249
250 # Pass the requested url to the downloader.
251 my $request = HTTP::Request->new(GET => $url);
252
253 # Perform the request and save the output into the tmpfile.
254 my $response = $downloader->request($request, $tmpfile);
255
256 # Check if there was any error.
257 unless ($response->is_success) {
258 # Obtain error.
259 my $error = $response->content;
260
261 # Log error message.
262 &_log_to_syslog("Unable to download the ruleset. \($error\)");
263
264 # Return "1" - false.
265 return 1;
266 }
267
268 # Load perl stat module.
269 use File::stat;
270
271 # Perform stat on the tmpfile.
272 my $stat = stat($tmpfile);
273
274 # Grab the local filesize of the downloaded tarball.
275 my $local_filesize = $stat->size;
276
277 # Check if both file sizes match.
278 if (($remote_filesize) && ($remote_filesize ne $local_filesize)) {
279 # Log error message.
280 &_log_to_syslog("Unable to completely download the ruleset. ");
281 &_log_to_syslog("Only got $local_filesize Bytes instead of $remote_filesize Bytes. ");
282
283 # Delete temporary file.
284 unlink("$tmpfile");
285
286 # Return "1" - false.
287 return 1;
288 }
289
290 # Load file copy module, which contains the move() function.
291 use File::Copy;
292
293 # Overwrite existing rules tarball with the new downloaded one.
294 move("$tmpfile", "$rulestarball");
295
296 # If we got here, everything worked fine. Return nothing.
297 return;
298 }
299
300 #
301 ## A tiny wrapper function to call the oinkmaster script.
302 #
303 sub oinkmaster () {
304 # Check if the files in rulesdir have the correct permissions.
305 &_check_rulesdir_permissions();
306
307 # Cleanup the rules directory before filling it with the new rulest.
308 &_cleanup_rulesdir();
309
310 # Load perl module to talk to the kernel syslog.
311 use Sys::Syslog qw(:DEFAULT setlogsock);
312
313 # Establish the connection to the syslog service.
314 openlog('oinkmaster', 'cons,pid', 'user');
315
316 # Call oinkmaster to generate ruleset.
317 open(OINKMASTER, "/usr/local/bin/oinkmaster.pl -s -u file://$rulestarball -C $settingsdir/oinkmaster.conf -o $rulespath 2>&1 |") or die "Could not execute oinkmaster $!\n";
318
319 # Log output of oinkmaster to syslog.
320 while(<OINKMASTER>) {
321 # The syslog function works best with an array based input,
322 # so generate one before passing the message details to syslog.
323 my @syslog = ("INFO", "$_");
324
325 # Send the log message.
326 syslog(@syslog);
327 }
328
329 # Close the pipe to oinkmaster process.
330 close(OINKMASTER);
331
332 # Close the log handle.
333 closelog();
334 }
335
336 #
337 ## Function to do all the logging stuff if the downloading or updating of the ruleset fails.
338 #
339 sub log_error ($) {
340 my ($error) = @_;
341
342 # Remove any newline.
343 chomp($error);
344
345 # Call private function to log the error message to syslog.
346 &_log_to_syslog($error);
347
348 # Call private function to write/store the error message in the storederrorfile.
349 &_store_error_message($error);
350 }
351
352 #
353 ## Function to log a given error message to the kernel syslog.
354 #
355 sub _log_to_syslog ($) {
356 my ($message) = @_;
357
358 # Load perl module to talk to the kernel syslog.
359 use Sys::Syslog qw(:DEFAULT setlogsock);
360
361 # The syslog function works best with an array based input,
362 # so generate one before passing the message details to syslog.
363 my @syslog = ("ERR", "<ERROR> $message");
364
365 # Establish the connection to the syslog service.
366 openlog('oinkmaster', 'cons,pid', 'user');
367
368 # Send the log message.
369 syslog(@syslog);
370
371 # Close the log handle.
372 closelog();
373 }
374
375 #
376 ## Private function to write a given error message to the storederror file.
377 #
378 sub _store_error_message ($) {
379 my ($message) = @_;
380
381 # Remove any newline.
382 chomp($message);
383
384 # Open file for writing.
385 open (ERRORFILE, ">$storederrorfile") or die "Could not write to $storederrorfile. $!\n";
386
387 # Write error to file.
388 print ERRORFILE "$message\n";
389
390 # Close file.
391 close (ERRORFILE);
392
393 # Set correct ownership for the file.
394 &set_ownership("$storederrorfile");
395 }
396
397 #
398 ## Function to get a list of all available network zones.
399 #
400 sub get_available_network_zones () {
401 # Get netsettings.
402 my %netsettings = ();
403 &General::readhash("${General::swroot}/ethernet/settings", \%netsettings);
404
405 # Obtain the configuration type from the netsettings hash.
406 my $config_type = $netsettings{'CONFIG_TYPE'};
407
408 # Hash which contains the conversation from the config mode
409 # to the existing network interface names. They are stored like
410 # an array.
411 #
412 # Mode "0" red is a modem and green
413 # Mode "1" red is a netdev and green
414 # Mode "2" red, green and orange
415 # Mode "3" red, green and blue
416 # Mode "4" red, green, blue, orange
417 my %config_type_to_interfaces = (
418 "0" => [ "red", "green" ],
419 "1" => [ "red", "green" ],
420 "2" => [ "red", "green", "orange" ],
421 "3" => [ "red", "green", "blue" ],
422 "4" => [ "red", "green", "blue", "orange" ]
423 );
424
425 # Obtain and dereference the corresponding network interaces based on the read
426 # network config type.
427 my @network_zones = @{ $config_type_to_interfaces{$config_type} };
428
429 # Return them.
430 return @network_zones;
431 }
432
433 #
434 ## Function to check if the IDS is running.
435 #
436 sub ids_is_running () {
437 if(-f $idspidfile) {
438 # Open PID file for reading.
439 open(PIDFILE, "$idspidfile") or die "Could not open $idspidfile. $!\n";
440
441 # Grab the process-id.
442 my $pid = <PIDFILE>;
443
444 # Close filehandle.
445 close(PIDFILE);
446
447 # Remove any newline.
448 chomp($pid);
449
450 # Check if a directory for the process-id exists in proc.
451 if(-d "/proc/$pid") {
452 # The IDS daemon is running return the process id.
453 return $pid;
454 }
455 }
456
457 # Return nothing - IDS is not running.
458 return;
459 }
460
461 #
462 ## Function to call suricatactrl binary with a given command.
463 #
464 sub call_suricatactrl ($) {
465 # Get called option.
466 my ($option, $interval) = @_;
467
468 # Loop through the array of supported commands and check if
469 # the given one is part of it.
470 foreach my $cmd (@suricatactrl_cmds) {
471 # Skip current command unless the given one has been found.
472 next unless($cmd eq $option);
473
474 # Check if the given command is "cron".
475 if ($option eq "cron") {
476 # Check if an interval has been given.
477 if ($interval) {
478 # Check if the given interval is valid.
479 foreach my $element (@cron_intervals) {
480 # Skip current element until the given one has been found.
481 next unless($element eq $interval);
482
483 # Call the suricatactrl binary and pass the "cron" command
484 # with the requrested interval.
485 system("$suricatactrl $option $interval &>/dev/null");
486
487 # Return "1" - True.
488 return 1;
489 }
490 }
491
492 # If we got here, the given interval is not supported or none has been given. - Return nothing.
493 return;
494 } else {
495 # Call the suricatactrl binary and pass the requrested
496 # option to it.
497 system("$suricatactrl $option &>/dev/null");
498
499 # Return "1" - True.
500 return 1;
501 }
502 }
503
504 # Command not found - return nothing.
505 return;
506 }
507
508 #
509 ## Function to create a new empty file.
510 #
511 sub create_empty_file($) {
512 my ($file) = @_;
513
514 # Check if the given file exists.
515 if(-e $file) {
516 # Do nothing to prevent from overwriting existing files.
517 return;
518 }
519
520 # Open the file for writing.
521 open(FILE, ">$file") or die "Could not write to $file. $!\n";
522
523 # Close file handle.
524 close(FILE);
525
526 # Return true.
527 return 1;
528 }
529
530 #
531 ## Private function to check if the file permission of the rulespath are correct.
532 ## If not, call suricatactrl to fix them.
533 #
534 sub _check_rulesdir_permissions() {
535 # Check if the rulepath main directory is writable.
536 unless (-W $rulespath) {
537 # If not call suricatctrl to fix it.
538 &call_suricatactrl("fix-rules-dir");
539 }
540
541 # Open snort rules directory and do a directory listing.
542 opendir(DIR, $rulespath) or die $!;
543 # Loop through the direcory.
544 while (my $file = readdir(DIR)) {
545 # We only want files.
546 next unless (-f "$rulespath/$file");
547
548 # Check if the file is writable by the user.
549 if (-W "$rulespath/$file") {
550 # Everything is okay - go on to the next file.
551 next;
552 } else {
553 # There are wrong permissions, call suricatactrl to fix it.
554 &call_suricatactrl("fix-rules-dir");
555 }
556 }
557 }
558
559 #
560 ## Private function to cleanup the directory which contains
561 ## the IDS rules, before extracting and modifing the new ruleset.
562 #
563 sub _cleanup_rulesdir() {
564 # Open rules directory and do a directory listing.
565 opendir(DIR, $rulespath) or die $!;
566
567 # Loop through the direcory.
568 while (my $file = readdir(DIR)) {
569 # We only want files.
570 next unless (-f "$rulespath/$file");
571
572 # Skip element if it has config as file extension.
573 next if ($file =~ m/\.config$/);
574
575 # Skip rules file for whitelisted hosts.
576 next if ("$rulespath/$file" eq $whitelist_file);
577
578 # Delete the current processed file, if not, exit this function
579 # and return an error message.
580 unlink("$rulespath/$file") or return "Could not delete $rulespath/$file. $!\n";
581 }
582
583 # Return nothing;
584 return;
585 }
586
587 #
588 ## Function to generate the file which contains the home net information.
589 #
590 sub generate_home_net_file() {
591 my %netsettings;
592
593 # Read-in network settings.
594 &General::readhash("${General::swroot}/ethernet/settings", \%netsettings);
595
596 # Get available network zones.
597 my @network_zones = &get_available_network_zones();
598
599 # Temporary array to store network address and prefix of the configured
600 # networks.
601 my @networks;
602
603 # Loop through the array of available network zones.
604 foreach my $zone (@network_zones) {
605 # Check if the current processed zone is red.
606 if($zone eq "red") {
607 # Grab the IP-address of the red interface.
608 my $red_address = &get_red_address();
609
610 # Check if an address has been obtained.
611 if ($red_address) {
612 # Generate full network string.
613 my $red_network = join("/", $red_address, "32");
614
615 # Add the red network to the array of networks.
616 push(@networks, $red_network);
617 }
618
619 # Check if the configured RED_TYPE is static.
620 if ($netsettings{'RED_TYPE'} eq "STATIC") {
621 # Get configured and enabled aliases.
622 my @aliases = &get_aliases();
623
624 # Loop through the array.
625 foreach my $alias (@aliases) {
626 # Add "/32" prefix.
627 my $network = join("/", $alias, "32");
628
629 # Add the generated network to the array of networks.
630 push(@networks, $network);
631 }
632 }
633 # Process remaining network zones.
634 } else {
635 # Convert current zone name into upper case.
636 $zone = uc($zone);
637
638 # Generate key to access the required data from the netsettings hash.
639 my $zone_netaddress = $zone . "_NETADDRESS";
640 my $zone_netmask = $zone . "_NETMASK";
641
642 # Obtain the settings from the netsettings hash.
643 my $netaddress = $netsettings{$zone_netaddress};
644 my $netmask = $netsettings{$zone_netmask};
645
646 # Convert the subnetmask into prefix notation.
647 my $prefix = &Network::convert_netmask2prefix($netmask);
648
649 # Generate full network string.
650 my $network = join("/", $netaddress,$prefix);
651
652 # Check if the network is valid.
653 if(&Network::check_subnet($network)) {
654 # Add the generated network to the array of networks.
655 push(@networks, $network);
656 }
657 }
658 }
659
660 # Format home net declaration.
661 my $line = "\"\[";
662
663 # Loop through the array of networks.
664 foreach my $network (@networks) {
665 # Add the network to the line.
666 $line = "$line" . "$network";
667
668 # Check if the current network was the last in the array.
669 if ($network eq $networks[-1]) {
670 # Close the line.
671 $line = "$line" . "\]\"";
672 } else {
673 # Add "," for the next network.
674 $line = "$line" . "\,";
675 }
676 }
677
678 # Open file to store the addresses of the home net.
679 open(FILE, ">$homenet_file") or die "Could not open $homenet_file. $!\n";
680
681 # Print yaml header.
682 print FILE "%YAML 1.1\n";
683 print FILE "---\n\n";
684
685 # Print notice about autogenerated file.
686 print FILE "#Autogenerated file. Any custom changes will be overwritten!\n";
687
688 # Print the generated and required HOME_NET declaration to the file.
689 print FILE "HOME_NET:\t$line\n";
690
691 # Close file handle.
692 close(FILE);
693 }
694
695 #
696 ## Function to generate and write the file for used rulefiles.
697 #
698 sub write_used_rulefiles_file(@) {
699 my @files = @_;
700
701 # Open file for used rulefiles.
702 open (FILE, ">$used_rulefiles_file") or die "Could not write to $used_rulefiles_file. $!\n";
703
704 # Write yaml header to the file.
705 print FILE "%YAML 1.1\n";
706 print FILE "---\n\n";
707
708 # Write header to file.
709 print FILE "#Autogenerated file. Any custom changes will be overwritten!\n";
710
711 # Allways use the whitelist.
712 print FILE " - whitelist.rules\n";
713
714 # Loop through the array of given files.
715 foreach my $file (@files) {
716 # Check if the given filename exists and write it to the file of used rulefiles.
717 if(-f "$rulespath/$file") {
718 print FILE " - $file\n";
719 }
720 }
721
722 # Close file after writing.
723 close(FILE);
724 }
725
726 #
727 ## Function to generate and write the file for modify the ruleset.
728 #
729 sub write_modify_sids_file($) {
730 my ($ruleaction) = @_;
731
732 # Open modify sid's file for writing.
733 open(FILE, ">$modify_sids_file") or die "Could not write to $modify_sids_file. $!\n";
734
735 # Write file header.
736 print FILE "#Autogenerated file. Any custom changes will be overwritten!\n";
737
738 # Check if the traffic only should be monitored.
739 unless($ruleaction eq "alert") {
740 # Tell oinkmaster to switch all rules from alert to drop.
741 print FILE "modifysid \* \"alert\" \| \"drop\"\n";
742 }
743
744 # Close file handle.
745 close(FILE);
746 }
747
748 #
749 ## Function to gather the version of suricata.
750 #
751 sub get_suricata_version($) {
752 my ($format) = @_;
753
754 # Execute piped suricata command and return the version information.
755 open(SURICATA, "suricata -V |") or die "Couldn't execute program: $!";
756
757 # Grab and store the output of the piped program.
758 my $version_string = <SURICATA>;
759
760 # Close pipe.
761 close(SURICATA);
762
763 # Remove newlines.
764 chomp($version_string);
765
766 # Grab the version from the version string.
767 $version_string =~ /([0-9]+([.][0-9]+)+)/;
768
769 # Splitt the version into single chunks.
770 my ($major_ver, $minor_ver, $patchlevel) = split(/\./, $1);
771
772 # Check and return the requested version sheme.
773 if ($format eq "major") {
774 # Return the full version.
775 return "$major_ver";
776 } elsif ($format eq "minor") {
777 # Return the major and minor part.
778 return "$major_ver.$minor_ver";
779 } else {
780 # Return the full version string.
781 return "$major_ver.$minor_ver.$patchlevel";
782 }
783 }
784
785 #
786 ## Function to generate the rules file with whitelisted addresses.
787 #
788 sub generate_ignore_file() {
789 my %ignored = ();
790
791 # SID range 1000000-1999999 Reserved for Local Use
792 # Put your custom rules in this range to avoid conflicts
793 my $sid = 1500000;
794
795 # Read-in ignoredfile.
796 &General::readhasharray($IDS::ignored_file, \%ignored);
797
798 # Open ignorefile for writing.
799 open(FILE, ">$IDS::whitelist_file") or die "Could not write to $IDS::whitelist_file. $!\n";
800
801 # Config file header.
802 print FILE "# Autogenerated file.\n";
803 print FILE "# All user modifications will be overwritten.\n\n";
804
805 # Add all user defined addresses to the whitelist.
806 #
807 # Check if the hash contains any elements.
808 if (keys (%ignored)) {
809 # Loop through the entire hash and write the host/network
810 # and remark to the ignore file.
811 while ( (my $key) = each %ignored) {
812 my $address = $ignored{$key}[0];
813 my $remark = $ignored{$key}[1];
814 my $status = $ignored{$key}[2];
815
816 # Check if the status of the entry is "enabled".
817 if ($status eq "enabled") {
818 # Check if the address/network is valid.
819 if ((&General::validip($address)) || (&General::validipandmask($address))) {
820 # Write rule line to the file to pass any traffic from this IP
821 print FILE "pass ip $address any -> any any (msg:\"pass all traffic from/to $address\"\; sid:$sid\;)\n";
822
823 # Increment sid.
824 $sid++;
825 }
826 }
827 }
828 }
829
830 close(FILE);
831 }
832
833 #
834 ## Function to set correct ownership for single files and directories.
835 #
836
837 sub set_ownership($) {
838 my ($target) = @_;
839
840 # User and group of the WUI.
841 my $uname = "nobody";
842 my $grname = "nobody";
843
844 # The chown function implemented in perl requies the user and group as nummeric id's.
845 my $uid = getpwnam($uname);
846 my $gid = getgrnam($grname);
847
848 # Check if the given target exists.
849 unless ($target) {
850 # Stop the script and print error message.
851 die "The $target does not exist. Cannot change the ownership!\n";
852 }
853
854 # Check weather the target is a file or directory.
855 if (-f $target) {
856 # Change ownership ot the single file.
857 chown($uid, $gid, "$target");
858 } elsif (-d $target) {
859 # Do a directory listing.
860 opendir(DIR, $target) or die $!;
861 # Loop through the direcory.
862 while (my $file = readdir(DIR)) {
863
864 # We only want files.
865 next unless (-f "$target/$file");
866
867 # Set correct ownership for the files.
868 chown($uid, $gid, "$target/$file");
869 }
870
871 closedir(DIR);
872
873 # Change ownership of the directory.
874 chown($uid, $gid, "$target");
875 }
876 }
877
878 #
879 ## Function to read-in the aliases file and returns all configured and enabled aliases.
880 #
881 sub get_aliases() {
882 # Location of the aliases file.
883 my $aliases_file = "${General::swroot}/ethernet/aliases";
884
885 # Array to store the aliases.
886 my @aliases;
887
888 # Check if the file is empty.
889 if (-z $aliases_file) {
890 # Abort nothing to do.
891 return;
892 }
893
894 # Open the aliases file.
895 open(ALIASES, $aliases_file) or die "Could not open $aliases_file. $!\n";
896
897 # Loop through the file content.
898 while (my $line = <ALIASES>) {
899 # Remove newlines.
900 chomp($line);
901
902 # Splitt line content into single chunks.
903 my ($address, $state, $remark) = split(/\,/, $line);
904
905 # Check if the state of the current processed alias is "on".
906 if ($state eq "on") {
907 # Check if the address is valid.
908 if(&Network::check_ip_address($address)) {
909 # Add the alias to the array of aliases.
910 push(@aliases, $address);
911 }
912 }
913 }
914
915 # Close file handle.
916 close(ALIASES);
917
918 # Return the array.
919 return @aliases;
920 }
921
922 #
923 ## Function to grab the current assigned IP-address on red.
924 #
925 sub get_red_address() {
926 # File, which contains the current IP-address of the red interface.
927 my $file = "${General::swroot}/red/local-ipaddress";
928
929 # Check if the file exists.
930 if (-e $file) {
931 # Open the given file.
932 open(FILE, "$file") or die "Could not open $file.";
933
934 # Obtain the address from the first line of the file.
935 my $address = <FILE>;
936
937 # Close filehandle
938 close(FILE);
939
940 # Remove newlines.
941 chomp $address;
942
943 # Check if the grabbed address is valid.
944 if (&General::validip($address)) {
945 # Return the address.
946 return $address;
947 }
948 }
949
950 # Return nothing.
951 return;
952 }
953
954 #
955 ## Function to write the lock file for locking the WUI, while
956 ## the autoupdate script runs.
957 #
958 sub lock_ids_page() {
959 # Call subfunction to create the file.
960 &create_empty_file($ids_page_lock_file);
961 }
962
963 #
964 ## Function to release the lock of the WUI, again.
965 #
966 sub unlock_ids_page() {
967 # Delete lock file.
968 unlink($ids_page_lock_file);
969 }
970
971 1;