]>
Commit | Line | Data |
---|---|---|
1 | #!/usr/bin/perl -w | |
2 | ############################################################################ | |
3 | # # | |
4 | # This file is part of the IPFire Firewall. # | |
5 | # # | |
6 | # IPFire is free software; you can redistribute it and/or modify # | |
7 | # it under the terms of the GNU General Public License as published by # | |
8 | # the Free Software Foundation; either version 2 of the License, or # | |
9 | # (at your option) any later version. # | |
10 | # # | |
11 | # IPFire is distributed in the hope that it will be useful, # | |
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of # | |
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # | |
14 | # GNU General Public License for more details. # | |
15 | # # | |
16 | # You should have received a copy of the GNU General Public License # | |
17 | # along with IPFire; if not, write to the Free Software # | |
18 | # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # | |
19 | # # | |
20 | # Copyright (C) 2018-2019 IPFire Team <info@ipfire.org> # | |
21 | # # | |
22 | ############################################################################ | |
23 | ||
24 | package IDS; | |
25 | ||
26 | require '/var/ipfire/general-functions.pl'; | |
27 | ||
28 | # Location where all config and settings files are stored. | |
29 | our $settingsdir = "${General::swroot}/suricata"; | |
30 | ||
31 | # File where the used rulefiles are stored. | |
32 | our $used_rulefiles_file = "$settingsdir/suricata-used-rulefiles.yaml"; | |
33 | ||
34 | # File where the addresses of the homenet are stored. | |
35 | our $homenet_file = "$settingsdir/suricata-homenet.yaml"; | |
36 | ||
37 | # File where the addresses of the used DNS servers are stored. | |
38 | our $dns_servers_file = "$settingsdir/suricata-dns-servers.yaml"; | |
39 | ||
40 | # File which contains the enabled sids. | |
41 | our $enabled_sids_file = "$settingsdir/oinkmaster-enabled-sids.conf"; | |
42 | ||
43 | # File which contains the disabled sids. | |
44 | our $disabled_sids_file = "$settingsdir/oinkmaster-disabled-sids.conf"; | |
45 | ||
46 | # File which contains wheater the rules should be changed. | |
47 | our $modify_sids_file = "$settingsdir/oinkmaster-modify-sids.conf"; | |
48 | ||
49 | # File which stores the configured IPS settings. | |
50 | our $ids_settings_file = "$settingsdir/settings"; | |
51 | ||
52 | # File which stores the configured rules-settings. | |
53 | our $rules_settings_file = "$settingsdir/rules-settings"; | |
54 | ||
55 | # File which stores the configured settings for whitelisted addresses. | |
56 | our $ignored_file = "$settingsdir/ignored"; | |
57 | ||
58 | # Location and name of the tarball which contains the ruleset. | |
59 | our $rulestarball = "/var/tmp/idsrules.tar.gz"; | |
60 | ||
61 | # File to store any errors, which also will be read and displayed by the wui. | |
62 | our $storederrorfile = "/tmp/ids_storederror"; | |
63 | ||
64 | # File to lock the WUI, while the autoupdate script runs. | |
65 | our $ids_page_lock_file = "/tmp/ids_page_locked"; | |
66 | ||
67 | # Location where the rulefiles are stored. | |
68 | our $rulespath = "/var/lib/suricata"; | |
69 | ||
70 | # File which contains the rules to whitelist addresses on suricata. | |
71 | our $whitelist_file = "$rulespath/whitelist.rules"; | |
72 | ||
73 | # File which contains a list of all supported ruleset sources. | |
74 | # (Sourcefire, Emergingthreads, etc..) | |
75 | our $rulesetsourcesfile = "$settingsdir/ruleset-sources"; | |
76 | ||
77 | # The pidfile of the IDS. | |
78 | our $idspidfile = "/var/run/suricata.pid"; | |
79 | ||
80 | # Location of suricatactrl. | |
81 | my $suricatactrl = "/usr/local/bin/suricatactrl"; | |
82 | ||
83 | # Array with allowed commands of suricatactrl. | |
84 | my @suricatactrl_cmds = ( 'start', 'stop', 'restart', 'reload', 'fix-rules-dir', 'cron' ); | |
85 | ||
86 | # Array with supported cron intervals. | |
87 | my @cron_intervals = ('off', 'daily', 'weekly' ); | |
88 | ||
89 | # | |
90 | ## Function to check and create all IDS related files, if the does not exist. | |
91 | # | |
92 | sub check_and_create_filelayout() { | |
93 | # Check if the files exist and if not, create them. | |
94 | unless (-f "$enabled_sids_file") { &create_empty_file($enabled_sids_file); } | |
95 | unless (-f "$disabled_sids_file") { &create_empty_file($disabled_sids_file); } | |
96 | unless (-f "$modify_sids_file") { &create_empty_file($modify_sids_file); } | |
97 | unless (-f "$used_rulefiles_file") { &create_empty_file($used_rulefiles_file); } | |
98 | unless (-f "$ids_settings_file") { &create_empty_file($ids_settings_file); } | |
99 | unless (-f "$rules_settings_file") { &create_empty_file($rules_settings_file); } | |
100 | unless (-f "$ignored_file") { &create_empty_file($ignored_file); } | |
101 | unless (-f "$whitelist_file" ) { &create_empty_file($whitelist_file); } | |
102 | } | |
103 | ||
104 | # | |
105 | ## Function for checking if at least 300MB of free disk space are available | |
106 | ## on the "/var" partition. | |
107 | # | |
108 | sub checkdiskspace () { | |
109 | # Call diskfree to gather the free disk space of /var. | |
110 | my @df = `/bin/df -B M /var`; | |
111 | ||
112 | # Loop through the output. | |
113 | foreach my $line (@df) { | |
114 | # Ignore header line. | |
115 | next if $line =~ m/^Filesystem/; | |
116 | ||
117 | # Search for a line with the device information. | |
118 | if ($line =~ m/dev/ ) { | |
119 | # Split the line into single pieces. | |
120 | my @values = split(' ', $line); | |
121 | my ($filesystem, $blocks, $used, $available, $used_perenctage, $mounted_on) = @values; | |
122 | ||
123 | # Check if the available disk space is more than 300MB. | |
124 | if ($available < 300) { | |
125 | # Log error to syslog. | |
126 | &_log_to_syslog("Not enough free disk space on /var. Only $available MB from 300 MB available."); | |
127 | ||
128 | # Exit function and return "1" - False. | |
129 | return 1; | |
130 | } | |
131 | } | |
132 | } | |
133 | ||
134 | # Everything okay, return nothing. | |
135 | return; | |
136 | } | |
137 | ||
138 | # | |
139 | ## This function is responsible for downloading the configured IDS ruleset. | |
140 | ## | |
141 | ## * At first it obtains from the stored rules settings which ruleset should be downloaded. | |
142 | ## * The next step is to get the download locations for all available rulesets. | |
143 | ## * After that, the function will check if an upstream proxy should be used and grab the settings. | |
144 | ## * The last step will be to generate the final download url, by obtaining the URL for the desired | |
145 | ## ruleset, add the settings for the upstream proxy and final grab the rules tarball from the server. | |
146 | # | |
147 | sub downloadruleset { | |
148 | # Get rules settings. | |
149 | my %rulessettings=(); | |
150 | &General::readhash("$rules_settings_file", \%rulessettings); | |
151 | ||
152 | # Check if a ruleset has been configured. | |
153 | unless($rulessettings{'RULES'}) { | |
154 | # Log that no ruleset has been configured and abort. | |
155 | &_log_to_syslog("No ruleset source has been configured."); | |
156 | ||
157 | # Return "1". | |
158 | return 1; | |
159 | } | |
160 | ||
161 | # Get all available ruleset locations. | |
162 | my %rulesetsources=(); | |
163 | &General::readhash($rulesetsourcesfile, \%rulesetsources); | |
164 | ||
165 | # Read proxysettings. | |
166 | my %proxysettings=(); | |
167 | &General::readhash("${General::swroot}/proxy/settings", \%proxysettings); | |
168 | ||
169 | # Load required perl module to handle the download. | |
170 | use LWP::UserAgent; | |
171 | ||
172 | # Init the download module. | |
173 | my $downloader = LWP::UserAgent->new; | |
174 | ||
175 | # Set timeout to 10 seconds. | |
176 | $downloader->timeout(10); | |
177 | ||
178 | # Check if an upstream proxy is configured. | |
179 | if ($proxysettings{'UPSTREAM_PROXY'}) { | |
180 | my $proxy_url; | |
181 | ||
182 | $proxy_url = "http://"; | |
183 | ||
184 | # Check if the proxy requires authentication. | |
185 | if (($proxysettings{'UPSTREAM_USER'}) && ($proxysettings{'UPSTREAM_PASSWORD'})) { | |
186 | $proxy_url .= "$proxysettings{'UPSTREAM_USER'}\:$proxysettings{'UPSTREAM_PASSWORD'}\@"; | |
187 | } | |
188 | ||
189 | # Add proxy server address and port. | |
190 | $proxy_url .= $proxysettings{'UPSTREAM_PROXY'}; | |
191 | ||
192 | # Setup proxy settings. | |
193 | $downloader->proxy(['http', 'https'], $proxy_url); | |
194 | } | |
195 | ||
196 | # Grab the right url based on the configured vendor. | |
197 | my $url = $rulesetsources{$rulessettings{'RULES'}}; | |
198 | ||
199 | # Check if the vendor requires an oinkcode and add it if needed. | |
200 | $url =~ s/\<oinkcode\>/$rulessettings{'OINKCODE'}/g; | |
201 | ||
202 | # Abort if no url could be determined for the vendor. | |
203 | unless ($url) { | |
204 | # Log error and abort. | |
205 | &_log_to_syslog("Unable to gather a download URL for the selected ruleset."); | |
206 | return 1; | |
207 | } | |
208 | ||
209 | # Variable to store the filesize of the remote object. | |
210 | my $remote_filesize; | |
211 | ||
212 | # The sourcfire (snort rules) does not allow to send "HEAD" requests, so skip this check | |
213 | # for this webserver. | |
214 | # | |
215 | # Check if the ruleset source contains "snort.org". | |
216 | unless ($url =~ /\.snort\.org/) { | |
217 | # Pass the requrested url to the downloader. | |
218 | my $request = HTTP::Request->new(HEAD => $url); | |
219 | ||
220 | # Accept the html header. | |
221 | $request->header('Accept' => 'text/html'); | |
222 | ||
223 | # Perform the request and fetch the html header. | |
224 | my $response = $downloader->request($request); | |
225 | ||
226 | # Check if there was any error. | |
227 | unless ($response->is_success) { | |
228 | # Obtain error. | |
229 | my $error = $response->status_line(); | |
230 | ||
231 | # Log error message. | |
232 | &_log_to_syslog("Unable to download the ruleset. \($error\)"); | |
233 | ||
234 | # Return "1" - false. | |
235 | return 1; | |
236 | } | |
237 | ||
238 | # Assign the fetched header object. | |
239 | my $header = $response->headers(); | |
240 | ||
241 | # Grab the remote file size from the object and store it in the | |
242 | # variable. | |
243 | $remote_filesize = $header->content_length; | |
244 | } | |
245 | ||
246 | # Load perl module to deal with temporary files. | |
247 | use File::Temp; | |
248 | ||
249 | # Generate temporary file name, located in "/var/tmp" and with a suffix of ".tar.gz". | |
250 | my $tmp = File::Temp->new( SUFFIX => ".tar.gz", DIR => "/var/tmp/", UNLINK => 0 ); | |
251 | my $tmpfile = $tmp->filename(); | |
252 | ||
253 | # Pass the requested url to the downloader. | |
254 | my $request = HTTP::Request->new(GET => $url); | |
255 | ||
256 | # Perform the request and save the output into the tmpfile. | |
257 | my $response = $downloader->request($request, $tmpfile); | |
258 | ||
259 | # Check if there was any error. | |
260 | unless ($response->is_success) { | |
261 | # Obtain error. | |
262 | my $error = $response->content; | |
263 | ||
264 | # Log error message. | |
265 | &_log_to_syslog("Unable to download the ruleset. \($error\)"); | |
266 | ||
267 | # Return "1" - false. | |
268 | return 1; | |
269 | } | |
270 | ||
271 | # Load perl stat module. | |
272 | use File::stat; | |
273 | ||
274 | # Perform stat on the tmpfile. | |
275 | my $stat = stat($tmpfile); | |
276 | ||
277 | # Grab the local filesize of the downloaded tarball. | |
278 | my $local_filesize = $stat->size; | |
279 | ||
280 | # Check if both file sizes match. | |
281 | if (($remote_filesize) && ($remote_filesize ne $local_filesize)) { | |
282 | # Log error message. | |
283 | &_log_to_syslog("Unable to completely download the ruleset. "); | |
284 | &_log_to_syslog("Only got $local_filesize Bytes instead of $remote_filesize Bytes. "); | |
285 | ||
286 | # Delete temporary file. | |
287 | unlink("$tmpfile"); | |
288 | ||
289 | # Return "1" - false. | |
290 | return 1; | |
291 | } | |
292 | ||
293 | # Load file copy module, which contains the move() function. | |
294 | use File::Copy; | |
295 | ||
296 | # Overwrite existing rules tarball with the new downloaded one. | |
297 | move("$tmpfile", "$rulestarball"); | |
298 | ||
299 | # Set correct ownership for the rulesdir and files. | |
300 | set_ownership("$rulestarball"); | |
301 | ||
302 | # If we got here, everything worked fine. Return nothing. | |
303 | return; | |
304 | } | |
305 | ||
306 | # | |
307 | ## A tiny wrapper function to call the oinkmaster script. | |
308 | # | |
309 | sub oinkmaster () { | |
310 | # Check if the files in rulesdir have the correct permissions. | |
311 | &_check_rulesdir_permissions(); | |
312 | ||
313 | # Cleanup the rules directory before filling it with the new rulest. | |
314 | &_cleanup_rulesdir(); | |
315 | ||
316 | # Load perl module to talk to the kernel syslog. | |
317 | use Sys::Syslog qw(:DEFAULT setlogsock); | |
318 | ||
319 | # Establish the connection to the syslog service. | |
320 | openlog('oinkmaster', 'cons,pid', 'user'); | |
321 | ||
322 | # Call oinkmaster to generate ruleset. | |
323 | open(OINKMASTER, "/usr/local/bin/oinkmaster.pl -s -u file://$rulestarball -C $settingsdir/oinkmaster.conf -o $rulespath 2>&1 |") or die "Could not execute oinkmaster $!\n"; | |
324 | ||
325 | # Log output of oinkmaster to syslog. | |
326 | while(<OINKMASTER>) { | |
327 | # The syslog function works best with an array based input, | |
328 | # so generate one before passing the message details to syslog. | |
329 | my @syslog = ("INFO", "$_"); | |
330 | ||
331 | # Send the log message. | |
332 | syslog(@syslog); | |
333 | } | |
334 | ||
335 | # Close the pipe to oinkmaster process. | |
336 | close(OINKMASTER); | |
337 | ||
338 | # Close the log handle. | |
339 | closelog(); | |
340 | } | |
341 | ||
342 | # | |
343 | ## Function to do all the logging stuff if the downloading or updating of the ruleset fails. | |
344 | # | |
345 | sub log_error ($) { | |
346 | my ($error) = @_; | |
347 | ||
348 | # Remove any newline. | |
349 | chomp($error); | |
350 | ||
351 | # Call private function to log the error message to syslog. | |
352 | &_log_to_syslog($error); | |
353 | ||
354 | # Call private function to write/store the error message in the storederrorfile. | |
355 | &_store_error_message($error); | |
356 | } | |
357 | ||
358 | # | |
359 | ## Function to log a given error message to the kernel syslog. | |
360 | # | |
361 | sub _log_to_syslog ($) { | |
362 | my ($message) = @_; | |
363 | ||
364 | # Load perl module to talk to the kernel syslog. | |
365 | use Sys::Syslog qw(:DEFAULT setlogsock); | |
366 | ||
367 | # The syslog function works best with an array based input, | |
368 | # so generate one before passing the message details to syslog. | |
369 | my @syslog = ("ERR", "<ERROR> $message"); | |
370 | ||
371 | # Establish the connection to the syslog service. | |
372 | openlog('oinkmaster', 'cons,pid', 'user'); | |
373 | ||
374 | # Send the log message. | |
375 | syslog(@syslog); | |
376 | ||
377 | # Close the log handle. | |
378 | closelog(); | |
379 | } | |
380 | ||
381 | # | |
382 | ## Private function to write a given error message to the storederror file. | |
383 | # | |
384 | sub _store_error_message ($) { | |
385 | my ($message) = @_; | |
386 | ||
387 | # Remove any newline. | |
388 | chomp($message); | |
389 | ||
390 | # Open file for writing. | |
391 | open (ERRORFILE, ">$storederrorfile") or die "Could not write to $storederrorfile. $!\n"; | |
392 | ||
393 | # Write error to file. | |
394 | print ERRORFILE "$message\n"; | |
395 | ||
396 | # Close file. | |
397 | close (ERRORFILE); | |
398 | ||
399 | # Set correct ownership for the file. | |
400 | &set_ownership("$storederrorfile"); | |
401 | } | |
402 | ||
403 | # | |
404 | ## Function to get a list of all available network zones. | |
405 | # | |
406 | sub get_available_network_zones () { | |
407 | # Get netsettings. | |
408 | my %netsettings = (); | |
409 | &General::readhash("${General::swroot}/ethernet/settings", \%netsettings); | |
410 | ||
411 | # Obtain the configuration type from the netsettings hash. | |
412 | my $config_type = $netsettings{'CONFIG_TYPE'}; | |
413 | ||
414 | # Hash which contains the conversation from the config mode | |
415 | # to the existing network interface names. They are stored like | |
416 | # an array. | |
417 | # | |
418 | # Mode "0" red is a modem and green | |
419 | # Mode "1" red is a netdev and green | |
420 | # Mode "2" red, green and orange | |
421 | # Mode "3" red, green and blue | |
422 | # Mode "4" red, green, blue, orange | |
423 | my %config_type_to_interfaces = ( | |
424 | "0" => [ "red", "green" ], | |
425 | "1" => [ "red", "green" ], | |
426 | "2" => [ "red", "green", "orange" ], | |
427 | "3" => [ "red", "green", "blue" ], | |
428 | "4" => [ "red", "green", "blue", "orange" ] | |
429 | ); | |
430 | ||
431 | # Obtain and dereference the corresponding network interaces based on the read | |
432 | # network config type. | |
433 | my @network_zones = @{ $config_type_to_interfaces{$config_type} }; | |
434 | ||
435 | # Return them. | |
436 | return @network_zones; | |
437 | } | |
438 | ||
439 | # | |
440 | ## Function to check if the IDS is running. | |
441 | # | |
442 | sub ids_is_running () { | |
443 | if(-f $idspidfile) { | |
444 | # Open PID file for reading. | |
445 | open(PIDFILE, "$idspidfile") or die "Could not open $idspidfile. $!\n"; | |
446 | ||
447 | # Grab the process-id. | |
448 | my $pid = <PIDFILE>; | |
449 | ||
450 | # Close filehandle. | |
451 | close(PIDFILE); | |
452 | ||
453 | # Remove any newline. | |
454 | chomp($pid); | |
455 | ||
456 | # Check if a directory for the process-id exists in proc. | |
457 | if(-d "/proc/$pid") { | |
458 | # The IDS daemon is running return the process id. | |
459 | return $pid; | |
460 | } | |
461 | } | |
462 | ||
463 | # Return nothing - IDS is not running. | |
464 | return; | |
465 | } | |
466 | ||
467 | # | |
468 | ## Function to call suricatactrl binary with a given command. | |
469 | # | |
470 | sub call_suricatactrl ($) { | |
471 | # Get called option. | |
472 | my ($option, $interval) = @_; | |
473 | ||
474 | # Loop through the array of supported commands and check if | |
475 | # the given one is part of it. | |
476 | foreach my $cmd (@suricatactrl_cmds) { | |
477 | # Skip current command unless the given one has been found. | |
478 | next unless($cmd eq $option); | |
479 | ||
480 | # Check if the given command is "cron". | |
481 | if ($option eq "cron") { | |
482 | # Check if an interval has been given. | |
483 | if ($interval) { | |
484 | # Check if the given interval is valid. | |
485 | foreach my $element (@cron_intervals) { | |
486 | # Skip current element until the given one has been found. | |
487 | next unless($element eq $interval); | |
488 | ||
489 | # Call the suricatactrl binary and pass the "cron" command | |
490 | # with the requrested interval. | |
491 | system("$suricatactrl $option $interval &>/dev/null"); | |
492 | ||
493 | # Return "1" - True. | |
494 | return 1; | |
495 | } | |
496 | } | |
497 | ||
498 | # If we got here, the given interval is not supported or none has been given. - Return nothing. | |
499 | return; | |
500 | } else { | |
501 | # Call the suricatactrl binary and pass the requrested | |
502 | # option to it. | |
503 | system("$suricatactrl $option &>/dev/null"); | |
504 | ||
505 | # Return "1" - True. | |
506 | return 1; | |
507 | } | |
508 | } | |
509 | ||
510 | # Command not found - return nothing. | |
511 | return; | |
512 | } | |
513 | ||
514 | # | |
515 | ## Function to create a new empty file. | |
516 | # | |
517 | sub create_empty_file($) { | |
518 | my ($file) = @_; | |
519 | ||
520 | # Check if the given file exists. | |
521 | if(-e $file) { | |
522 | # Do nothing to prevent from overwriting existing files. | |
523 | return; | |
524 | } | |
525 | ||
526 | # Open the file for writing. | |
527 | open(FILE, ">$file") or die "Could not write to $file. $!\n"; | |
528 | ||
529 | # Close file handle. | |
530 | close(FILE); | |
531 | ||
532 | # Return true. | |
533 | return 1; | |
534 | } | |
535 | ||
536 | # | |
537 | ## Private function to check if the file permission of the rulespath are correct. | |
538 | ## If not, call suricatactrl to fix them. | |
539 | # | |
540 | sub _check_rulesdir_permissions() { | |
541 | # Check if the rulepath main directory is writable. | |
542 | unless (-W $rulespath) { | |
543 | # If not call suricatctrl to fix it. | |
544 | &call_suricatactrl("fix-rules-dir"); | |
545 | } | |
546 | ||
547 | # Open snort rules directory and do a directory listing. | |
548 | opendir(DIR, $rulespath) or die $!; | |
549 | # Loop through the direcory. | |
550 | while (my $file = readdir(DIR)) { | |
551 | # We only want files. | |
552 | next unless (-f "$rulespath/$file"); | |
553 | ||
554 | # Check if the file is writable by the user. | |
555 | if (-W "$rulespath/$file") { | |
556 | # Everything is okay - go on to the next file. | |
557 | next; | |
558 | } else { | |
559 | # There are wrong permissions, call suricatactrl to fix it. | |
560 | &call_suricatactrl("fix-rules-dir"); | |
561 | } | |
562 | } | |
563 | } | |
564 | ||
565 | # | |
566 | ## Private function to cleanup the directory which contains | |
567 | ## the IDS rules, before extracting and modifing the new ruleset. | |
568 | # | |
569 | sub _cleanup_rulesdir() { | |
570 | # Open rules directory and do a directory listing. | |
571 | opendir(DIR, $rulespath) or die $!; | |
572 | ||
573 | # Loop through the direcory. | |
574 | while (my $file = readdir(DIR)) { | |
575 | # We only want files. | |
576 | next unless (-f "$rulespath/$file"); | |
577 | ||
578 | # Skip element if it has config as file extension. | |
579 | next if ($file =~ m/\.config$/); | |
580 | ||
581 | # Skip rules file for whitelisted hosts. | |
582 | next if ("$rulespath/$file" eq $whitelist_file); | |
583 | ||
584 | # Delete the current processed file, if not, exit this function | |
585 | # and return an error message. | |
586 | unlink("$rulespath/$file") or return "Could not delete $rulespath/$file. $!\n"; | |
587 | } | |
588 | ||
589 | # Return nothing; | |
590 | return; | |
591 | } | |
592 | ||
593 | # | |
594 | ## Function to generate the file which contains the home net information. | |
595 | # | |
596 | sub generate_home_net_file() { | |
597 | my %netsettings; | |
598 | ||
599 | # Read-in network settings. | |
600 | &General::readhash("${General::swroot}/ethernet/settings", \%netsettings); | |
601 | ||
602 | # Get available network zones. | |
603 | my @network_zones = &get_available_network_zones(); | |
604 | ||
605 | # Temporary array to store network address and prefix of the configured | |
606 | # networks. | |
607 | my @networks; | |
608 | ||
609 | # Loop through the array of available network zones. | |
610 | foreach my $zone (@network_zones) { | |
611 | # Check if the current processed zone is red. | |
612 | if($zone eq "red") { | |
613 | # Grab the IP-address of the red interface. | |
614 | my $red_address = &get_red_address(); | |
615 | ||
616 | # Check if an address has been obtained. | |
617 | if ($red_address) { | |
618 | # Generate full network string. | |
619 | my $red_network = join("/", $red_address, "32"); | |
620 | ||
621 | # Add the red network to the array of networks. | |
622 | push(@networks, $red_network); | |
623 | } | |
624 | ||
625 | # Check if the configured RED_TYPE is static. | |
626 | if ($netsettings{'RED_TYPE'} eq "STATIC") { | |
627 | # Get configured and enabled aliases. | |
628 | my @aliases = &get_aliases(); | |
629 | ||
630 | # Loop through the array. | |
631 | foreach my $alias (@aliases) { | |
632 | # Add "/32" prefix. | |
633 | my $network = join("/", $alias, "32"); | |
634 | ||
635 | # Add the generated network to the array of networks. | |
636 | push(@networks, $network); | |
637 | } | |
638 | } | |
639 | # Process remaining network zones. | |
640 | } else { | |
641 | # Convert current zone name into upper case. | |
642 | $zone = uc($zone); | |
643 | ||
644 | # Generate key to access the required data from the netsettings hash. | |
645 | my $zone_netaddress = $zone . "_NETADDRESS"; | |
646 | my $zone_netmask = $zone . "_NETMASK"; | |
647 | ||
648 | # Obtain the settings from the netsettings hash. | |
649 | my $netaddress = $netsettings{$zone_netaddress}; | |
650 | my $netmask = $netsettings{$zone_netmask}; | |
651 | ||
652 | # Convert the subnetmask into prefix notation. | |
653 | my $prefix = &Network::convert_netmask2prefix($netmask); | |
654 | ||
655 | # Generate full network string. | |
656 | my $network = join("/", $netaddress,$prefix); | |
657 | ||
658 | # Check if the network is valid. | |
659 | if(&Network::check_subnet($network)) { | |
660 | # Add the generated network to the array of networks. | |
661 | push(@networks, $network); | |
662 | } | |
663 | } | |
664 | } | |
665 | ||
666 | # Format home net declaration. | |
667 | my $line = "\"\["; | |
668 | ||
669 | # Loop through the array of networks. | |
670 | foreach my $network (@networks) { | |
671 | # Add the network to the line. | |
672 | $line = "$line" . "$network"; | |
673 | ||
674 | # Check if the current network was the last in the array. | |
675 | if ($network eq $networks[-1]) { | |
676 | # Close the line. | |
677 | $line = "$line" . "\]\""; | |
678 | } else { | |
679 | # Add "," for the next network. | |
680 | $line = "$line" . "\,"; | |
681 | } | |
682 | } | |
683 | ||
684 | # Open file to store the addresses of the home net. | |
685 | open(FILE, ">$homenet_file") or die "Could not open $homenet_file. $!\n"; | |
686 | ||
687 | # Print yaml header. | |
688 | print FILE "%YAML 1.1\n"; | |
689 | print FILE "---\n\n"; | |
690 | ||
691 | # Print notice about autogenerated file. | |
692 | print FILE "#Autogenerated file. Any custom changes will be overwritten!\n"; | |
693 | ||
694 | # Print the generated and required HOME_NET declaration to the file. | |
695 | print FILE "HOME_NET:\t$line\n"; | |
696 | ||
697 | # Close file handle. | |
698 | close(FILE); | |
699 | } | |
700 | ||
701 | # | |
702 | # Function to generate and write the file which contains the configured and used DNS servers. | |
703 | # | |
704 | sub generate_dns_servers_file() { | |
705 | # Open file which contains the current used DNS configuration. | |
706 | open (FILE, "${General::swroot}/red/dns") or die "Could not read DNS configuration from ${General::swroot}/red/dns. $!\n"; | |
707 | ||
708 | # Read-in whole file content and store it in a temporary array. | |
709 | my @file_content = split(' ', <FILE>); | |
710 | ||
711 | # Close file handle. | |
712 | close(FILE); | |
713 | ||
714 | # Format dns servers declaration. | |
715 | my $line = "\"\["; | |
716 | ||
717 | # Check if the current DNS configuration is using the local recursor mode. | |
718 | if ($file_content[0] eq "local" && $file_content[1] eq "recursor") { | |
719 | # The responsible DNS servers on red are directly used, and because we are not able | |
720 | # to specify each single DNS server address here, we currently have to thread each | |
721 | # address which is not part of the HOME_NET as possible DNS server. | |
722 | $line = "$line" . "!\$HOME_NET"; | |
723 | ||
724 | } else { | |
725 | # Loop through the array which contains the file content. | |
726 | foreach my $server (@file_content) { | |
727 | # Remove newlines. | |
728 | chomp($server); | |
729 | ||
730 | # Add the DNS server to the line. | |
731 | $line = "$line" . "$server"; | |
732 | ||
733 | # Check if the current DNS server was the last in the array. | |
734 | if ($server ne $file_content[-1]) { | |
735 | # Add "," for the next DNS server. | |
736 | $line = "$line" . "\,"; | |
737 | } | |
738 | } | |
739 | } | |
740 | ||
741 | # Close the line... | |
742 | $line = "$line" . "\]\""; | |
743 | ||
744 | # Open file to store the used DNS server addresses. | |
745 | open(FILE, ">$dns_servers_file") or die "Could not open $dns_servers_file. $!\n"; | |
746 | ||
747 | # Print yaml header. | |
748 | print FILE "%YAML 1.1\n"; | |
749 | print FILE "---\n\n"; | |
750 | ||
751 | # Print notice about autogenerated file. | |
752 | print FILE "#Autogenerated file. Any custom changes will be overwritten!\n"; | |
753 | ||
754 | # Print the generated DNS declaration to the file. | |
755 | print FILE "DNS_SERVERS:\t$line\n"; | |
756 | ||
757 | # Close file handle. | |
758 | close(FILE); | |
759 | } | |
760 | ||
761 | # | |
762 | ## Function to generate and write the file for used rulefiles. | |
763 | # | |
764 | sub write_used_rulefiles_file(@) { | |
765 | my @files = @_; | |
766 | ||
767 | # Open file for used rulefiles. | |
768 | open (FILE, ">$used_rulefiles_file") or die "Could not write to $used_rulefiles_file. $!\n"; | |
769 | ||
770 | # Write yaml header to the file. | |
771 | print FILE "%YAML 1.1\n"; | |
772 | print FILE "---\n\n"; | |
773 | ||
774 | # Write header to file. | |
775 | print FILE "#Autogenerated file. Any custom changes will be overwritten!\n"; | |
776 | ||
777 | # Allways use the whitelist. | |
778 | print FILE " - whitelist.rules\n"; | |
779 | ||
780 | # Loop through the array of given files. | |
781 | foreach my $file (@files) { | |
782 | # Check if the given filename exists and write it to the file of used rulefiles. | |
783 | if(-f "$rulespath/$file") { | |
784 | print FILE " - $file\n"; | |
785 | } | |
786 | } | |
787 | ||
788 | # Close file after writing. | |
789 | close(FILE); | |
790 | } | |
791 | ||
792 | # | |
793 | ## Function to generate and write the file for modify the ruleset. | |
794 | # | |
795 | sub write_modify_sids_file() { | |
796 | # Get configured settings. | |
797 | my %idssettings=(); | |
798 | my %rulessettings=(); | |
799 | &General::readhash("$ids_settings_file", \%idssettings); | |
800 | &General::readhash("$rules_settings_file", \%rulessettings); | |
801 | ||
802 | # Gather the configured ruleset. | |
803 | my $ruleset = $rulessettings{'RULES'}; | |
804 | ||
805 | # Open modify sid's file for writing. | |
806 | open(FILE, ">$modify_sids_file") or die "Could not write to $modify_sids_file. $!\n"; | |
807 | ||
808 | # Write file header. | |
809 | print FILE "#Autogenerated file. Any custom changes will be overwritten!\n"; | |
810 | ||
811 | # Check if the traffic only should be monitored. | |
812 | unless($idssettings{'MONITOR_TRAFFIC_ONLY'} eq 'on') { | |
813 | # Suricata is in IPS mode, which means that the rule actions have to be changed | |
814 | # from 'alert' to 'drop', however not all rules should be changed. Some rules | |
815 | # exist purely to set a flowbit which is used to convey other information, such | |
816 | # as a specific type of file being downloaded, to other rulewhich then check for | |
817 | # malware in that file. Rules which fall into the first category should stay as | |
818 | # alert since not all flows of that type contain malware. | |
819 | ||
820 | if($ruleset eq 'registered' or $ruleset eq 'subscripted' or $ruleset eq 'community') { | |
821 | # These types of rulesfiles contain meta-data which gives the action that should | |
822 | # be used when in IPS mode. Do the following: | |
823 | # | |
824 | # 1. Disable all rules and set the action to 'drop' | |
825 | # 2. Set the action back to 'alert' if the rule contains 'flowbits:noalert;' | |
826 | # This should give rules not in the policy a reasonable default if the user | |
827 | # manually enables them. | |
828 | # 3. Enable rules and set actions according to the meta-data strings. | |
829 | ||
830 | my $policy = 'balanced'; # Placeholder to allow policy to be changed. | |
831 | ||
832 | print FILE <<END; | |
833 | modifysid * "^#?(?:alert|drop)" | "#drop" | |
834 | modifysid * "^#drop(.+flowbits:noalert;)" | "#alert\${1}" | |
835 | modifysid * "^#(?:alert|drop)(.+policy $policy-ips alert)" | "alert\${1}" | |
836 | modifysid * "^#(?:alert|drop)(.+policy $policy-ips drop)" | "drop\${1}" | |
837 | END | |
838 | } else { | |
839 | # These rulefiles don't have the metadata, so set rules to 'drop' unless they | |
840 | # contain the string 'flowbits:noalert;'. | |
841 | print FILE <<END; | |
842 | modifysid * "^(#?)(?:alert|drop)" | "\${1}drop" | |
843 | modifysid * "^(#?)drop(.+flowbits:noalert;)" | "\${1}alert\${2}" | |
844 | END | |
845 | } | |
846 | } | |
847 | ||
848 | # Close file handle. | |
849 | close(FILE); | |
850 | } | |
851 | ||
852 | # | |
853 | ## Function to gather the version of suricata. | |
854 | # | |
855 | sub get_suricata_version($) { | |
856 | my ($format) = @_; | |
857 | ||
858 | # Execute piped suricata command and return the version information. | |
859 | open(SURICATA, "suricata -V |") or die "Couldn't execute program: $!"; | |
860 | ||
861 | # Grab and store the output of the piped program. | |
862 | my $version_string = <SURICATA>; | |
863 | ||
864 | # Close pipe. | |
865 | close(SURICATA); | |
866 | ||
867 | # Remove newlines. | |
868 | chomp($version_string); | |
869 | ||
870 | # Grab the version from the version string. | |
871 | $version_string =~ /([0-9]+([.][0-9]+)+)/; | |
872 | ||
873 | # Splitt the version into single chunks. | |
874 | my ($major_ver, $minor_ver, $patchlevel) = split(/\./, $1); | |
875 | ||
876 | # Check and return the requested version sheme. | |
877 | if ($format eq "major") { | |
878 | # Return the full version. | |
879 | return "$major_ver"; | |
880 | } elsif ($format eq "minor") { | |
881 | # Return the major and minor part. | |
882 | return "$major_ver.$minor_ver"; | |
883 | } else { | |
884 | # Return the full version string. | |
885 | return "$major_ver.$minor_ver.$patchlevel"; | |
886 | } | |
887 | } | |
888 | ||
889 | # | |
890 | ## Function to generate the rules file with whitelisted addresses. | |
891 | # | |
892 | sub generate_ignore_file() { | |
893 | my %ignored = (); | |
894 | ||
895 | # SID range 1000000-1999999 Reserved for Local Use | |
896 | # Put your custom rules in this range to avoid conflicts | |
897 | my $sid = 1500000; | |
898 | ||
899 | # Read-in ignoredfile. | |
900 | &General::readhasharray($IDS::ignored_file, \%ignored); | |
901 | ||
902 | # Open ignorefile for writing. | |
903 | open(FILE, ">$IDS::whitelist_file") or die "Could not write to $IDS::whitelist_file. $!\n"; | |
904 | ||
905 | # Config file header. | |
906 | print FILE "# Autogenerated file.\n"; | |
907 | print FILE "# All user modifications will be overwritten.\n\n"; | |
908 | ||
909 | # Add all user defined addresses to the whitelist. | |
910 | # | |
911 | # Check if the hash contains any elements. | |
912 | if (keys (%ignored)) { | |
913 | # Loop through the entire hash and write the host/network | |
914 | # and remark to the ignore file. | |
915 | while ( (my $key) = each %ignored) { | |
916 | my $address = $ignored{$key}[0]; | |
917 | my $remark = $ignored{$key}[1]; | |
918 | my $status = $ignored{$key}[2]; | |
919 | ||
920 | # Check if the status of the entry is "enabled". | |
921 | if ($status eq "enabled") { | |
922 | # Check if the address/network is valid. | |
923 | if ((&General::validip($address)) || (&General::validipandmask($address))) { | |
924 | # Write rule line to the file to pass any traffic from this IP | |
925 | print FILE "pass ip $address any -> any any (msg:\"pass all traffic from/to $address\"\; sid:$sid\;)\n"; | |
926 | ||
927 | # Increment sid. | |
928 | $sid++; | |
929 | } | |
930 | } | |
931 | } | |
932 | } | |
933 | ||
934 | close(FILE); | |
935 | } | |
936 | ||
937 | # | |
938 | ## Function to set correct ownership for single files and directories. | |
939 | # | |
940 | ||
941 | sub set_ownership($) { | |
942 | my ($target) = @_; | |
943 | ||
944 | # User and group of the WUI. | |
945 | my $uname = "nobody"; | |
946 | my $grname = "nobody"; | |
947 | ||
948 | # The chown function implemented in perl requies the user and group as nummeric id's. | |
949 | my $uid = getpwnam($uname); | |
950 | my $gid = getgrnam($grname); | |
951 | ||
952 | # Check if the given target exists. | |
953 | unless ($target) { | |
954 | # Stop the script and print error message. | |
955 | die "The $target does not exist. Cannot change the ownership!\n"; | |
956 | } | |
957 | ||
958 | # Check weather the target is a file or directory. | |
959 | if (-f $target) { | |
960 | # Change ownership ot the single file. | |
961 | chown($uid, $gid, "$target"); | |
962 | } elsif (-d $target) { | |
963 | # Do a directory listing. | |
964 | opendir(DIR, $target) or die $!; | |
965 | # Loop through the direcory. | |
966 | while (my $file = readdir(DIR)) { | |
967 | ||
968 | # We only want files. | |
969 | next unless (-f "$target/$file"); | |
970 | ||
971 | # Set correct ownership for the files. | |
972 | chown($uid, $gid, "$target/$file"); | |
973 | } | |
974 | ||
975 | closedir(DIR); | |
976 | ||
977 | # Change ownership of the directory. | |
978 | chown($uid, $gid, "$target"); | |
979 | } | |
980 | } | |
981 | ||
982 | # | |
983 | ## Function to read-in the aliases file and returns all configured and enabled aliases. | |
984 | # | |
985 | sub get_aliases() { | |
986 | # Location of the aliases file. | |
987 | my $aliases_file = "${General::swroot}/ethernet/aliases"; | |
988 | ||
989 | # Array to store the aliases. | |
990 | my @aliases; | |
991 | ||
992 | # Check if the file is empty. | |
993 | if (-z $aliases_file) { | |
994 | # Abort nothing to do. | |
995 | return; | |
996 | } | |
997 | ||
998 | # Open the aliases file. | |
999 | open(ALIASES, $aliases_file) or die "Could not open $aliases_file. $!\n"; | |
1000 | ||
1001 | # Loop through the file content. | |
1002 | while (my $line = <ALIASES>) { | |
1003 | # Remove newlines. | |
1004 | chomp($line); | |
1005 | ||
1006 | # Splitt line content into single chunks. | |
1007 | my ($address, $state, $remark) = split(/\,/, $line); | |
1008 | ||
1009 | # Check if the state of the current processed alias is "on". | |
1010 | if ($state eq "on") { | |
1011 | # Check if the address is valid. | |
1012 | if(&Network::check_ip_address($address)) { | |
1013 | # Add the alias to the array of aliases. | |
1014 | push(@aliases, $address); | |
1015 | } | |
1016 | } | |
1017 | } | |
1018 | ||
1019 | # Close file handle. | |
1020 | close(ALIASES); | |
1021 | ||
1022 | # Return the array. | |
1023 | return @aliases; | |
1024 | } | |
1025 | ||
1026 | # | |
1027 | ## Function to grab the current assigned IP-address on red. | |
1028 | # | |
1029 | sub get_red_address() { | |
1030 | # File, which contains the current IP-address of the red interface. | |
1031 | my $file = "${General::swroot}/red/local-ipaddress"; | |
1032 | ||
1033 | # Check if the file exists. | |
1034 | if (-e $file) { | |
1035 | # Open the given file. | |
1036 | open(FILE, "$file") or die "Could not open $file."; | |
1037 | ||
1038 | # Obtain the address from the first line of the file. | |
1039 | my $address = <FILE>; | |
1040 | ||
1041 | # Close filehandle | |
1042 | close(FILE); | |
1043 | ||
1044 | # Remove newlines. | |
1045 | chomp $address; | |
1046 | ||
1047 | # Check if the grabbed address is valid. | |
1048 | if (&General::validip($address)) { | |
1049 | # Return the address. | |
1050 | return $address; | |
1051 | } | |
1052 | } | |
1053 | ||
1054 | # Return nothing. | |
1055 | return; | |
1056 | } | |
1057 | ||
1058 | # | |
1059 | ## Function to write the lock file for locking the WUI, while | |
1060 | ## the autoupdate script runs. | |
1061 | # | |
1062 | sub lock_ids_page() { | |
1063 | # Call subfunction to create the file. | |
1064 | &create_empty_file($ids_page_lock_file); | |
1065 | } | |
1066 | ||
1067 | # | |
1068 | ## Function to release the lock of the WUI, again. | |
1069 | # | |
1070 | sub unlock_ids_page() { | |
1071 | # Delete lock file. | |
1072 | unlink($ids_page_lock_file); | |
1073 | } | |
1074 | ||
1075 | 1; |