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

filter: Statementstmt 0.0% 0 / 151 Branchbran 0.0% 0 / 64 Conditioncond 0.0% 0 / 29 MC/DCmcdc 0.0% 0 / 17 Subroutinesub 0.0% 0 / 13 Podpod 0.0% 0 / 8 totaltotal 0.0% 0 / 282 CC 33 SCAR 55.5
CC
33
Cov
0%
parseFilters
506.0
initializeFilters
30.0
_readConfigFile
30.0
CRAP 256.2
1 package Lemonldap::NG::Portal::Lib::CrowdSecFilter;
2  
3 use strict;
4 use Mouse::Role;
5 use Regexp::Assemble;
6  
7 our $VERSION = '2.23.0';
8  
9 # Known special categories (urlskip is whitelist, url is legacy fallback)
10 use constant knownCat => (qw(url urlskip));
11 use constant knownSuffixes => (qw(re txt));
12  
13 # Note: 'scenarios' attribute must be defined in consuming class
14  
15 # Initialization functions for CrowdsecFilter feature
16  
17 sub initializeFilters {
18 my ($self) = @_;
19 my $filters = $self->parseFilters( $self->conf->{crowdsecFilters} );
20 if ( $filters and %$filters ) {
21 foreach my $cat ( keys %$filters ) {
22 my $re = Regexp::Assemble->new;
23 eval {
24 $re->add( map { qr/(?i)$_/ } @{ $filters->{$cat}->{re} } )
25 if $filters->{$cat}->{re};
26 $re->add( map { qr/(?i)\Q$_\E/ } @{ $filters->{$cat}->{txt} } )
27 if $filters->{$cat}->{txt};
28 };
29 if ($@) {
30 $self->logger->error("Unable to parse category $cat: $@");
31 }
32 else {
33 $self->filters->{$cat} = $re->re;
34 $self->logger->debug("RE $cat: $re");
35 }
36 }
37 }
38 }
39  
40 sub parseFilters {
41 my ( $self, $dirname, $res, $cat ) = @_;
42 $self->logger->debug("Crowdsec filters, parsing $dirname");
43 $res //= {};
44 my $fh;
45 unless ( opendir $fh, $dirname ) {
46 $self->logger->error("Unable to read directory $dirname: $!");
47 return $res;
48 }
49 my @files = grep /\w/, readdir $fh;
50 closedir $fh;
51 LOOP: foreach my $file (@files) {
52  
53 # Sub-directories fixes the category
54 my $path = "$dirname/$file";
55 if ( -d $path ) {
56 if ($cat) {
57 $self->parseFilters( $path, $res, $cat );
58 }
59 else {
60 # Check for .scenario file to determine if this is a named scenario
61 my $scenarioFile = "$path/.scenario";
62 if ( -f $scenarioFile ) {
63  
64 # This is a named scenario directory
65 my $scenarioName = $self->_readScenarioFile($scenarioFile);
66 if ($scenarioName) {
67 $self->scenarios->{$file} = $scenarioName;
68 $self->logger->debug(
69 "Found scenario '$scenarioName' in directory $file"
70 );
71  
72 # Check for optional .maxfailures file
73 my $maxFailuresFile = "$path/.maxfailures";
74 if ( -f $maxFailuresFile ) {
75 my $maxFailures =
76 $self->_readMaxFailuresFile($maxFailuresFile);
77 if ( defined $maxFailures ) {
78 $self->scenarioMaxFailures->{$file} =
79 $maxFailures;
80 $self->logger->debug(
81 "Found maxfailures '$maxFailures' for scenario in directory $file"
82 );
83 }
84 }
85  
86 # Check for optional .banduration file
87 my $banDurationFile = "$path/.banduration";
88 if ( -f $banDurationFile ) {
89 my $banDuration =
90 $self->_readBanDurationFile($banDurationFile);
91 if ( defined $banDuration ) {
92 $self->scenarioBanDuration->{$file} =
93 $banDuration;
94 $self->logger->debug(
95 "Found banduration '$banDuration' for scenario in directory $file"
96 );
97 }
98 }
99  
100 # Check for optional .timewindow file
101 my $timeWindowFile = "$path/.timewindow";
102 if ( -f $timeWindowFile ) {
103 my $timeWindow =
104 $self->_readTimeWindowFile($timeWindowFile);
105 if ( defined $timeWindow ) {
106 $self->scenarioTimeWindow->{$file} =
107 $timeWindow;
108 $self->logger->debug(
109 "Found timewindow '$timeWindow' for scenario in directory $file"
110 );
111 }
112 }
113  
114 $self->parseFilters( $path, $res, $file );
115 }
116 else {
117 $self->logger->error(
118 "Empty or invalid .scenario file in $path");
119 }
120 }
121 elsif (
122 my ($t) =
123 grep { $file =~ m/^${_}(?:[_\s-]|$)/ } knownCat
124 )
125 {
126 # Legacy known category (url, urlskip)
127 $self->parseFilters( $path, $res, $t );
128  
129 }
130 else {
131 $self->logger->error(
132 "Unknown category for directory $path");
133 }
134 }
135 next LOOP;
136 }
137  
138 # Skip .scenario, .maxfailures, .banduration, .timewindow files (already processed at directory level)
139 next LOOP
140 if $file eq '.scenario'
141 or $file eq '.maxfailures'
142 or $file eq '.banduration'
143 or $file eq '.timewindow';
144  
145 $file =~ s/\.([^\.]+)$//;
146 my $type = $1;
147 unless ( $type and grep { $_ eq $type } knownSuffixes ) {
148 $self->logger->error("Bad suffix for $path, skipping");
149 next LOOP;
150 }
151 my $lcat = $cat;
152 unless ($lcat) {
153 $file =~ s/\.([^\.]+)$//;
154 $lcat = $1;
155 unless ($lcat) {
156 $self->logger->error("Malformed file $path (missing category)");
157 next LOOP;
158 }
159  
160 # For files in root directory, must be known category
161 unless ( grep { $_ eq $lcat } knownCat ) {
162 $self->logger->error("Unknown category $lcat for $path");
163 next LOOP;
164 }
165 }
166 unless ( open $fh, '<', $path ) {
167 $self->logger->error("Unable to read file $path: $!");
168 next LOOP;
169 }
170 $self->logger->debug(
171 "Crowdsec filters, adding content of $path into category $lcat, type $type"
172 );
173 my $c = 0;
174 foreach (<$fh>) {
175 next if /^\s*#/;
176 next unless /\w/;
177 s/[\r\n]//g;
178 s/^\s+//;
179 # For regex files, preserve trailing escaped spaces (e.g. '\ ')
180 if ( $type eq 're' ) {
181 s/(?<!\\)\s+$//;
182 }
183 else {
184 s/\s+$//;
185 }
186 push @{ $res->{$lcat}->{$type} }, $_;
187 $c++;
188 }
189 close $fh;
190 $self->logger->debug(" -> $c lines added");
191 }
192 return $res;
193 }
194  
195 # Generic config file reader
196 # Args: $file, $fieldName, $validationRegex (optional, undef = any non-empty value)
197 sub _readConfigFile {
198 my ( $self, $file, $fieldName, $validationRegex ) = @_;
199 my $fh;
200 unless ( open $fh, '<', $file ) {
201 $self->logger->error("Unable to read $fieldName file $file: $!");
202 return undef;
203 }
204 my $value;
205 while (<$fh>) {
206 chomp;
207 s/[^\x21-\x7E]//g; # Remove non-printable characters and spaces
208 s/^\s+//;
209 s/\s+$//;
210 next if /^#/;
211 next unless /\S/;
212  
213 if ( !$validationRegex or /$validationRegex/ ) {
214 $value = $_;
215 last;
216 }
217 else {
218 $self->logger->error("Invalid $fieldName value in $file: $_");
219 }
220 }
221 close $fh;
222 return $value;
223 }
224  
225 sub _readScenarioFile {
226 my ( $self, $file ) = @_;
227 return $self->_readConfigFile( $file, 'scenario', undef );
228 }
229  
230 sub _readMaxFailuresFile {
231 my ( $self, $file ) = @_;
232 return $self->_readConfigFile( $file, 'maxfailures', qr/^\d+$/ );
233 }
234  
235 sub _readBanDurationFile {
236 my ( $self, $file ) = @_;
237  
238 # Accept CrowdSec duration format: 4h, 1d, 30m, 1h30m, etc.
239 return $self->_readConfigFile( $file, 'banduration', qr/^[\dsmhd]+$/i );
240 }
241  
242 sub _readTimeWindowFile {
243 my ( $self, $file ) = @_;
244  
245 # Accept integer (seconds) for time window
246 return $self->_readConfigFile( $file, 'timewindow', qr/^\d+$/ );
247 }
248  
249 # Find which scenario matches the given URI
250 # Returns: (scenario_name, category, maxFailures, banDuration, timeWindow)
251 # or (undef, undef, undef, undef, undef) if no match
252 # maxFailures, banDuration and timeWindow are undef if not specified for the scenario
253 sub matchScenario {
254 my ( $self, $uri ) = @_;
255  
256 # First check if URI is whitelisted
257 if ( $self->filters->{urlskip} and $uri =~ $self->filters->{urlskip} ) {
258 return ( undef, 'urlskip', undef, undef, undef );
259 }
260  
261 # Check named scenarios first (they have priority over generic 'url')
262 foreach my $cat ( keys %{ $self->scenarios } ) {
263 if ( $self->filters->{$cat} and $uri =~ $self->filters->{$cat} ) {
264 return (
265 $self->scenarios->{$cat},
266 $cat,
267 $self->scenarioMaxFailures->{$cat},
268 $self->scenarioBanDuration->{$cat},
269 $self->scenarioTimeWindow->{$cat}
270 );
271 }
272 }
273  
274 # Finally check generic 'url' category (legacy behavior)
275 if ( $self->filters->{url} and $uri =~ $self->filters->{url} ) {
276 return ( 'llng/urlscan', 'url', undef, undef, undef );
277 }
278  
279 return ( undef, undef, undef, undef, undef );
280 }
281  
282 1;