« blib/lib/Lemonldap/NG/Portal/Plugins/GlobalLogout.pm
↑ Summary
blib/lib/Lemonldap/NG/Portal/Lib/Key.pm »
| 1 | package Lemonldap::NG::Portal::Plugins::CrowdSec; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use Mouse; | ||
| 5 | use Lemonldap::NG::Portal::Main::Constants qw( | ||
| 6 | PE_OK | ||
| 7 | PE_SESSIONNOTGRANTED | ||
| 8 | ); | ||
| 9 | |||
| 10 | our $VERSION = '2.23.0'; | ||
| 11 | |||
| 12 | extends 'Lemonldap::NG::Portal::Main::Plugin'; | ||
| 13 | with 'Lemonldap::NG::Portal::Lib::CrowdSec'; | ||
| 14 | |||
| 15 | # Entrypoint | ||
| 16 | use constant aroundSub => { controlUrl => 'checkCrowdsec' }; | ||
| 17 | |||
| 18 | has rule => ( is => 'rw', default => sub { 0 } ); | ||
| 19 | |||
| 20 | sub init { | ||
| 21 | my ($self) = @_; | ||
| 22 | $self->_init or return 0; | ||
| 23 | |||
| 24 | # Parse activation rule | ||
| 25 | unless ( $self->conf->{crowdsecKey} ) { | ||
| 26 | $self->logger->error('Missing Crowdsec Bouncer key'); | ||
| 27 | return 0; | ||
| 28 | } | ||
| 29 | $self->logger->info( | ||
| 30 | 'CrowdSec policy is: ' . ( $self->conf->{crowdsecAction} || 'warn' ) ); | ||
| 31 | $self->rule( $self->p->buildRule( $self->conf->{crowdsec}, 'crowdsec' ) ); | ||
| 32 | return 1; | ||
| 33 | } | ||
| 34 | |||
| 35 | sub checkCrowdsec { | ||
| 36 | my ( $self, $sub, $req ) = @_; | ||
| 37 | if ( !$self->rule->( $req, $req->sessionInfo ) ) { | ||
| 38 | $self->logger->debug('Crowdsec disabled for this env'); | ||
| 39 | return $sub->($req); | ||
| 40 | } | ||
| 41 | my $ip = $req->address; | ||
| 42 | my ( $ok, $err ) = $self->bouncer($ip); | ||
| 43 | |||
| 44 | # bouncer() answer $ok=0 only when Crowdsec response rejects the given IP | ||
| 45 | return $sub->($req) | ||
| 46 | if ( $ok and $err and $self->conf->{crowdsecIgnoreFailures} ); | ||
| 47 | |||
| 48 | # When $ok==0, $err contains the Crowdsec decision | ||
| 49 | unless ($ok) { | ||
| 50 | if ( $self->conf->{crowdsecAction} eq 'reject' ) { | ||
| 51 | $self->auditLog( | ||
| 52 | $req, | ||
| 53 | code => 403, | ||
| 54 | message => $err, | ||
| 55 | ip => $ip, | ||
| 56 | ); | ||
| 57 | return PE_SESSIONNOTGRANTED; | ||
| 58 | } | ||
| 59 | else { | ||
| 60 | $self->auditLog( | ||
| 61 | $req, | ||
| 62 | code => 200, | ||
| 63 | message => "$err (ignored)", | ||
| 64 | ip => $ip, | ||
| 65 | ); | ||
| 66 | $req->env->{CROWDSEC_REJECT} = 1; | ||
| 67 | return $sub->($req); | ||
| 68 | } | ||
| 69 | } | ||
| 70 | return $err ? $err : $sub->($req); | ||
| 71 | } | ||
| 72 | |||
| 73 | 1; |