-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcrowdsec-2.23.patch
More file actions
772 lines (743 loc) · 26.7 KB
/
crowdsec-2.23.patch
File metadata and controls
772 lines (743 loc) · 26.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
--- a/usr/share/perl5/Lemonldap/NG/Portal/Lib/CrowdSec.pm
+++ b/usr/share/perl5/Lemonldap/NG/Portal/Lib/CrowdSec.pm
@@ -13,7 +13,7 @@ use Lemonldap::NG::Portal::Main::Constants qw(
PE_SESSIONNOTGRANTED
);
-our $VERSION = '2.22.0';
+our $VERSION = '2.23.0';
our $defaultBanValues = {
events_count => 1,
@@ -137,23 +137,104 @@ sub alert {
my ($notBanned) = $self->bouncer($ip);
$data ||= {};
- my $max = $self->conf->{crowdsecMaxFailures};
- my $count = $self->getAlertsByIp($ip) || 0;
+
+ # Use per-scenario maxFailures if provided, otherwise use global config
+ my $max = $data->{maxFailures} // $self->conf->{crowdsecMaxFailures};
+
+ # Get both count and previous alerts for enrichment
+ my @prevAlerts =
+ $self->getAlertsByIp( $ip, $data->{scenario}, $data->{timeWindow} );
+
$data->{remediation} =
- ( $max and $count >= ( $max - 1 ) and $notBanned )
+ ( $max and @prevAlerts >= ( $max - 1 ) and $notBanned )
? JSON::true
: JSON::false;
- $self->logger->debug("Crowdsec alerts count is $count for $ip");
+ $self->logger->debug(
+ "Crowdsec alerts count is " . scalar(@prevAlerts) . " for $ip" );
$data->{reason} ||= 'Reported by LLNG';
$msg ||= 'Reported by LLNG';
+
+ # Pass previous alerts for enrichment when ban decision is made
+ # Only include alerts that contributed to the decision (max - 1), capped at 30
+ if ( $data->{remediation} and @prevAlerts ) {
+ my $limit = ( $max && $max > 1 ) ? $max - 1 : 30;
+ $limit = 30 if $limit > 30;
+ if ( @prevAlerts > $limit ) {
+
+ # Take most recent alerts (sorted by start_at desc)
+ my @sorted =
+ sort { ( $b->{start_at} || '' ) cmp( $a->{start_at} || '' ) }
+ @prevAlerts;
+ $data->{_prevAlerts} = [ @sorted[ 0 .. $limit - 1 ] ];
+ }
+ else {
+ $data->{_prevAlerts} = \@prevAlerts;
+ }
+ }
+
return $self->ban( $ip, $msg, $data );
}
+# Extract context from previous alerts for enrichment
+sub _extractAlertContext {
+ my ( $self, $prevAlerts ) = @_;
+ return unless $prevAlerts and @$prevAlerts;
+
+ my ( @logins, @uris, @timestamps );
+ my ( %seen_logins, %seen_uris );
+
+ foreach my $alert (@$prevAlerts) {
+
+ # Extract timestamp
+ push @timestamps, $alert->{start_at} if $alert->{start_at};
+
+ # Extract login and uri from events meta
+ if ( $alert->{events} and @{ $alert->{events} } ) {
+ foreach my $event ( @{ $alert->{events} } ) {
+ if ( $event->{meta} and @{ $event->{meta} } ) {
+ foreach my $m ( @{ $event->{meta} } ) {
+ if ( $m->{key} eq 'login'
+ and $m->{value}
+ and !$seen_logins{ $m->{value} }++ )
+ {
+ push @logins, $m->{value};
+ }
+ if ( $m->{key} eq 'uri'
+ and $m->{value}
+ and !$seen_uris{ $m->{value} }++ )
+ {
+ push @uris, $m->{value};
+ }
+ }
+ }
+ }
+ }
+ }
+
+ # Sort timestamps chronologically
+ @timestamps = sort @timestamps if @timestamps;
+
+ return {
+ logins => \@logins,
+ uris => \@uris,
+ first_alert => $timestamps[0],
+ last_alert => $timestamps[-1],
+ count => scalar @$prevAlerts,
+ };
+}
+
sub getAlertsByIp {
- my ( $self, $ip, $scenario ) = @_;
+ my ( $self, $ip, $scenario, $timeWindow ) = @_;
$scenario ||= $defaultBanValues->{scenario};
if ( my $token = $self->getToken ) {
- my $url = $self->crowdsecUrl . '/v1/alerts';
+
+ # Use API filters to avoid default 50 alerts limit
+ my $url =
+ $self->crowdsecUrl
+ . '/v1/alerts?scope=ip&value='
+ . $ip
+ . '&scenario='
+ . $scenario;
my $request = HTTP::Request->new(
GET => $url,
[
@@ -166,32 +247,48 @@ sub getAlertsByIp {
join ' ', 'Unable to get alerts',
$resp->status_line, $resp->decoded_content
);
- return;
+ return ();
}
- my $alerts = eval { from_json( $resp->decoded_content ) };
- if ( $@ or !$alerts ) {
+ my $content = $resp->decoded_content;
+
+ # CrowdSec returns "null" when there are no alerts
+ if ( !$content or $content eq 'null' ) {
+ $self->logger->debug("No alerts found for $ip");
+ return ();
+ }
+ my $alerts = eval { from_json($content) };
+ if ($@) {
$self->logger->error( join ' ', 'Unable to read Crowdsec response:',
- $@, $resp->decoded_content );
- return;
+ $@, ", $content" );
+ return ();
}
- my $timeLimit = time - ( $self->conf->{crowdsecBlockDelay} || 180 );
+
+ # Use per-scenario timeWindow if provided, otherwise use global config
+ # Default: 900 seconds (15 minutes)
+ my $delay = $timeWindow // $self->conf->{crowdsecBlockDelay} // 900;
+ my $timeLimit = time - $delay;
+
+ # API already filters by IP and scenario, just filter by time
my @ipAlerts =
- grep {
- $_->{source}->{value} eq $ip
- and $_->{scenario} eq $scenario
- and str2time( $_->{start_at} ) > $timeLimit
- } @$alerts;
- return ( scalar @ipAlerts );
+ grep { str2time( $_->{start_at} ) > $timeLimit } @$alerts;
+
+ # In list context, return both count and alerts for enrichment
+ return @ipAlerts;
}
else {
- $self->logger->error('Unable to push Crowdsec decision');
- return;
+ $self->logger->error('Unable to query Crowdsec');
+ return ();
}
}
sub _banPayload {
my ( $self, $ip, $msg, $data ) = @_;
- $msg ||= 'Banned by LLNG Crowdsec plugin';
+ $msg ||= 'Banned by LLNG Crowdsec plugin';
+ $data ||= {};
+
+ # Extract and remove internal data
+ my $prevAlerts = delete $data->{_prevAlerts};
+
foreach my $k ( keys %$defaultBanValues ) {
$data->{$k} //= $defaultBanValues->{$k};
}
@@ -200,29 +297,116 @@ sub _banPayload {
$data->{stop_at} ||= $timestamp;
$data->{source} ||= { scope => 'ip', value => $ip };
my $reason = delete( $data->{reason} ) || 'Banned by LLNG';
+ my $login = delete( $data->{login} );
+ my $uri = delete( $data->{uri} );
+
+ # Include login in message for CAPI transmission
+ # (events[].meta is NOT forwarded by LAPI to CAPI)
+ $msg .= " (login: $login)" if $login;
+
$data->{scenario_hash} = sha256_hex( $data->{scenario} );
- return to_json( [ {
- %$data,
- message => $msg,
- events => [ {
- timestamp => $data->{start_at},
- meta => [
- { key => 'log_type', value => 'llng-auth' },
- { key => 'reason', value => $reason }
- ],
- source => $data->{source},
- }
- ],
- }
- ]
+ my @meta = (
+ { key => 'log_type', value => 'llng-auth' },
+ { key => 'reason', value => $reason }
);
+ push @meta, { key => 'login', value => $login } if $login;
+ push @meta, { key => 'uri', value => $uri } if $uri;
+
+ # Enrich with historical context when ban decision is made
+ if ( $data->{remediation} and $prevAlerts ) {
+ my $context = $self->_extractAlertContext($prevAlerts);
+ if ($context) {
+ my @msg_parts;
+
+ # Add historical metadata
+ if ( @{ $context->{logins} } ) {
+ my $all_logins = join ', ', @{ $context->{logins} };
+ push @meta, { key => 'previous_logins', value => $all_logins };
+
+ # Truncate for message display
+ my $login_summary =
+ @{ $context->{logins} } <= 3
+ ? $all_logins
+ : join( ', ', @{ $context->{logins} }[ 0 .. 2 ] ) . '...';
+ push @msg_parts, "attempted logins: $login_summary";
+ }
+
+ if ( @{ $context->{uris} } ) {
+ my $all_uris = join ', ', @{ $context->{uris} };
+ push @meta, { key => 'previous_uris', value => $all_uris };
+
+ # Truncate for message display
+ my $uri_summary =
+ @{ $context->{uris} } <= 3
+ ? $all_uris
+ : join( ', ', @{ $context->{uris} }[ 0 .. 2 ] ) . '...';
+ push @msg_parts, "scanned URIs: $uri_summary";
+ }
+
+ if ( $context->{count} ) {
+ push @meta,
+ {
+ key => 'previous_alert_count',
+ value => "" . $context->{count}
+ };
+ }
+
+ if ( $context->{first_alert} ) {
+ push @meta,
+ { key => 'first_alert', value => $context->{first_alert} };
+ }
+
+ if ( $context->{last_alert} ) {
+ push @meta,
+ { key => 'last_alert', value => $context->{last_alert} };
+ }
+
+ # Enrich human-readable message
+ if ( $context->{count} ) {
+ $msg .= sprintf "; after %d previous alert(s)",
+ $context->{count};
+ }
+ if (@msg_parts) {
+ $msg .= "; " . join( "; ", @msg_parts );
+ }
+ }
+ }
+
+ my $alert = {
+ %$data,
+ message => $msg,
+ events => [ {
+ timestamp => $data->{start_at},
+ meta => \@meta,
+ source => $data->{source},
+ }
+ ],
+ };
+
+ # Add decisions array when remediation is requested
+ # This ensures the IP is immediately banned by CrowdSec
+ if ( $data->{remediation} ) {
+ my $duration =
+ $data->{banDuration} || $self->conf->{crowdsecBanDuration} || '4h';
+ $alert->{decisions} = [ {
+ duration => $duration,
+ type => 'ban',
+ scope => 'ip',
+ value => $ip,
+ origin => 'llng',
+ scenario => $data->{scenario},
+ }
+ ];
+ }
+
+ return to_json( [$alert] );
}
sub getToken {
my ($self) = @_;
# Use token if available
- return $self->token if $self->token and $self->tokenExp < time - 10;
+ return $self->token if $self->token and $self->tokenExp > time + 10;
# Get new token
my ( $user, $pwd ) =
--- a/usr/share/perl5/Lemonldap/NG/Portal/Lib/CrowdSecFilter.pm
+++ b/usr/share/perl5/Lemonldap/NG/Portal/Lib/CrowdSecFilter.pm
@@ -4,9 +4,14 @@ use strict;
use Mouse::Role;
use Regexp::Assemble;
-use constant knownCat => (qw(url));
+our $VERSION = '2.23.0';
+
+# Known special categories (urlskip is whitelist, url is legacy fallback)
+use constant knownCat => (qw(url urlskip));
use constant knownSuffixes => (qw(re txt));
+# Note: 'scenarios' attribute must be defined in consuming class
+
# Initialization functions for CrowdsecFilter feature
sub initializeFilters {
@@ -19,10 +24,10 @@ sub initializeFilters {
$re->add( map { qr/(?i)$_/ } @{ $filters->{$cat}->{re} } )
if $filters->{$cat}->{re};
$re->add( map { qr/(?i)\Q$_\E/ } @{ $filters->{$cat}->{txt} } )
- if @{ $filters->{$cat}->{txt} };
+ if $filters->{$cat}->{txt};
};
if ($@) {
- $self->logger->error("Unable to parst category $cat: $@");
+ $self->logger->error("Unable to parse category $cat: $@");
}
else {
$self->filters->{$cat} = $re->re;
@@ -51,14 +56,92 @@ sub parseFilters {
if ($cat) {
$self->parseFilters( $path, $res, $cat );
}
- elsif ( my ($t) = grep { $file =~ m/^$_/ } knownCat ) {
- $self->parseFilters( $path, $res, $t );
- }
else {
- $self->logger->error("Unknwon category for directory $path");
+ # Check for .scenario file to determine if this is a named scenario
+ my $scenarioFile = "$path/.scenario";
+ if ( -f $scenarioFile ) {
+
+ # This is a named scenario directory
+ my $scenarioName = $self->_readScenarioFile($scenarioFile);
+ if ($scenarioName) {
+ $self->scenarios->{$file} = $scenarioName;
+ $self->logger->debug(
+ "Found scenario '$scenarioName' in directory $file"
+ );
+
+ # Check for optional .maxfailures file
+ my $maxFailuresFile = "$path/.maxfailures";
+ if ( -f $maxFailuresFile ) {
+ my $maxFailures =
+ $self->_readMaxFailuresFile($maxFailuresFile);
+ if ( defined $maxFailures ) {
+ $self->scenarioMaxFailures->{$file} =
+ $maxFailures;
+ $self->logger->debug(
+"Found maxfailures '$maxFailures' for scenario in directory $file"
+ );
+ }
+ }
+
+ # Check for optional .banduration file
+ my $banDurationFile = "$path/.banduration";
+ if ( -f $banDurationFile ) {
+ my $banDuration =
+ $self->_readBanDurationFile($banDurationFile);
+ if ( defined $banDuration ) {
+ $self->scenarioBanDuration->{$file} =
+ $banDuration;
+ $self->logger->debug(
+"Found banduration '$banDuration' for scenario in directory $file"
+ );
+ }
+ }
+
+ # Check for optional .timewindow file
+ my $timeWindowFile = "$path/.timewindow";
+ if ( -f $timeWindowFile ) {
+ my $timeWindow =
+ $self->_readTimeWindowFile($timeWindowFile);
+ if ( defined $timeWindow ) {
+ $self->scenarioTimeWindow->{$file} =
+ $timeWindow;
+ $self->logger->debug(
+"Found timewindow '$timeWindow' for scenario in directory $file"
+ );
+ }
+ }
+
+ $self->parseFilters( $path, $res, $file );
+ }
+ else {
+ $self->logger->error(
+ "Empty or invalid .scenario file in $path");
+ }
+ }
+ elsif (
+ my ($t) =
+ grep { $file =~ m/^${_}(?:[_\s-]|$)/ } knownCat
+ )
+ {
+ # Legacy known category (url, urlskip)
+ $self->parseFilters( $path, $res, $t );
+
+ }
+ else {
+ $self->logger->error(
+ "Unknown category for directory $path");
+ }
}
next LOOP;
}
+
+# Skip .scenario, .maxfailures, .banduration, .timewindow files (already processed at directory level)
+ next LOOP
+ if $file eq '.scenario'
+ or $file eq '.maxfailures'
+ or $file eq '.banduration'
+ or $file eq '.timewindow';
+
$file =~ s/\.([^\.]+)$//;
my $type = $1;
unless ( $type and grep { $_ eq $type } knownSuffixes ) {
@@ -73,6 +156,8 @@ sub parseFilters {
$self->logger->error("Malformed file $path (missing category)");
next LOOP;
}
+
+ # For files in root directory, must be known category
unless ( grep { $_ eq $lcat } knownCat ) {
$self->logger->error("Unknown category $lcat for $path");
next LOOP;
@@ -90,12 +175,108 @@ sub parseFilters {
next if /^\s*#/;
next unless /\w/;
s/[\r\n]//g;
+ s/^\s+//;
+ # For regex files, preserve trailing escaped spaces (e.g. '\ ')
+ if ( $type eq 're' ) {
+ s/(?<!\\)\s+$//;
+ }
+ else {
+ s/\s+$//;
+ }
push @{ $res->{$lcat}->{$type} }, $_;
$c++;
}
+ close $fh;
$self->logger->debug(" -> $c lines added");
}
return $res;
}
+# Generic config file reader
+# Args: $file, $fieldName, $validationRegex (optional, undef = any non-empty value)
+sub _readConfigFile {
+ my ( $self, $file, $fieldName, $validationRegex ) = @_;
+ my $fh;
+ unless ( open $fh, '<', $file ) {
+ $self->logger->error("Unable to read $fieldName file $file: $!");
+ return undef;
+ }
+ my $value;
+ while (<$fh>) {
+ chomp;
+ s/[^\x21-\x7E]//g; # Remove non-printable characters and spaces
+ s/^\s+//;
+ s/\s+$//;
+ next if /^#/;
+ next unless /\S/;
+
+ if ( !$validationRegex or /$validationRegex/ ) {
+ $value = $_;
+ last;
+ }
+ else {
+ $self->logger->error("Invalid $fieldName value in $file: $_");
+ }
+ }
+ close $fh;
+ return $value;
+}
+
+sub _readScenarioFile {
+ my ( $self, $file ) = @_;
+ return $self->_readConfigFile( $file, 'scenario', undef );
+}
+
+sub _readMaxFailuresFile {
+ my ( $self, $file ) = @_;
+ return $self->_readConfigFile( $file, 'maxfailures', qr/^\d+$/ );
+}
+
+sub _readBanDurationFile {
+ my ( $self, $file ) = @_;
+
+ # Accept CrowdSec duration format: 4h, 1d, 30m, 1h30m, etc.
+ return $self->_readConfigFile( $file, 'banduration', qr/^[\dsmhd]+$/i );
+}
+
+sub _readTimeWindowFile {
+ my ( $self, $file ) = @_;
+
+ # Accept integer (seconds) for time window
+ return $self->_readConfigFile( $file, 'timewindow', qr/^\d+$/ );
+}
+
+# Find which scenario matches the given URI
+# Returns: (scenario_name, category, maxFailures, banDuration, timeWindow)
+# or (undef, undef, undef, undef, undef) if no match
+# maxFailures, banDuration and timeWindow are undef if not specified for the scenario
+sub matchScenario {
+ my ( $self, $uri ) = @_;
+
+ # First check if URI is whitelisted
+ if ( $self->filters->{urlskip} and $uri =~ $self->filters->{urlskip} ) {
+ return ( undef, 'urlskip', undef, undef, undef );
+ }
+
+ # Check named scenarios first (they have priority over generic 'url')
+ foreach my $cat ( keys %{ $self->scenarios } ) {
+ if ( $self->filters->{$cat} and $uri =~ $self->filters->{$cat} ) {
+ return (
+ $self->scenarios->{$cat},
+ $cat,
+ $self->scenarioMaxFailures->{$cat},
+ $self->scenarioBanDuration->{$cat},
+ $self->scenarioTimeWindow->{$cat}
+ );
+ }
+ }
+
+ # Finally check generic 'url' category (legacy behavior)
+ if ( $self->filters->{url} and $uri =~ $self->filters->{url} ) {
+ return ( 'llng/urlscan', 'url', undef, undef, undef );
+ }
+
+ return ( undef, undef, undef, undef, undef );
+}
+
1;
--- a/usr/share/perl5/Lemonldap/NG/Portal/Plugins/CrowdSec.pm
+++ b/usr/share/perl5/Lemonldap/NG/Portal/Plugins/CrowdSec.pm
@@ -13,7 +13,7 @@ extends 'Lemonldap::NG::Portal::Main::Plugin';
with 'Lemonldap::NG::Portal::Lib::CrowdSec';
# Entrypoint
-use constant beforeAuth => 'checkIpStatus';
+use constant aroundSub => { controlUrl => 'checkCrowdsec' };
has rule => ( is => 'rw', default => sub { 0 } );
@@ -32,17 +32,18 @@ sub init {
return 1;
}
-sub checkIpStatus {
- my ( $self, $req ) = @_;
+sub checkCrowdsec {
+ my ( $self, $sub, $req ) = @_;
if ( !$self->rule->( $req, $req->sessionInfo ) ) {
$self->logger->debug('Crowdsec disabled for this env');
- return PE_OK;
+ return $sub->($req);
}
my $ip = $req->address;
my ( $ok, $err ) = $self->bouncer($ip);
# bouncer() answer $ok=0 only when Crowdsec response rejects the given IP
- return PE_OK if ( $ok and $err and $self->conf->{crowdsecIgnoreFailures} );
+ return $sub->($req)
+ if ( $ok and $err and $self->conf->{crowdsecIgnoreFailures} );
# When $ok==0, $err contains the Crowdsec decision
unless ($ok) {
@@ -63,10 +64,10 @@ sub checkIpStatus {
ip => $ip,
);
$req->env->{CROWDSEC_REJECT} = 1;
- return PE_OK;
+ return $sub->($req);
}
}
- return $err ? $err : PE_OK;
+ return $err ? $err : $sub->($req);
}
1;
--- a/usr/share/perl5/Lemonldap/NG/Portal/Plugins/CrowdSecAgent.pm
+++ b/usr/share/perl5/Lemonldap/NG/Portal/Plugins/CrowdSecAgent.pm
@@ -13,15 +13,17 @@ use Lemonldap::NG::Portal::Main::Constants qw(
PE_SAML_SIGNATURE_ERROR
PE_SENDRESPONSE
PE_USERNOTFOUND
+ PE_WAIT
);
-our $VERSION = '2.22.0';
+our $VERSION = '2.23.0';
our @ALERTS = (
PE_USERNOTFOUND, PE_BADCREDENTIALS,
PE_BADCERTIFICATE, PE_MALFORMEDUSER,
PE_SAML_SIGNATURE_ERROR, PE_OPENID_BADID,
PE_CAPTCHAERROR, PE_BADOTP,
+ PE_WAIT,
);
extends 'Lemonldap::NG::Portal::Main::Plugin';
@@ -31,6 +33,14 @@ has rule => ( is => 'rw', default => sub { 0 } );
has filters => ( is => 'rw', default => sub { {} } );
+has scenarios => ( is => 'rw', default => sub { {} } );
+
+has scenarioMaxFailures => ( is => 'rw', default => sub { {} } );
+
+has scenarioBanDuration => ( is => 'rw', default => sub { {} } );
+
+has scenarioTimeWindow => ( is => 'rw', default => sub { {} } );
+
# Entrypoint
use constant aroundSub => {
@@ -87,8 +97,9 @@ sub sendIpAlerts {
}
my $msg = 'Authentication failed: '
. &Lemonldap::NG::Portal::Main::Constants::portalConsts->{$ret};
+ my $login = $req->user // '';
$self->alert( $req->address, $msg,
- { scenario => 'llng/badcredentials', reason => $msg, } )
+ { scenario => 'llng/badcredentials', reason => $msg, login => $login } )
? $self->auditLog(
$req,
code => 200,
@@ -110,59 +121,64 @@ sub controlUrl {
return $ret;
}
- return $ret unless $self->filters;
- if ( $self->filters->{url}
- and $req->env->{REQUEST_URI} =~ $self->filters->{url} )
- {
- my $msg = 'Bad URI detected: ' . $req->env->{REQUEST_URI};
- $self->alert( $req->address, $msg,
- { scenario => 'llng/urlscan', reason => $msg, } )
- ? $self->auditLog(
+ return $ret unless %{ $self->filters };
+
+ # Use matchScenario to find matching scenario (with whitelist check)
+ my $uri = $req->env->{REQUEST_URI};
+ my ( $scenario, $cat, $maxFailures, $banDuration, $timeWindow ) =
+ $self->matchScenario($uri);
+
+ # No match or whitelisted
+ return $ret unless $scenario;
+
+ my $msg = "Bad URI detected: $uri";
+ my $data = { scenario => $scenario, reason => $msg, uri => $uri };
+ $data->{maxFailures} = $maxFailures if defined $maxFailures;
+ $data->{banDuration} = $banDuration if defined $banDuration;
+ $data->{timeWindow} = $timeWindow if defined $timeWindow;
+ $self->alert( $req->address, $msg, $data )
+ ? $self->auditLog(
+ $req,
+ code => 200,
+ message => "Alert sent to Crowdsec: $msg",
+ ip => $req->address,
+ uri => $uri,
+ scenario => $scenario,
+ )
+ : $self->logger->error(
+ "Unable to send alert to Crowdsec (was '$msg' for " . $req->address );
+
+ $req->response(
+
+ # Case "redirection", crowdSecAgentResponseValue is the "location" value
+ $self->conf->{crowdSecAgentResponseCode} =~ /^3/
+ ? $self->p->sendRawHtml(
$req,
- code => 200,
- message => "Alert sent to Crowdsec: $msg",
- ip => $req->address,
- uri => $req->env->{REQUEST_URI},
- matchingPart => $&,
+ $self->conf->{crowdSecAgentResponseValue},
+ {
+ code => $self->conf->{crowdSecAgentResponseCode},
+ headers => [
+ Location => (
+ $self->conf->{crowdSecAgentResponseValue}
+ || 'https://somewhere.else'
+ )
+ ],
+ }
)
- : $self->logger->error(
- "Unable to send alert to Crowdsec (was '$msg' for "
- . $req->address );
- $req->response(
+ # Case "custom response
+ : $self->conf->{crowdSecAgentResponseValue} ? $self->p->sendRawHtml(
+ $req,
+ $self->conf->{crowdSecAgentResponseValue},
+ { code => $self->conf->{crowdSecAgentResponseCode} }
+ )
- # Case "redirection", crowdSecAgentResponseValue is the "location" value
- $self->conf->{crowdSecAgentResponseCode} =~ /^3/
- ? $self->p->sendRawHtml(
- $req,
- $self->conf->{crowdSecAgentResponseValue},
- {
- code => $self->conf->{crowdSecAgentResponseCode},
- headers => [
- Location => (
- $self->conf->{crowdSecAgentResponseValue}
- || 'https://somewhere.else'
- )
- ],
- }
- )
-
- # Case "custom response
- : $self->conf->{crowdSecAgentResponseValue}
- ? $self->p->sendRawHtml(
- $req,
- $self->conf->{crowdSecAgentResponseValue},
- { code => $self->conf->{crowdSecAgentResponseCode} }
- )
-
- # Case "default Lemon response
- : $self->sendError(
- $req, '', $self->conf->{crowdSecAgentResponseCode}
- )
- );
- return PE_SENDRESPONSE;
- }
- return $ret;
+ # Case "default Lemon response
+ : $self->sendError(
+ $req, '', $self->conf->{crowdSecAgentResponseCode}
+ )
+ );
+ return PE_SENDRESPONSE;
}
1;