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