]>
git.ipfire.org Git - people/stevee/guardian.git/blob - modules/Events.pm
1 package Guardian
::Events
;
5 use Exporter
qw(import);
7 our @EXPORT_OK = qw(Init CheckAction GenerateIgnoreList Update);
9 # Hash which stores all supported commands from the queue.
12 'block' => \
&CallBlock
,
13 'unblock' => \
&CallUnblock
,
14 'flush' => \
&CallFlush
,
15 'reload' => \
&main
::Reload
,
16 'reload-ignore-list' => \
&main
::ReloadIgnoreList
,
17 'logrotate' => \
&main
::Logrotate
,
20 # Hash to store addresses and their current count.
23 # Hash to store all currentyl blocked addresses and a timestamp
24 # when the block for this address can be released.
27 # Hash to store user-defined IP addresses and/or subnets which should be
28 # ignored in case any events should be repored for them.
31 # Array to store localhost related IP addresses.
32 # They are always white-listed to prevent guardian from blocking
34 my @localhost_addresses = ("127.0.0.1", "::1");
36 # This object will contain the reference to the logger object after calling Init.
40 ## The "Init" (Block) function.
42 ## This function is responsible to initialize Block as a class based object.
43 ## It has to be called once before any blocking event can be processed.
45 ## The following arguments must be passed, during initialization:
46 ## "BlockCount" and "BlockTime" which both have to be natural numbers.
49 my ( $class, %args ) = @_;
52 # Fail, if some critical arguments are missing.
53 unless ((exists($self->{BlockCount
})) && (exists($self->{BlockTime
}))) {
54 die "Could not initialize Block: Too less arguments are given.\n";
57 # Use bless to make "$self" to an object of class "$class".
60 # Assign logger object.
61 $logger = $self->{Logger
};
63 # Log used firewall engine.
64 $logger->Log("debug", "Using firewall engine: $self->{FirewallEngine}");
66 # Try to load the specified firewall engine or die.
67 my $module_name = "Guardian::" . $self->{FirewallEngine
};
68 eval "use $module_name; 1" or die "Could not load a module for firewall engine: $self->{FirewallEngine}!";
70 # Check if an IgnoreFile has been configured.
71 if (exists($self->{IgnoreFile
})) {
72 # Call function to handle the ignore mechanism.
73 &GenerateIgnoreList
($self->{IgnoreFile
});
75 # Whitelist local addresses.
76 %ignorehash = &_whitelist_localhost
();
79 # Return the class object.
84 ## The main "CheckAction" function.
86 ## This function is used to handle each recived event from the main event queue of guardian.
88 ## It will check if the given command is valid and will pass it to the responsible function.
90 sub CheckAction
($$) {
92 my @event = split(/ /, $_[0], 4);
93 my ($command, $address, $module, $message) = @event;
95 # Check if we got an invalid command.
96 unless(exists($commands{$command})) {
97 $logger->Log("err", "The CheckAction function has been called with an unsupported command ($command)!");
101 # Check if the given event contains an address.
103 # Convert and validate the given address.
104 my $bin_address = &Guardian
::Base
::IPOrNet2Int
($address);
106 # Abort if the given address could not be converted because it is not valid.
107 unless ($bin_address) {
108 $logger->Log("err", "Invalid IP address: $address");
112 # Check if address should be ignored.
113 if(&_IsOnIgnoreList
($bin_address)) {
115 $logger->Log("info", "Ignoring event for $address, because it is part of the ignore list.");
120 # Call required handler.
121 my $error = $commands{$command}->($self, $address, $module, $message);
123 # If we got any return code, something went wrong and should be logged.
125 $logger->Log("err", "Got error: $error");
131 ## The main "Counter" function.
133 ## This function is used to handle each count message + address, which has been sent by the main event
136 ## It stores the address and the current count into the counthash and increase the count each time when
137 ## the same address should be counted again. When the current count reaches the configured BlockCount,
138 ## the responsible function will be called to block the address.
142 my ($address, $module, $message) = @_;
145 $logger->Log("debug", "$module reported $message for address: $address");
147 # Increase existing count or start counting for new source addresses.
148 if (exists($counthash{$address})) {
149 # Skip already blocked addresses.
150 if (exists($blockhash{$address})) {
154 # Increase count of the existing entry.
155 $counthash{$address} = $counthash{$address} + 1;
157 # Log altered count of the address.
158 $logger->Log("debug", "Source $address now has count $counthash{$address}/$self->{BlockCount}...");
160 # Log that counting for the address has been started.
161 $logger->Log("debug", "Start counting for $address...");
164 $counthash{$address} = 1;
167 # Check if the address has reached the configured count limit.
168 if ($counthash{$address} >= $self->{BlockCount
}) {
169 # Write out log message.
170 $logger->Log("info", "Blocking $address for $self->{BlockTime} seconds...");
172 # Call block subroutine to block the address.
173 my $error = &CallBlock
($self, $address, $module, $message);
175 # Return the message if an error occurs.
179 # Everything worked well, return nothing.
184 ## The RemoveBlocks function.
186 ## This function periodly will be called and is responsible for releasing the block if the Blocktime
187 ## on an address has expired.
189 ## To do this, the code will loop through all entries of the blockhash and check
190 ## if the estimiated BlockTime of each address has reached and so the block can be released.
192 sub RemoveBlocks
() {
195 # Get the current time.
198 # Loop through the blockhash.
199 foreach my $address (keys %blockhash) {
200 # Check if the blocktime for the address has expired.
201 if ($blockhash{$address} <= $time) {
202 # Call unblock subroutine.
203 my $error = &CallUnblock
($self, $address, "BlockTime", "has expired for $address");
205 # Log error messages if returned.
207 $logger->Log("err", "$error");
212 # Everything okay, return nothing.
217 ## The CallBlock function.
219 ## This function is called, if the BlockCount for an address is reached or a direct
220 ## request for blocking an address has been recieved.
224 my ($address, $module, $message) = @_;
226 # Log the call for blocking an address.
227 $logger->Log("info", "$module - $message");
229 # Check if an entry for this address exists
230 # in the blockhash. If not, the address has
231 # not been blocked yet, call the responisible
232 # function to do this now.
233 unless (exists($blockhash{$address})) {
234 # Obtain the configured FirewallAction.
235 my $action = $self->{FirewallAction
};
237 # Block the given address.
238 my $error = &DoBlock
($address, $action);
240 # If we got back an error message something went wrong.
242 # Exit function and return the used FirewallEngine and the error message.
243 return "$self->{FirewallEngine} - $error";
245 # Address has been successfully blocked, print a log message.
246 $logger->Log("debug", "Address $address successfully has been blocked...");
250 # Generate time when the block will expire.
251 my $expire = time() + $self->{BlockTime
};
253 # Store the blocked address and the expire time
255 $blockhash{$address} = $expire;
257 # Return nothing "undef" if everything is okay.
262 ## CallUnblock function.
264 ## This function is responsible for unblocking and deleting a given
265 ## address from the blockhash.
267 sub CallUnblock
($) {
269 my ($address, $module, $message) = @_;
271 # Log the call for unblocking an address.
272 $logger->Log("info", "$module - $message");
274 # Return an error if no entry for the given address
275 # is present in the blockhash.
276 unless (exists($blockhash{$address})) {
277 return "Address $address was not blocked!";
280 # Unblock the address.
281 my $error = &DoUnblock
($address);
283 # If an error message is returned, something went wrong.
285 # Exit function and return the error message.
288 # Address successfully has been unblocked.
289 $logger->Log("debug", "Address $address successfully has been unblocked...");
292 # Drop address from blockhash.
293 delete ($blockhash{$address});
295 # Everything worked well, return nothing.
300 ## CallFlush function.
302 ## This function is responsible for calling the used firewall
303 ## engine to do a flush of the used firewall chain. This will
304 ## clean the entire firewall chain.
309 # Log the call for flushing.
310 $logger->Log("info", "Flush has been called...");
313 my $error = &DoFlush
();
315 # If an error message is returned, something went wrong.
317 # Exit function and return the error message.
320 # Flush successfully has been performed.
321 $logger->Log("debug", "Flush successfully has been performed...");
327 # Everything worked well, return nothing.
332 ## GenerateIgnoreList function.
334 ## This function is responsible for generating/updating the
335 ## IgnoreHash which contains all ignored IP addresses and
338 sub GenerateIgnoreList
($) {
342 # Reset current ignore hash and add
343 # localhost related IP addresses.
344 %ignorehash = &_whitelist_localhost
();
346 # Check if the given IgnoreFile could be opened.
348 $logger->Log("err", "The configured IgnoreFile \($file\) could not be opened. Skipped!");
352 # Open the given IgnoreFile.
353 open (IGNORE
, $file);
355 # Read-in the file line by line.
363 # Remove any newlines.
366 # Check for an include instruction.
367 if ($_ =~ /^Include_File = (.*)/) {
368 my $include_file = $1;
370 # Check if the parsed include file exists and is read-able.
371 if (-e
$include_file) {
372 # Add file to the array of files wich will be included.
373 push(@include_files, $include_file);
375 # Write out log message.
376 $logger->Log("debug", "Addresses from $include_file will be included...");
379 $logger->Log("err", "$include_file will not be included. File does not exist!");
382 # Check if the line contains a valid single address or network and
383 # convert it into binary format. Store the result/start and
384 # end values in a temporary array.
385 my @values = &Guardian
::Base
::IPOrNet2Int
($_);
387 # If the function returned any values, the line contained a valid
388 # single address or network which successfully has been converted into
391 # Assign the array as value to the ignorehash.
392 $ignorehash{$_} = [@values];
395 $logger->Log("err", "IgnoreFile contains an invalid address/network: $_");
403 # Close filehandle for the IgnoreFile.
406 # Check if any files should be included.
407 if (@include_files) {
408 # Loop through the array of files which should be included.
409 foreach my $file (@include_files) {
411 open(INCLUDE
, $file);
413 # Read-in file line by line.
418 # Skip any blank lines.
421 # Chomp any newlines.
424 # Check if the line contains a valid single address or network and
425 # convert it into binary format. Store the result/start and
426 # end values in a temporary array.
427 my @values = &Guardian
::Base
::IPOrNet2Int
($_);
429 # If the function returned any values, the line contained a valid
430 # single address or network which successfully has been converted into
433 # Assign the array as value to the ignorehash.
434 $ignorehash{$_} = [@values];
437 $logger->Log("err", "$file contains an invalid address/network: $_");
449 # Get amount of current elements in hash.
450 my $amount = scalar(keys(%ignorehash));
452 # Write out log message.
453 $logger->Log("debug", "Ignore list currently contains $amount entries.");
457 ## Private function to check if an address is part of the Ignore Hash.
459 ## This function checks if a passed IP address in binary format (!),
460 ## directly or as part of an ignored network is stored in the ignore hash.
462 sub _IsOnIgnoreList
($) {
463 my $bin_address = shift;
465 # Loop through the ignore hash and grab the stored values.
466 foreach my $key ( keys %ignorehash ) {
467 # Dereference values array.
468 my @values = @
{$ignorehash{$key}};
470 # Obtain amount of items for the current value array.
471 my $items = scalar @values;
473 # Whether the amount equals one, the given binary address just
474 # needs to be compared against a single address.
476 my ($ignored_address) = @values;
478 # Simple check if the stored and the given binary address
480 if ($bin_address eq $ignored_address) {
481 # The given address is part of the ignore list.
482 $logger->Log("debug", "Address $key found on the ignore list.");
489 # If the amount equals two, for passed binary address needs to
490 # be checked if it is part of the ignored network range.
491 elsif ($items eq "2") {
492 my ($first_address, $last_address) = @values;
494 # Check if the passed binary address is bigger than
495 # the first address and smaler than the last address
496 # (between) the stored network range.
497 if (($bin_address >= $first_address) && ($bin_address <= $last_address)) {
498 # The address is part of an ignored network.
499 $logger->Log("debug", "Address is found inside the ignored network $key.");
505 # If the amount is not eighter one or two, the current entry of the ignorehash seems
506 # to be corrupted. Skip and log it.
508 # Write log message about this corruped item in the ignore hash.
509 $logger->Log("err", "Invalid item in the Ignore Hash: $key - @values");
511 # Skip this element of the ignore hash.
516 # If we got here, the given address is not part of the ignore hash.
517 # Return nothing (False).
522 ## The _whitelist_localhost function.
524 ## This tiny private function simple generates and returns a hash which contains
525 ## the clear and binary converted addresses for all array-stored
526 ## (@localhost_addresses) in an ignorelist compatible format.
528 sub _whitelist_localhost
() {
531 # Loop through the array of localhost related addresses.
532 foreach my $address (@localhost_addresses) {
533 # Validate and convert the addresss into binary format.
534 my @values = &Guardian
::Base
::IPOrNet2Int
($address);
536 # Check if any values are returned.
538 # Store the converted binary values in the temporary hash.
539 $temphash{$address} = [@values];
543 # Return the temporary hash.