]> git.ipfire.org Git - people/pmueller/ipfire-2.x.git/blame_incremental - html/cgi-bin/ids.cgi
ddns: Import latest upstream patches for ddns-013
[people/pmueller/ipfire-2.x.git] / html / cgi-bin / ids.cgi
... / ...
CommitLineData
1#!/usr/bin/perl
2###############################################################################
3# #
4# IPFire.org - A linux based firewall #
5# Copyright (C) 2007-2018 IPFire Team <info@ipfire.org> #
6# #
7# This program is free software: you can redistribute it and/or modify #
8# it under the terms of the GNU General Public License as published by #
9# the Free Software Foundation, either version 3 of the License, or #
10# (at your option) any later version. #
11# #
12# This program is distributed in the hope that it will be useful, #
13# but WITHOUT ANY WARRANTY; without even the implied warranty of #
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
15# GNU General Public License for more details. #
16# #
17# You should have received a copy of the GNU General Public License #
18# along with this program. If not, see <http://www.gnu.org/licenses/>. #
19# #
20###############################################################################
21
22use strict;
23
24# enable only the following on debugging purpose
25#use warnings;
26#use CGI::Carp 'fatalsToBrowser';
27
28require '/var/ipfire/general-functions.pl';
29require "${General::swroot}/lang.pl";
30require "${General::swroot}/header.pl";
31require "${General::swroot}/ids-functions.pl";
32
33my %color = ();
34my %mainsettings = ();
35my %idsrules = ();
36my %idssettings=();
37my %rulessettings=();
38my %rulesetsources = ();
39my %cgiparams=();
40my %checked=();
41my %selected=();
42my %ignored=();
43
44# Read-in main settings, for language, theme and colors.
45&General::readhash("${General::swroot}/main/settings", \%mainsettings);
46&General::readhash("/srv/web/ipfire/html/themes/".$mainsettings{'THEME'}."/include/colors.txt", \%color);
47
48# Get the available network zones, based on the config type of the system and store
49# the list of zones in an array.
50my @network_zones = &IDS::get_available_network_zones();
51
52# Check if openvpn is started and add it to the array of network zones.
53if ( -e "/var/run/openvpn.pid") {
54 push(@network_zones, "ovpn");
55}
56
57my $errormessage;
58
59# Create files if they does not exist yet.
60&IDS::check_and_create_filelayout();
61
62# Hash which contains the colour code of a network zone.
63my %colourhash = (
64 'red' => $Header::colourred,
65 'green' => $Header::colourgreen,
66 'blue' => $Header::colourblue,
67 'orange' => $Header::colourorange,
68 'ovpn' => $Header::colourovpn
69);
70
71&Header::showhttpheaders();
72
73#Get GUI values
74&Header::getcgihash(\%cgiparams);
75
76## Add/edit an entry to the ignore file.
77#
78if (($cgiparams{'WHITELIST'} eq $Lang::tr{'add'}) || ($cgiparams{'WHITELIST'} eq $Lang::tr{'update'})) {
79
80 # Check if any input has been performed.
81 if ($cgiparams{'IGNORE_ENTRY_ADDRESS'} ne '') {
82
83 # Check if the given input is no valid IP-address or IP-address with subnet, display an error message.
84 if ((!&General::validip($cgiparams{'IGNORE_ENTRY_ADDRESS'})) && (!&General::validipandmask($cgiparams{'IGNORE_ENTRY_ADDRESS'}))) {
85 $errormessage = "$Lang::tr{'guardian invalid address or subnet'}";
86 }
87 } else {
88 $errormessage = "$Lang::tr{'guardian empty input'}";
89 }
90
91 # Go further if there was no error.
92 if ($errormessage eq '') {
93 my %ignored = ();
94 my $id;
95 my $status;
96
97 # Assign hash values.
98 my $new_entry_address = $cgiparams{'IGNORE_ENTRY_ADDRESS'};
99 my $new_entry_remark = $cgiparams{'IGNORE_ENTRY_REMARK'};
100
101 # Read-in ignoredfile.
102 &General::readhasharray($IDS::ignored_file, \%ignored);
103
104 # Check if we should edit an existing entry and got an ID.
105 if (($cgiparams{'WHITELIST'} eq $Lang::tr{'update'}) && ($cgiparams{'ID'})) {
106 # Assin the provided id.
107 $id = $cgiparams{'ID'};
108
109 # Undef the given ID.
110 undef($cgiparams{'ID'});
111
112 # Grab the configured status of the corresponding entry.
113 $status = $ignored{$id}[2];
114 } else {
115 # Each newly added entry automatically should be enabled.
116 $status = "enabled";
117
118 # Generate the ID for the new entry.
119 #
120 # Sort the keys by their ID and store them in an array.
121 my @keys = sort { $a <=> $b } keys %ignored;
122
123 # Reverse the key array.
124 my @reversed = reverse(@keys);
125
126 # Obtain the last used id.
127 my $last_id = @reversed[0];
128
129 # Increase the last id by one and use it as id for the new entry.
130 $id = ++$last_id;
131 }
132
133 # Add/Modify the entry to/in the ignored hash.
134 $ignored{$id} = ["$new_entry_address", "$new_entry_remark", "$status"];
135
136 # Write the changed ignored hash to the ignored file.
137 &General::writehasharray($IDS::ignored_file, \%ignored);
138
139 # Regenerate the ignore file.
140 &IDS::generate_ignore_file();
141 }
142
143 # Check if the IDS is running.
144 if(&IDS::ids_is_running()) {
145 # Call suricatactrl to perform a reload.
146 &IDS::call_suricatactrl("reload");
147 }
148
149## Toggle Enabled/Disabled for an existing entry on the ignore list.
150#
151
152} elsif ($cgiparams{'WHITELIST'} eq $Lang::tr{'toggle enable disable'}) {
153 my %ignored = ();
154
155 # Only go further, if an ID has been passed.
156 if ($cgiparams{'ID'}) {
157 # Assign the given ID.
158 my $id = $cgiparams{'ID'};
159
160 # Undef the given ID.
161 undef($cgiparams{'ID'});
162
163 # Read-in ignoredfile.
164 &General::readhasharray($IDS::ignored_file, \%ignored);
165
166 # Grab the configured status of the corresponding entry.
167 my $status = $ignored{$id}[2];
168
169 # Switch the status.
170 if ($status eq "disabled") {
171 $status = "enabled";
172 } else {
173 $status = "disabled";
174 }
175
176 # Modify the status of the existing entry.
177 $ignored{$id} = ["$ignored{$id}[0]", "$ignored{$id}[1]", "$status"];
178
179 # Write the changed ignored hash to the ignored file.
180 &General::writehasharray($IDS::ignored_file, \%ignored);
181
182 # Regenerate the ignore file.
183 &IDS::generate_ignore_file();
184
185 # Check if the IDS is running.
186 if(&IDS::ids_is_running()) {
187 # Call suricatactrl to perform a reload.
188 &IDS::call_suricatactrl("reload");
189 }
190 }
191
192## Remove entry from ignore list.
193#
194} elsif ($cgiparams{'WHITELIST'} eq $Lang::tr{'remove'}) {
195 my %ignored = ();
196
197 # Read-in ignoredfile.
198 &General::readhasharray($IDS::ignored_file, \%ignored);
199
200 # Drop entry from the hash.
201 delete($ignored{$cgiparams{'ID'}});
202
203 # Undef the given ID.
204 undef($cgiparams{'ID'});
205
206 # Write the changed ignored hash to the ignored file.
207 &General::writehasharray($IDS::ignored_file, \%ignored);
208
209 # Regenerate the ignore file.
210 &IDS::generate_ignore_file();
211
212 # Check if the IDS is running.
213 if(&IDS::ids_is_running()) {
214 # Call suricatactrl to perform a reload.
215 &IDS::call_suricatactrl("reload");
216 }
217}
218
219# Check if the page is locked, in this case, the ids_page_lock_file exists.
220if (-e $IDS::ids_page_lock_file) {
221 # Lock the webpage and print notice about autoupgrade of the ruleset
222 # is in progess.
223 &working_notice("$Lang::tr{'ids ruleset autoupdate in progress'}");
224
225 # Loop and check if the file still exists.
226 while(-e $IDS::ids_page_lock_file) {
227 # Sleep for a second and re-check.
228 sleep 1;
229 }
230
231 # Page has been unlocked, perform a reload.
232 &reload();
233}
234
235# Check if any error has been stored.
236if (-e $IDS::storederrorfile) {
237 # Open file to read in the stored error message.
238 open(FILE, "<$IDS::storederrorfile") or die "Could not open $IDS::storederrorfile. $!\n";
239
240 # Read the stored error message.
241 $errormessage = <FILE>;
242
243 # Close file.
244 close (FILE);
245
246 # Delete the file, which is now not longer required.
247 unlink($IDS::storederrorfile);
248}
249
250## Grab all available rules and store them in the idsrules hash.
251#
252# Open rules directory and do a directory listing.
253opendir(DIR, $IDS::rulespath) or die $!;
254 # Loop through the direcory.
255 while (my $file = readdir(DIR)) {
256
257 # We only want files.
258 next unless (-f "$IDS::rulespath/$file");
259
260 # Ignore empty files.
261 next if (-z "$IDS::rulespath/$file");
262
263 # Use a regular expression to find files ending in .rules
264 next unless ($file =~ m/\.rules$/);
265
266 # Ignore files which are not read-able.
267 next unless (-R "$IDS::rulespath/$file");
268
269 # Skip whitelist rules file.
270 next if( $file eq "whitelist.rules");
271
272 # Call subfunction to read-in rulefile and add rules to
273 # the idsrules hash.
274 &readrulesfile("$file");
275 }
276
277closedir(DIR);
278
279# Gather used rulefiles.
280#
281# Check if the file for activated rulefiles is not empty.
282if(-f $IDS::used_rulefiles_file) {
283 # Open the file for used rulefile and read-in content.
284 open(FILE, $IDS::used_rulefiles_file) or die "Could not open $IDS::used_rulefiles_file. $!\n";
285
286 # Read-in content.
287 my @lines = <FILE>;
288
289 # Close file.
290 close(FILE);
291
292 # Loop through the array.
293 foreach my $line (@lines) {
294 # Remove newlines.
295 chomp($line);
296
297 # Skip comments.
298 next if ($line =~ /\#/);
299
300 # Skip blank lines.
301 next if ($line =~ /^\s*$/);
302
303 # Gather rule sid and message from the ruleline.
304 if ($line =~ /.*- (.*)/) {
305 my $rulefile = $1;
306
307 # Check if the current rulefile exists in the %idsrules hash.
308 # If not, the file probably does not exist anymore or contains
309 # no rules.
310 if($idsrules{$rulefile}) {
311 # Add the rulefile state to the %idsrules hash.
312 $idsrules{$rulefile}{'Rulefile'}{'State'} = "on";
313 }
314 }
315 }
316}
317
318# Save ruleset configuration.
319if ($cgiparams{'RULESET'} eq $Lang::tr{'save'}) {
320 my %oldsettings;
321 my %rulesetsources;
322
323 # Read-in current (old) IDS settings.
324 &General::readhash("$IDS::rules_settings_file", \%oldsettings);
325
326 # Get all available ruleset locations.
327 &General::readhash("$IDS::rulesetsourcesfile", \%rulesetsources);
328
329 # Prevent form name from been stored in conf file.
330 delete $cgiparams{'RULESET'};
331
332 # Grab the URL based on the choosen vendor.
333 my $url = $rulesetsources{$cgiparams{'RULES'}};
334
335 # Check if the choosen vendor (URL) requires an subscription/oinkcode.
336 if ($url =~ /\<oinkcode\>/ ) {
337 # Check if an subscription/oinkcode has been provided.
338 if ($cgiparams{'OINKCODE'}) {
339 # Check if the oinkcode contains unallowed chars.
340 unless ($cgiparams{'OINKCODE'} =~ /^[a-z0-9]+$/) {
341 $errormessage = $Lang::tr{'invalid input for oink code'};
342 }
343 } else {
344 # Print an error message, that an subsription/oinkcode is required for this
345 # vendor.
346 $errormessage = $Lang::tr{'ids oinkcode required'};
347 }
348 }
349
350 # Go on if there are no error messages.
351 if (!$errormessage) {
352 # Store settings into settings file.
353 &General::writehash("$IDS::rules_settings_file", \%cgiparams);
354
355 # Check if the the automatic rule update hass been touched.
356 if($cgiparams{'AUTOUPDATE_INTERVAL'} ne $oldsettings{'AUTOUPDATE_INTERVAL'}) {
357 # Call suricatactrl to set the new interval.
358 &IDS::call_suricatactrl("cron", $cgiparams{'AUTOUPDATE_INTERVAL'});
359 }
360
361 # Check if a ruleset is present - if not or the source has been changed download it.
362 if((! %idsrules) || ($oldsettings{'RULES'} ne $cgiparams{'RULES'})) {
363 # Check if the red device is active.
364 unless (-e "${General::swroot}/red/active") {
365 $errormessage = "$Lang::tr{'could not download latest updates'} - $Lang::tr{'system is offline'}";
366 }
367
368 # Check if enough free disk space is availabe.
369 if(&IDS::checkdiskspace()) {
370 $errormessage = "$Lang::tr{'not enough disk space'}";
371 }
372
373 # Check if any errors happend.
374 unless ($errormessage) {
375 # Lock the webpage and print notice about downloading
376 # a new ruleset.
377 &working_notice("$Lang::tr{'ids working'}");
378
379 # Write the modify sid's file and pass the taken ruleaction.
380 &IDS::write_modify_sids_file();
381
382 # Call subfunction to download the ruleset.
383 if(&IDS::downloadruleset()) {
384 $errormessage = $Lang::tr{'could not download latest updates'};
385
386 # Call function to store the errormessage.
387 &IDS::_store_error_message($errormessage);
388 } else {
389 # Call subfunction to launch oinkmaster.
390 &IDS::oinkmaster();
391 }
392
393 # Check if the IDS is running.
394 if(&IDS::ids_is_running()) {
395 # Call suricatactrl to stop the IDS - because of the changed
396 # ruleset - the use has to configure it before suricata can be
397 # used again.
398 &IDS::call_suricatactrl("stop");
399 }
400
401 # Perform a reload of the page.
402 &reload();
403 }
404 }
405 }
406
407# Save ruleset.
408} elsif ($cgiparams{'RULESET'} eq $Lang::tr{'ids apply'}) {
409 # Arrays to store which rulefiles have been enabled and will be used.
410 my @enabled_rulefiles;
411
412 # Hash to store the user-enabled and disabled sids.
413 my %enabled_disabled_sids;
414
415 # Loop through the hash of idsrules.
416 foreach my $rulefile(keys %idsrules) {
417 # Check if the rulefile is enabled.
418 if ($cgiparams{$rulefile} eq "on") {
419 # Add rulefile to the array of enabled rulefiles.
420 push(@enabled_rulefiles, $rulefile);
421
422 # Drop item from cgiparams hash.
423 delete $cgiparams{$rulefile};
424 }
425 }
426
427 # Read-in the files for enabled/disabled sids.
428 # This will be done by calling the read_enabled_disabled_sids_file function two times
429 # and merge the returned hashes together into the enabled_disabled_sids hash.
430 %enabled_disabled_sids = (
431 &read_enabled_disabled_sids_file($IDS::disabled_sids_file),
432 &read_enabled_disabled_sids_file($IDS::enabled_sids_file));
433
434 # Loop through the hash of idsrules.
435 foreach my $rulefile (keys %idsrules) {
436 # Loop through the single rules of the rulefile.
437 foreach my $sid (keys %{$idsrules{$rulefile}}) {
438 # Skip the current sid if it is not numeric.
439 next unless ($sid =~ /\d+/ );
440
441 # Check if there exists a key in the cgiparams hash for this sid.
442 if (exists($cgiparams{$sid})) {
443 # Look if the rule is disabled.
444 if ($idsrules{$rulefile}{$sid}{'State'} eq "off") {
445 # Check if the state has been set to 'on'.
446 if ($cgiparams{$sid} eq "on") {
447 # Add/Modify the sid to/in the enabled_disabled_sids hash.
448 $enabled_disabled_sids{$sid} = "enabled";
449
450 # Drop item from cgiparams hash.
451 delete $cgiparams{$rulefile}{$sid};
452 }
453 }
454 } else {
455 # Look if the rule is enabled.
456 if ($idsrules{$rulefile}{$sid}{'State'} eq "on") {
457 # Check if the state is 'on' and should be disabled.
458 # In this case there is no entry
459 # for the sid in the cgiparams hash.
460 # Add/Modify it to/in the enabled_disabled_sids hash.
461 $enabled_disabled_sids{$sid} = "disabled";
462
463 # Drop item from cgiparams hash.
464 delete $cgiparams{$rulefile}{$sid};
465 }
466 }
467 }
468 }
469
470 # Open enabled sid's file for writing.
471 open(ENABLED_FILE, ">$IDS::enabled_sids_file") or die "Could not write to $IDS::enabled_sids_file. $!\n";
472
473 # Open disabled sid's file for writing.
474 open(DISABLED_FILE, ">$IDS::disabled_sids_file") or die "Could not write to $IDS::disabled_sids_file. $!\n";
475
476 # Write header to the files.
477 print ENABLED_FILE "#Autogenerated file. Any custom changes will be overwritten!\n";
478 print DISABLED_FILE "#Autogenerated file. Any custom changes will be overwritten!\n";
479
480 # Check if the hash for enabled/disabled files contains any entries.
481 if (%enabled_disabled_sids) {
482 # Loop through the hash.
483 foreach my $sid (keys %enabled_disabled_sids) {
484 # Check if the sid is enabled.
485 if ($enabled_disabled_sids{$sid} eq "enabled") {
486 # Print the sid to the enabled_sids file.
487 print ENABLED_FILE "enablesid $sid\n";
488 # Check if the sid is disabled.
489 } elsif ($enabled_disabled_sids{$sid} eq "disabled") {
490 # Print the sid to the disabled_sids file.
491 print DISABLED_FILE "disablesid $sid\n";
492 # Something strange happende - skip the current sid.
493 } else {
494 next;
495 }
496 }
497 }
498
499 # Close file for enabled_sids after writing.
500 close(ENABLED_FILE);
501
502 # Close file for disabled_sids after writing.
503 close(DISABLED_FILE);
504
505 # Call function to generate and write the used rulefiles file.
506 &IDS::write_used_rulefiles_file(@enabled_rulefiles);
507
508 # Lock the webpage and print message.
509 &working_notice("$Lang::tr{'ids apply ruleset changes'}");
510
511 # Call oinkmaster to alter the ruleset.
512 &IDS::oinkmaster();
513
514 # Check if the IDS is running.
515 if(&IDS::ids_is_running()) {
516 # Call suricatactrl to perform a reload.
517 &IDS::call_suricatactrl("reload");
518 }
519
520 # Reload page.
521 &reload();
522
523# Download new ruleset.
524} elsif ($cgiparams{'RULESET'} eq $Lang::tr{'update ruleset'}) {
525 # Check if the red device is active.
526 unless (-e "${General::swroot}/red/active") {
527 $errormessage = "$Lang::tr{'could not download latest updates'} - $Lang::tr{'system is offline'}";
528 }
529
530 # Check if enought free disk space is availabe.
531 if(&IDS::checkdiskspace()) {
532 $errormessage = "$Lang::tr{'not enough disk space'}";
533 }
534
535 # Check if any errors happend.
536 unless ($errormessage) {
537 # Lock the webpage and print notice about downloading
538 # a new ruleset.
539 &working_notice("$Lang::tr{'ids download new ruleset'}");
540
541 # Call subfunction to download the ruleset.
542 if(&IDS::downloadruleset()) {
543 $errormessage = $Lang::tr{'could not download latest updates'};
544
545 # Call function to store the errormessage.
546 &IDS::_store_error_message($errormessage);
547
548 # Preform a reload of the page.
549 &reload();
550 } else {
551 # Call subfunction to launch oinkmaster.
552 &IDS::oinkmaster();
553
554 # Check if the IDS is running.
555 if(&IDS::ids_is_running()) {
556 # Call suricatactrl to perform a reload.
557 &IDS::call_suricatactrl("reload");
558 }
559
560 # Perform a reload of the page.
561 &reload();
562 }
563 }
564# Save IDS settings.
565} elsif ($cgiparams{'IDS'} eq $Lang::tr{'save'}) {
566 my %oldidssettings;
567 my $reload_page;
568 my $monitored_zones = 0;
569
570 # Read-in current (old) IDS settings.
571 &General::readhash("$IDS::ids_settings_file", \%oldidssettings);
572
573 # Prevent form name from been stored in conf file.
574 delete $cgiparams{'IDS'};
575
576 # Check if the IDS should be enabled.
577 if ($cgiparams{'ENABLE_IDS'} eq "on") {
578 # Check if any ruleset is available. Otherwise abort and display an error.
579 unless(%idsrules) {
580 $errormessage = $Lang::tr{'ids no ruleset available'};
581 }
582
583 # Loop through the array of available interfaces.
584 foreach my $zone (@network_zones) {
585 # Convert interface name into upper case.
586 my $zone_upper = uc($zone);
587
588 # Check if the IDS is enabled for this interaces.
589 if ($cgiparams{"ENABLE_IDS_$zone_upper"}) {
590 # Increase count.
591 $monitored_zones++;
592 }
593 }
594
595 # Check if at least one zone should be monitored, or show an error.
596 unless ($monitored_zones >= 1) {
597 $errormessage = $Lang::tr{'ids no network zone'};
598 }
599 }
600
601 # Go on if there are no error messages.
602 if (!$errormessage) {
603 # Store settings into settings file.
604 &General::writehash("$IDS::ids_settings_file", \%cgiparams);
605 }
606
607 # Generate file to store the home net.
608 &IDS::generate_home_net_file();
609
610 # Generate file to the store the DNS servers.
611 &IDS::generate_dns_servers_file();
612
613 # Write the modify sid's file and pass the taken ruleaction.
614 &IDS::write_modify_sids_file();
615
616 # Check if "MONITOR_TRAFFIC_ONLY" has been changed.
617 if($cgiparams{'MONITOR_TRAFFIC_ONLY'} ne $oldidssettings{'MONITOR_TRAFFIC_ONLY'}) {
618 # Check if a ruleset exists.
619 if (%idsrules) {
620 # Lock the webpage and print message.
621 &working_notice("$Lang::tr{'ids working'}");
622
623 # Call oinkmaster to alter the ruleset.
624 &IDS::oinkmaster();
625
626 # Set reload_page to "True".
627 $reload_page="True";
628 }
629 }
630
631 # Check if the IDS currently is running.
632 if(&IDS::ids_is_running()) {
633 # Check if ENABLE_IDS is set to on.
634 if($cgiparams{'ENABLE_IDS'} eq "on") {
635 # Call suricatactrl to perform a reload of suricata.
636 &IDS::call_suricatactrl("reload");
637 } else {
638 # Call suricatactrl to stop suricata.
639 &IDS::call_suricatactrl("stop");
640 }
641 } else {
642 # Call suricatactrl to start suricata.
643 &IDS::call_suricatactrl("start");
644 }
645
646 # Check if the page should be reloaded.
647 if ($reload_page) {
648 # Perform a reload of the page.
649 &reload();
650 }
651}
652
653# Read-in idssettings and rulesetsettings
654&General::readhash("$IDS::ids_settings_file", \%idssettings);
655&General::readhash("$IDS::rules_settings_file", \%rulessettings);
656
657# If no autoupdate intervall has been configured yet, set default value.
658unless(exists($rulessettings{'AUTOUPDATE_INTERVAL'})) {
659 # Set default to "weekly".
660 $rulessettings{'AUTOUPDATE_INTERVAL'} = 'weekly';
661}
662
663# Read-in ignored hosts.
664&General::readhasharray("$IDS::settingsdir/ignored", \%ignored);
665
666$checked{'ENABLE_IDS'}{'off'} = '';
667$checked{'ENABLE_IDS'}{'on'} = '';
668$checked{'ENABLE_IDS'}{$idssettings{'ENABLE_IDS'}} = "checked='checked'";
669$checked{'MONITOR_TRAFFIC_ONLY'}{'off'} = '';
670$checked{'MONITOR_TRAFFIC_ONLY'}{'on'} = '';
671$checked{'MONITOR_TRAFFIC_ONLY'}{$idssettings{'MONITOR_TRAFFIC_ONLY'}} = "checked='checked'";
672$selected{'RULES'}{'nothing'} = '';
673$selected{'RULES'}{'community'} = '';
674$selected{'RULES'}{'emerging'} = '';
675$selected{'RULES'}{'registered'} = '';
676$selected{'RULES'}{'subscripted'} = '';
677$selected{'RULES'}{$rulessettings{'RULES'}} = "selected='selected'";
678$selected{'AUTOUPDATE_INTERVAL'}{'off'} = '';
679$selected{'AUTOUPDATE_INTERVAL'}{'daily'} = '';
680$selected{'AUTOUPDATE_INTERVAL'}{'weekly'} = '';
681$selected{'AUTOUPDATE_INTERVAL'}{$rulessettings{'AUTOUPDATE_INTERVAL'}} = "selected='selected'";
682
683&Header::openpage($Lang::tr{'intrusion detection system'}, 1, '');
684
685### Java Script ###
686print"<script>\n";
687
688# Java script variable declaration for show and hide.
689print"var show = \"$Lang::tr{'ids show'}\"\;\n";
690print"var hide = \"$Lang::tr{'ids hide'}\"\;\n";
691
692print <<END
693 // Java Script function to show/hide the text input field for
694 // Oinkcode/Subscription code.
695 var update_code = function() {
696 if(\$('#RULES').val() == 'registered') {
697 \$('#code').show();
698 } else if(\$('#RULES').val() == 'subscripted') {
699 \$('#code').show();
700 } else if(\$('#RULES').val() == 'emerging_pro') {
701 \$('#code').show();
702 } else {
703 \$('#code').hide();
704 }
705 };
706
707 // JQuery function to call corresponding function when
708 // the ruleset is changed or the page is loaded for showing/hiding
709 // the code area.
710 \$(document).ready(function() {
711 \$('#RULES').change(update_code);
712 update_code();
713 });
714
715 // Tiny java script function to show/hide the rules
716 // of a given category.
717 function showhide(tblname) {
718 \$("#" + tblname).toggle();
719
720 // Get current content of the span element.
721 var content = document.getElementById("span_" + tblname);
722
723 if (content.innerHTML === show) {
724 content.innerHTML = hide;
725 } else {
726 content.innerHTML = show;
727 }
728 }
729</script>
730END
731;
732
733&Header::openbigbox('100%', 'left', '', $errormessage);
734
735if ($errormessage) {
736 &Header::openbox('100%', 'left', $Lang::tr{'error messages'});
737 print "<class name='base'>$errormessage\n";
738 print "&nbsp;</class>\n";
739 &Header::closebox();
740}
741
742# Draw current state of the IDS
743&Header::openbox('100%', 'left', $Lang::tr{'intrusion detection system'});
744
745# Check if the IDS is running and obtain the process-id.
746my $pid = &IDS::ids_is_running();
747
748# Display some useful information, if suricata daemon is running.
749if ($pid) {
750 # Gather used memory.
751 my $memory = &get_memory_usage($pid);
752
753 print <<END;
754 <table width='95%' cellspacing='0' class='tbl'>
755 <tr>
756 <th bgcolor='$color{'color20'}' colspan='3' align='left'><strong>$Lang::tr{'intrusion detection'}</strong></th>
757 </tr>
758
759 <tr>
760 <td class='base'>$Lang::tr{'guardian daemon'}</td>
761 <td align='center' colspan='2' width='75%' bgcolor='${Header::colourgreen}'><font color='white'><strong>$Lang::tr{'running'}</strong></font></td>
762 </tr>
763
764 <tr>
765 <td class='base'></td>
766 <td bgcolor='$color{'color20'}' align='center'><strong>PID</strong></td>
767 <td bgcolor='$color{'color20'}' align='center'><strong>$Lang::tr{'memory'}</strong></td>
768 </tr>
769
770 <tr>
771 <td class='base'></td>
772 <td bgcolor='$color{'color22'}' align='center'>$pid</td>
773 <td bgcolor='$color{'color22'}' align='center'>$memory KB</td>
774 </tr>
775 </table>
776END
777} else {
778 # Otherwise display a hint that the service is not launched.
779 print <<END;
780 <table width='95%' cellspacing='0' class='tbl'>
781 <tr>
782 <th bgcolor='$color{'color20'}' colspan='3' align='left'><strong>$Lang::tr{'intrusion detection'}</strong></th>
783 </tr>
784
785 <tr>
786 <td class='base'>$Lang::tr{'guardian daemon'}</td>
787 <td align='center' width='75%' bgcolor='${Header::colourred}'><font color='white'><strong>$Lang::tr{'stopped'}</strong></font></td>
788 </tr>
789 </table>
790END
791}
792
793# Only show this area, if a ruleset is present.
794if (%idsrules) {
795
796 print <<END
797
798 <br><br><h2>$Lang::tr{'settings'}</h2>
799
800 <form method='post' action='$ENV{'SCRIPT_NAME'}'>
801 <table width='100%' border='0'>
802 <tr>
803 <td class='base' colspan='2'>
804 <input type='checkbox' name='ENABLE_IDS' $checked{'ENABLE_IDS'}{'on'}>&nbsp;$Lang::tr{'ids enable'}
805 </td>
806
807 <td class='base' colspan='2'>
808 <input type='checkbox' name='MONITOR_TRAFFIC_ONLY' $checked{'MONITOR_TRAFFIC_ONLY'}{'on'}>&nbsp;$Lang::tr{'ids monitor traffic only'}
809 </td>
810 </tr>
811
812 <tr>
813 <td><br><br></td>
814 <td><br><br></td>
815 <td><br><br></td>
816 <td><br><br></td>
817 </tr>
818
819 <tr>
820 <td colspan='4'><b>$Lang::tr{'ids monitored interfaces'}</b><br></td>
821 </tr>
822
823 <tr>
824END
825;
826
827 # Loop through the array of available networks and print config options.
828 foreach my $zone (@network_zones) {
829 my $checked_input;
830 my $checked_forward;
831
832 # Convert current zone name to upper case.
833 my $zone_upper = uc($zone);
834
835 # Set zone name.
836 my $zone_name = $zone;
837
838 # Dirty hack to get the correct language string for the red zone.
839 if ($zone eq "red") {
840 $zone_name = "red1";
841 }
842
843 # Grab checkbox status from settings hash.
844 if ($idssettings{"ENABLE_IDS_$zone_upper"} eq "on") {
845 $checked_input = "checked = 'checked'";
846 }
847
848 print "<td class='base' width='20%'>\n";
849 print "<input type='checkbox' name='ENABLE_IDS_$zone_upper' $checked_input>\n";
850 print "&nbsp;$Lang::tr{'enabled on'}<font color='$colourhash{$zone}'> $Lang::tr{$zone_name}</font>\n";
851 print "</td>\n";
852 }
853
854print <<END
855 </tr>
856 </table>
857
858 <br><br>
859
860 <table width='100%'>
861 <tr>
862 <td align='right'><input type='submit' name='IDS' value='$Lang::tr{'save'}' /></td>
863 </tr>
864 </table>
865 </form>
866END
867;
868
869}
870
871&Header::closebox();
872
873# Draw elements for ruleset configuration.
874&Header::openbox('100%', 'center', $Lang::tr{'ids ruleset settings'});
875
876print <<END
877<form method='post' action='$ENV{'SCRIPT_NAME'}'>
878 <table width='100%' border='0'>
879 <tr>
880 <td><b>$Lang::tr{'ids rules update'}</b></td>
881 <td><b>$Lang::tr{'ids automatic rules update'}</b></td>
882 </tr>
883
884 <tr>
885 <td><select name='RULES' id='RULES'>
886 <option value='emerging' $selected{'RULES'}{'emerging'} >$Lang::tr{'emerging rules'}</option>
887 <option value='emerging_pro' $selected{'RULES'}{'emerging_pro'} >$Lang::tr{'emerging pro rules'}</option>
888 <option value='community' $selected{'RULES'}{'community'} >$Lang::tr{'community rules'}</option>
889 <option value='registered' $selected{'RULES'}{'registered'} >$Lang::tr{'registered user rules'}</option>
890 <option value='subscripted' $selected{'RULES'}{'subscripted'} >$Lang::tr{'subscripted user rules'}</option>
891 </select>
892 </td>
893
894 <td>
895 <select name='AUTOUPDATE_INTERVAL'>
896 <option value='off' $selected{'AUTOUPDATE_INTERVAL'}{'off'} >- $Lang::tr{'Disabled'} -</option>
897 <option value='daily' $selected{'AUTOUPDATE_INTERVAL'}{'daily'} >$Lang::tr{'Daily'}</option>
898 <option value='weekly' $selected{'AUTOUPDATE_INTERVAL'}{'weekly'} >$Lang::tr{'Weekly'}</option>
899 </select>
900 </td>
901 </tr>
902
903 <tr>
904 <td colspan='2'><br><br></td>
905 </tr>
906
907 <tr style='display:none' id='code'>
908 <td colspan='2'>Oinkcode:&nbsp;<input type='text' size='40' name='OINKCODE' value='$rulessettings{'OINKCODE'}'></td>
909 </tr>
910
911 <tr>
912 <td>&nbsp;</td>
913
914 <td align='right'>
915END
916;
917 # Show the "Update Ruleset"-Button only if a ruleset has been downloaded yet and automatic updates are disabled.
918 if ((%idsrules) && ($rulessettings{'AUTOUPDATE_INTERVAL'} eq "off")) {
919 # Display button to update the ruleset.
920 print"<input type='submit' name='RULESET' value='$Lang::tr{'update ruleset'}'>\n";
921 }
922print <<END;
923 <input type='submit' name='RULESET' value='$Lang::tr{'save'}'>
924 </td>
925
926 </tr>
927 </table>
928</form>
929END
930;
931
932&Header::closebox();
933
934#
935# Whitelist / Ignorelist
936#
937&Header::openbox('100%', 'center', $Lang::tr{'ids ignored hosts'});
938
939print <<END;
940 <table width='100%'>
941 <tr>
942 <td class='base' bgcolor='$color{'color20'}'><b>$Lang::tr{'ip address'}</b></td>
943 <td class='base' bgcolor='$color{'color20'}'><b>$Lang::tr{'remark'}</b></td>
944 <td class='base' colspan='3' bgcolor='$color{'color20'}'></td>
945 </tr>
946END
947 # Check if some hosts have been added to be ignored.
948 if (keys (%ignored)) {
949 my $col = "";
950
951 # Loop through all entries of the hash.
952 while( (my $key) = each %ignored) {
953 # Assign data array positions to some nice variable names.
954 my $address = $ignored{$key}[0];
955 my $remark = $ignored{$key}[1];
956 my $status = $ignored{$key}[2];
957
958 # Check if the key (id) number is even or not.
959 if ($cgiparams{'ID'} eq $key) {
960 $col="bgcolor='${Header::colouryellow}'";
961 } elsif ($key % 2) {
962 $col="bgcolor='$color{'color22'}'";
963 } else {
964 $col="bgcolor='$color{'color20'}'";
965 }
966
967 # Choose icon for the checkbox.
968 my $gif;
969 my $gdesc;
970
971 # Check if the status is enabled and select the correct image and description.
972 if ($status eq 'enabled' ) {
973 $gif = 'on.gif';
974 $gdesc = $Lang::tr{'click to disable'};
975 } else {
976 $gif = 'off.gif';
977 $gdesc = $Lang::tr{'click to enable'};
978 }
979
980print <<END;
981 <tr>
982 <td width='20%' class='base' $col>$address</td>
983 <td width='65%' class='base' $col>$remark</td>
984
985 <td align='center' $col>
986 <form method='post' action='$ENV{'SCRIPT_NAME'}'>
987 <input type='hidden' name='WHITELIST' value='$Lang::tr{'toggle enable disable'}' />
988 <input type='image' name='$Lang::tr{'toggle enable disable'}' src='/images/$gif' alt='$gdesc' title='$gdesc' />
989 <input type='hidden' name='ID' value='$key' />
990 </form>
991 </td>
992
993 <td align='center' $col>
994 <form method='post' action='$ENV{'SCRIPT_NAME'}'>
995 <input type='hidden' name='WHITELIST' value='$Lang::tr{'edit'}' />
996 <input type='image' name='$Lang::tr{'edit'}' src='/images/edit.gif' alt='$Lang::tr{'edit'}' title='$Lang::tr{'edit'}' />
997 <input type='hidden' name='ID' value='$key' />
998 </form>
999 </td>
1000
1001 <td align='center' $col>
1002 <form method='post' name='$key' action='$ENV{'SCRIPT_NAME'}'>
1003 <input type='image' name='$Lang::tr{'remove'}' src='/images/delete.gif' title='$Lang::tr{'remove'}' alt='$Lang::tr{'remove'}'>
1004 <input type='hidden' name='ID' value='$key'>
1005 <input type='hidden' name='WHITELIST' value='$Lang::tr{'remove'}'>
1006 </form>
1007 </td>
1008 </tr>
1009END
1010 }
1011 } else {
1012 # Print notice that currently no hosts are ignored.
1013 print "<tr>\n";
1014 print "<td class='base' colspan='2'>$Lang::tr{'guardian no entries'}</td>\n";
1015 print "</tr>\n";
1016 }
1017
1018 print "</table>\n";
1019
1020 # Section to add new elements or edit existing ones.
1021print <<END;
1022 <br>
1023 <hr>
1024 <br>
1025
1026 <div align='center'>
1027 <table width='100%'>
1028END
1029
1030 # Assign correct headline and button text.
1031 my $buttontext;
1032 my $entry_address;
1033 my $entry_remark;
1034
1035 # Check if an ID (key) has been given, in this case an existing entry should be edited.
1036 if ($cgiparams{'ID'} ne '') {
1037 $buttontext = $Lang::tr{'update'};
1038 print "<tr><td class='boldbase' colspan='3'><b>$Lang::tr{'update'}</b></td></tr>\n";
1039
1040 # Grab address and remark for the given key.
1041 $entry_address = $ignored{$cgiparams{'ID'}}[0];
1042 $entry_remark = $ignored{$cgiparams{'ID'}}[1];
1043 } else {
1044 $buttontext = $Lang::tr{'add'};
1045 print "<tr><td class='boldbase' colspan='3'><b>$Lang::tr{'dnsforward add a new entry'}</b></td></tr>\n";
1046 }
1047
1048print <<END;
1049 <form method='post' action='$ENV{'SCRIPT_NAME'}'>
1050 <input type='hidden' name='ID' value='$cgiparams{'ID'}'>
1051 <tr>
1052 <td width='30%'>$Lang::tr{'ip address'}: </td>
1053 <td width='50%'><input type='text' name='IGNORE_ENTRY_ADDRESS' value='$entry_address' size='24' /></td>
1054
1055 <td width='30%'>$Lang::tr{'remark'}: </td>
1056 <td wicth='50%'><input type='text' name=IGNORE_ENTRY_REMARK value='$entry_remark' size='24' /></td>
1057 <td align='center' width='20%'><input type='submit' name='WHITELIST' value='$buttontext' /></td>
1058 </tr>
1059 </form>
1060 </table>
1061 </div>
1062END
1063
1064&Header::closebox();
1065
1066# Only show the section for configuring the ruleset if one is present.
1067if (%idsrules) {
1068 # Load neccessary perl modules for file stat and to format the timestamp.
1069 use File::stat;
1070 use POSIX qw( strftime );
1071
1072 # Call stat on the rulestarball.
1073 my $stat = stat("$IDS::rulestarball");
1074
1075 # Get timestamp the file creation.
1076 my $mtime = $stat->mtime;
1077
1078 # Convert into human read-able format.
1079 my $rulesdate = strftime('%Y-%m-%d %H:%M:%S', localtime($mtime));
1080
1081 &Header::openbox('100%', 'LEFT', "$Lang::tr{'intrusion detection system rules'} ($rulesdate)" );
1082
1083 print"<form method='POST' action='$ENV{'SCRIPT_NAME'}'>\n";
1084
1085 # Output display table for rule files
1086 print "<table width='100%'>\n";
1087
1088 # Loop over each rule file
1089 foreach my $rulefile (sort keys(%idsrules)) {
1090 my $rulechecked = '';
1091
1092 # Check if rule file is enabled
1093 if ($idsrules{$rulefile}{'Rulefile'}{'State'} eq 'on') {
1094 $rulechecked = 'CHECKED';
1095 }
1096
1097 # Convert rulefile name into category name.
1098 my $categoryname = &_rulefile_to_category($rulefile);
1099
1100 # Table and rows for the rule files.
1101 print"<tr>\n";
1102 print"<td class='base' width='5%'>\n";
1103 print"<input type='checkbox' name='$rulefile' $rulechecked>\n";
1104 print"</td>\n";
1105 print"<td class='base' width='90%'><b>$rulefile</b></td>\n";
1106 print"<td class='base' width='5%' align='right'>\n";
1107 print"<a href=\"javascript:showhide('$categoryname')\"><span id='span_$categoryname'>$Lang::tr{'ids show'}</span></a>\n";
1108 print"</td>\n";
1109 print"</tr>\n";
1110
1111 # Rows which will be hidden per default and will contain the single rules.
1112 print"<tr style='display:none' id='$categoryname'>\n";
1113 print"<td colspan='3'>\n";
1114
1115 # Local vars
1116 my $lines;
1117 my $rows;
1118 my $col;
1119
1120 # New table for the single rules.
1121 print "<table width='100%'>\n";
1122
1123 # Loop over rule file rules
1124 foreach my $sid (sort {$a <=> $b} keys(%{$idsrules{$rulefile}})) {
1125 # Local vars
1126 my $ruledefchecked = '';
1127
1128 # Skip rulefile itself.
1129 next if ($sid eq "Rulefile");
1130
1131 # If 2 rules have been displayed, start a new row
1132 if (($lines % 2) == 0) {
1133 print "</tr><tr>\n";
1134
1135 # Increase rows by once.
1136 $rows++;
1137 }
1138
1139 # Colour lines.
1140 if ($rows % 2) {
1141 $col="bgcolor='$color{'color20'}'";
1142 } else {
1143 $col="bgcolor='$color{'color22'}'";
1144 }
1145
1146 # Set rule state
1147 if ($idsrules{$rulefile}{$sid}{'State'} eq 'on') {
1148 $ruledefchecked = 'CHECKED';
1149 }
1150
1151 # Create rule checkbox and display rule description
1152 print "<td class='base' width='5%' align='right' $col>\n";
1153 print "<input type='checkbox' NAME='$sid' $ruledefchecked>\n";
1154 print "</td>\n";
1155 print "<td class='base' width='45%' $col>$idsrules{$rulefile}{$sid}{'Description'}</td>";
1156
1157 # Increment rule count
1158 $lines++;
1159 }
1160
1161 # If do not have a second rule for row, create empty cell
1162 if (($lines % 2) != 0) {
1163 print "<td class='base'></td>";
1164 }
1165
1166 # Close display table
1167 print "</tr></table></td></tr>";
1168 }
1169
1170 # Close display table
1171 print "</table>";
1172
1173print <<END
1174<table width='100%'>
1175<tr>
1176 <td width='100%' align='right'><input type='submit' name='RULESET' value='$Lang::tr{'ids apply'}'></td>
1177</tr>
1178</table>
1179</form>
1180END
1181;
1182 &Header::closebox();
1183}
1184
1185&Header::closebigbox();
1186&Header::closepage();
1187
1188#
1189## A function to display a notice, to lock the webpage and
1190## tell the user which action currently will be performed.
1191#
1192sub working_notice ($) {
1193 my ($message) = @_;
1194
1195 &Header::openpage($Lang::tr{'intrusion detection system'}, 1, '');
1196 &Header::openbigbox('100%', 'left', '', $errormessage);
1197 &Header::openbox( 'Waiting', 1,);
1198 print <<END;
1199 <table>
1200 <tr>
1201 <td><img src='/images/indicator.gif' alt='$Lang::tr{'aktiv'}' /></td>
1202 <td>$message</td>
1203 </tr>
1204 </table>
1205END
1206 &Header::closebox();
1207 &Header::closebigbox();
1208 &Header::closepage();
1209}
1210
1211#
1212## A tiny function to perform a reload of the webpage after one second.
1213#
1214sub reload () {
1215 print "<meta http-equiv='refresh' content='1'>\n";
1216
1217 # Stop the script.
1218 exit;
1219}
1220
1221#
1222## Private function to read-in and parse rules of a given rulefile.
1223#
1224## The given file will be read, parsed and all valid rules will be stored by ID,
1225## message/description and it's state in the idsrules hash.
1226#
1227sub readrulesfile ($) {
1228 my $rulefile = shift;
1229
1230 # Open rule file and read in contents
1231 open(RULEFILE, "$IDS::rulespath/$rulefile") or die "Unable to read $rulefile!";
1232
1233 # Store file content in an array.
1234 my @lines = <RULEFILE>;
1235
1236 # Close file.
1237 close(RULEFILE);
1238
1239 # Loop over rule file contents
1240 foreach my $line (@lines) {
1241 # Remove whitespaces.
1242 chomp $line;
1243
1244 # Skip blank lines.
1245 next if ($line =~ /^\s*$/);
1246
1247 # Local vars.
1248 my $sid;
1249 my $msg;
1250
1251 # Gather rule sid and message from the ruleline.
1252 if ($line =~ m/.*msg:\"(.*?)\"\; .* sid:(.*?); /) {
1253 $msg = $1;
1254 $sid = $2;
1255
1256 # Check if a rule has been found.
1257 if ($sid && $msg) {
1258 # Add rule to the idsrules hash.
1259 $idsrules{$rulefile}{$sid}{'Description'} = $msg;
1260
1261 # Grab status of the rule. Check if ruleline starts with a "dash".
1262 if ($line =~ /^\#/) {
1263 # If yes, the rule is disabled.
1264 $idsrules{$rulefile}{$sid}{'State'} = "off";
1265 } else {
1266 # Otherwise the rule is enabled.
1267 $idsrules{$rulefile}{$sid}{'State'} = "on";
1268 }
1269 }
1270 }
1271 }
1272}
1273
1274#
1275## Function to get the used memory of a given process-id.
1276#
1277sub get_memory_usage($) {
1278 my ($pid) = @_;
1279
1280 my $memory = 0;
1281
1282 # Try to open the status file for the given process-id on the pseudo
1283 # file system proc.
1284 if (open(FILE, "/proc/$pid/status")) {
1285 # Loop through the entire file.
1286 while (<FILE>) {
1287 # Splitt current line content and store them into variables.
1288 my ($key, $value) = split(":", $_, 2);
1289
1290 # Check if the current key is the one which contains the memory usage.
1291 # The wanted one is VmRSS which contains the Real-memory (resident set)
1292 # of the entire process.
1293 if ($key eq "VmRSS") {
1294 # Found the memory usage add it to the memory variable.
1295 $memory += $value;
1296
1297 # Break the loop.
1298 last;
1299 }
1300 }
1301
1302 # Close file handle.
1303 close(FILE);
1304
1305 # Return memory usage.
1306 return $memory;
1307 }
1308
1309 # If the file could not be open, return nothing.
1310 return;
1311}
1312
1313#
1314## Function to read-in the given enabled or disables sids file.
1315#
1316sub read_enabled_disabled_sids_file($) {
1317 my ($file) = @_;
1318
1319 # Temporary hash to store the sids and their state. It will be
1320 # returned at the end of this function.
1321 my %temphash;
1322
1323 # Open the given filename.
1324 open(FILE, "$file") or die "Could not open $file. $!\n";
1325
1326 # Loop through the file.
1327 while(<FILE>) {
1328 # Remove newlines.
1329 chomp $_;
1330
1331 # Skip blank lines.
1332 next if ($_ =~ /^\s*$/);
1333
1334 # Skip coments.
1335 next if ($_ =~ /^\#/);
1336
1337 # Splitt line into sid and state part.
1338 my ($state, $sid) = split(" ", $_);
1339
1340 # Skip line if the sid is not numeric.
1341 next unless ($sid =~ /\d+/ );
1342
1343 # Check if the sid was enabled.
1344 if ($state eq "enablesid") {
1345 # Add the sid and its state as enabled to the temporary hash.
1346 $temphash{$sid} = "enabled";
1347 # Check if the sid was disabled.
1348 } elsif ($state eq "disablesid") {
1349 # Add the sid and its state as disabled to the temporary hash.
1350 $temphash{$sid} = "disabled";
1351 # Invalid state - skip the current sid and state.
1352 } else {
1353 next;
1354 }
1355 }
1356
1357 # Close filehandle.
1358 close(FILE);
1359
1360 # Return the hash.
1361 return %temphash;
1362}
1363
1364#
1365## Private function to convert a given rulefile to a category name.
1366## ( No file extension anymore and if the name contained a dot, it
1367## would be replaced by a underline sign.)
1368#
1369sub _rulefile_to_category($) {
1370 my ($filename) = @_;
1371
1372 # Splitt the filename into single chunks and store them in a
1373 # temorary array.
1374 my @parts = split(/\./, $filename);
1375
1376 # Return / Remove last element of the temporary array.
1377 # This removes the file extension.
1378 pop @parts;
1379
1380 # Join together the single elements of the temporary array.
1381 # If these are more than one, use a "underline" for joining.
1382 my $category = join '_', @parts;
1383
1384 # Return the converted filename.
1385 return $category;
1386}