blib/lib/Lemonldap/NG/Portal/Auth/SAML.pm

filter: Statementstmt 86.6% 13 / 15 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 5 / 5 Podpod n/a totaltotal 90.0% 18 / 20 CC 1 SCAR 0.6
CC
1
Cov
87%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
« blib/lib/Lemonldap/NG/Portal/Auth/Kerberos.pm ↑ Summary blib/lib/Lemonldap/NG/Portal/Issuer/SAML.pm »
1 package Lemonldap::NG::Portal::Auth::SAML;
2  
3 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use MIME::Base64 qw/encode_base64/;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use Mouse;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use HTML::Entities qw(encode_entities);
Subroutine BEGIN: called CC=1 SCAR=0.0
7 0 ▶use Lemonldap::NG::Portal::Lib::SAML;
Subroutine BEGIN: called CC=1 SCAR=2.6
8 use Lemonldap::NG::Common::FormEncode;
9 use Lemonldap::NG::Portal::Main::Constants qw(
10 PE_OK
11 PE_CONFIRM
12 PE_IDPCHOICE
13 PE_LOGOUT_OK
14 PE_REDIRECT
15 PE_SAML_ART_ERROR
16 PE_SAML_CONDITIONS_ERROR
17 PE_SAML_DESTINATION_ERROR
18 PE_SAML_ERROR
19 PE_SAML_IDPSSOINITIATED_NOTALLOWED
20 PE_SAML_SESSION_ERROR
21 PE_SAML_SIGNATURE_ERROR
22 PE_SLO_ERROR
23 PE_SAML_SSO_ERROR
24 PE_SAML_UNKNOWN_ENTITY
25 PE_SENDRESPONSE
26 );
27  
28 our $VERSION = '2.23.0';
29  
30 extends qw(
31 Lemonldap::NG::Portal::Main::Auth
32 Lemonldap::NG::Portal::Lib::SAML
33 );
34  
35 with 'Lemonldap::NG::Portal::Lib::Key';
36  
37 # INTERFACE
38  
39 has ssoAssConsumerRe => ( is => 'rw' );
40 has sloRe => ( is => 'rw' );
41 has artRe => ( is => 'rw' );
42 has catch => ( is => 'rw' );
43 use constant sessionKind => 'SAML';
44 use constant lsDump => '_lassoSessionDump';
45 use constant liDump => '_lassoIdentityDump';
46 use constant niDump => '_lassoNameIdDump';
47 use constant sIndex => '_lassoSessionIndex';
48 use constant afterData => 'authFinish';
49  
50 sub forAuthUser { 'handleAuthRequests' }
51  
52 # INITIALIZATION
53  
54 sub init {
55 my ($self) = @_;
56  
57 my $saml_acs_art_url = $self->getMetaDataURL(
58 "samlSPSSODescriptorAssertionConsumerServiceHTTPArtifact");
59 my $saml_acs_post_url = $self->getMetaDataURL(
60 "samlSPSSODescriptorAssertionConsumerServiceHTTPPost");
61 my $saml_acs_get_url = $self->getMetaDataURL(
62 "samlSPSSODescriptorAssertionConsumerServiceHTTPRedirect");
63 $self->ssoAssConsumerRe(
64 qr/^($saml_acs_art_url|$saml_acs_post_url|$saml_acs_get_url)(?:\?.*)?$/i
65 );
66 my $saml_slo_soap_url =
67 $self->getMetaDataURL( "samlSPSSODescriptorSingleLogoutServiceSOAP", 1 );
68 my $saml_slo_soap_url_ret =
69 $self->getMetaDataURL( "samlSPSSODescriptorSingleLogoutServiceSOAP", 1 );
70 my $saml_slo_get_url = $self->getMetaDataURL(
71 "samlSPSSODescriptorSingleLogoutServiceHTTPRedirect", 1 );
72 my $saml_slo_get_url_ret = $self->getMetaDataURL(
73 "samlSPSSODescriptorSingleLogoutServiceHTTPRedirect", 2 );
74 my $saml_slo_post_url =
75 $self->getMetaDataURL( "samlSPSSODescriptorSingleLogoutServiceHTTPPost",
76 1 );
77 my $saml_slo_post_url_ret =
78 $self->getMetaDataURL( "samlSPSSODescriptorSingleLogoutServiceHTTPPost",
79 2 );
80 $self->sloRe(
81 qr/^($saml_slo_soap_url|$saml_slo_soap_url_ret|$saml_slo_get_url|$saml_slo_get_url_ret|$saml_slo_post_url|$saml_slo_post_url_ret)(?:\?.*)?$/i
82 );
83  
84 my $saml_ars_url = $self->getMetaDataURL(
85 "samlSPSSODescriptorArtifactResolutionServiceArtifact");
86 $self->artRe(qr/^($saml_ars_url)(?:\?.*)?$/i);
87 $self->catch(
88 qr/^($saml_acs_art_url|$saml_acs_post_url|$saml_acs_get_url$saml_slo_soap_url|$saml_slo_soap_url_ret|$saml_slo_get_url|$saml_slo_get_url_ret|$saml_slo_post_url|$saml_slo_post_url_ret)(?:\?.*)?$/i
89 );
90  
91 # Load SAML service and SAML IdP list
92 return ( $self->SUPER::init and $self->loadIDPs );
93 }
94  
95 # RUNNING METHODS
96  
97 sub extractFormInfo {
98 my ( $self, $req ) = @_;
99  
100 # 1. Get HTTP request information to know
101 # if we are receving SAML request or response
102 my $url = $req->uri;
103 my $request_method = $req->method;
104 my $content_type = $req->content_type;
105  
106 # 1.1 SSO assertion consumer
107 if ( $self->isCallback($req) ) {
108 $self->logger->debug(
109 "URL $url detected as an SSO assertion consumer URL");
110  
111 # Check SAML Message
112 my ( $request, $response, $method, $relaystate, $artifact ) =
113 $self->checkMessage( $req, $url, $request_method, $content_type,
114 "login" );
115  
116 # Create Login object
117 my $login = $self->createLogin( $self->lassoServer );
118  
119 # Ignore signature verification
120 $self->disableSignatureVerification($login);
121  
122 if ($response) {
123  
124 # Process authentication response
125 my $result;
126 if ($artifact) {
127 $result = $self->processArtResponseMsg( $login, $response );
128 }
129 else {
130 $result = $self->processAuthnResponseMsg( $login, $response );
131 }
132  
133 unless ($result) {
134 $self->logger->error(
135 "SAML SSO: Fail to process authentication response");
136 return PE_SAML_SSO_ERROR;
137 }
138  
139 $self->logger->debug("SSO: authentication response is valid");
140  
141 # Get IDP entityID
142 my $idp = $login->remote_providerID();
143  
144 $self->logger->debug("Found entityID $idp in SAML message");
145  
146 # IDP conf key
147 my $idpConfKey = $self->getIDPConfKey($idp);
148  
149 unless ($idpConfKey) {
150 $self->userLogger->error(
151 "$idp do not match any IDP in configuration");
152 return PE_SAML_UNKNOWN_ENTITY;
153 }
154  
155 $self->logger->debug("$idp match $idpConfKey IDP in configuration");
156  
157 # Do we check signature?
158 my $checkSSOMessageSignature =
159 $self->idpOptions->{$idp}
160 ->{samlIDPMetaDataOptionsCheckSSOMessageSignature};
161  
162 if ($checkSSOMessageSignature) {
163  
164 $self->forceSignatureVerification($login);
165  
166 if ($artifact) {
167 $result = $self->processArtResponseMsg( $login, $response );
168 }
169 else {
170 $result =
171 $self->processAuthnResponseMsg( $login, $response );
172 }
173  
174 unless ($result) {
175 $self->userLogger->error("Signature is not valid");
176 return PE_SAML_SIGNATURE_ERROR;
177 }
178 else {
179 $self->logger->debug("Signature is valid");
180 }
181 }
182 else {
183 $self->logger->debug("Message signature will not be checked");
184 }
185  
186 # Get SAML response
187 my $saml_response = $login->response();
188 unless ($saml_response) {
189 $self->userLogger->error("No SAML response found");
190 return PE_SAML_SSO_ERROR;
191 }
192  
193 # Call samlGotAuthnResponse
194 my $h =
195 $self->p->processHook( $req, 'samlGotAuthnResponse', $idp,
196 $login );
197 return PE_SAML_SSO_ERROR if ( $h != PE_OK );
198  
199 # Check Destination
200 return PE_SAML_DESTINATION_ERROR
201 unless ( $self->checkDestination( $saml_response, $url ) );
202  
203 # Replay protection if this is a response to a created authn request
204 my $assertion_responded = $saml_response->InResponseTo;
205 if ($assertion_responded) {
206 unless ( $self->replayProtection($assertion_responded) ) {
207  
208 # Assertion was already consumed or is expired
209 # Force authentication replay
210 $self->userLogger->error(
211 "Message $assertion_responded already used or expired, replay authentication"
212 );
213 delete $req->{urldc};
214 $req->mustRedirect(1);
215 $req->steps( [] );
216 $req->continue(1);
217 return PE_OK;
218 }
219 }
220 else {
221 $self->logger->debug(
222 "Assertion is not a response to a created authentication request, do not control replay"
223 );
224 }
225  
226 # Get SAML assertion
227 my $assertion = $self->getAssertion($login);
228  
229 unless ($assertion) {
230 $self->userLogger->error("No assertion found");
231 return PE_SAML_SSO_ERROR;
232 }
233  
234 # Do we check conditions?
235 my $checkTime =
236 $self->idpOptions->{$idp}->{samlIDPMetaDataOptionsCheckTime};
237 my $checkAudience =
238 $self->idpOptions->{$idp}->{samlIDPMetaDataOptionsCheckAudience};
239  
240 # Check conditions - time and audience
241 unless (
242 $self->validateConditions(
243 $assertion, $self->getMetaDataURL( "samlEntityID", 0, 1 ),
244 $checkTime, $checkAudience
245 )
246 )
247 {
248 $self->userLogger->error("Conditions not validated");
249 return PE_SAML_CONDITIONS_ERROR;
250 }
251  
252 my $relayStateURL =
253 $self->idpOptions->{$idp}->{samlIDPMetaDataOptionsRelayStateURL};
254  
255 # Extract RelayState information
256 if ( $self->extractRelayState( $req, $relaystate, $relayStateURL ) )
257 {
258 $self->logger->debug("RelayState $relaystate extracted");
259 }
260  
261 # Check if we accept direct login from IDP
262 my $allowLoginFromIDP =
263 $self->idpOptions->{$idp}
264 ->{samlIDPMetaDataOptionsAllowLoginFromIDP};
265 if ( !$assertion_responded and !$allowLoginFromIDP ) {
266 $self->userLogger->error(
267 "Direct login from IDP $idpConfKey is not allowed");
268 return PE_SAML_IDPSSOINITIATED_NOTALLOWED;
269 }
270  
271 # Check authentication context
272 my $responseAuthnContext;
273 eval {
274 $responseAuthnContext =
275 $assertion->AuthnStatement()
276 ->AuthnContext()
277 ->AuthnContextClassRef();
278 };
279 if ($@) {
280 $self->logger->debug(
281 "Unable to get authentication context from $idpConfKey");
282 $responseAuthnContext = $self->getAuthnContext("unspecified");
283 }
284 else {
285 $self->logger->debug(
286 "Found authentication context: $responseAuthnContext");
287 }
288  
289 # Map authentication context to authentication level
290 $req->sessionInfo->{authenticationLevel} =
291 $self->authnContext2authnLevel($responseAuthnContext);
292  
293 # Force redirection to portal if no urldc found
294 # (avoid displaying the whole SAML URL in user browser URL field)
295 $req->mustRedirect(1) unless ( $req->urldc );
296  
297 # Get SessionIndex
298 my $session_index;
299  
300 eval {
301 $session_index = $assertion->AuthnStatement()->SessionIndex();
302 };
303 if ( $@ or !defined($session_index) ) {
304 $self->logger->debug("No SessionIndex found");
305 }
306 else {
307 $self->logger->debug("Found SessionIndex $session_index");
308 }
309  
310 # Get NameID
311 my $nameid = $login->nameIdentifier;
312 unless ($nameid) {
313 $self->userLogger->error("No NameID element found");
314 return PE_SAML_SSO_ERROR;
315 }
316  
317 my $nameid_content = $nameid->content;
318 unless ($nameid_content) {
319 $self->userLogger->error("No NameID value found");
320 return PE_SAML_SSO_ERROR;
321 }
322  
323 $self->logger->debug("Found NameID content $nameid_content");
324  
325 # Set user
326 my $user = $nameid_content;
327 my $userAttribute =
328 $self->idpOptions->{$idp}->{samlIDPMetaDataOptionsUserAttribute};
329  
330 if ($userAttribute) {
331 $self->logger->debug(
332 "Try to set user value from SAML attribute $userAttribute");
333  
334 my $force_utf8 =
335 $self->idpOptions->{$idp}->{samlIDPMetaDataOptionsForceUTF8};
336  
337 my $attr_statement = $assertion->AttributeStatement();
338 if ($attr_statement) {
339  
340 # Get attributes
341 my @attributes = $attr_statement->Attribute();
342 #
343 # Try to get value
344 my $value =
345 $self->getAttributeValue( $userAttribute, undef, undef,
346 \@attributes, $force_utf8 );
347  
348 # Store value as user
349 if ( defined $value ) {
350 $user = $value;
351 $self->logger->debug(
352 "Found value $value for attribute $userAttribute");
353 }
354 else {
355 $self->logger->warn(
356 "No value for $userAttribute found in SAML assertion"
357 );
358 }
359 }
360 else {
361 $self->logger->warn(
362 "No attributes found in SAML assertion");
363 }
364 }
365  
366 $req->user($user);
367 $self->logger->debug("Set user value to $user");
368  
369 # Store Lasso objects
370 $req->data->{_lassoLogin} = $login;
371 $req->data->{_idp} = $idp;
372 $req->data->{_idpConfKey} = $idpConfKey;
373 $req->data->{_nameID} = $nameid;
374 $req->data->{_sessionIndex} = $session_index;
375  
376 # Store Token
377 my $saml_token = $assertion->export_to_xml;
378  
379 $self->logger->debug("SAML Token: $saml_token");
380  
381 $req->data->{_samlToken} = $saml_token;
382  
383 # Restore initial SAML request in case of proxying
384 if ($assertion_responded) {
385  
386 my $saml_sessions =
387 Lemonldap::NG::Common::Apache::Session->searchOn(
388 $self->amOpts, "ProxyID", $assertion_responded );
389  
390 if (
391 my @saml_sessions_keys = grep {
392 $saml_sessions->{$_}->{_session_kind} eq
393 $self->sessionKind
394 } keys %$saml_sessions
395 )
396 {
397  
398 # Warning if more than one session found
399 if ( $#saml_sessions_keys > 0 ) {
400 $self->logger->warn(
401 "More than one SAML proxy session found for ID $assertion_responded"
402 );
403 }
404  
405 # Take the first session
406 my $saml_session = shift @saml_sessions_keys;
407  
408 # Get session
409 $self->logger->debug(
410 "Retrieve SAML proxy session $saml_session for ID $assertion_responded"
411 );
412  
413 my $samlSessionInfo = $self->getSamlSession($saml_session);
414  
415 $req->data->{_proxiedRequest} =
416 $samlSessionInfo->data->{Request};
417 $req->data->{_proxiedMethod} =
418 $samlSessionInfo->data->{Method};
419 $req->data->{_proxiedRelayState} =
420 $samlSessionInfo->data->{RelayState};
421 $req->data->{_proxiedArtifact} =
422 $samlSessionInfo->data->{Artifact};
423  
424 # Save values in hidden fields in case of other user interactions
425 $self->p->setHiddenFormValue( $req, 'SAMLRequest',
426 $self->{_proxiedRequest} );
427 $self->p->setHiddenFormValue( $req, 'Method',
428 $self->{_proxiedMethod} );
429 $self->p->setHiddenFormValue( $req, 'RelayState',
430 $self->{_proxiedRelayState} );
431 $self->p->setHiddenFormValue( $req, 'SAMLart',
432 $self->{_proxiedArtifact} );
433  
434 # Delete session
435 $samlSessionInfo->remove();
436 }
437 }
438  
439 return PE_OK;
440 }
441 elsif ($request) {
442  
443 # Do nothing
444 $self->logger->debug(
445 "This module do not manage SSO request, see IssuerDBSAML");
446  
447 return PE_OK;
448 }
449 else {
450  
451 # This should not happen
452 $self->userLogger->error("SSO request or response was not found");
453  
454 return PE_SAML_ERROR;
455 }
456  
457 }
458  
459 # 1.2 SLO
460 elsif ( $url =~ $self->sloRe ) {
461 $self->logger->debug("URL $url detected as an SLO URL");
462  
463 # TODO: call authLogout instead of duplicating SLO
464 $req->steps( [ @{ $self->p->beforeLogout }, 'deleteSession' ] );
465  
466 # Don't fail on "beforeLogout" errors
467 $req->data->{nofail} = 1;
468  
469 # Check SAML Message
470 my ( $request, $response, $method, $relaystate, $artifact ) =
471 $self->checkMessage( $req, $url, $request_method, $content_type,
472 "logout" );
473  
474 # Create Logout object
475 my $logout = $self->createLogout( $self->lassoServer );
476  
477 # Ignore signature verification
478 $self->disableSignatureVerification($logout);
479  
480 if ($response) {
481  
482 # Process logout response
483 my $result = $self->processLogoutResponseMsg( $logout, $response );
484  
485 unless ($result) {
486 $self->userLogger->error("Fail to process logout response");
487 return PE_SLO_ERROR;
488 }
489  
490 $self->logger->debug("Logout response is valid");
491  
492 # Check Destination
493 return PE_SAML_DESTINATION_ERROR
494 unless ( $self->checkDestination( $logout->response, $url ) );
495  
496 # Get IDP entityID
497 my $idp = $logout->remote_providerID();
498  
499 $self->logger->debug("Found entityID $idp in SAML message");
500  
501 # IDP conf key
502 my $idpConfKey = $self->getIDPConfKey($idp);
503  
504 unless ($idpConfKey) {
505 $self->userLogger->error(
506 "$idp do not match any IDP in configuration");
507 return PE_SAML_UNKNOWN_ENTITY;
508 }
509  
510 $self->logger->debug("$idp match $idpConfKey IDP in configuration");
511  
512 # Do we check signature?
513 my $checkSLOMessageSignature =
514 $self->idpOptions->{$idp}
515 ->{samlIDPMetaDataOptionsCheckSLOMessageSignature};
516  
517 if ($checkSLOMessageSignature) {
518  
519 $self->forceSignatureVerification($logout);
520  
521 $result = $self->processLogoutResponseMsg( $logout, $response );
522  
523 unless ($result) {
524 $self->userLogger->error("Signature is not valid");
525 return PE_SAML_SIGNATURE_ERROR;
526 }
527 else {
528 $self->logger->debug("Signature is valid");
529 }
530 }
531 else {
532 $self->logger->debug("Message signature will not be checked");
533 }
534  
535 # Replay protection
536 my $samlID = $logout->response()->InResponseTo;
537  
538 unless ( $self->replayProtection($samlID) ) {
539  
540 # Logout request was already consumed or is expired
541 $self->userLogger->error(
542 "Message $samlID already used or expired");
543 return PE_SLO_ERROR;
544 }
545  
546 # If URL in RelayState, different from portal, redirect user
547 if ( $self->extractRelayState( $req, $relaystate ) ) {
548 $self->logger->debug("RelayState $relaystate extracted");
549 $self->logger->debug(
550 "URL " . $req->urldc . " found in RelayState" );
551 }
552  
553 if ( $req->urldc
554 and $req->portal !~ /$req->{urldc}\/?/ )
555 {
556 $req->steps( [] );
557 $req->user('TODO');
558 return PE_OK;
559 }
560  
561 # Else, inform user that logout is OK
562 $req->user('TODO');
563 return PE_OK;
564 }
565  
566 elsif ($request) {
567  
568 # Logout error
569 my $logout_error = 0;
570  
571 # Lasso::Session dump
572 my $session_dump;
573  
574 # Process logout request
575 unless ( $self->processLogoutRequestMsg( $logout, $request ) ) {
576 $self->userLogger->error("Fail to process logout request");
577 return PE_SLO_ERROR;
578 }
579  
580 $self->logger->debug("Logout request is valid");
581  
582 # Check Destination
583 return PE_SAML_DESTINATION_ERROR
584 unless ( $self->checkDestination( $logout->request, $url ) );
585  
586 # Get IDP entityID
587 my $idp = $logout->remote_providerID();
588  
589 $self->logger->debug("Found entityID $idp in SAML message");
590  
591 # IDP conf key
592 my $idpConfKey = $self->getIDPConfKey($idp);
593  
594 unless ($idpConfKey) {
595 $self->userLogger->error(
596 "$idp do not match any IDP in configuration");
597 return PE_SAML_UNKNOWN_ENTITY;
598 }
599  
600 $self->logger->debug("$idp match $idpConfKey IDP in configuration");
601  
602 # Do we check signature?
603 my $checkSLOMessageSignature =
604 $self->idpOptions->{$idp}
605 ->{samlIDPMetaDataOptionsCheckSLOMessageSignature};
606  
607 if ($checkSLOMessageSignature) {
608 unless ( $self->checkSignatureStatus($logout) ) {
609 $self->userLogger->error("Signature is not valid");
610 return PE_SAML_SIGNATURE_ERROR;
611 }
612 else {
613 $self->logger->debug("Signature is valid");
614 }
615 }
616 else {
617 $self->logger->debug("Message signature will not be checked");
618 }
619  
620 # Get NameID and SessionIndex
621 my $name_id = $logout->request()->NameID;
622 my $session_index = $logout->request()->SessionIndex;
623 my $user = $name_id->content;
624  
625 unless ($name_id) {
626 $self->userLogger->error(
627 "Fail to get NameID from logout request");
628 $logout_error = 1;
629 }
630  
631 $self->logger->debug("Logout request NameID content: $user");
632  
633 # Get SAML sessions with the same NameID
634  
635 my $local_sessions =
636 Lemonldap::NG::Common::Apache::Session->searchOn( $self->amOpts,
637 "_nameID", $name_id->dump );
638  
639 if (
640 my @local_sessions_keys = grep {
641 $local_sessions->{$_}->{_session_kind} eq $self->sessionKind
642 } keys %$local_sessions
643 )
644 {
645  
646 # At least one session was found
647 foreach (@local_sessions_keys) {
648  
649 my $local_session = $_;
650  
651 # Get session
652 $self->logger->debug(
653 "Retrieve SAML session $local_session for user $user");
654  
655 my $sessionInfo = $self->getSamlSession($local_session);
656  
657 # If session index is defined and not equal to SAML session index,
658 # jump to next session
659 if ( defined $session_index
660 and $session_index ne
661 $sessionInfo->data->{_sessionIndex} )
662 {
663 $self->logger->debug(
664 "Session $local_session has not the good session index, skipping"
665 );
666 next;
667 }
668  
669 # Delete session
670 else {
671  
672 # Open real session
673 my $real_session = $sessionInfo->data->{_saml_id};
674  
675 my $ssoSession =
676 $self->p->getApacheSession($real_session);
677  
678 # Import SSO session in $req
679 $self->importRealSession( $req, $ssoSession );
680  
681 # Get Lasso::Session dump
682 # This value is erased if a next session match the SLO request
683 if ( $ssoSession
684 && $ssoSession->data->{ $self->lsDump } )
685 {
686 $self->logger->debug(
687 "Get Lasso::Session dump from session $real_session"
688 );
689 $session_dump =
690 $ssoSession->data->{ $self->lsDump };
691 }
692  
693 # Real session will be deleted after (see $req->steps... before)
694  
695 # Delete SAML session
696 my $del_saml_result = $sessionInfo->remove();
697  
698 $self->logger->debug(
699 "Delete SAML session $local_session result: $del_saml_result"
700 );
701  
702 $logout_error = 1 unless $del_saml_result;
703 }
704 }
705  
706 # Set session from dump
707 unless ( $self->setSessionFromDump( $logout, $session_dump ) ) {
708 $self->userLogger->error(
709 "Cannot set session from dump in logout");
710 $logout_error = 1;
711 }
712  
713 }
714 else {
715  
716 # No corresponding session found
717 $self->logger->debug("No SAML session found for user $user");
718  
719 $logout_error = 1;
720  
721 }
722  
723 # Validate request if no previous error
724 unless ($logout_error) {
725 unless ( $self->validateLogoutRequest($logout) ) {
726 $self->userLogger->error("SLO request is not valid");
727 }
728 }
729  
730 # Set RelayState
731 if ($relaystate) {
732 $logout->msg_relayState($relaystate);
733 $self->logger->debug("Set $relaystate in RelayState");
734 }
735  
736 # Do we set signature?
737 my $signSLOMessage =
738 $self->idpOptions->{$idp}->{samlIDPMetaDataOptionsSignSLOMessage};
739  
740 if ( $signSLOMessage == 0 ) {
741 $self->logger->debug(
742 "SLO message to IDP $idpConfKey will not be signed");
743 $self->disableSignature($logout);
744 }
745 elsif ( $signSLOMessage == 1 ) {
746 $self->logger->debug(
747 "SLO message to IDP $idpConfKey will be signed");
748 $self->forceSignature($logout);
749 }
750 else {
751 $self->logger->debug(
752 "SLO message to IDP $idpConfKey signature according to metadata"
753 );
754 }
755  
756 # Logout response
757 unless ( $self->buildLogoutResponseMsg($logout) ) {
758 $self->logger->error("Unable to build SLO response");
759 return PE_SLO_ERROR;
760 }
761  
762 # Send response depending on request method
763 # HTTP-REDIRECT
764 if ( $method == Lasso::Constants::HTTP_METHOD_REDIRECT ) {
765  
766 # Redirect user to response URL
767 my $slo_url = $logout->msg_url;
768 $self->logger->debug("Redirect user to $slo_url");
769  
770 $req->urldc($slo_url);
771  
772 return PE_OK;
773 }
774  
775 # HTTP-POST
776 elsif ( $method == Lasso::Constants::HTTP_METHOD_POST ) {
777  
778 # Use autosubmit form
779 my $slo_url = $logout->msg_url;
780 my $slo_body = $logout->msg_body;
781  
782 $req->postUrl($slo_url);
783 $req->postFields( { 'SAMLResponse' => $slo_body } );
784  
785 # RelayState
786 if ($relaystate) {
787 $req->{postFields}->{'RelayState'} =
788 encode_entities($relaystate);
789 $req->data->{safeHiddenFormValues}->{RelayState} = 1;
790 }
791  
792 # TODO: verify this
793 push @{ $req->steps }, 'autoPost';
794 return PE_OK;
795 }
796  
797 # HTTP-SOAP
798 elsif ( $method == Lasso::Constants::HTTP_METHOD_SOAP ) {
799  
800 my $slo_body = $logout->msg_body;
801  
802 $self->logger->debug("SOAP response $slo_body");
803  
804 $req->response(
805 $self->p->sendBinaryResponse(
806 $req, $slo_body, type => 'text/xml'
807 )
808 );
809 $req->data->{_continueLogout} = 1;
810 $req->steps( [
811 @{ $self->p->beforeLogout },
812 'deleteSession',
813 [ returnPE => PE_SENDRESPONSE ]
814 ]
815 );
816  
817 $req->user('SOAP client');
818 return PE_OK;
819 }
820  
821 }
822 else {
823  
824 # This should not happen
825 $self->userLogger->error("SLO request or response was not found");
826  
827 # Redirect user
828 $req->mustRedirect(1);
829 $req->steps( [] );
830 return PE_REDIRECT;
831 }
832 }
833  
834 # 1.3 Artifact
835 elsif ( $url =~ $self->artRe ) {
836  
837 $self->logger->debug(
838 "URL $url detected as an artifact resolution service URL");
839  
840 # Artifact request are sent with SOAP trough POST
841 my $art_request = $req->content;
842 my $art_response;
843  
844 # Create Login object
845 my $login = $self->createLogin( $self->lassoServer );
846  
847 # Process request message
848 unless ( $self->processArtRequestMsg( $login, $art_request ) ) {
849 $self->userLogger->error(
850 "Unable to process artifact request message");
851 return PE_SAML_ART_ERROR;
852 }
853  
854 # Check Destination
855 return PE_SAML_DESTINATION_ERROR
856 unless ( $self->checkDestination( $login->request, $url ) );
857  
858 # Create artifact response
859 unless ( $art_response = $self->createArtifactResponse( $req, $login ) )
860 {
861 $self->logger("Unable to create artifact response message");
862 return PE_SAML_ART_ERROR;
863 }
864  
865 $req->response(
866 $self->p->sendBinaryResponse(
867 $req, $art_response, type => 'text/xml'
868 )
869 );
870 $req->user('SOAP client');
871 return PE_SENDRESPONSE;
872 }
873  
874 # 2. IDP resolution
875  
876 # Search a selected IdP
877 my $idp = $self->getIDP($req);
878  
879 # Use Common Domain Cookie
880 if ( !$idp
881 and $self->conf->{samlCommonDomainCookieActivation}
882 and $self->conf->{samlCommonDomainCookieReader} )
883 {
884 $self->logger->debug(
885 "Will try to use Common Domain Cookie for IDP resolution");
886  
887 # Add current URL to CDC Reader URL
888 my $return_url = encode_base64( $self->p->fullUrl($req), '' );
889  
890 my $cdc_reader_url = $self->conf->{samlCommonDomainCookieReader};
891  
892 $cdc_reader_url .= ( $cdc_reader_url =~ /\?/ ? '&' : '?' )
893 . build_urlencoded( url => $return_url );
894  
895 $self->logger->debug("Redirect user to $cdc_reader_url");
896  
897 $req->urldc($cdc_reader_url);
898  
899 $req->steps( [] );
900 return PE_REDIRECT;
901 }
902  
903 # Use SAML Discovery Protocol
904 if ( !$idp
905 and $self->conf->{samlDiscoveryProtocolActivation}
906 and defined $self->conf->{samlDiscoveryProtocolURL} )
907 {
908 $self->logger->debug(
909 "Will try to use SAML Discovery Protocol for IDP resolution");
910  
911 if ( $req->urldc ) {
912 $req->pdata->{_url} = encode_base64( $req->urldc, '' );
913 }
914 my $disco_url = $self->conf->{samlDiscoveryProtocolURL};
915 my $portal = $req->portal;
916 $disco_url .= ( $disco_url =~ /\?/ ? '&' : '?' )
917 . build_urlencoded(
918 entityID => $self->getMetaDataURL( 'samlEntityID', 0, 1 ),
919 return => $portal,
920 returnIDParam => 'idp'
921 );
922  
923 if ( defined $self->conf->{samlDiscoveryProtocolPolicy} ) {
924 my $dppolicy = $self->conf->{samlDiscoveryProtocolPolicy};
925 $disco_url .= "&" . build_urlencoded( policy => $dppolicy );
926 }
927  
928 if ( defined $self->conf->{samlDiscoveryProtocolIsPassive} ) {
929 my $dpispassive = $self->conf->{samlDiscoveryProtocolIsPassive};
930 $disco_url .= "&"
931 . build_urlencoded(
932 isPassive => $dpispassive
933 ? "true"
934 : "false"
935 );
936 }
937  
938 $self->logger->debug("Redirect user to $disco_url");
939  
940 $req->urldc($disco_url);
941  
942 $req->steps( [] );
943 return PE_REDIRECT;
944 }
945  
946 # If IDP was not resolved, let the user choose its IDP
947 unless ($idp) {
948 $self->logger->debug("Redirecting user to IDP list");
949  
950 # Control url parameter
951 my $urlcheck = $self->p->controlUrl($req);
952 return $urlcheck unless ( $urlcheck == PE_OK );
953  
954 # IDP list
955 my @list = ();
956  
957 foreach ( keys %{ $self->idpList } ) {
958 my $idpName = $self->{idpList}->{$_}->{name};
959 $idpName = $self->{idpList}->{$_}->{displayName}
960 if $self->{idpList}->{$_}->{displayName};
961 my $icon = $self->{idpList}->{$_}->{icon};
962 my $order = $self->{idpList}->{$_}->{order} // 999999;
963 my $tooltip = $self->{idpList}->{$_}->{tooltip} || $idpName;
964 my $img_src = '';
965  
966 if ($icon) {
967 $img_src =
968 ( $icon =~ m#^https?://# )
969 ? $icon
970 : $self->p->staticPrefix . "/common/" . $icon;
971 }
972 $self->logger->debug( "IDP "
973 . $self->{idpList}->{$_}->{name}
974 . " -> DisplayName : $idpName with Icon : $img_src at order : $order"
975 );
976 push @list,
977 {
978 val => $_,
979 name => $idpName,
980 title => $tooltip,
981 icon => $img_src,
982 order => $order
983 };
984 }
985 @list =
986 sort {
987 $a->{order} <=> $b->{order}
988 or $a->{name} cmp $b->{name}
989 or $a->{val} cmp $b->{val}
990 } @list;
991 $req->data->{list} = \@list;
992  
993 #TODO: check this
994 $req->data->{login} = 1;
995 return PE_IDPCHOICE;
996 }
997  
998 # 3. Build authentication request
999  
1000 # IDP conf key
1001 my $idpConfKey = $self->getIDPConfKey($idp);
1002  
1003 unless ($idpConfKey) {
1004 $self->userLogger->error("$idp do not match any IDP in configuration");
1005 return PE_SAML_UNKNOWN_ENTITY;
1006 }
1007  
1008 $self->logger->debug("$idp match $idpConfKey IDP in configuration");
1009  
1010 # IDP ForceAuthn
1011 my $forceAuthn =
1012 $self->idpOptions->{$idp}->{samlIDPMetaDataOptionsForceAuthn};
1013  
1014 # IDP IsPassive
1015 my $isPassive =
1016 $self->idpOptions->{$idp}->{samlIDPMetaDataOptionsIsPassive};
1017  
1018 # IDP NameIDFormat
1019 my $nameIDFormat =
1020 $self->idpOptions->{$idp}->{samlIDPMetaDataOptionsNameIDFormat};
1021 $nameIDFormat = $self->getNameIDFormat($nameIDFormat) if $nameIDFormat;
1022  
1023 # IDP HTTP method
1024 my $method = $self->idpOptions->{$idp}->{samlIDPMetaDataOptionsSSOBinding};
1025 $method = $self->getHttpMethod($method);
1026  
1027 # If no method defined, get first HTTP method
1028 unless ( defined $method ) {
1029 my $protocolType = Lasso::Constants::MD_PROTOCOL_TYPE_SINGLE_SIGN_ON;
1030 $method =
1031 $self->getFirstHttpMethod( $self->lassoServer, $idp, $protocolType );
1032 }
1033  
1034 # Failback to HTTP-REDIRECT
1035 unless ( defined $method and $method != -1 ) {
1036 $self->logger->debug(
1037 "No method found with IDP $idpConfKey for SSO profile");
1038 $method = $self->getHttpMethod("redirect");
1039 }
1040  
1041 $self->logger->debug( "Use method "
1042 . $self->getHttpMethodString($method)
1043 . " with IDP $idpConfKey for SSO profile" );
1044  
1045 # Set signature
1046 my $signSSOMessage =
1047 $self->idpOptions->{$idp}->{samlIDPMetaDataOptionsSignSSOMessage} // -1;
1048  
1049 # Authentication Context
1050 my $requestedAuthnContext =
1051 $self->idpOptions->{$idp}->{samlIDPMetaDataOptionsRequestedAuthnContext}
1052 // '';
1053 $requestedAuthnContext = $self->getAuthnContext($requestedAuthnContext)
1054 if $requestedAuthnContext;
1055  
1056 # Create SSO request
1057 my $login = $self->createAuthnRequest(
1058 $req, $self->lassoServer, $idp,
1059 $method, $forceAuthn, $isPassive,
1060 $nameIDFormat, 0, $signSSOMessage,
1061 $requestedAuthnContext
1062 );
1063  
1064 unless ($login) {
1065 $self->userLogger->error(
1066 "Could not create authentication request on $idpConfKey");
1067 return PE_SAML_SSO_ERROR;
1068 }
1069  
1070 $self->logger->debug("Authentication request created");
1071  
1072 # Keep assertion ID in memory to prevent replay
1073 my $samlID = $login->request()->ID;
1074 unless ( $self->storeReplayProtection($samlID) ) {
1075 $self->logger->error("Unable to store assertion ID");
1076 return PE_SAML_SSO_ERROR;
1077 }
1078  
1079 # Keep initial SAML request data in memory in case of proxing
1080 if ( $req->data->{_proxiedSamlRequest} ) {
1081  
1082 my $infos;
1083  
1084 $infos->{type} = 'proxy';
1085 $infos->{_utime} = time;
1086 $infos->{Request} = $req->data->{_proxiedRequest};
1087 $infos->{Method} = $req->data->{_proxiedMethod};
1088 $infos->{RelayState} = $req->data->{_proxiedRelayState};
1089 $infos->{Artifact} = $req->data->{_proxiedArtifact};
1090 $infos->{ProxyID} = $samlID;
1091  
1092 my $samlSessionInfo = $self->getSamlSession( undef, $infos );
1093  
1094 return PE_SAML_SESSION_ERROR unless $samlSessionInfo;
1095  
1096 $self->logger->debug(
1097 "Keep initial SAML request data in memory for ID $samlID");
1098 }
1099  
1100 # Send SSO request depending on request method
1101 # HTTP-REDIRECT
1102 if ( $method == $self->getHttpMethod('redirect')
1103 or $method == $self->getHttpMethod('artifact-get') )
1104 {
1105  
1106 # Redirect user to response URL
1107 my $sso_url = $login->msg_url;
1108 $self->logger->debug("Redirect user to $sso_url");
1109  
1110 $req->urldc($sso_url);
1111  
1112 return PE_REDIRECT;
1113 }
1114  
1115 # HTTP-POST
1116 elsif ($method == $self->getHttpMethod('post')
1117 or $method == $self->getHttpMethod('artifact-post') )
1118 {
1119  
1120 # Use autosubmit form
1121 my $sso_url = $login->msg_url;
1122 my $sso_body = $login->msg_body;
1123  
1124 $req->postUrl($sso_url);
1125  
1126 if ( $method == $self->getHttpMethod("artifact-post") ) {
1127 $req->{postFields} = { 'SAMLart' => $sso_body };
1128 }
1129 else {
1130 $req->{postFields} = { 'SAMLRequest' => $sso_body };
1131 }
1132  
1133 # RelayState
1134 if ( $login->msg_relayState ) {
1135 $req->{postFields}->{'RelayState'} =
1136 encode_entities( $login->msg_relayState );
1137 $req->data->{safeHiddenFormValues}->{RelayState} = 1;
1138 }
1139  
1140 # TODO: verify this
1141 $req->steps( ['autoPost'] );
1142 $req->continue(1);
1143 return PE_OK;
1144 }
1145  
1146 # No SOAP transport for SSO request
1147 return PE_SAML_SSO_ERROR;
1148 }
1149  
1150 sub authenticate {
1151 return PE_OK;
1152 }
1153  
1154 sub setAuthSessionInfo {
1155 my ( $self, $req ) = @_;
1156 my $login = $req->data->{_lassoLogin};
1157 my $idp = $req->data->{_idp};
1158 my $idpConfKey = $req->data->{_idpConfKey};
1159 my $nameIdentifier = $req->data->{_nameID};
1160 my $session_index = $req->data->{_sessionIndex};
1161  
1162 # Get SAML assertion
1163 my $assertion = $self->getAssertion($login);
1164  
1165 unless ($assertion) {
1166 $self->userLogger->error("No assertion found");
1167 return PE_SAML_SSO_ERROR;
1168 }
1169  
1170 # Force UTF-8
1171 my $force_utf8 =
1172 $self->idpOptions->{$idp}->{samlIDPMetaDataOptionsForceUTF8};
1173  
1174 # Try to get attributes if attribute statement is present in assertion
1175 my $attr_statement = $assertion->AttributeStatement();
1176 if ($attr_statement) {
1177  
1178 # Get attributes
1179 my @attributes = $attr_statement->Attribute();
1180  
1181 # Wanted attributes are defined in IDP configuration
1182 foreach ( keys %{ $self->idpAttributes->{$idp} } ) {
1183  
1184 # Extract fields from exportedAttr value
1185 my ( $mandatory, $name, $format, $friendly_name ) =
1186 split( /;/, $self->idpAttributes->{$idp}->{$_} );
1187  
1188 # Try to get value
1189 my $value =
1190 $self->getAttributeValue( $name, $format, $friendly_name,
1191 \@attributes, $force_utf8 );
1192  
1193 # Store value in sessionInfo
1194 $req->{sessionInfo}->{$_} = $value if defined $value;
1195 }
1196 }
1197  
1198 # Store other information in session
1199 $req->{sessionInfo}->{_idp} = $idp;
1200 $req->{sessionInfo}->{_idpConfKey} = $idpConfKey;
1201  
1202 # Adapt _utime with SessionNotOnOrAfter
1203 my $sessionNotOnOrAfter;
1204 eval {
1205 $sessionNotOnOrAfter =
1206 $assertion->AuthnStatement()->SessionNotOnOrAfter();
1207 };
1208  
1209 if ( $@ or !$sessionNotOnOrAfter ) {
1210 $self->logger->debug("No SessionNotOnOrAfter value found");
1211 }
1212 else {
1213  
1214 my $samltime = $self->samldate2timestamp($sessionNotOnOrAfter);
1215 my $utime = time();
1216 my $timeout = $self->conf->{timeout};
1217 my $adaptSessionUtime =
1218 $self->idpOptions->{$idp}->{samlIDPMetaDataOptionsAdaptSessionUtime};
1219  
1220 if ( ( $utime + $timeout > $samltime ) and $adaptSessionUtime ) {
1221  
1222 # Use SAML time to determine the start of the session
1223 my $new_utime = $samltime - $timeout;
1224 $req->{sessionInfo}->{_utime} = $new_utime;
1225 $self->logger->debug(
1226 "Adapt _utime with SessionNotOnOrAfter value, new _utime: $new_utime"
1227 );
1228 }
1229  
1230 }
1231  
1232 # Establish federation (required for attribute request in UserDBSAML)
1233 unless ( $self->acceptSSO($login) ) {
1234 $self->userLogger->error(
1235 "Error while accepting SSO from IDP $idpConfKey");
1236 return PE_SAML_SSO_ERROR;
1237 }
1238  
1239 # Get created Lasso::Session and Lasso::Identity
1240 my $session = $login->get_session;
1241 my $identity = $login->get_identity;
1242  
1243 # Dump Lasso objects in session
1244 $req->{sessionInfo}->{ $self->lsDump } = $session->dump() if $session;
1245 $req->{sessionInfo}->{ $self->liDump } = $identity->dump() if $identity;
1246 $req->{sessionInfo}->{ $self->niDump } = $nameIdentifier->dump()
1247 if ref($nameIdentifier);
1248 $req->{sessionInfo}->{ $self->sIndex } = $session_index if $session_index;
1249  
1250 # Keep SAML Token in session
1251 my $store_samlToken =
1252 $self->idpOptions->{$idp}->{samlIDPMetaDataOptionsStoreSAMLToken};
1253 if ($store_samlToken) {
1254 $self->logger->debug("Store SAML Token in session");
1255 $req->{sessionInfo}->{_samlToken} = $req->data->{_samlToken};
1256 }
1257 else {
1258 $self->logger->debug("SAML Token will not be stored in session");
1259 }
1260  
1261 $req->data->{_lassoLogin} = $login;
1262  
1263 return PE_OK;
1264 }
1265  
1266 # Saves the link between IDP-side Session ID/NameID and LLNG session
1267 sub authFinish {
1268 my ( $self, $req ) = @_;
1269  
1270 # Get saved Lasso objects
1271 my $nameid = $req->sessionInfo->{ $self->niDump };
1272 my $session_index = $req->sessionInfo->{ $self->sIndex };
1273  
1274 # Auth::SAML was not used for this session
1275 return unless ($nameid);
1276  
1277 # Real session was stored, get id and utime
1278 my $id = $req->{id};
1279 my $utime = $req->{sessionInfo}->{_utime};
1280  
1281 $self->logger->debug( "Store NameID "
1282 . $nameid
1283 . ( $session_index ? " and SessionIndex $session_index" : "" )
1284 . " for session $id" );
1285  
1286 my $infos;
1287 $infos->{type} = 'saml'; # Session type
1288 $infos->{_utime} = $utime; # Creation time
1289 $infos->{_saml_id} = $id; # SSO session id
1290 $infos->{_nameID} = $nameid; # SAML NameID
1291 $infos->{_sessionIndex} = $session_index; # SAML SessionIndex
1292  
1293 # Save SAML session
1294 my $samlSessionInfo = $self->getSamlSession( undef, $infos );
1295  
1296 return PE_SAML_SESSION_ERROR unless $samlSessionInfo;
1297  
1298 my $session_id = $samlSessionInfo->id;
1299  
1300 $self->logger->debug("Link session $id to SAML session $session_id");
1301  
1302 return PE_OK;
1303 }
1304  
1305 sub authLogout {
1306 my ( $self, $req ) = @_;
1307 my $idp = $req->sessionInfo->{_idp};
1308 my $idpConfKey = $req->sessionInfo->{_idpConfKey};
1309 my $session_id = $req->sessionInfo->{_session_id};
1310 my $method;
1311  
1312 # Real session was previously deleted,
1313 # remove corresponding SAML sessions
1314 $self->deleteSAMLSecondarySessions($session_id);
1315  
1316 # Recover Lasso::Session dump
1317 my $session_dump = $req->{sessionInfo}->{ $self->lsDump };
1318  
1319 unless ($session_dump) {
1320 $self->userLogger->error("Could not get session dump from session");
1321 return PE_SLO_ERROR;
1322 }
1323  
1324 # IDP HTTP method
1325 $method = $self->idpOptions->{$idp}->{samlIDPMetaDataOptionsSLOBinding};
1326 $method = $self->getHttpMethod($method);
1327  
1328 # If no method defined, get first HTTP method
1329 unless ( defined $method ) {
1330 my $protocolType = Lasso::Constants::MD_PROTOCOL_TYPE_SINGLE_LOGOUT;
1331 $method =
1332 $self->getFirstHttpMethod( $self->lassoServer, $idp, $protocolType );
1333 }
1334  
1335 # Skip SLO if no method found
1336 unless ( defined $method and $method != -1 ) {
1337 $self->logger->debug(
1338 "No method found with IDP $idpConfKey for SLO profile");
1339 return PE_OK;
1340 }
1341  
1342 $self->logger->debug( "Use method "
1343 . $self->getHttpMethodString($method)
1344 . " with IDP $idpConfKey for SLO profile" );
1345  
1346 # Set signature
1347 my $signSLOMessage =
1348 $self->idpOptions->{$idp}->{samlIDPMetaDataOptionsSignSLOMessage} // 0;
1349  
1350 # Build Logout Request
1351 my $logout =
1352 $self->createLogoutRequest( $req, $self->lassoServer, $session_dump,
1353 $method, $signSLOMessage );
1354 unless ($logout) {
1355 $self->logger->error("Could not create logout request");
1356 return PE_SLO_ERROR;
1357 }
1358  
1359 $self->logger->debug("Logout request created");
1360  
1361 # Keep request ID in memory to prevent replay
1362 unless ( $self->storeReplayProtection( $logout->request()->ID ) ) {
1363 $self->logger->error("Unable to store Logout request ID");
1364 return PE_SLO_ERROR;
1365 }
1366  
1367 # Send request depending on request method
1368 # HTTP-REDIRECT
1369 if ( $method == Lasso::Constants::HTTP_METHOD_REDIRECT
1370 or $method == Lasso::Constants::HTTP_METHOD_ARTIFACT_GET )
1371 {
1372  
1373 # Redirect user to response URL
1374 my $slo_url = $logout->msg_url;
1375 $self->logger->debug("Redirect user to $slo_url");
1376  
1377 $req->urldc($slo_url);
1378  
1379 # Redirect done in Portal
1380 return PE_OK;
1381 }
1382  
1383 # HTTP-POST
1384 elsif ($method == Lasso::Constants::HTTP_METHOD_POST
1385 or $method == Lasso::Constants::HTTP_METHOD_ARTIFACT_POST )
1386 {
1387  
1388 # Use autosubmit form
1389 my $slo_url = $logout->msg_url;
1390 my $slo_body = $logout->msg_body;
1391 $self->logger->debug("Redirect user to $slo_url using autoPost");
1392  
1393 $req->postUrl($slo_url);
1394 $req->postFields( { 'SAMLRequest' => $slo_body } );
1395  
1396 # RelayState
1397 if ( $logout->msg_relayState ) {
1398 $req->{postFields}->{'RelayState'} =
1399 encode_entities( $logout->msg_relayState );
1400 $req->data->{safeHiddenFormValues}->{RelayState} = 1;
1401 }
1402  
1403 # Post done in Portal
1404 $req->steps( [ 'deleteSession', 'autoPost' ] );
1405 return PE_OK;
1406 }
1407  
1408 # HTTP-SOAP
1409 elsif ( $method == Lasso::Constants::HTTP_METHOD_SOAP ) {
1410  
1411 my $slo_url = $logout->msg_url;
1412 my $slo_body = $logout->msg_body;
1413  
1414 # Send SOAP request and manage response
1415 my $response = $self->sendSOAPMessage( $slo_url, $slo_body );
1416  
1417 unless ($response) {
1418 $self->logger->error("No logout response to SOAP request");
1419 return PE_SLO_ERROR;
1420 }
1421  
1422 # Create Logout object
1423 $logout = $self->createLogout( $self->lassoServer );
1424  
1425 # Do we check signature?
1426 my $checkSLOMessageSignature =
1427 $self->idpOptions->{$idp}
1428 ->{samlIDPMetaDataOptionsCheckSLOMessageSignature};
1429  
1430 unless ($checkSLOMessageSignature) {
1431 $self->disableSignatureVerification($logout);
1432 }
1433  
1434 # Process logout response
1435 my $result = $self->processLogoutResponseMsg( $logout, $response );
1436  
1437 unless ($result) {
1438 $self->logger->error("Fail to process logout response");
1439 return PE_SLO_ERROR;
1440 }
1441  
1442 $self->logger->debug("Logout response is valid");
1443  
1444 # Replay protection
1445 my $samlID = $logout->response()->InResponseTo;
1446  
1447 unless ( $self->replayProtection($samlID) ) {
1448  
1449 # Logout request was already consumed or is expired
1450 $self->userLogger->error("Message $samlID already used or expired");
1451 return PE_SLO_ERROR;
1452 }
1453  
1454 return PE_OK;
1455 }
1456 else {
1457 $self->userLogger->error("Lasso method $method not implemented here");
1458 return PE_SLO_ERROR;
1459 }
1460 }
1461  
1462 sub isCallback {
1463 my ( $self, $req ) = @_;
1464 return $req->uri =~ $self->ssoAssConsumerRe;
1465 }
1466  
1467 sub handleAuthRequests {
1468 my ( $self, $req ) = @_;
1469 if ( $req->uri =~ $self->sloRe ) {
1470 return $self->extractFormInfo($req);
1471 }
1472 return PE_OK;
1473 }
1474  
1475 # TODO: authForce
1476  
1477 sub getDisplayType {
1478 return "logo";
1479 }
1480  
1481 # Internal methods
1482  
1483 sub getIDPConfKey {
1484 my ( $self, $entityID ) = @_;
1485  
1486 # Make sure we don't modify the hash by reading it
1487 if ( $self->idpList->{$entityID} ) {
1488 return $self->idpList->{$entityID}->{confKey};
1489 }
1490 return undef;
1491 }
1492  
1493 sub getEntityID {
1494 my ( $self, $confKey ) = @_;
1495  
1496 foreach ( keys %{ $self->idpList } ) {
1497 my $idpConfKey = $self->idpList->{$_}->{confKey} // "";
1498 if ( $confKey eq $idpConfKey ) {
1499 return $_;
1500 }
1501 }
1502 return undef;
1503 }
1504  
1505 # Try to find an IdP using :
1506 # * HTTP parameter
1507 # * Rules
1508 #
1509 # @return Array containing :
1510 # * IdP found (or undef)
1511 # * Cookie value if exists
1512 sub getIDP {
1513 my ( $self, $req ) = @_;
1514 my $idp;
1515 my $idpName;
1516  
1517 # Case 1: Recover IDP from idp URL Parameter
1518 unless ( $idp = $req->param("idp") ) {
1519  
1520 # Case 2: Recover IDP from idpName URL Parameter
1521 if ( $idpName = $req->param("idpName") ) {
1522 $idp = $self->getEntityID($idpName);
1523 $self->logger->debug(
1524 "IDP $idp selected from idpName URL Parameter ($idpName)")
1525 if $idp;
1526 }
1527  
1528 # Case 3: check all IDP resolution rules
1529 # The first match win
1530 else {
1531 foreach ( keys %{ $self->idpList } ) {
1532 my $idpConfKey = $self->idpList->{$_}->{confKey};
1533 my $cond = $self->idpRules->{$_} or next;
1534 if ( $cond->( $req, $req->sessionInfo ) ) {
1535 $self->logger->debug(
1536 "IDP $idpConfKey selected from resolution rule");
1537 $idp = $_;
1538 last;
1539 }
1540 }
1541 }
1542 $self->logger->debug('No IDP selected') unless ($idp);
1543 }
1544 else {
1545 $self->logger->debug("IDP $idp selected from idp URL Parameter");
1546 }
1547  
1548 # Lazy load IDP
1549 $self->lazy_load_entityid($idp) if $idp;
1550  
1551 # Case 6: auto select IDP if only one IDP defined and WAYF is disabled
1552 if (
1553 scalar keys %{ $self->idpList } == 1
1554 and not( $self->conf->{samlDiscoveryProtocolActivation}
1555 and defined $self->conf->{samlDiscoveryProtocolURL} )
1556 )
1557 {
1558 ($idp) = keys %{ $self->idpList };
1559 $self->logger->debug("Selecting the only defined SAML IDP: $idp");
1560 }
1561  
1562 # Alert when selected IDP is unknown
1563 if ( $idp and !exists $self->idpList->{$idp} ) {
1564 $self->logger->error("Required IDP $idp does not exists");
1565 $idp = undef;
1566 }
1567  
1568 return $idp;
1569 }
1570  
1571 1;
« blib/lib/Lemonldap/NG/Portal/Auth/Kerberos.pm ↑ Summary blib/lib/Lemonldap/NG/Portal/Issuer/SAML.pm »