]>
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
,
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 # This object will contain the reference to the logger object after calling Init.
33 ## The "Init" (Block) function.
35 ## This function is responsible to initialize Block as a class based object.
36 ## It has to be called once before any blocking event can be processed.
38 ## The following arguments must be passed, during initialization:
39 ## "BlockCount" and "BlockTime" which both have to be natural numbers.
42 my ( $class, %args ) = @_;
45 # Fail, if some critical arguments are missing.
46 unless ((exists($self->{BlockCount
})) && (exists($self->{BlockTime
}))) {
47 die "Could not initialize Block: Too less arguments are given.\n";
50 # Use bless to make "$self" to an object of class "$class".
53 # Assign logger object.
54 $logger = $self->{Logger
};
56 # Log used firewall engine.
57 $logger->Log("debug", "Using firewall engine: $self->{FirewallEngine}");
59 # Try to load the specified firewall engine or die.
60 my $module_name = "Guardian::" . $self->{FirewallEngine
};
61 eval "use $module_name; 1" or die "Could not load a module for firewall engine: $self->{FirewallEngine}!";
63 # Check if an IgnoreFile has been configured.
64 if (exists($self->{IgnoreFile
})) {
65 # Call function to handle the ignore mechanism.
66 &GenerateIgnoreList
($self->{IgnoreFile
});
69 # Return the class object.
74 ## The main "CheckAction" function.
76 ## This function is used to handle each recived event from the main event queue of guardian.
78 ## It will check if the given command is valid and will pass it to the responsible function.
80 sub CheckAction
($$) {
82 my @event = split(/ /, $_[0], 4);
83 my ($command, $address, $module, $message) = @event;
85 # Check if we got an invalid command.
86 unless(exists($commands{$command})) {
87 $logger->Log("err", "The CheckAction function has been called with an unsupported command ($command)!");
91 # Check if the given event contains an address.
93 # Convert and validate the given address.
94 my $bin_address = &Guardian
::Base
::IPOrNet2Int
($address);
96 # Abort if the given address could not be converted because it is not valid.
97 unless ($bin_address) {
98 $logger->Log("err", "Invalid IP address: $address");
102 # Check if address should be ignored.
103 if(&_IsOnIgnoreList
($bin_address)) {
105 $logger->Log("info", "Ignoring event for $address, because it is part of the ignore list.");
110 # Call required handler.
111 my $error = $commands{$command}->($self, $address, $module, $message);
113 # If we got any return code, something went wrong and should be logged.
115 $logger->Log("err", "Got error: $error");
121 ## The main "Counter" function.
123 ## This function is used to handle each count message + address, which has been sent by the main event
126 ## It stores the address and the current count into the counthash and increase the count each time when
127 ## the same address should be counted again. When the current count reaches the configured BlockCount,
128 ## the responsible function will be called to block the address.
132 my ($address, $module, $message) = @_;
135 $logger->Log("debug", "$module reported $message for address: $address");
137 # Increase existing count or start counting for new source addresses.
138 if (exists($counthash{$address})) {
139 # Skip already blocked addresses.
140 if (exists($blockhash{$address})) {
144 # Increase count of the existing entry.
145 $counthash{$address} = $counthash{$address} + 1;
147 # Log altered count of the address.
148 $logger->Log("debug", "Source $address now has count $counthash{$address}/$self->{BlockCount}...");
150 # Log that counting for the address has been started.
151 $logger->Log("debug", "Start counting for $address...");
154 $counthash{$address} = 1;
157 # Check if the address has reached the configured count limit.
158 if ($counthash{$address} >= $self->{BlockCount
}) {
159 # Write out log message.
160 $logger->Log("info", "Blocking $address for $self->{BlockTime} seconds...");
162 # Call block subroutine to block the address.
163 my $error = &CallBlock
($self, $address, $module, $message);
165 # Return the message if an error occurs.
169 # Everything worked well, return nothing.
174 ## The RemoveBlocks function.
176 ## This function periodly will be called and is responsible for releasing the block if the Blocktime
177 ## on an address has expired.
179 ## To do this, the code will loop through all entries of the blockhash and check
180 ## if the estimiated BlockTime of each address has reached and so the block can be released.
182 sub RemoveBlocks
() {
185 # Get the current time.
188 # Loop through the blockhash.
189 foreach my $address (keys %blockhash) {
190 # Check if the blocktime for the address has expired.
191 if ($blockhash{$address} <= $time) {
192 # Call unblock subroutine.
193 my $error = &CallUnblock
($self, $address, "BlockTime", "has expired for $address");
195 # Log error messages if returned.
197 $logger->Log("err", "$error");
202 # Everything okay, return nothing.
207 ## The CallBlock function.
209 ## This function is called, if the BlockCount for an address is reached or a direct
210 ## request for blocking an address has been recieved.
214 my ($address, $module, $message) = @_;
216 # Log the call for blocking an address.
217 $logger->Log("info", "$module - $message");
219 # Check if an entry for this address exists
220 # in the blockhash. If not, the address has
221 # not been blocked yet, call the responisible
222 # function to do this now.
223 unless (exists($blockhash{$address})) {
224 # Obtain the configured FirewallAction.
225 my $action = $self->{FirewallAction
};
227 # Block the given address.
228 my $error = &DoBlock
($address, $action);
230 # If we got back an error message something went wrong.
232 # Exit function and return the used FirewallEngine and the error message.
233 return "$self->{FirewallEngine} - $error";
235 # Address has been successfully blocked, print a log message.
236 $logger->Log("debug", "Address $address successfully has been blocked...");
240 # Generate time when the block will expire.
241 my $expire = time() + $self->{BlockTime
};
243 # Store the blocked address and the expire time
245 $blockhash{$address} = $expire;
247 # Return nothing "undef" if everything is okay.
252 ## CallUnblock function.
254 ## This function is responsible for unblocking and deleting a given
255 ## address from the blockhash.
257 sub CallUnblock
($) {
259 my ($address, $module, $message) = @_;
261 # Log the call for unblocking an address.
262 $logger->Log("info", "$module - $message");
264 # Return an error if no entry for the given address
265 # is present in the blockhash.
266 unless (exists($blockhash{$address})) {
267 return "Address $address was not blocked!";
270 # Unblock the address.
271 my $error = &DoUnblock
($address);
273 # If an error message is returned, something went wrong.
275 # Exit function and return the error message.
278 # Address successfully has been unblocked.
279 $logger->Log("debug", "Address $address successfully has been unblocked...");
282 # Drop address from blockhash.
283 delete ($blockhash{$address});
285 # Everything worked well, return nothing.
290 ## GenerateIgnoreList function.
292 ## This function is responsible for generating/updating the
293 ## IgnoreHash which contains all ignored IP addresses and
296 sub GenerateIgnoreList
($) {
299 # Check if the given IgnoreFile could be opened.
301 $logger->Log("err", "The configured IgnoreFile \($file\) could not be opened. Skipped!");
305 # Open the given IgnoreFile.
306 open (IGNORE
, $file);
308 # Read-in the file line by line.
316 # Remove any newlines.
319 # Check if the line contains a valid single address or network and
320 # convert it into binary format. Store the result/start and
321 # end values in a temporary array.
322 my @values = &Guardian
::Base
::IPOrNet2Int
($_);
324 # If the function returned any values, the line contained a valid
325 # single address or network which successfully has been converted into
328 # Assign the array as value to the ignorehash.
329 $ignorehash{$_} = [@values];
332 $logger->Log("err", "IgnoreFile contains an invalid address/network: $_");
339 # Close filehandle for the IgnoreFile.
344 ## Private function to check if an address is part of the Ignore Hash.
346 ## This function checks if a passed IP address in binary format (!),
347 ## directly or as part of an ignored network is stored in the ignore hash.
349 sub _IsOnIgnoreList
($) {
350 my $bin_address = shift;
352 # Loop through the ignore hash and grab the stored values.
353 foreach my $key ( keys %ignorehash ) {
354 # Dereference values array.
355 my @values = @
{$ignorehash{$key}};
357 # Obtain amount of items for the current value array.
358 my $items = scalar @values;
360 # Whether the amount equals one, the given binary address just
361 # needs to be compared against a single address.
363 my ($ignored_address) = @values;
365 # Simple check if the stored and the given binary address
367 if ($bin_address eq $ignored_address) {
368 # The given address is part of the ignore list.
369 $logger->Log("debug", "Address $key found on the ignore list.");
376 # If the amount equals two, for passed binary address needs to
377 # be checked if it is part of the ignored network range.
378 elsif ($items eq "2") {
379 my ($first_address, $last_address) = @values;
381 # Check if the passed binary address is bigger than
382 # the first address and smaler than the last address
383 # (between) the stored network range.
384 if (($bin_address >= $first_address) && ($bin_address <= $last_address)) {
385 # The address is part of an ignored network.
386 $logger->Log("debug", "Address is found inside the ignored network $key.");
392 # If the amount is not eighter one or two, the current entry of the ignorehash seems
393 # to be corrupted. Skip and log it.
395 # Write log message about this corruped item in the ignore hash.
396 $logger->Log("err", "Invalid item in the Ignore Hash: $key - @values");
398 # Skip this element of the ignore hash.
403 # If we got here, the given address is not part of the ignore hash.
404 # Return nothing (False).