Debian Codegraph @

lemonldap-ng-manager/lib/Lemonldap/NG/Manager/Sessions.pm

raw
1 package Lemonldap::NG::Manager::Sessions;
2
3 use strict;
4 use utf8;
5 use Mouse;
6
7 use Lemonldap::NG::Common::Session;
8 use Lemonldap::NG::Common::PSGI::Constants;
9 use Lemonldap::NG::Common::Conf::Constants;
10 use Lemonldap::NG::Common::Conf::ReConstants;
11 use Lemonldap::NG::Common::FormEncode;
12 use Lemonldap::NG::Common::IPv6;
13
14 extends qw(
15 Lemonldap::NG::Manager::Plugin
16 Lemonldap::NG::Common::Session::REST
17 Lemonldap::NG::Common::Conf::AccessLib
18 );
19
20 our $VERSION = '2.23.0';
21
22 #############################
23 # I. INITIALIZATION METHODS #
24 #############################
25
26 use constant defaultRoute => 'sessions.html';
27 use constant icon => 'duplicate';
28
29 sub init {
30 my ( $self, $conf ) = @_;
31
32 $self->ua( Lemonldap::NG::Common::UserAgent->new($conf) );
33
34 # HTML template
35 $self->addRoute( 'sessions.html', undef, ['GET'] )
36
37 # READ
38 ->addRoute( sessions => { ':sessionType' => 'sessions' }, ['GET'] )
39
40 # DELETE
41 ->addRoute(
42 sessions => { ':sessionType' => { ':sessionId' => 'delSession' } },
43 ['DELETE']
44 )
45
46 # DELETE ALL SESSIONS FOR A USER
47 ->addRoute(
48 sessions =>
49 { glogout => { ':sessionType' => { ':sessionId' => 'userLogout' } } },
50 ['POST']
51 )
52
53 # DELETE OIDC CONSENT
54 ->addRoute(
55 sessions => {
56 OIDCConsent =>
57 { ':sessionType' => { ':sessionId' => 'delOIDCConsent' } }
58 },
59 ['DELETE']
60 );
61
62 $self->setTypes($conf);
63
64 $self->{ipField} ||= 'ipAddr';
65 $self->{portal} ||= $conf->{portal};
66 $self->{cookieName} ||= $conf->{cookieName};
67 $self->{multiValuesSeparator} ||= '; ';
68 $self->{impersonationPrefix} = $conf->{impersonationPrefix} || 'real_';
69 $self->{hiddenAttributes} //= '_password';
70 $self->{hiddenAttributes} .= ' _session_id'
71 unless $conf->{displaySessionId};
72 $self->{tokenRevokeSecret} = $conf->{adminLogoutServerSecret};
73 return 1;
74 }
75
76 #
77 # User logout
78 #
79
80 sub userLogout {
81 my ( $self, $req ) = @_;
82
83 my $mod = $self->getMod($req)
84 or return $self->sendError( $req, undef, 400 );
85 my $id = $req->params('sessionId')
86 or return $self->sendError( $req, 'sessionId is missing', 400 );
87 my $session = $self->getApacheSession( $mod, $id )
88 or return $self->sendError( $req, "session $id not found" );
89
90 my $uidKey = Lemonldap::NG::Handler::Main->tsv->{whatToTrace};
91 my $uid = $session->data->{$uidKey} || $session->data->{_session_uid};
92
93 my $count = 0;
94 foreach my $storage (qw(oidcStorage sessionStorage)) {
95 my $storageModule =
96 Lemonldap::NG::Handler::Main->tsv->{"${storage}Module"};
97 if ( defined $storageModule ) {
98 next if ( $storageModule eq "Apache::Session::Memcached" );
99 my $opts = Lemonldap::NG::Handler::Main->tsv->{"${storage}Options"};
100 $opts->{backend} = $storageModule;
101 my $sessions =
102 Lemonldap::NG::Common::Apache::Session->searchOn( $opts, $uidKey,
103 $uid );
104 my @keys;
105 if ( $sessions and %$sessions ) {
106 @keys = keys %$sessions;
107 foreach my $sid (@keys) {
108 my $kind = $sessions->{$sid}->{_session_kind};
109 my $deletedByPortal = 0;
110 if (
111 $self->{tokenRevokeSecret}
112 and (
113 $kind eq 'SSO'
114 or ( $kind eq 'OIDCI'
115 and $sessions->{$sid}->{_type} eq
116 'refresh_token' )
117 )
118 )
119 {
120 my $type =
121 $kind eq 'SSO' ? 'SSO' : $sessions->{$sid}->{_type};
122 my $s = build_urlencoded(
123 token_hint => $type,
124 token => $sid,
125 raw => 1,
126 );
127 my $portal = $self->{portal};
128 $portal =~ s#/+$##;
129 my $lreq = HTTP::Request->new(
130 POST => "$portal/admintokenrevoke",
131 [
132 Authorization =>
133 "Bearer $self->{tokenRevokeSecret}",
134 'Content-Length' => length($s),
135 'Content-Type' =>
136 'application/x-www-form-urlencoded',
137 Accept => 'application/json',
138 ],
139 $s
140 );
141 my $resp = $self->ua->request($lreq);
142 if ( $resp->is_success ) {
143 $self->logger->info(
144 "Session $type/$sid deleted by portal");
145 $deletedByPortal = 1;
146 $count++;
147 }
148 else {
149 $self->logger->error(
150 "Error when calling portal to logout: "
151 . $resp->status_line );
152 }
153 }
154
155 # Skip manual removal if already deleted by portal
156 next if $deletedByPortal;
157
158 my $session = Lemonldap::NG::Common::Session->new(
159 storageModule => $storageModule,
160 storageModuleOptions => $opts,
161 cacheModule => Lemonldap::NG::Handler::Main->tsv
162 ->{sessionCacheModule},
163 cacheModuleOptions => Lemonldap::NG::Handler::Main->tsv
164 ->{sessionCacheOptions},
165 id => $sid,
166 );
167 if ( $session->data ) {
168 $session->remove;
169 $count++;
170 }
171 }
172 }
173 }
174 }
175 Lemonldap::NG::Handler::PSGI::Main->localUnlog( $req, $id );
176 return $self->sendJSONresponse( $req, { result => 1, count => $count } );
177 }
178
179 #######################
180 # II. CONSENT METHODS #
181 #######################
182
183 sub delOIDCConsent {
184
185 my ( $self, $req ) = @_;
186
187 my $mod = $self->getMod($req)
188 or return $self->sendError( $req, undef, 400 );
189
190 my $params = $req->parameters();
191 my $epoch = $params->{epoch};
192 my $rp = $params->{rp};
193
194 my $id = $req->params('sessionId')
195 or return $self->sendError( $req, 'sessionId is missing', 400 );
196
197 $req->parameters->set( 'sessionId', $self->_maybeDecryptSessionId($id) );
198
199 if ( $rp =~ /\b[\w-]+\b/ and defined $epoch ) {
200 $self->logger->debug(
201 "Call procedure deleteOIDCConsent with RP=$rp and epoch=$epoch");
202 return $self->deleteOIDCConsent($req);
203 }
204 else {
205 return $self->sendError( $req, undef, 400 );
206 }
207 }
208
209 ########################
210 # III. DISPLAY METHODS #
211 ########################
212
213 sub sessions {
214 my ( $self, $req, $session, $skey ) = @_;
215
216 # Case 1: only one session is required
217 if ($session) {
218 return $self->session( $req, $session, $skey );
219 }
220
221 my $mod = $self->getMod($req)
222 or return $self->sendError( $req, undef, 400 );
223 my $params = $req->parameters();
224 my $type = delete $params->{sessionType};
225 $type = $type eq 'global' ? 'SSO' : ucfirst($type);
226 $type = $type eq 'Offline' ? 'OIDCI' : ucfirst($type);
227
228 my $res;
229
230 # Case 2: list of sessions
231
232 my $whatToTrace = Lemonldap::NG::Handler::Main->tsv->{whatToTrace};
233
234 # 2.1 Get fields to require
235 my @fields = ( '_httpSessionType', $self->{ipField}, $whatToTrace );
236 if ( my $groupBy = $params->{groupBy} ) {
237 $groupBy =~ s/^substr\((\w+)(?:,\d+(?:,\d+)?)?\)$/$1/
238 or $groupBy =~ s/^net(?:4|6|)\(([\w:]+),\d+(?:,\d+)?\)$/$1/;
239 $groupBy =~ s/^_whatToTrace$/$whatToTrace/o
240 or push @fields, $groupBy;
241 }
242 elsif ( my $order = $params->{orderBy} ) {
243 $order =~ s/^net(?:4|6|)\(([\w:]+)\)$/$1/;
244 $order =~ s/^_whatToTrace$/$whatToTrace/o
245 or push @fields, split( /, /, $order );
246 }
247 else {
248 push @fields, '_utime';
249 }
250
251 # 2.2 Restrict query if possible: search for filters (any query arg that is
252 # not a keyword)
253 my $moduleOptions = $mod->{options};
254 $moduleOptions->{backend} = $mod->{module};
255 my %filters = map {
256 my $s = $_;
257 $s =~ s/\b_whatToTrace\b/$whatToTrace/o;
258 /^(?:(?:group|order)By|doubleIp)$/
259 ? ()
260 : ( $s => $params->{$_} );
261 } keys %$params;
262 $filters{_session_kind} = $type;
263 push @fields, keys(%filters);
264 {
265 my %seen;
266 @fields = grep { !$seen{$_}++ } @fields;
267 }
268
269 # For now, only one argument can be passed to
270 # Lemonldap::NG::Common::Apache::Session so just the first filter is
271 # used
272 my ($firstFilter) = sort {
273 $filters{$a} =~ m#^[\w:]+/\d+\*?$# ? 1
274 : $filters{$b} =~ m#^[\w:]+/\d+\*?$# ? -1
275 : $a eq '_session_kind' ? 1
276 : $b eq '_session_kind' ? -1
277 : $a cmp $b
278 } keys %filters;
279
280 # Check if a '*' is required
281 my $function = 'searchOn';
282 $function = 'searchOnExpr'
283 if ( grep { /\*/ and not m#^[\w:]+/\d+\*?$# }
284 ( $filters{$firstFilter} ) );
285 $self->logger->debug(
286 "First filter: $firstFilter = $filters{$firstFilter} ($function)");
287
288 $res =
289 Lemonldap::NG::Common::Apache::Session->$function( $moduleOptions,
290 $firstFilter, $filters{$firstFilter}, @fields );
291
292 return $self->sendJSONresponse(
293 $req,
294 {
295 result => 1,
296 count => 0,
297 total => 0,
298 values => []
299 }
300 ) unless ( $res and %$res );
301
302 delete $filters{$firstFilter}
303 unless ( grep { /\*/ and not m#^[\w:]+/\d+\*?$# }
304 ( $filters{$firstFilter} ) );
305 foreach my $k ( keys %filters ) {
306 $self->logger->debug("Removing unless $k =~ /^$filters{$k}\$/");
307 if ( $filters{$k} =~ m#^([\w:]+)/(\d+)\*?$# ) {
308 my ( $net, $bits ) = ( $1, $2 );
309 foreach my $session ( keys %$res ) {
310 delete $res->{$session}
311 unless ( net6( $res->{$session}->{$k}, $bits ) eq $net );
312 }
313 }
314 else {
315 $filters{$k} =~ s/\./\\./g;
316 $filters{$k} =~ s/\*/\.\*/g;
317 foreach my $session ( keys %$res ) {
318 if ( $res->{$session}->{$k} ) {
319 delete $res->{$session}
320 unless ( $res->{$session}->{$k} =~ /^$filters{$k}$/ );
321 }
322 }
323 }
324 }
325
326 my $total = ( keys %$res );
327
328 # 2.4 Special case doubleIp (users connected from more than 1 IP)
329 if ( defined $params->{doubleIp} ) {
330 my %r;
331
332 # 2.4.1 Store user IP addresses in %r
333 foreach my $id ( keys %$res ) {
334 my $entry = $res->{$id};
335 next if ( $entry->{_httpSessionType} );
336 $r{ $entry->{$whatToTrace} }->{ $entry->{ $self->{ipField} } }++;
337 }
338
339 # 2.4.2 Store sessions owned by users that has more than one IP address in $r
340 my $r;
341 $total = 0;
342 foreach my $k ( keys %$res ) {
343 my @tmp = keys %{ $r{ $res->{$k}->{$whatToTrace} } };
344 if ( @tmp > 1 ) {
345 $total += 1;
346 $res->{$k}->{_sessionId} = $k;
347 push @{ $r->{ $res->{$k}->{$whatToTrace} } }, $res->{$k};
348 }
349 }
350
351 # 2.4.3 Store these session in an array. Array elements are :
352 # {
353 # uid => whatToTraceFieldValue,
354 # sessions => [
355 # { session => <session-id-1>, date => <_utime> },
356 # { session => <session-id-2>, date => <_utime> },
357 # ]
358 # }
359 $res = [];
360 foreach my $uid ( sort keys %$r ) {
361 push @$res, {
362 value => $uid,
363 count => scalar( @{ $r->{$uid} } ),
364 sessions => [
365 map {
366 {
367 session =>
368 $self->_maybeEncryptSessionId( $_->{_sessionId} ),
369 date => $_->{_utime}
370 }
371 } @{ $r->{$uid} }
372 ]
373 };
374 }
375 }
376
377 # 2.4 Order and group by
378 # $res will become an array ref here (except for doubleIp, already done below).
379
380 # If "groupBy" is asked, elements will be like:
381 # { uid => 'foo.bar', count => 3 }
382 elsif ( my $group = $req->params('groupBy') ) {
383 my $r;
384 $group =~ s/\b_whatToTrace\b/$whatToTrace/o;
385
386 # Substrings
387 if ( $group =~ /^substr\((\w+)(?:,(\d+)(?:,(\d+))?)?\)$/ ) {
388 my ( $field, $length, $start ) = ( $1, $2, $3 );
389
390 # "next" is a try with $length+1, if only one account, $length++
391 # This permits UI to jump directly to the uid
392 # -d (300)
393 # -> dwho (300)
394 # ... sessions
395 #
396 $start ||= 0;
397 $length = 1 if ( $length < 1 );
398 while (1) {
399 my $next = {};
400 my $stop;
401 foreach my $k ( keys %$res ) {
402 my $subk = substr $res->{$k}->{$field}, $start, $length + 1;
403 $next->{$subk}++
404 if ( $res->{$k}->{$field} );
405
406 # End of the loop if we reached the length of uid
407 $stop++
408 if $start + $length >= length( $res->{$k}->{$field} );
409 }
410
411 # Loop if only one result
412 my @k = keys %$next;
413 if ( @k == 1 and !$stop ) {
414 $length++;
415 next;
416 }
417
418 # Result calculation
419 foreach my $k ( keys %$res ) {
420 $r->{ substr $res->{$k}->{$field}, $start, $length }++
421 if ( $res->{$k}->{$field} );
422 }
423 $group = $field;
424 last;
425 }
426 }
427
428 # Subnets IPv4
429 elsif ( $group =~ /^net4\((\w+),(\d)\)$/ ) {
430 my $field = $1;
431 my $nb = $2 - 1;
432 foreach my $k ( keys %$res ) {
433 if ( $res->{$k}->{$field} =~ /^((((\d+)\.\d+)\.\d+)\.\d+)$/ ) {
434 my @d = ( $4, $3, $2, $1 );
435 $r->{ $d[$nb] }++;
436 }
437 }
438 $group = $field;
439 }
440
441 # Subnets IPv6
442 elsif ( $group =~ /^net6\(([\w:]+),(\d)\)$/ ) {
443 my $field = $1;
444 my $bits = $2;
445 foreach my $k ( keys %$res ) {
446 $r->{ net6( $res->{$k}->{$field}, $bits ) . "/$bits" }++
447 if ( isIPv6( $res->{$k}->{$field} ) );
448 }
449 }
450
451 # Both IPv4 and IPv6
452 elsif ( $group =~ /^net\(([\w:]+),(\d+),(\d+)\)$/ ) {
453 my $field = $1;
454 my $bits = $2;
455 my $nb = $3 - 1;
456 foreach my $k ( keys %$res ) {
457 if ( isIPv6( $res->{$k}->{$field} ) ) {
458 $r->{ net6( $res->{$k}->{$field}, $bits ) . "/$bits" }++;
459 }
460 elsif ( $res->{$k}->{$field} =~ /^((((\d+)\.\d+)\.\d+)\.\d+)$/ )
461 {
462 my @d = ( $4, $3, $2, $1 );
463 $r->{ $d[$nb] }++;
464 }
465 }
466 }
467
468 # Simple field groupBy query
469 elsif ( $group =~ /^\w+$/ ) {
470 eval {
471 foreach my $k ( keys %$res ) {
472 $r->{ $res->{$k}->{$group} }++;
473 }
474 };
475 return $self->sendError(
476 $req,
477 qq{Use of an uninitialized attribute "$group" to group sessions},
478 400
479 ) if ($@);
480 }
481 else {
482 return $self->sendError( $req, 'Syntax error in groupBy', 400 );
483 }
484
485 # Build result
486 $total = 0;
487 $res = [
488 sort {
489 my @a = ( $a->{value} =~ /^(\d+)(?:\.(\d+))*$/ );
490 my @b = ( $b->{value} =~ /^(\d+)(?:\.(\d+))*$/ );
491 ( @a and @b )
492 ? ( $a[0] <=> $b[0]
493 or $a[1] <=> $b[1]
494 or $a[2] <=> $b[2]
495 or $a[3] <=> $b[3] )
496 : $a->{value} cmp $b->{value}
497 }
498 map { $total += $r->{$_}; { value => $_, count => $r->{$_} } }
499 keys %$r
500 ];
501 }
502
503 # Else if "orderBy" is asked, $res elements will be like:
504 # { uid => 'foo.bar', session => <sessionId> }
505 elsif ( my $f = $req->params('orderBy') ) {
506 my @fields = split /,/, $f;
507 my @r = map {
508 my $tmp = { session => $self->_maybeEncryptSessionId($_) };
509 foreach my $f (@fields) {
510 my $s = $f;
511 $s =~ s/^net(?:4|6|)\(([\w:]+)\)$/$1/;
512 $tmp->{$s} = $res->{$_}->{$s};
513 }
514 $tmp
515 } keys %$res;
516 while ( my $f = pop @fields ) {
517 if ( $f =~ s/^net4\((\w+)\)$/$1/ ) {
518 @r = sort { cmpIPv4( $a->{$f}, $b->{$f} ); } @r;
519 }
520 elsif ( $f =~ s/^net6\(([:\w]+)\)$/$1/ ) {
521 @r = sort { expand6( $a->{$f} ) cmp expand6( $b->{$f} ); } @r;
522 }
523 elsif ( $f =~ s/^net\(([:\w]+)\)$/$1/ ) {
524 @r = sort {
525 my $ip1 = $a->{$f};
526 my $ip2 = $b->{$f};
527 isIPv6($ip1)
528 ? (
529 isIPv6($ip2)
530 ? expand6($ip1) cmp expand6($ip2)
531 : -1
532 )
533 : isIPv6($ip2) ? 1
534 : cmpIPv4( $ip1, $ip2 );
535 } @r;
536 }
537 else {
538 @r = sort { $a->{$f} cmp $b->{$f} } @r;
539 }
540 }
541 $res = [@r];
542 }
543
544 # Else, $res elements will be like:
545 # { session => <sessionId>, date => <timestamp> }
546 else {
547 $res = [
548 sort { $a->{date} <=> $b->{date} }
549 map {
550 {
551 session => $self->_maybeEncryptSessionId($_),
552 date => $res->{$_}->{_utime}
553 }
554 }
555 keys %$res
556 ];
557 }
558
559 return $self->sendJSONresponse(
560 $req,
561 {
562 result => 1,
563 count => scalar(@$res),
564 total => $total,
565 values => $res
566 }
567 );
568 }
569
570 sub session {
571 my ( $self, $req, $session, $skey ) = @_;
572
573 $session = $self->_maybeDecryptSessionId($session);
574 return $self->SUPER::session( $req, $session, $skey );
575 }
576
577 sub _maybeDecryptSessionId {
578 my ( $self, $session ) = @_;
579
580 if ( $self->{hiddenAttributes} =~ /\b_session_id\b/ ) {
581 $session =
582 Lemonldap::NG::Handler::Main->tsv->{cipher}->decryptHex($session);
583 }
584
585 return $session;
586 }
587
588 sub _maybeEncryptSessionId {
589 my ( $self, $session ) = @_;
590
591 if ( $self->{hiddenAttributes} =~ /\b_session_id\b/ ) {
592 $session =
593 Lemonldap::NG::Handler::Main->tsv->{cipher}->encryptHex($session);
594 }
595
596 return $session;
597 }
598
599 sub delSession {
600 my ( $self, $req ) = @_;
601 my $id = $req->params('sessionId')
602 or return $self->sendError( $req, 'sessionId is missing', 400 );
603
604 $req->parameters->set( 'sessionId', $self->_maybeDecryptSessionId($id) );
605
606 return $self->SUPER::delSession($req);
607 }
608
609 sub cmpIPv4 {
610 my @a = split /\./, $_[0];
611 my @b = split /\./, $_[1];
612 my $cmp = 0;
613 F: for ( my $i = 0 ; $i < 4 ; $i++ ) {
614 if ( $a[$i] != $b[$i] ) {
615 $cmp = $a[$i] <=> $b[$i];
616 last F;
617 }
618 }
619 $cmp;
620 }
621
622 1;