blib/lib/Lemonldap/NG/Portal/Lib/CrowdSec.pm untested

filter: Statementstmt 0.0% 0 / 152 Branchbran 0.0% 0 / 32 Conditioncond 0.0% 0 / 58 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 15 Podpod 0.0% 0 / 7 totaltotal 0.0% 0 / 264 CC 17 SCAR 28.9
CC
17
Cov
0%
bouncer
42.0
getToken
30.0
getAlertsByIp
20.0
CRAP 18.1
1 package Lemonldap::NG::Portal::Lib::CrowdSec;
2  
3 use strict;
4 use Date::Parse;
5 use Digest::SHA qw(sha256_hex);
6 use JSON qw(from_json to_json);
7 use Mouse::Role;
8 use POSIX qw(strftime);
9 use Lemonldap::NG::Common::UserAgent;
10 use Lemonldap::NG::Portal::Main::Constants qw(
11 PE_OK
12 PE_ERROR
13 PE_SESSIONNOTGRANTED
14 );
15  
16 our $VERSION = '2.22.0';
17  
18 our $defaultBanValues = {
19 events_count => 1,
20 scenario => 'llng',
21 scenario_version => $VERSION,
22 leakspeed => '1s',
23 remediation => JSON::true,
24 simulated => JSON::false,
25 capacity => 1,
26 };
27  
28 has ua => (
29 is => 'rw',
30 lazy => 1,
31 builder => sub {
32 my $ua = Lemonldap::NG::Common::UserAgent->new( $_[0]->{conf} );
33 $ua->agent( 'LLNG-CrowdsecAgent/' . $VERSION );
34 $ua->default_headers->header( 'Accept' => 'application/json' );
35 $ua->default_headers->header( 'Content-Type' => 'application/json' );
36 return $ua;
37 }
38 );
39  
40 has token => ( is => 'rw' );
41 has tokenExp => ( is => 'rw', default => 0 );
42  
43 has crowdsecUrl => ( is => 'rw' );
44  
45 sub _init {
46 my ($self) = @_;
47 if ( $self->conf->{crowdsecUrl} ) {
48 my $tmp = $self->conf->{crowdsecUrl};
49 $tmp =~ s#/+$##;
50 $self->crowdsecUrl($tmp);
51 }
52 else {
53 $self->logger->warn(
54 "crowdsecUrl isn't set, fallback to http://localhost:8080");
55 $self->crowdsecUrl('http://localhost:8080');
56 }
57 return 1;
58 }
59  
60 sub bouncer {
61 my ( $self, $ip ) = @_;
62 my $resp = $self->ua->get(
63 $self->crowdsecUrl . "/v1/decisions?ip=$ip",
64 'Accept' => 'application/json',
65 'X-Api-Key' => $self->conf->{crowdsecKey},
66 );
67 if ( $resp->is_error ) {
68 $self->logger->error( 'Bad CrowdSec response: ' . $resp->message );
69 $self->logger->debug( $resp->content );
70 return ( 1, PE_ERROR );
71 }
72 my $content = $resp->decoded_content;
73 if ( !$content or $content eq 'null' ) {
74 $self->userLogger->debug("$ip isn't known by CrowdSec");
75 return ( 1, PE_OK );
76 }
77 my $json_hash;
78 eval { $json_hash = from_json( $content, { allow_nonref => 1 } ); };
79 if ($@) {
80 $self->logger->error("Unable to decode CrowdSec response: $content");
81 $self->logger->debug($@);
82 return ( 1, PE_ERROR );
83 }
84 $self->logger->debug("CrowdSec response: $content");
85  
86 # Response is "null" when IP is unknown
87 if ($json_hash) {
88  
89 # CrowdSec may return more than one decision
90 foreach my $decision (@$json_hash) {
91 if ( $decision->{type} and $decision->{type} eq 'ban' ) {
92 return ( 0,
93 "$ip banned by CrowdSec ('"
94 . $decision->{scenario}
95 . "' for $decision->{duration})" );
96 }
97 }
98 $self->userLogger->info("$ip not banned by CrowdSec");
99 return ( 1, PE_OK );
100 }
101 }
102  
103 sub ban {
104 my $self = shift;
105 my ( $ip, $msg, $data ) = @_;
106 if ( my $token = $self->getToken ) {
107 my $request = HTTP::Request->new(
108 POST => $self->crowdsecUrl . '/v1/alerts',
109 [
110 'Content-Type' => 'application/json',
111 'Authorization' => "Bearer " . $self->token,
112 ],
113 $self->_banPayload(@_)
114 );
115 my $resp = $self->ua->request($request);
116 unless ( $resp->is_success ) {
117 $self->logger->error(
118 join ' ', 'Unable to push alert',
119 $resp->status_line, $resp->decoded_content
120 );
121 return;
122 }
123 $self->logger->notice("Push new Crowdsec alert for $ip: $msg");
124 return 1;
125 }
126 else {
127 $self->logger->error('Unable to push Crowdsec decision');
128 return;
129 }
130 }
131  
132 sub alert {
133 my $self = shift;
134 my ( $ip, $msg, $data ) = @_;
135  
136 # No new ban decision for already banned IPs
137 my ($notBanned) = $self->bouncer($ip);
138  
139 $data ||= {};
140 my $max = $self->conf->{crowdsecMaxFailures};
141 my $count = $self->getAlertsByIp($ip) || 0;
142 $data->{remediation} =
143 ( $max and $count >= ( $max - 1 ) and $notBanned )
144 ? JSON::true
145 : JSON::false;
146 $self->logger->debug("Crowdsec alerts count is $count for $ip");
147 $data->{reason} ||= 'Reported by LLNG';
148 $msg ||= 'Reported by LLNG';
149 return $self->ban( $ip, $msg, $data );
150 }
151  
152 sub getAlertsByIp {
153 my ( $self, $ip, $scenario ) = @_;
154 $scenario ||= $defaultBanValues->{scenario};
155 if ( my $token = $self->getToken ) {
156 my $url = $self->crowdsecUrl . '/v1/alerts';
157 my $request = HTTP::Request->new(
158 GET => $url,
159 [
160 'Authorization' => "Bearer " . $self->token,
161 ],
162 );
163 my $resp = $self->ua->request($request);
164 unless ( $resp->is_success ) {
165 $self->logger->error(
166 join ' ', 'Unable to get alerts',
167 $resp->status_line, $resp->decoded_content
168 );
169 return;
170 }
171 my $alerts = eval { from_json( $resp->decoded_content ) };
172 if ( $@ or !$alerts ) {
173 $self->logger->error( join ' ', 'Unable to read Crowdsec response:',
174 $@, $resp->decoded_content );
175 return;
176 }
177 my $timeLimit = time - ( $self->conf->{crowdsecBlockDelay} || 180 );
178 my @ipAlerts =
179 grep {
180 $_->{source}->{value} eq $ip
181 and $_->{scenario} eq $scenario
182 and str2time( $_->{start_at} ) > $timeLimit
183 } @$alerts;
184 return ( scalar @ipAlerts );
185 }
186 else {
187 $self->logger->error('Unable to push Crowdsec decision');
188 return;
189 }
190 }
191  
192 sub _banPayload {
193 my ( $self, $ip, $msg, $data ) = @_;
194 $msg ||= 'Banned by LLNG Crowdsec plugin';
195 foreach my $k ( keys %$defaultBanValues ) {
196 $data->{$k} //= $defaultBanValues->{$k};
197 }
198 my $timestamp = strftime( "%Y-%m-%dT%H:%M:%SZ", gmtime );
199 $data->{start_at} ||= $timestamp;
200 $data->{stop_at} ||= $timestamp;
201 $data->{source} ||= { scope => 'ip', value => $ip };
202 my $reason = delete( $data->{reason} ) || 'Banned by LLNG';
203 $data->{scenario_hash} = sha256_hex( $data->{scenario} );
204 return to_json( [ {
205 %$data,
206 message => $msg,
207 events => [ {
208 timestamp => $data->{start_at},
209 meta => [
210 { key => 'log_type', value => 'llng-auth' },
211 { key => 'reason', value => $reason }
212 ],
213 source => $data->{source},
214 }
215 ],
216 }
217 ]
218 );
219 }
220  
221 sub getToken {
222 my ($self) = @_;
223  
224 # Use token if available
225 return $self->token if $self->token and $self->tokenExp < time - 10;
226  
227 # Get new token
228 my ( $user, $pwd ) =
229 map { $self->conf->{$_} } qw(crowdsecMachineId crowdsecPassword);
230 unless ( $user and $pwd ) {
231 $self->logger->error('Missing crowdsec credentials, aborting');
232 return;
233 }
234 my $request = HTTP::Request->new(
235 POST => $self->crowdsecUrl . '/v1/watchers/login',
236 [ 'Content-Type' => 'application/json' ],
237 to_json( {
238 machine_id => $user,
239 password => $pwd,
240 }
241 )
242 );
243 my $resp = $self->ua->request($request);
244 unless ( $resp->is_success ) {
245 $self->logger->error( join ' ', 'Unable to connect to Crowdsec:',
246 $resp->status_line, $resp->decoded_content );
247 return;
248 }
249 my $json = eval { from_json( $resp->decoded_content ) };
250 if ( $@ or !$json ) {
251 $self->logger->error( join ' ', 'Unable to read Crowdsec response:',
252 $@, $resp->decoded_content );
253 return;
254 }
255 $self->tokenExp( str2time( $json->{expire} ) );
256 $self->logger->debug("Get Crowdsec token");
257 return $self->token( $json->{token} );
258 }
259  
260 1;