]> git.ipfire.org Git - ipfire-2.x.git/blob - html/cgi-bin/ids.cgi
Merge branch 'next' of ssh://git.ipfire.org/pub/git/ipfire-2.x into next-suricata
[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 # Temporary variable to set the ruleaction.
531 # Default is "drop" to use suricata as IPS.
532 my $ruleaction="drop";
533
534 # Check if the traffic only should be monitored.
535 if($cgiparams{'MONITOR_TRAFFIC_ONLY'} eq 'on') {
536 # Switch the ruleaction to "alert".
537 # Suricata acts as an IDS only.
538 $ruleaction="alert";
539 }
540
541 # Write the modify sid's file and pass the taken ruleaction.
542 &IDS::write_modify_sids_file($ruleaction);
543
544 # Check if "MONITOR_TRAFFIC_ONLY" has been changed.
545 if($cgiparams{'MONITOR_TRAFFIC_ONLY'} ne $oldidssettings{'MONITOR_TRAFFIC_ONLY'}) {
546 # Check if a ruleset exists.
547 if (%idsrules) {
548 # Lock the webpage and print message.
549 &working_notice("$Lang::tr{'snort working'}");
550
551 # Call oinkmaster to alter the ruleset.
552 &IDS::oinkmaster();
553
554 # Set reload_page to "True".
555 $reload_page="True";
556 }
557 }
558
559 # Check if the IDS currently is running.
560 if(&IDS::ids_is_running()) {
561 # Check if ENABLE_IDS is set to on.
562 if($cgiparams{'ENABLE_IDS'} eq "on") {
563 # Call suricatactrl to perform a reload of suricata.
564 &IDS::call_suricatactrl("reload");
565 } else {
566 # Call suricatactrl to stop suricata.
567 &IDS::call_suricatactrl("stop");
568 }
569 } else {
570 # Call suricatactrl to start suricata.
571 &IDS::call_suricatactrl("start");
572 }
573
574 # Check if the page should be reloaded.
575 if ($reload_page) {
576 # Perform a reload of the page.
577 &reload();
578 }
579 }
580
581 # Read-in idssettings and rulesetsettings
582 &General::readhash("$IDS::ids_settings_file", \%idssettings);
583 &General::readhash("$IDS::rules_settings_file", \%rulessettings);
584
585 # If no autoupdate intervall has been configured yet, set default value.
586 unless(exists($rulessettings{'AUTOUPDATE_INTERVAL'})) {
587 # Set default to "weekly".
588 $rulessettings{'AUTOUPDATE_INTERVAL'} = 'weekly';
589 }
590
591 # Read-in ignored hosts.
592 &General::readhasharray("$IDS::settingsdir/ignored", \%ignored);
593
594 $checked{'ENABLE_IDS'}{'off'} = '';
595 $checked{'ENABLE_IDS'}{'on'} = '';
596 $checked{'ENABLE_IDS'}{$idssettings{'ENABLE_IDS'}} = "checked='checked'";
597 $checked{'MONITOR_TRAFFIC_ONLY'}{'off'} = '';
598 $checked{'MONITOR_TRAFFIC_ONLY'}{'on'} = '';
599 $checked{'MONITOR_TRAFFIC_ONLY'}{$idssettings{'MONITOR_TRAFFIC_ONLY'}} = "checked='checked'";
600 $selected{'RULES'}{'nothing'} = '';
601 $selected{'RULES'}{'community'} = '';
602 $selected{'RULES'}{'emerging'} = '';
603 $selected{'RULES'}{'registered'} = '';
604 $selected{'RULES'}{'subscripted'} = '';
605 $selected{'RULES'}{$rulessettings{'RULES'}} = "selected='selected'";
606 $selected{'AUTOUPDATE_INTERVAL'}{'off'} = '';
607 $selected{'AUTOUPDATE_INTERVAL'}{'daily'} = '';
608 $selected{'AUTOUPDATE_INTERVAL'}{'weekly'} = '';
609 $selected{'AUTOUPDATE_INTERVAL'}{$rulessettings{'AUTOUPDATE_INTERVAL'}} = "selected='selected'";
610
611 &Header::openpage($Lang::tr{'intrusion detection system'}, 1, '');
612
613 ### Java Script ###
614 print <<END
615 <script>
616 // Tiny java script function to show/hide the rules
617 // of a given category.
618 function showhide(tblname) {
619 \$("#" + tblname).toggle();
620 }
621 </script>
622 END
623 ;
624
625 &Header::openbigbox('100%', 'left', '', $errormessage);
626
627 if ($errormessage) {
628 &Header::openbox('100%', 'left', $Lang::tr{'error messages'});
629 print "<class name='base'>$errormessage\n";
630 print "&nbsp;</class>\n";
631 &Header::closebox();
632 }
633
634 # Draw current state of the IDS
635 &Header::openbox('100%', 'left', $Lang::tr{'intrusion detection system'});
636
637 # Check if the IDS is running and obtain the process-id.
638 my $pid = &IDS::ids_is_running();
639
640 # Display some useful information, if suricata daemon is running.
641 if ($pid) {
642 # Gather used memory.
643 my $memory = &get_memory_usage($pid);
644
645 print <<END;
646 <table width='95%' cellspacing='0' class='tbl'>
647 <tr>
648 <th bgcolor='$color{'color20'}' colspan='3' align='left'><strong>$Lang::tr{'intrusion detection'}</strong></th>
649 </tr>
650
651 <tr>
652 <td class='base'>$Lang::tr{'guardian daemon'}</td>
653 <td align='center' colspan='2' width='75%' bgcolor='${Header::colourgreen}'><font color='white'><strong>$Lang::tr{'running'}</strong></font></td>
654 </tr>
655
656 <tr>
657 <td class='base'></td>
658 <td bgcolor='$color{'color20'}' align='center'><strong>PID</strong></td>
659 <td bgcolor='$color{'color20'}' align='center'><strong>$Lang::tr{'memory'}</strong></td>
660 </tr>
661
662 <tr>
663 <td class='base'></td>
664 <td bgcolor='$color{'color22'}' align='center'>$pid</td>
665 <td bgcolor='$color{'color22'}' align='center'>$memory KB</td>
666 </tr>
667 </table>
668 END
669 } else {
670 # Otherwise display a hint that the service is not launched.
671 print <<END;
672 <table width='95%' cellspacing='0' class='tbl'>
673 <tr>
674 <th bgcolor='$color{'color20'}' colspan='3' align='left'><strong>$Lang::tr{'intrusion detection'}</strong></th>
675 </tr>
676
677 <tr>
678 <td class='base'>$Lang::tr{'guardian daemon'}</td>
679 <td align='center' width='75%' bgcolor='${Header::colourred}'><font color='white'><strong>$Lang::tr{'stopped'}</strong></font></td>
680 </tr>
681 </table>
682 END
683 }
684 &Header::closebox();
685
686 my $rulesdate;
687
688 # Check if a ruleset allready has been downloaded.
689 if ( -f "$IDS::rulestarball"){
690 # Call stat on the filename to obtain detailed information.
691 my @Info = stat("$IDS::rulestarball");
692
693 # Grab details about the creation time.
694 $rulesdate = localtime($Info[9]);
695 }
696
697 # Draw elements for IDS configuration.
698 &Header::openbox('100%', 'center', $Lang::tr{'settings'});
699
700 print <<END
701 <form method='post' action='$ENV{'SCRIPT_NAME'}'>
702 <table width='100%' border='0'>
703 <tr>
704 <td class='base' colspan='2'>
705 <input type='checkbox' name='ENABLE_IDS' $checked{'ENABLE_IDS'}{'on'}>$Lang::tr{'ids activate'} $Lang::tr{'intrusion detection system'}
706 </td>
707
708 <td class='base' colspan='2'>
709 <input type='checkbox' name='MONITOR_TRAFFIC_ONLY' $checked{'MONITOR_TRAFFIC_ONLY'}{'on'}>$Lang::tr{'ids monitor traffic only'}
710 </td>
711 </tr>
712
713 <tr>
714 <td><br><br></td>
715 <td><br><br></td>
716 <td><br><br></td>
717 <td><br><br></td>
718 </tr>
719
720 <tr>
721 <td colspan='4'><b>$Lang::tr{'ids monitored interfaces'}</b><br></td>
722 </tr>
723
724 <tr>
725 END
726 ;
727
728 # Loop through the array of available networks and print config options.
729 foreach my $zone (@network_zones) {
730 my $checked_input;
731 my $checked_forward;
732
733 # Convert current zone name to upper case.
734 my $zone_upper = uc($zone);
735
736 # Set zone name.
737 my $zone_name = $zone;
738
739 # Dirty hack to get the correct language string for the red zone.
740 if ($zone eq "red") {
741 $zone_name = "red1";
742 }
743
744 # Grab checkbox status from settings hash.
745 if ($idssettings{"ENABLE_IDS_$zone_upper"} eq "on") {
746 $checked_input = "checked = 'checked'";
747 }
748
749 print "<td class='base' width='25%'>\n";
750 print "<input type='checkbox' name='ENABLE_IDS_$zone_upper' $checked_input>\n";
751 print "&nbsp$Lang::tr{'enabled on'}<font color='$colourhash{$zone}'> $Lang::tr{$zone_name}</font>\n";
752 print "</td>\n";
753 }
754
755 print <<END
756 </tr>
757 </table>
758
759 <br><br>
760
761 <table width='100%'>
762 <tr>
763 <td align='right'><input type='submit' name='IDS' value='$Lang::tr{'save'}' /></td>
764 </tr>
765 </table>
766 </form>
767 END
768 ;
769
770 &Header::closebox();
771
772 # Draw elements for ruleset configuration.
773 &Header::openbox('100%', 'center', $Lang::tr{'ids ruleset settings'});
774
775 print <<END
776 <form method='post' action='$ENV{'SCRIPT_NAME'}'>
777 <table width='100%' border='0'>
778 <tr>
779 <td><b>$Lang::tr{'ids rules update'}</b></td>
780 <td><b>$Lang::tr{'ids automatic rules update'}</b></td>
781 </tr>
782
783 <tr>
784 <td><select name='RULES'>
785 <option value='emerging' $selected{'RULES'}{'emerging'} >$Lang::tr{'emerging rules'}</option>
786 <option value='community' $selected{'RULES'}{'community'} >$Lang::tr{'community rules'}</option>
787 <option value='registered' $selected{'RULES'}{'registered'} >$Lang::tr{'registered user rules'}</option>
788 <option value='subscripted' $selected{'RULES'}{'subscripted'} >$Lang::tr{'subscripted user rules'}</option>
789 </select>
790 </td>
791
792 <td>
793 <select name='AUTOUPDATE_INTERVAL'>
794 <option value='off' $selected{'AUTOUPDATE_INTERVAL'}{'off'} >$Lang::tr{'no'}</option>
795 <option value='daily' $selected{'AUTOUPDATE_INTERVAL'}{'daily'} >$Lang::tr{'urlfilter daily'}</option>
796 <option value='weekly' $selected{'AUTOUPDATE_INTERVAL'}{'weekly'} >$Lang::tr{'urlfilter weekly'}</option>
797 </select>
798 </td>
799 </tr>
800
801 <tr>
802 <td colspan='2'>
803 <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>
804 <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>
805 </td>
806 </tr>
807
808 <tr>
809 <td colspan='2' nowrap='nowrap'>Oinkcode:&nbsp;<input type='text' size='40' name='OINKCODE' value='$rulessettings{'OINKCODE'}'></td>
810 </tr>
811
812 <tr>
813 <td>&nbsp;</td>
814
815 <td align='right'>
816 END
817 ;
818 # Check if a ruleset source has been configured yet.
819 unless($rulessettings{'RULES'}) {
820 # If no ruleset settings have been saved yet, disable the button to download / update the ruleset.
821 print"<input type='submit' name='RULESET' disabled='disabled' value='$Lang::tr{'download new ruleset'}'>\n";
822 } else {
823 # Ruleset setting have been saved. - Check if a ruleset already is downloaded.
824 if (%idsrules) {
825 # Allow to press the button and show it as "update ruleset".
826 print"<input type='submit' name='RULESET' value='$Lang::tr{'update ruleset'}'>\n";
827 } else {
828 # Also allow to press the button, but show it as "download new ruleset".
829 print"<input type='submit' name='RULESET' value='$Lang::tr{'download new ruleset'}'>\n";
830 }
831 }
832 print <<END;
833 <input type='submit' name='RULESET' value='$Lang::tr{'save'}'>
834 </td>
835
836 </tr>
837 </table>
838 </form>
839 END
840 ;
841
842 &Header::closebox();
843
844 #
845 # Whitelist / Ignorelist
846 #
847 &Header::openbox('100%', 'center', $Lang::tr{'guardian ignored hosts'});
848
849 print <<END;
850 <table width='100%'>
851 <tr>
852 <td class='base' bgcolor='$color{'color20'}'><b>$Lang::tr{'ip address'}</b></td>
853 <td class='base' bgcolor='$color{'color20'}'><b>$Lang::tr{'remark'}</b></td>
854 <td class='base' colspan='3' bgcolor='$color{'color20'}'></td>
855 </tr>
856 END
857 # Check if some hosts have been added to be ignored.
858 if (keys (%ignored)) {
859 my $col = "";
860
861 # Loop through all entries of the hash.
862 while( (my $key) = each %ignored) {
863 # Assign data array positions to some nice variable names.
864 my $address = $ignored{$key}[0];
865 my $remark = $ignored{$key}[1];
866 my $status = $ignored{$key}[2];
867
868 # Check if the key (id) number is even or not.
869 if ($cgiparams{'ID'} eq $key) {
870 $col="bgcolor='${Header::colouryellow}'";
871 } elsif ($key % 2) {
872 $col="bgcolor='$color{'color22'}'";
873 } else {
874 $col="bgcolor='$color{'color20'}'";
875 }
876
877 # Choose icon for the checkbox.
878 my $gif;
879 my $gdesc;
880
881 # Check if the status is enabled and select the correct image and description.
882 if ($status eq 'enabled' ) {
883 $gif = 'on.gif';
884 $gdesc = $Lang::tr{'click to disable'};
885 } else {
886 $gif = 'off.gif';
887 $gdesc = $Lang::tr{'click to enable'};
888 }
889
890 print <<END;
891 <tr>
892 <td width='20%' class='base' $col>$address</td>
893 <td width='65%' class='base' $col>$remark</td>
894
895 <td align='center' $col>
896 <form method='post' action='$ENV{'SCRIPT_NAME'}'>
897 <input type='hidden' name='WHITELIST' value='$Lang::tr{'toggle enable disable'}' />
898 <input type='image' name='$Lang::tr{'toggle enable disable'}' src='/images/$gif' alt='$gdesc' title='$gdesc' />
899 <input type='hidden' name='ID' value='$key' />
900 </form>
901 </td>
902
903 <td align='center' $col>
904 <form method='post' action='$ENV{'SCRIPT_NAME'}'>
905 <input type='hidden' name='WHITELIST' value='$Lang::tr{'edit'}' />
906 <input type='image' name='$Lang::tr{'edit'}' src='/images/edit.gif' alt='$Lang::tr{'edit'}' title='$Lang::tr{'edit'}' />
907 <input type='hidden' name='ID' value='$key' />
908 </form>
909 </td>
910
911 <td align='center' $col>
912 <form method='post' name='$key' action='$ENV{'SCRIPT_NAME'}'>
913 <input type='image' name='$Lang::tr{'remove'}' src='/images/delete.gif' title='$Lang::tr{'remove'}' alt='$Lang::tr{'remove'}'>
914 <input type='hidden' name='ID' value='$key'>
915 <input type='hidden' name='WHITELIST' value='$Lang::tr{'remove'}'>
916 </form>
917 </td>
918 </tr>
919 END
920 }
921 } else {
922 # Print notice that currently no hosts are ignored.
923 print "<tr>\n";
924 print "<td class='base' colspan='2'>$Lang::tr{'guardian no entries'}</td>\n";
925 print "</tr>\n";
926 }
927
928 print "</table>\n";
929
930 # Section to add new elements or edit existing ones.
931 print <<END;
932 <br>
933 <hr>
934 <br>
935
936 <div align='center'>
937 <table width='100%'>
938 END
939
940 # Assign correct headline and button text.
941 my $buttontext;
942 my $entry_address;
943 my $entry_remark;
944
945 # Check if an ID (key) has been given, in this case an existing entry should be edited.
946 if ($cgiparams{'ID'} ne '') {
947 $buttontext = $Lang::tr{'update'};
948 print "<tr><td class='boldbase' colspan='3'><b>$Lang::tr{'update'}</b></td></tr>\n";
949
950 # Grab address and remark for the given key.
951 $entry_address = $ignored{$cgiparams{'ID'}}[0];
952 $entry_remark = $ignored{$cgiparams{'ID'}}[1];
953 } else {
954 $buttontext = $Lang::tr{'add'};
955 print "<tr><td class='boldbase' colspan='3'><b>$Lang::tr{'dnsforward add a new entry'}</b></td></tr>\n";
956 }
957
958 print <<END;
959 <form method='post' action='$ENV{'SCRIPT_NAME'}'>
960 <input type='hidden' name='ID' value='$cgiparams{'ID'}'>
961 <tr>
962 <td width='30%'>$Lang::tr{'ip address'}: </td>
963 <td width='50%'><input type='text' name='IGNORE_ENTRY_ADDRESS' value='$entry_address' size='24' /></td>
964
965 <td width='30%'>$Lang::tr{'remark'}: </td>
966 <td wicth='50%'><input type='text' name=IGNORE_ENTRY_REMARK value='$entry_remark' size='24' /></td>
967 <td align='center' width='20%'><input type='submit' name='WHITELIST' value='$buttontext' /></td>
968 </tr>
969 </form>
970 </table>
971 </div>
972 END
973
974 &Header::closebox();
975
976 # Only show the section for configuring the ruleset if one is present.
977 if (%idsrules) {
978 &Header::openbox('100%', 'LEFT', $Lang::tr{'intrusion detection system rules'});
979
980 print"<form method='POST' action='$ENV{'SCRIPT_NAME'}'>\n";
981
982 # Output display table for rule files
983 print "<table width='100%'>\n";
984
985 # Loop over each rule file
986 foreach my $rulefile (sort keys(%idsrules)) {
987 my $rulechecked = '';
988
989 # Check if rule file is enabled
990 if ($idsrules{$rulefile}{'Rulefile'}{'State'} eq 'on') {
991 $rulechecked = 'CHECKED';
992 }
993
994 # Convert rulefile name into category name.
995 my $categoryname = &_rulefile_to_category($rulefile);
996
997 # Table and rows for the rule files.
998 print"<tr>\n";
999 print"<td class='base' width='5%'>\n";
1000 print"<input type='checkbox' name='$rulefile' $rulechecked>\n";
1001 print"</td>\n";
1002 print"<td class='base' width='90%'><b>$rulefile</b></td>\n";
1003 print"<td class='base' width='5%' align='right'>\n";
1004 print"<a href=\"javascript:showhide('$categoryname')\">SHOW</a>\n";
1005 print"</td>\n";
1006 print"</tr>\n";
1007
1008 # Rows which will be hidden per default and will contain the single rules.
1009 print"<tr style='display:none' id='$categoryname'>\n";
1010 print"<td colspan='3'>\n";
1011
1012 # Local vars
1013 my $lines;
1014 my $rows;
1015 my $col;
1016
1017 # New table for the single rules.
1018 print "<table width='100%'>\n";
1019
1020 # Loop over rule file rules
1021 foreach my $sid (sort {$a <=> $b} keys(%{$idsrules{$rulefile}})) {
1022 # Local vars
1023 my $ruledefchecked = '';
1024
1025 # Skip rulefile itself.
1026 next if ($sid eq "Rulefile");
1027
1028 # If 2 rules have been displayed, start a new row
1029 if (($lines % 2) == 0) {
1030 print "</tr><tr>\n";
1031
1032 # Increase rows by once.
1033 $rows++;
1034 }
1035
1036 # Colour lines.
1037 if ($rows % 2) {
1038 $col="bgcolor='$color{'color20'}'";
1039 } else {
1040 $col="bgcolor='$color{'color22'}'";
1041 }
1042
1043 # Set rule state
1044 if ($idsrules{$rulefile}{$sid}{'State'} eq 'on') {
1045 $ruledefchecked = 'CHECKED';
1046 }
1047
1048 # Create rule checkbox and display rule description
1049 print "<td class='base' width='5%' align='right' $col>\n";
1050 print "<input type='checkbox' NAME='$sid' $ruledefchecked>\n";
1051 print "</td>\n";
1052 print "<td class='base' width='45%' $col>$idsrules{$rulefile}{$sid}{'Description'}</td>";
1053
1054 # Increment rule count
1055 $lines++;
1056 }
1057
1058 # If do not have a second rule for row, create empty cell
1059 if (($lines % 2) != 0) {
1060 print "<td class='base'></td>";
1061 }
1062
1063 # Close display table
1064 print "</tr></table></td></tr>";
1065 }
1066
1067 # Close display table
1068 print "</table>";
1069
1070 print <<END
1071 <table width='100%'>
1072 <tr>
1073 <td width='100%' align='right'><input type='submit' name='RULESET' value='$Lang::tr{'update'}'>
1074 &nbsp; <!-- space for future online help link -->
1075 </td>
1076 </tr>
1077 </table>
1078 </form>
1079 END
1080 ;
1081 &Header::closebox();
1082 }
1083
1084 &Header::closebigbox();
1085 &Header::closepage();
1086
1087 #
1088 ## A function to display a notice, to lock the webpage and
1089 ## tell the user which action currently will be performed.
1090 #
1091 sub working_notice ($) {
1092 my ($message) = @_;
1093
1094 &Header::openpage($Lang::tr{'intrusion detection system'}, 1, '');
1095 &Header::openbigbox('100%', 'left', '', $errormessage);
1096 &Header::openbox( 'Waiting', 1,);
1097 print <<END;
1098 <table>
1099 <tr>
1100 <td><img src='/images/indicator.gif' alt='$Lang::tr{'aktiv'}' /></td>
1101 <td>$message</td>
1102 </tr>
1103 </table>
1104 END
1105 &Header::closebox();
1106 &Header::closebigbox();
1107 &Header::closepage();
1108 }
1109
1110 #
1111 ## A tiny function to perform a reload of the webpage after one second.
1112 #
1113 sub reload () {
1114 print "<meta http-equiv='refresh' content='1'>\n";
1115
1116 # Stop the script.
1117 exit;
1118 }
1119
1120 #
1121 ## Private function to read-in and parse rules of a given rulefile.
1122 #
1123 ## The given file will be read, parsed and all valid rules will be stored by ID,
1124 ## message/description and it's state in the idsrules hash.
1125 #
1126 sub readrulesfile ($) {
1127 my $rulefile = shift;
1128
1129 # Open rule file and read in contents
1130 open(RULEFILE, "$IDS::rulespath/$rulefile") or die "Unable to read $rulefile!";
1131
1132 # Store file content in an array.
1133 my @lines = <RULEFILE>;
1134
1135 # Close file.
1136 close(RULEFILE);
1137
1138 # Loop over rule file contents
1139 foreach my $line (@lines) {
1140 # Remove whitespaces.
1141 chomp $line;
1142
1143 # Skip blank lines.
1144 next if ($line =~ /^\s*$/);
1145
1146 # Local vars.
1147 my $sid;
1148 my $msg;
1149
1150 # Gather rule sid and message from the ruleline.
1151 if ($line =~ m/.*msg:\"(.*?)\"\; .* sid:(.*?); /) {
1152 $msg = $1;
1153 $sid = $2;
1154
1155 # Check if a rule has been found.
1156 if ($sid && $msg) {
1157 # Add rule to the idsrules hash.
1158 $idsrules{$rulefile}{$sid}{'Description'} = $msg;
1159
1160 # Grab status of the rule. Check if ruleline starts with a "dash".
1161 if ($line =~ /^\#/) {
1162 # If yes, the rule is disabled.
1163 $idsrules{$rulefile}{$sid}{'State'} = "off";
1164 } else {
1165 # Otherwise the rule is enabled.
1166 $idsrules{$rulefile}{$sid}{'State'} = "on";
1167 }
1168 }
1169 }
1170 }
1171 }
1172
1173 #
1174 ## Function to get the used memory of a given process-id.
1175 #
1176 sub get_memory_usage($) {
1177 my ($pid) = @_;
1178
1179 my $memory = 0;
1180
1181 # Try to open the status file for the given process-id on the pseudo
1182 # file system proc.
1183 if (open(FILE, "/proc/$pid/status")) {
1184 # Loop through the entire file.
1185 while (<FILE>) {
1186 # Splitt current line content and store them into variables.
1187 my ($key, $value) = split(":", $_, 2);
1188
1189 # Check if the current key is the one which contains the memory usage.
1190 # The wanted one is VmRSS which contains the Real-memory (resident set)
1191 # of the entire process.
1192 if ($key eq "VmRSS") {
1193 # Found the memory usage add it to the memory variable.
1194 $memory += $value;
1195
1196 # Break the loop.
1197 last;
1198 }
1199 }
1200
1201 # Close file handle.
1202 close(FILE);
1203
1204 # Return memory usage.
1205 return $memory;
1206 }
1207
1208 # If the file could not be open, return nothing.
1209 return;
1210 }
1211
1212 #
1213 ## Function to generate the rules file with whitelisted addresses.
1214 #
1215 sub GenerateIgnoreFile() {
1216 my %ignored = ();
1217
1218 # SID range 1000000-1999999 Reserved for Local Use
1219 # Put your custom rules in this range to avoid conflicts
1220 my $sid = 1500000;
1221
1222 # Read-in ignoredfile.
1223 &General::readhasharray($IDS::ignored_file, \%ignored);
1224
1225 # Open ignorefile for writing.
1226 open(FILE, ">$IDS::whitelist_file") or die "Could not write to $IDS::whitelist_file. $!\n";
1227
1228 # Config file header.
1229 print FILE "# Autogenerated file.\n";
1230 print FILE "# All user modifications will be overwritten.\n\n";
1231
1232 # Add all user defined addresses to the whitelist.
1233 #
1234 # Check if the hash contains any elements.
1235 if (keys (%ignored)) {
1236 # Loop through the entire hash and write the host/network
1237 # and remark to the ignore file.
1238 while ( (my $key) = each %ignored) {
1239 my $address = $ignored{$key}[0];
1240 my $remark = $ignored{$key}[1];
1241 my $status = $ignored{$key}[2];
1242
1243 # Check if the status of the entry is "enabled".
1244 if ($status eq "enabled") {
1245 # Check if the address/network is valid.
1246 if ((&General::validip($address)) || (&General::validipandmask($address))) {
1247 # Write rule line to the file to pass any traffic from this IP
1248 print FILE "pass ip $address any -> any any (msg:\"pass all traffic from/to $address\"\; sid:$sid\;)\n";
1249
1250 # Increment sid.
1251 $sid++;
1252 }
1253 }
1254 }
1255 }
1256
1257 close(FILE);
1258 }
1259
1260 #
1261 ## Function to read-in the given enabled or disables sids file.
1262 #
1263 sub read_enabled_disabled_sids_file($) {
1264 my ($file) = @_;
1265
1266 # Temporary hash to store the sids and their state. It will be
1267 # returned at the end of this function.
1268 my %temphash;
1269
1270 # Open the given filename.
1271 open(FILE, "$file") or die "Could not open $file. $!\n";
1272
1273 # Loop through the file.
1274 while(<FILE>) {
1275 # Remove newlines.
1276 chomp $_;
1277
1278 # Skip blank lines.
1279 next if ($_ =~ /^\s*$/);
1280
1281 # Skip coments.
1282 next if ($_ =~ /^\#/);
1283
1284 # Splitt line into sid and state part.
1285 my ($state, $sid) = split(" ", $_);
1286
1287 # Skip line if the sid is not numeric.
1288 next unless ($sid =~ /\d+/ );
1289
1290 # Check if the sid was enabled.
1291 if ($state eq "enablesid") {
1292 # Add the sid and its state as enabled to the temporary hash.
1293 $temphash{$sid} = "enabled";
1294 # Check if the sid was disabled.
1295 } elsif ($state eq "disablesid") {
1296 # Add the sid and its state as disabled to the temporary hash.
1297 $temphash{$sid} = "disabled";
1298 # Invalid state - skip the current sid and state.
1299 } else {
1300 next;
1301 }
1302 }
1303
1304 # Close filehandle.
1305 close(FILE);
1306
1307 # Return the hash.
1308 return %temphash;
1309 }
1310
1311 #
1312 ## Private function to convert a given rulefile to a category name.
1313 ## ( No file extension anymore and if the name contained a dot, it
1314 ## would be replaced by a underline sign.)
1315 #
1316 sub _rulefile_to_category($) {
1317 my ($filename) = @_;
1318
1319 # Splitt the filename into single chunks and store them in a
1320 # temorary array.
1321 my @parts = split(/\./, $filename);
1322
1323 # Return / Remove last element of the temporary array.
1324 # This removes the file extension.
1325 pop @parts;
1326
1327 # Join together the single elements of the temporary array.
1328 # If these are more than one, use a "underline" for joining.
1329 my $category = join '_', @parts;
1330
1331 # Return the converted filename.
1332 return $category;
1333 }