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