]>
git.ipfire.org Git - people/stevee/guardian.git/blob - modules/Events.pm
025fe4f243fa4e685d3dabb6cf83a97ccd22feb3
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
,
18 # Hash to store addresses and their current count.
21 # Hash to store all currentyl blocked addresses and a timestamp
22 # when the block for this address can be released.
25 # Hash to store user-defined IP addresses and/or subnets which should be
26 # ignored in case any events should be repored for them.
29 # Array to store localhost related IP addresses.
30 # They are always white-listed to prevent guardian from blocking
32 my @localhost_addresses = ("127.0.0.1", "::1");
34 # This object will contain the reference to the logger object after calling Init.
38 ## The "Init" (Block) function.
40 ## This function is responsible to initialize Block as a class based object.
41 ## It has to be called once before any blocking event can be processed.
43 ## The following arguments must be passed, during initialization:
44 ## "BlockCount" and "BlockTime" which both have to be natural numbers.
47 my ( $class, %args ) = @_;
50 # Fail, if some critical arguments are missing.
51 unless ((exists($self->{BlockCount
})) && (exists($self->{BlockTime
}))) {
52 die "Could not initialize Block: Too less arguments are given.\n";
55 # Use bless to make "$self" to an object of class "$class".
58 # Assign logger object.
59 $logger = $self->{Logger
};
61 # Log used firewall engine.
62 $logger->Log("debug", "Using firewall engine: $self->{FirewallEngine}");
64 # Try to load the specified firewall engine or die.
65 my $module_name = "Guardian::" . $self->{FirewallEngine
};
66 eval "use $module_name; 1" or die "Could not load a module for firewall engine: $self->{FirewallEngine}!";
68 # Check if an IgnoreFile has been configured.
69 if (exists($self->{IgnoreFile
})) {
70 # Call function to handle the ignore mechanism.
71 &GenerateIgnoreList
($self->{IgnoreFile
});
73 # Whitelist local addresses.
74 %ignorehash = &_whitelist_localhost
();
77 # Return the class object.
82 ## The main "CheckAction" function.
84 ## This function is used to handle each recived event from the main event queue of guardian.
86 ## It will check if the given command is valid and will pass it to the responsible function.
88 sub CheckAction
($$) {
90 my @event = split(/ /, $_[0], 4);
91 my ($command, $address, $module, $message) = @event;
93 # Check if we got an invalid command.
94 unless(exists($commands{$command})) {
95 $logger->Log("err", "The CheckAction function has been called with an unsupported command ($command)!");
99 # Check if the given event contains an address.
101 # Convert and validate the given address.
102 my $bin_address = &Guardian
::Base
::IPOrNet2Int
($address);
104 # Abort if the given address could not be converted because it is not valid.
105 unless ($bin_address) {
106 $logger->Log("err", "Invalid IP address: $address");
110 # Check if address should be ignored.
111 if(&_IsOnIgnoreList
($bin_address)) {
113 $logger->Log("info", "Ignoring event for $address, because it is part of the ignore list.");
118 # Call required handler.
119 my $error = $commands{$command}->($self, $address, $module, $message);
121 # If we got any return code, something went wrong and should be logged.
123 $logger->Log("err", "Got error: $error");
129 ## The main "Counter" function.
131 ## This function is used to handle each count message + address, which has been sent by the main event
134 ## It stores the address and the current count into the counthash and increase the count each time when
135 ## the same address should be counted again. When the current count reaches the configured BlockCount,
136 ## the responsible function will be called to block the address.
140 my ($address, $module, $message) = @_;
143 $logger->Log("debug", "$module reported $message for address: $address");
145 # Increase existing count or start counting for new source addresses.
146 if (exists($counthash{$address})) {
147 # Skip already blocked addresses.
148 if (exists($blockhash{$address})) {
152 # Increase count of the existing entry.
153 $counthash{$address} = $counthash{$address} + 1;
155 # Log altered count of the address.
156 $logger->Log("debug", "Source $address now has count $counthash{$address}/$self->{BlockCount}...");
158 # Log that counting for the address has been started.
159 $logger->Log("debug", "Start counting for $address...");
162 $counthash{$address} = 1;
165 # Check if the address has reached the configured count limit.
166 if ($counthash{$address} >= $self->{BlockCount
}) {
167 # Write out log message.
168 $logger->Log("info", "Blocking $address for $self->{BlockTime} seconds...");
170 # Call block subroutine to block the address.
171 my $error = &CallBlock
($self, $address, $module, $message);
173 # Return the message if an error occurs.
177 # Everything worked well, return nothing.
182 ## The RemoveBlocks function.
184 ## This function periodly will be called and is responsible for releasing the block if the Blocktime
185 ## on an address has expired.
187 ## To do this, the code will loop through all entries of the blockhash and check
188 ## if the estimiated BlockTime of each address has reached and so the block can be released.
190 sub RemoveBlocks
() {
193 # Get the current time.
196 # Loop through the blockhash.
197 foreach my $address (keys %blockhash) {
198 # Check if the blocktime for the address has expired.
199 if ($blockhash{$address} <= $time) {
200 # Call unblock subroutine.
201 my $error = &CallUnblock
($self, $address, "BlockTime", "has expired for $address");
203 # Log error messages if returned.
205 $logger->Log("err", "$error");
210 # Everything okay, return nothing.
215 ## The CallBlock function.
217 ## This function is called, if the BlockCount for an address is reached or a direct
218 ## request for blocking an address has been recieved.
222 my ($address, $module, $message) = @_;
224 # Log the call for blocking an address.
225 $logger->Log("info", "$module - $message");
227 # Check if an entry for this address exists
228 # in the blockhash. If not, the address has
229 # not been blocked yet, call the responisible
230 # function to do this now.
231 unless (exists($blockhash{$address})) {
232 # Obtain the configured FirewallAction.
233 my $action = $self->{FirewallAction
};
235 # Block the given address.
236 my $error = &DoBlock
($address, $action);
238 # If we got back an error message something went wrong.
240 # Exit function and return the used FirewallEngine and the error message.
241 return "$self->{FirewallEngine} - $error";
243 # Address has been successfully blocked, print a log message.
244 $logger->Log("debug", "Address $address successfully has been blocked...");
248 # Generate time when the block will expire.
249 my $expire = time() + $self->{BlockTime
};
251 # Store the blocked address and the expire time
253 $blockhash{$address} = $expire;
255 # Return nothing "undef" if everything is okay.
260 ## CallUnblock function.
262 ## This function is responsible for unblocking and deleting a given
263 ## address from the blockhash.
265 sub CallUnblock
($) {
267 my ($address, $module, $message) = @_;
269 # Log the call for unblocking an address.
270 $logger->Log("info", "$module - $message");
272 # Return an error if no entry for the given address
273 # is present in the blockhash.
274 unless (exists($blockhash{$address})) {
275 return "Address $address was not blocked!";
278 # Unblock the address.
279 my $error = &DoUnblock
($address);
281 # If an error message is returned, something went wrong.
283 # Exit function and return the error message.
286 # Address successfully has been unblocked.
287 $logger->Log("debug", "Address $address successfully has been unblocked...");
290 # Drop address from blockhash.
291 delete ($blockhash{$address});
293 # Everything worked well, return nothing.
298 ## GenerateIgnoreList function.
300 ## This function is responsible for generating/updating the
301 ## IgnoreHash which contains all ignored IP addresses and
304 sub GenerateIgnoreList
($) {
307 # Check if the given IgnoreFile could be opened.
309 $logger->Log("err", "The configured IgnoreFile \($file\) could not be opened. Skipped!");
313 # Reset current ignore hash and add
314 # localhost related IP addresses.
315 %ignorehash = &_whitelist_localhost
();
317 # Open the given IgnoreFile.
318 open (IGNORE
, $file);
320 # Read-in the file line by line.
328 # Remove any newlines.
331 # Check if the line contains a valid single address or network and
332 # convert it into binary format. Store the result/start and
333 # end values in a temporary array.
334 my @values = &Guardian
::Base
::IPOrNet2Int
($_);
336 # If the function returned any values, the line contained a valid
337 # single address or network which successfully has been converted into
340 # Assign the array as value to the ignorehash.
341 $ignorehash{$_} = [@values];
344 $logger->Log("err", "IgnoreFile contains an invalid address/network: $_");
351 # Close filehandle for the IgnoreFile.
354 # Get amount of current elements in hash.
355 my $amount = scalar(keys(%ignorehash));
357 # Write out log message.
358 $logger->Log("debug", "Ignore list currently contains $amount entries.");
362 ## Private function to check if an address is part of the Ignore Hash.
364 ## This function checks if a passed IP address in binary format (!),
365 ## directly or as part of an ignored network is stored in the ignore hash.
367 sub _IsOnIgnoreList
($) {
368 my $bin_address = shift;
370 # Loop through the ignore hash and grab the stored values.
371 foreach my $key ( keys %ignorehash ) {
372 # Dereference values array.
373 my @values = @
{$ignorehash{$key}};
375 # Obtain amount of items for the current value array.
376 my $items = scalar @values;
378 # Whether the amount equals one, the given binary address just
379 # needs to be compared against a single address.
381 my ($ignored_address) = @values;
383 # Simple check if the stored and the given binary address
385 if ($bin_address eq $ignored_address) {
386 # The given address is part of the ignore list.
387 $logger->Log("debug", "Address $key found on the ignore list.");
394 # If the amount equals two, for passed binary address needs to
395 # be checked if it is part of the ignored network range.
396 elsif ($items eq "2") {
397 my ($first_address, $last_address) = @values;
399 # Check if the passed binary address is bigger than
400 # the first address and smaler than the last address
401 # (between) the stored network range.
402 if (($bin_address >= $first_address) && ($bin_address <= $last_address)) {
403 # The address is part of an ignored network.
404 $logger->Log("debug", "Address is found inside the ignored network $key.");
410 # If the amount is not eighter one or two, the current entry of the ignorehash seems
411 # to be corrupted. Skip and log it.
413 # Write log message about this corruped item in the ignore hash.
414 $logger->Log("err", "Invalid item in the Ignore Hash: $key - @values");
416 # Skip this element of the ignore hash.
421 # If we got here, the given address is not part of the ignore hash.
422 # Return nothing (False).
427 ## The _whitelist_localhost function.
429 ## This tiny private function simple generates and returns a hash which contains
430 ## the clear and binary converted addresses for all array-stored
431 ## (@localhost_addresses) in an ignorelist compatible format.
433 sub _whitelist_localhost
() {
436 # Loop through the array of localhost related addresses.
437 foreach my $address (@localhost_addresses) {
438 # Validate and convert the addresss into binary format.
439 my @values = &Guardian
::Base
::IPOrNet2Int
($address);
441 # Check if any values are returned.
443 # Store the converted binary values in the temporary hash.
444 $temphash{$address} = [@values];
448 # Return the temporary hash.