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