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