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