blib/lib/Lemonldap/NG/Portal/Plugins/Impersonation.pm untested

filter: Statementstmt 0.0% 0 / 170 Branchbran 0.0% 0 / 56 Conditioncond 0.0% 0 / 27 MC/DCmcdc 0.0% 0 / 15 Subroutinesub 0.0% 0 / 9 Podpod 0.0% 0 / 4 totaltotal 0.0% 0 / 281 CC 29 SCAR 48.2
CC
29
Cov
0%
run
240.0
_userData
90.0
init
30.0
CRAP 124.5
1 package Lemonldap::NG::Portal::Plugins::Impersonation;
2  
3 use strict;
4 use Mouse;
5 use Lemonldap::NG::Common::Util qw(isHiddenAttr);
6 use Lemonldap::NG::Portal::Main::Constants qw(
7 PE_MALFORMEDUSER
8 PE_OK PE_BADCREDENTIALS
9 PE_IMPERSONATION_SERVICE_NOT_ALLOWED
10 );
11  
12 our $VERSION = '2.23.0';
13  
14 extends qw(
15 Lemonldap::NG::Portal::Main::Plugin
16 Lemonldap::NG::Portal::Lib::_tokenRule
17 );
18  
19 # INITIALIZATION
20  
21 use constant afterData => 'run';
22  
23 has rule => ( is => 'rw', default => sub { 1 } );
24 has idRule => ( is => 'rw', default => sub { 1 } );
25 has unrestrictedUsersRule => ( is => 'rw', default => sub { 0 } );
26  
27 # Form timeout token generator (used if requireToken is set)
28 has ott => ( is => 'rw' );
29  
30 # Captcha generator
31 has captcha => ( is => 'rw' );
32 has needCaptcha => ( is => 'rw' );
33  
34 # Prefix used for renaming session attributes
35 has prefix => (
36 is => 'ro',
37 lazy => 1,
38 default => sub {
39 my $self = $_[0];
40 return $self->conf->{impersonationPrefix};
41 }
42 );
43  
44 sub init {
45 my ($self) = @_;
46  
47 # Parse Impersonation rules
48 $self->rule(
49 $self->p->buildRule(
50 $self->conf->{impersonationRule}, 'impersonation'
51 )
52 );
53 return 0 unless $self->rule;
54  
55 $self->idRule(
56 $self->p->buildRule(
57 $self->conf->{impersonationIdRule},
58 'impersonationId'
59 )
60 );
61 return 0 unless $self->idRule;
62  
63 $self->unrestrictedUsersRule(
64 $self->p->buildRule(
65 $self->conf->{impersonationUnrestrictedUsersRule},
66 'impersonationUnrestrictedUsers'
67 )
68 );
69 return 0 unless $self->unrestrictedUsersRule;
70  
71 # Initialize Captcha if needed
72 $self->needCaptcha(
73 $self->p->buildRule(
74 $self->{conf}->{captcha_login_enabled},
75 'captchaLogin'
76 )
77 );
78 if ( $self->{conf}->{captcha_login_enabled} ) {
79 $self->captcha( $self->p->loadModule('::Lib::Captcha') ) or return 0;
80 }
81  
82 # Initialize form token if needed (captcha provides also a token)
83 else {
84 $self->ott( $self->p->loadModule('::Lib::OneTimeToken') ) or return 0;
85 $self->ott->timeout( $self->conf->{formTimeout} );
86 }
87  
88 return 1;
89 }
90  
91 # RUNNING METHOD
92  
93 sub run {
94 my ( $self, $req ) = @_;
95  
96 return $req->authResult
97 if $req->authResult >
98 PE_OK; # Skip Impersonation if an error occurs during Auth process
99  
100 my $statut = PE_OK;
101 my $unUser = 0;
102 my $loginHistory =
103 $req->{sessionInfo}->{_loginHistory}; # Store login history
104 $req->{user} ||= $req->{sessionInfo}->{_impUser}; # If 2FA is enabled
105 my $spoofId = $req->param('spoofId') # Impersonation required
106 || $req->{sessionInfo}->{_impSpoofId} # If 2FA is enabled
107 || $req->{user}; # Impersonation not required
108  
109 $self->logger->debug("No impersonation required")
110 if ( $spoofId eq $req->{user} );
111  
112 unless ( $spoofId =~ /$self->{conf}->{userControl}/ ) {
113 $self->userLogger->warn('Malformed spoofed Id');
114 $self->logger->debug("Impersonation tried with spoofed Id: $spoofId");
115 $spoofId = $req->{user};
116 $statut = PE_MALFORMEDUSER;
117 }
118  
119 # Check activation & unrestrictedUsers rules
120 if ( $spoofId ne $req->{user} ) {
121 $self->logger->debug("Spoof Id: $spoofId / Real Id: $req->{user}");
122 unless ( $self->rule->( $req, $req->sessionInfo ) ) {
123 $self->userLogger->warn('Impersonation service not authorized');
124 $spoofId = $req->{user};
125 $statut = PE_IMPERSONATION_SERVICE_NOT_ALLOWED;
126 }
127 $unUser = $self->unrestrictedUsersRule->( $req, $req->sessionInfo );
128 }
129  
130 # Fill spoof session
131 my ( $realSession, $spoofSession ) = ( {}, {} );
132 $self->logger->debug("Rename real attributes...");
133 my @hidden = split /[,\s]+/, $self->conf->{impersonationHiddenAttributes};
134  
135 foreach my $k ( keys %{ $req->{sessionInfo} } ) {
136 if ( $self->{conf}->{impersonationSkipEmptyValues} ) {
137 next unless defined $req->{sessionInfo}->{$k};
138 }
139 my $spk = $self->prefix . $k;
140 unless ( isHiddenAttr( $self->conf, $k, @hidden )
141 || $k =~ /^(?:_imp|token|_type)\w*\b/ )
142 {
143 $realSession->{$spk} = $req->{sessionInfo}->{$k};
144 $self->logger->debug("-> Store $k in realSession key: $spk");
145 }
146 $self->logger->debug("Delete $k");
147 delete $req->{sessionInfo}->{$k};
148 }
149  
150 $spoofSession = $self->_userData( $req, $spoofId, $realSession, $unUser );
151 if ( $req->error ) {
152 $self->setSecurity($req);
153 if ( $req->error == PE_BADCREDENTIALS ) {
154 $statut = PE_BADCREDENTIALS; # Catch error to preserve protected Id
155 }
156 else {
157 return $req->error;
158 }
159 }
160  
161 # Merging SSO Groups and hGroups & dedup
162 $spoofSession->{groups} ||= '';
163 $spoofSession->{hGroups} ||= {};
164 if ( $self->{conf}->{impersonationMergeSSOgroups} ) {
165 $self->userLogger->warn("MERGING SSO groups and hGroups...");
166 my $spg = $self->prefix . 'groups';
167 my $sphg = $self->prefix . 'hGroups';
168 my $separator = $self->{conf}->{multiValuesSeparator};
169  
170 ## GROUPS
171 $realSession->{$spg} ||= '';
172 my @spoofGrps = split /\Q$separator/, $spoofSession->{groups};
173 my @realGrps = split /\Q$separator/, $realSession->{$spg};
174  
175 ## hGROUPS
176 $realSession->{$sphg} ||= {};
177  
178 # Merge specified groups/hGroups only
179 my %intersct = %{ $realSession->{$sphg} };
180 unless ( $self->{conf}->{impersonationMergeSSOgroups} eq 1 ) {
181 %intersct = ();
182 my %SSOgroups = map { $_, 1 } split /\Q$separator/,
183 $self->{conf}->{impersonationMergeSSOgroups};
184  
185 $self->logger->debug("Filtering specified groups/hGroups...");
186 @realGrps = grep { exists $SSOgroups{$_} } @realGrps;
187 %intersct =
188 map {
189 $realSession->{$sphg}->{$_}
190 ? ( $_, $realSession->{$sphg}->{$_} )
191 : ()
192 } keys %SSOgroups;
193 }
194  
195 $self->logger->debug("Processing groups...");
196 @spoofGrps = ( @spoofGrps, @realGrps );
197 my %hash = map { $_, 1 } @spoofGrps;
198 $spoofSession->{groups} = join $separator, sort keys %hash;
199  
200 $self->logger->debug("Processing hGroups...");
201 $spoofSession->{hGroups} =
202 { %{ $spoofSession->{hGroups} }, %intersct };
203 }
204  
205 # Main session
206 $self->p->updateSession( $req, $spoofSession );
207 $req->{sessionInfo}->{_loginHistory} =
208 $loginHistory; # Restore login history
209 $req->steps( [ $self->p->validSession, @{ $self->p->endAuth } ] );
210  
211 # Restore _httpSession for Double Cookies
212 if ( $self->conf->{securedCookie} >= 2 ) {
213 $self->p->updateSession( $req, $spoofSession,
214 $req->{sessionInfo}->{real__httpSession} );
215 $req->{sessionInfo}->{_httpSession} =
216 $req->{sessionInfo}->{real__httpSession};
217 }
218 return $statut;
219 }
220  
221 sub _userData {
222 my ( $self, $req, $spoofId, $realSession, $unUser ) = @_;
223 my $realId = $req->{user};
224 my $raz = 0;
225 $req->{user} = $spoofId;
226  
227 # Compute Macros and Groups with real and spoof sessions
228 $req->sessionInfo($realSession);
229 $req->steps( [
230 'getUser', 'setAuthSessionInfo',
231 'setSessionInfo', $self->p->groupsAndMacros,
232 'setLocalGroups'
233 ]
234 );
235 if ( my $error = $self->p->process($req) ) {
236 if ( $error == PE_BADCREDENTIALS ) {
237 $self->userLogger->warn(
238 'Impersonation requested for an invalid user ('
239 . $req->{user}
240 . ")" );
241 }
242 $self->logger->debug("Process returned error: $error");
243 $req->error($error);
244 $raz = 1;
245 }
246  
247 # Check identities rule if Impersonation required
248 if ( $realId ne $spoofId ) {
249 $self->logger->info("\"$realId\" is an unrestricted user!") if $unUser;
250 unless ( $unUser || $self->idRule->( $req, $req->sessionInfo ) ) {
251 $self->userLogger->warn(
252 'Impersonation requested for an invalid user ('
253 . $req->{user}
254 . ")" );
255 $self->logger->debug('Identity NOT authorized');
256 $raz = 1;
257 }
258 }
259  
260 # Same real and spoof session - Compute Macros and Groups
261 if ($raz) {
262 $req->{sessionInfo} = {};
263 $req->{sessionInfo} = {%$realSession};
264 $req->{user} = $realId;
265 $req->steps( [
266 'getUser', 'setSessionInfo',
267 $self->p->groupsAndMacros, 'setLocalGroups'
268 ]
269 );
270 $self->logger->debug('Reset Impersonation process');
271 $req->error(PE_BADCREDENTIALS);
272 if ( my $error = $self->p->process($req) ) {
273 $self->logger->debug("Process returned error: $error");
274 $req->error($error);
275 }
276 }
277  
278 # Compute groups & macros again with real authenticationLevel
279 $req->sessionInfo->{authenticationLevel} =
280 $realSession->{real_authenticationLevel};
281 delete $req->sessionInfo->{groups};
282 $req->steps(
283 [ 'setSessionInfo', $self->p->groupsAndMacros, 'setLocalGroups' ] );
284 if ( my $error = $self->p->process($req) ) {
285 $self->logger->debug("Impersonation: Process returned error: $error");
286 $req->error($error);
287 }
288  
289 $self->logger->debug("Return \"$req->{user}\" sessionInfo");
290 return $req->{sessionInfo};
291 }
292  
293 sub setSecurity {
294 my ( $self, $req ) = @_;
295 if ( $self->needCaptcha->( $req, {} ) ) {
296 $self->captcha->setCaptcha($req);
297 }
298 elsif ( $self->ottRule->( $req, {} ) ) {
299 $self->ott->setToken($req);
300 }
301 }
302  
303 1;