]>
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
,
19 # Hash to store addresses and their current count.
22 # Hash to store all currentyl blocked addresses and a timestamp
23 # when the block for this address can be released.
26 # Hash to store user-defined IP addresses and/or subnets which should be
27 # ignored in case any events should be repored for them.
30 # Array to store localhost related IP addresses.
31 # They are always white-listed to prevent guardian from blocking
33 my @localhost_addresses = ("127.0.0.1", "::1");
35 # This object will contain the reference to the logger object after calling Init.
39 ## The "Init" (Block) function.
41 ## This function is responsible to initialize Block as a class based object.
42 ## It has to be called once before any blocking event can be processed.
44 ## The following arguments must be passed, during initialization:
45 ## "BlockCount" and "BlockTime" which both have to be natural numbers.
48 my ( $class, %args ) = @_;
51 # Fail, if some critical arguments are missing.
52 unless ((exists($self->{BlockCount
})) && (exists($self->{BlockTime
}))) {
53 die "Could not initialize Block: Too less arguments are given.\n";
56 # Use bless to make "$self" to an object of class "$class".
59 # Assign logger object.
60 $logger = $self->{Logger
};
62 # Log used firewall engine.
63 $logger->Log("debug", "Using firewall engine: $self->{FirewallEngine}");
65 # Try to load the specified firewall engine or die.
66 my $module_name = "Guardian::" . $self->{FirewallEngine
};
67 eval "use $module_name; 1" or die "Could not load a module for firewall engine: $self->{FirewallEngine}!";
69 # Check if an IgnoreFile has been configured.
70 if (exists($self->{IgnoreFile
})) {
71 # Call function to handle the ignore mechanism.
72 &GenerateIgnoreList
($self->{IgnoreFile
});
74 # Whitelist local addresses.
75 %ignorehash = &_whitelist_localhost
();
78 # Return the class object.
83 ## The main "CheckAction" function.
85 ## This function is used to handle each recived event from the main event queue of guardian.
87 ## It will check if the given command is valid and will pass it to the responsible function.
89 sub CheckAction
($$) {
91 my @event = split(/ /, $_[0], 4);
92 my ($command, $address, $module, $message) = @event;
94 # Check if we got an invalid command.
95 unless(exists($commands{$command})) {
96 $logger->Log("err", "The CheckAction function has been called with an unsupported command ($command)!");
100 # Check if the given event contains an address.
102 # Convert and validate the given address.
103 my $bin_address = &Guardian
::Base
::IPOrNet2Int
($address);
105 # Abort if the given address could not be converted because it is not valid.
106 unless ($bin_address) {
107 $logger->Log("err", "Invalid IP address: $address");
111 # Check if address should be ignored.
112 if(&_IsOnIgnoreList
($bin_address)) {
114 $logger->Log("info", "Ignoring event for $address, because it is part of the ignore list.");
119 # Call required handler.
120 my $error = $commands{$command}->($self, $address, $module, $message);
122 # If we got any return code, something went wrong and should be logged.
124 $logger->Log("err", "Got error: $error");
130 ## The main "Counter" function.
132 ## This function is used to handle each count message + address, which has been sent by the main event
135 ## It stores the address and the current count into the counthash and increase the count each time when
136 ## the same address should be counted again. When the current count reaches the configured BlockCount,
137 ## the responsible function will be called to block the address.
141 my ($address, $module, $message) = @_;
144 $logger->Log("debug", "$module reported $message for address: $address");
146 # Increase existing count or start counting for new source addresses.
147 if (exists($counthash{$address})) {
148 # Skip already blocked addresses.
149 if (exists($blockhash{$address})) {
153 # Increase count of the existing entry.
154 $counthash{$address} = $counthash{$address} + 1;
156 # Log altered count of the address.
157 $logger->Log("debug", "Source $address now has count $counthash{$address}/$self->{BlockCount}...");
159 # Log that counting for the address has been started.
160 $logger->Log("debug", "Start counting for $address...");
163 $counthash{$address} = 1;
166 # Check if the address has reached the configured count limit.
167 if ($counthash{$address} >= $self->{BlockCount
}) {
168 # Write out log message.
169 $logger->Log("info", "Blocking $address for $self->{BlockTime} seconds...");
171 # Call block subroutine to block the address.
172 my $error = &CallBlock
($self, $address, $module, $message);
174 # Return the message if an error occurs.
178 # Everything worked well, return nothing.
183 ## The RemoveBlocks function.
185 ## This function periodly will be called and is responsible for releasing the block if the Blocktime
186 ## on an address has expired.
188 ## To do this, the code will loop through all entries of the blockhash and check
189 ## if the estimiated BlockTime of each address has reached and so the block can be released.
191 sub RemoveBlocks
() {
194 # Get the current time.
197 # Loop through the blockhash.
198 foreach my $address (keys %blockhash) {
199 # Check if the blocktime for the address has expired.
200 if ($blockhash{$address} <= $time) {
201 # Call unblock subroutine.
202 my $error = &CallUnblock
($self, $address, "BlockTime", "has expired for $address");
204 # Log error messages if returned.
206 $logger->Log("err", "$error");
211 # Everything okay, return nothing.
216 ## The CallBlock function.
218 ## This function is called, if the BlockCount for an address is reached or a direct
219 ## request for blocking an address has been recieved.
223 my ($address, $module, $message) = @_;
225 # Log the call for blocking an address.
226 $logger->Log("info", "$module - $message");
228 # Check if an entry for this address exists
229 # in the blockhash. If not, the address has
230 # not been blocked yet, call the responisible
231 # function to do this now.
232 unless (exists($blockhash{$address})) {
233 # Obtain the configured FirewallAction.
234 my $action = $self->{FirewallAction
};
236 # Block the given address.
237 my $error = &DoBlock
($address, $action);
239 # If we got back an error message something went wrong.
241 # Exit function and return the used FirewallEngine and the error message.
242 return "$self->{FirewallEngine} - $error";
244 # Address has been successfully blocked, print a log message.
245 $logger->Log("debug", "Address $address successfully has been blocked...");
249 # Generate time when the block will expire.
250 my $expire = time() + $self->{BlockTime
};
252 # Store the blocked address and the expire time
254 $blockhash{$address} = $expire;
256 # Return nothing "undef" if everything is okay.
261 ## CallUnblock function.
263 ## This function is responsible for unblocking and deleting a given
264 ## address from the blockhash.
266 sub CallUnblock
($) {
268 my ($address, $module, $message) = @_;
270 # Log the call for unblocking an address.
271 $logger->Log("info", "$module - $message");
273 # Return an error if no entry for the given address
274 # is present in the blockhash.
275 unless (exists($blockhash{$address})) {
276 return "Address $address was not blocked!";
279 # Unblock the address.
280 my $error = &DoUnblock
($address);
282 # If an error message is returned, something went wrong.
284 # Exit function and return the error message.
287 # Address successfully has been unblocked.
288 $logger->Log("debug", "Address $address successfully has been unblocked...");
291 # Drop address from blockhash.
292 delete ($blockhash{$address});
294 # Everything worked well, return nothing.
299 ## GenerateIgnoreList function.
301 ## This function is responsible for generating/updating the
302 ## IgnoreHash which contains all ignored IP addresses and
305 sub GenerateIgnoreList
($) {
309 # Reset current ignore hash and add
310 # localhost related IP addresses.
311 %ignorehash = &_whitelist_localhost
();
313 # Check if the given IgnoreFile could be opened.
315 $logger->Log("err", "The configured IgnoreFile \($file\) could not be opened. Skipped!");
319 # Open the given IgnoreFile.
320 open (IGNORE
, $file);
322 # Read-in the file line by line.
330 # Remove any newlines.
333 # Check for an include instruction.
334 if ($_ =~ /^Include_File = (.*)/) {
335 my $include_file = $1;
337 # Check if the parsed include file exists and is read-able.
338 if (-e
$include_file) {
339 # Add file to the array of files wich will be included.
340 push(@include_files, $include_file);
342 # Write out log message.
343 $logger->Log("debug", "Addresses from $include_file will be included...");
346 $logger->Log("err", "$include_file will not be included. File does not exist!");
349 # Check if the line contains a valid single address or network and
350 # convert it into binary format. Store the result/start and
351 # end values in a temporary array.
352 my @values = &Guardian
::Base
::IPOrNet2Int
($_);
354 # If the function returned any values, the line contained a valid
355 # single address or network which successfully has been converted into
358 # Assign the array as value to the ignorehash.
359 $ignorehash{$_} = [@values];
362 $logger->Log("err", "IgnoreFile contains an invalid address/network: $_");
370 # Close filehandle for the IgnoreFile.
373 # Check if any files should be included.
374 if (@include_files) {
375 # Loop through the array of files which should be included.
376 foreach my $file (@include_files) {
378 open(INCLUDE
, $file);
380 # Read-in file line by line.
385 # Skip any blank lines.
388 # Chomp any newlines.
391 # Check if the line contains a valid single address or network and
392 # convert it into binary format. Store the result/start and
393 # end values in a temporary array.
394 my @values = &Guardian
::Base
::IPOrNet2Int
($_);
396 # If the function returned any values, the line contained a valid
397 # single address or network which successfully has been converted into
400 # Assign the array as value to the ignorehash.
401 $ignorehash{$_} = [@values];
404 $logger->Log("err", "$file contains an invalid address/network: $_");
416 # Get amount of current elements in hash.
417 my $amount = scalar(keys(%ignorehash));
419 # Write out log message.
420 $logger->Log("debug", "Ignore list currently contains $amount entries.");
424 ## Private function to check if an address is part of the Ignore Hash.
426 ## This function checks if a passed IP address in binary format (!),
427 ## directly or as part of an ignored network is stored in the ignore hash.
429 sub _IsOnIgnoreList
($) {
430 my $bin_address = shift;
432 # Loop through the ignore hash and grab the stored values.
433 foreach my $key ( keys %ignorehash ) {
434 # Dereference values array.
435 my @values = @
{$ignorehash{$key}};
437 # Obtain amount of items for the current value array.
438 my $items = scalar @values;
440 # Whether the amount equals one, the given binary address just
441 # needs to be compared against a single address.
443 my ($ignored_address) = @values;
445 # Simple check if the stored and the given binary address
447 if ($bin_address eq $ignored_address) {
448 # The given address is part of the ignore list.
449 $logger->Log("debug", "Address $key found on the ignore list.");
456 # If the amount equals two, for passed binary address needs to
457 # be checked if it is part of the ignored network range.
458 elsif ($items eq "2") {
459 my ($first_address, $last_address) = @values;
461 # Check if the passed binary address is bigger than
462 # the first address and smaler than the last address
463 # (between) the stored network range.
464 if (($bin_address >= $first_address) && ($bin_address <= $last_address)) {
465 # The address is part of an ignored network.
466 $logger->Log("debug", "Address is found inside the ignored network $key.");
472 # If the amount is not eighter one or two, the current entry of the ignorehash seems
473 # to be corrupted. Skip and log it.
475 # Write log message about this corruped item in the ignore hash.
476 $logger->Log("err", "Invalid item in the Ignore Hash: $key - @values");
478 # Skip this element of the ignore hash.
483 # If we got here, the given address is not part of the ignore hash.
484 # Return nothing (False).
489 ## The _whitelist_localhost function.
491 ## This tiny private function simple generates and returns a hash which contains
492 ## the clear and binary converted addresses for all array-stored
493 ## (@localhost_addresses) in an ignorelist compatible format.
495 sub _whitelist_localhost
() {
498 # Loop through the array of localhost related addresses.
499 foreach my $address (@localhost_addresses) {
500 # Validate and convert the addresss into binary format.
501 my @values = &Guardian
::Base
::IPOrNet2Int
($address);
503 # Check if any values are returned.
505 # Store the converted binary values in the temporary hash.
506 $temphash{$address} = [@values];
510 # Return the temporary hash.