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

filter: Statementstmt 88.8% 16 / 18 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 6 / 6 Podpod n/a totaltotal 91.6% 22 / 24 CC 1 SCAR 0.5
CC
1
Cov
89%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« blib/lib/Lemonldap/NG/Portal/Auth/SAML.pm ↑ Summary blib/lib/Lemonldap/NG/Portal/UserDB/Combination.pm »
1 package Lemonldap::NG::Portal::Issuer::SAML;
2  
3 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use Mouse;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use URI;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use URI::QueryParam;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use HTML::Entities qw(encode_entities);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 0 ▶use Lemonldap::NG::Portal::Lib::SAML;
Subroutine BEGIN: called CC=1 SCAR=2.6
9 use Lemonldap::NG::Portal::Main::Constants qw(
10 portalConsts
11 PE_OK
12 PE_REDIRECT
13 PE_SESSIONEXPIRED
14 PE_SAML_ART_ERROR
15 PE_SAML_DESTINATION_ERROR
16 PE_SAML_SESSION_ERROR
17 PE_SAML_SIGNATURE_ERROR
18 PE_SLO_ERROR
19 PE_SAML_SSO_ERROR
20 PE_ISSUERMISSINGREQATTR
21 PE_UNKNOWNPARTNER
22 PE_SAML_SERVICE_NOT_ALLOWED
23 PE_UNAUTHORIZEDPARTNER
24 );
25  
26 our $VERSION = '2.23.0';
27  
28 extends 'Lemonldap::NG::Portal::Main::Issuer',
29 'Lemonldap::NG::Portal::Lib::SAML';
30  
31 with 'Lemonldap::NG::Portal::Lib::Key';
32  
33 has rule => ( is => 'rw' );
34 has ssoUrlRe => ( is => 'rw' );
35 has ssoUrlArtifact => ( is => 'rw' );
36 has ssoGetUrl => ( is => 'rw' );
37  
38 use constant sessionKind => 'ISAML';
39 use constant lsDump => '_lassoSessionDumpI';
40 use constant liDump => '_lassoIdentityDumpI';
41  
42 # INTERFACE
43  
44 # Simply store SP in $req->env
45 use constant beforeAuth => 'storeEnv';
46 use constant hook => { updateSessionId => 'updateSAMLSecondarySessions', };
47  
48 # INITIALIZATION
49  
50 sub init {
51 my ($self) = @_;
52  
53 # Parse activation rule
54 my $hd = $self->p->HANDLER;
55 $self->logger->debug( "SAML rule -> " . $self->conf->{issuerDBSAMLRule} );
56 my $rule =
57 $hd->buildSub( $hd->substitute( $self->conf->{issuerDBSAMLRule} ) );
58 unless ($rule) {
59 my $error = $hd->tsv->{jail}->error || '???';
60 $self->error("Bad SAML activation rule -> $error");
61 return 0;
62 }
63 $self->{rule} = $rule;
64  
65 # Prepare SSO URL catching
66 my $saml_sso_get_url = $self->ssoGetUrl(
67 $self->getMetaDataURL(
68 "samlIDPSSODescriptorSingleSignOnServiceHTTPRedirect", 1
69 )
70 );
71 my $saml_sso_get_url_ret = $self->getMetaDataURL(
72 "samlIDPSSODescriptorSingleSignOnServiceHTTPRedirect", 2 );
73 my $saml_sso_post_url =
74 $self->getMetaDataURL( "samlIDPSSODescriptorSingleSignOnServiceHTTPPost",
75 1 );
76 my $saml_sso_post_url_ret =
77 $self->getMetaDataURL( "samlIDPSSODescriptorSingleSignOnServiceHTTPPost",
78 2 );
79 my $saml_sso_art_url = $self->getMetaDataURL(
80 "samlIDPSSODescriptorSingleSignOnServiceHTTPArtifact", 1 );
81 my $saml_sso_art_url_ret = $self->getMetaDataURL(
82 "samlIDPSSODescriptorSingleSignOnServiceHTTPArtifact", 2 );
83 $self->ssoUrlRe(
84 qr/^($saml_sso_get_url|$saml_sso_get_url_ret|$saml_sso_post_url|$saml_sso_post_url_ret|$saml_sso_art_url|$saml_sso_art_url_ret)(?:\?.*)?$/i
85 );
86 $self->ssoUrlArtifact(
87 qr/^($saml_sso_art_url|$saml_sso_art_url_ret)(?:\?.*)?$/i);
88  
89 # Launch parents initialization subroutines, then launch IdP en SP lists
90 my $res = (
91 $self->Lemonldap::NG::Portal::Main::Issuer::init()
92  
93 # Load SAML service
94 and $self->Lemonldap::NG::Portal::Lib::SAML::init()
95  
96 # Load SAML service providers
97 and $self->loadSPs()
98  
99 # Load SAML identity providers
100 # Required to manage SLO in Proxy mode
101 and $self->loadIDPs()
102 );
103 return 0 unless ($res);
104  
105 if ( $self->conf->{samlOverrideIDPEntityID} ) {
106 $self->lassoServer->ProviderID(
107 $self->conf->{samlOverrideIDPEntityID} );
108 }
109  
110 # Single logout routes
111 $self->addUnauthRouteFromMetaDataURL(
112 "samlIDPSSODescriptorSingleLogoutServiceSOAP",
113 1, 'sloServer', ['POST'] );
114 $self->addUnauthRouteFromMetaDataURL(
115 "samlIDPSSODescriptorSingleLogoutServiceSOAP",
116 2, 'sloServer', ['POST'] );
117 $self->addUnauthRouteFromMetaDataURL(
118 "samlIDPSSODescriptorSingleLogoutServiceHTTPRedirect",
119 1, 'sloServer', ['GET'] );
120 $self->addUnauthRouteFromMetaDataURL(
121 "samlIDPSSODescriptorSingleLogoutServiceHTTPRedirect",
122 2, 'sloServer', ['GET'] );
123 $self->addUnauthRouteFromMetaDataURL(
124 "samlIDPSSODescriptorSingleLogoutServiceHTTPPost",
125 1, 'sloServer', ['POST'] );
126 $self->addUnauthRouteFromMetaDataURL(
127 "samlIDPSSODescriptorSingleLogoutServiceHTTPPost",
128 2, 'sloServer', ['POST'] );
129  
130 $self->addAuthRouteFromMetaDataURL(
131 "samlIDPSSODescriptorSingleLogoutServiceSOAP",
132 1, 'authSloServer', ['POST'] );
133 $self->addAuthRouteFromMetaDataURL(
134 "samlIDPSSODescriptorSingleLogoutServiceSOAP",
135 2, 'authSloServer', ['POST'] );
136 $self->addAuthRouteFromMetaDataURL(
137 "samlIDPSSODescriptorSingleLogoutServiceHTTPRedirect",
138 1, 'authSloServer', ['GET'] );
139 $self->addAuthRouteFromMetaDataURL(
140 "samlIDPSSODescriptorSingleLogoutServiceHTTPRedirect",
141 2, 'authSloServer', ['GET'] );
142 $self->addAuthRouteFromMetaDataURL(
143 "samlIDPSSODescriptorSingleLogoutServiceHTTPPost",
144 1, 'authSloServer', ['POST'] );
145 $self->addAuthRouteFromMetaDataURL(
146 "samlIDPSSODescriptorSingleLogoutServiceHTTPPost",
147 2, 'authSloServer', ['POST'] );
148  
149 # SOAP routes (access without authentication)
150 $self->addRouteFromMetaDataURL(
151 'samlIDPSSODescriptorArtifactResolutionServiceArtifact',
152 3, 'artifactServer', ['POST'] );
153 $self->addRouteFromMetaDataURL(
154 'samlAttributeAuthorityDescriptorAttributeServiceSOAP',
155 1, 'attributeServer', ['POST'] );
156  
157 $self->addUnauthRoute(
158 $self->path => { relaySingleLogoutSOAP => 'sloRelaySoap' },
159 [ 'GET', 'POST' ]
160 );
161 $self->addAuthRoute(
162 $self->path => { relaySingleLogoutPOST => 'sloRelayPost' },
163 [ 'GET', 'POST' ]
164 );
165 $self->addUnauthRoute(
166 $self->path => { relaySingleLogoutPOST => 'sloRelayPost' },
167 [ 'GET', 'POST' ]
168 );
169 $self->addUnauthRoute(
170 $self->path => { singleLogoutResume => 'sloResume' },
171 [ 'GET', 'POST' ]
172 );
173 $self->addUnauthRoute(
174 $self->path => { relaySingleLogoutTermination => 'sloRelayTerm' },
175 [ 'GET', 'POST' ]
176 );
177 return $res;
178 }
179  
180 # RUNNING METHODS
181  
182 # "beforeAuth" entry point. Store just SP and SP confKey in $req->env
183 sub storeEnv {
184 my ( $self, $req ) = @_;
185 return PE_OK
186 if ( $req->uri !~ $self->ssoUrlRe or $req->uri =~ $self->ssoUrlArtifact );
187  
188 # This doesn't always work, especially when coming from a HTTP-Redirect flow and
189 # POST-ing the login form
190 my ( $request, $response, $method, $relaystate, $artifact ) =
191 $self->checkMessage( $req, $req->uri, $req->method, $req->content_type );
192 return PE_OK if ( $artifact or !$request );
193 my $login = $self->createLogin( $self->lassoServer );
194 $self->disableSignatureVerification($login);
195 $self->processAuthnRequestMsgWithError( $login, $request, 'debug' );
196 if ( my $sp = $login->remote_providerID() ) {
197 $req->env->{llng_saml_sp} = $sp;
198 if ( my $spConfKey = $self->spList->{$sp}->{confKey} ) {
199 $req->env->{llng_saml_spconfkey} = $spConfKey;
200  
201 # Store target authentication level in pdata
202 my $targetAuthnLevel =
203 $self->spLevelRules->{$spConfKey}->( $req, {} );
204  
205 $req->pdata->{targetAuthnLevel} = $targetAuthnLevel
206 if $targetAuthnLevel;
207 }
208 if ( $login->request ) {
209 my $acs = $login->request->AssertionConsumerServiceURL;
210 $req->env->{llng_saml_acs} = $acs if $acs;
211 }
212 }
213 return PE_OK;
214 }
215  
216 sub ssoMatch {
217 my ( $self, $req ) = @_;
218 my $url = $self->normalize_url( $req->uri, $self->conf->{issuerDBSAMLPath},
219 $self->ssoGetUrl );
220 return (
221 $url =~ $self->ssoUrlRe or $req->data->{_proxiedRequest}
222 ? 1
223 : 0
224 );
225 }
226  
227 # Main method (launched only for authenticated users, see Main/Issuer)
228 sub run {
229 my ( $self, $req ) = @_;
230 my $login;
231 my $protocolProfile;
232 my $artifact_method;
233 my $authn_context;
234  
235 # Check activation rule
236 unless ( $self->rule->( $req, $req->sessionInfo ) ) {
237 $self->userLogger->error('SAML service not authorized');
238 return PE_SAML_SERVICE_NOT_ALLOWED;
239 }
240  
241 # Session ID
242 my $session_id = $req->{sessionInfo}->{_session_id} || $req->id;
243  
244 # Session creation timestamp
245 my $time = $req->{sessionInfo}->{_utime} || time();
246  
247 # Get HTTP request information to know
248 # if we are receving SAML request or response
249 my $url = $req->uri;
250 my $request_method = $req->param('issuerMethod') || $req->method;
251 my $content_type = $req->content_type();
252 my $idp_initiated = $req->param('IDPInitiated');
253 my $idp_initiated_sp = $req->param('sp');
254 my $idp_initiated_spConfKey = $req->param('spConfKey');
255 my $idp_initiated_spDest = $req->param('spDest');
256  
257 # Normalize URL to be tolerant to SAML Path
258 $url = $self->normalize_url( $url, $self->conf->{issuerDBSAMLPath},
259 $self->ssoGetUrl );
260  
261 # Get domain GET attribute
262 my $domain = $req->param('domain');
263  
264 if ($domain) {
265 $self->logger->debug("Found domain $domain in SAML GET parameter");
266 }
267  
268 # 1.1. SSO (SSO URL or Proxy Mode)
269 if ( $url =~ $self->ssoUrlRe or $req->data->{_proxiedRequest} ) {
270  
271 $self->logger->debug("URL $url detected as an SSO request URL");
272  
273 # Check message
274 my ( $request, $response, $method, $relaystate, $artifact ) =
275 $self->checkMessage( $req, $url, $request_method, $content_type );
276  
277 # Create Login object
278 my $login = $self->createLogin( $self->lassoServer );
279  
280 # Ignore signature verification
281 $self->disableSignatureVerification($login);
282  
283 if ($request) {
284 $req->data->{_proxiedSamlRequest} = $login->request();
285 $req->data->{_proxiedRequest} = $request;
286 $req->data->{_proxiedMethod} = $method;
287 $req->data->{_proxiedRelayState} = $relaystate,
288 $req->data->{_proxiedArtifact} = $artifact;
289 }
290  
291 # Process the request or use IDP initiated mode
292 if ( $request or $idp_initiated ) {
293  
294 # Load Session and Identity if they exist
295 my $session = $req->{sessionInfo}->{ $self->lsDump };
296 my $identity = $req->{sessionInfo}->{ $self->liDump };
297  
298 if ($session) {
299 unless ( $self->setSessionFromDump( $login, $session ) ) {
300 return $self->_failAuthnRequest( $req,
301 msg => "Unable to load Lasso Session" );
302 }
303 $self->logger->debug("Lasso Session loaded");
304 }
305  
306 if ($identity) {
307 unless ( $self->setIdentityFromDump( $login, $identity ) ) {
308 return $self->_failAuthnRequest( $req,
309 msg => "Unable to load Lasso Identity" );
310 }
311 $self->logger->debug("Lasso Identity loaded");
312 }
313  
314 my $result;
315  
316 # Create fake request if IDP initiated mode
317 if ($idp_initiated) {
318  
319 # Need sp or spConfKey parameter
320 unless ( $idp_initiated_sp or $idp_initiated_spConfKey ) {
321 return $self->_failAuthnRequest(
322 $req,
323 msg => (
324 "sp or spConfKey parameter needed"
325 . " to make IDP initiated SSO"
326 ),
327 userLogger => 1,
328 );
329 }
330  
331 unless ($idp_initiated_sp) {
332  
333 # Get SP from spConfKey
334 foreach ( keys %{ $self->spList } ) {
335 if ( $self->spList->{$_}->{confKey} eq
336 $idp_initiated_spConfKey )
337 {
338 $idp_initiated_sp = $_;
339 last;
340 }
341 }
342 }
343 else {
344 $self->lazy_load_entityid($idp_initiated_sp);
345  
346 unless ( defined $self->spList->{$idp_initiated_sp} ) {
347 return $self->_failAuthnRequest(
348 $req,
349 msg => "SP $idp_initiated_sp not known",
350 res => PE_UNKNOWNPARTNER,
351 userLogger => 1,
352 );
353 }
354 $idp_initiated_spConfKey =
355 $self->spList->{$idp_initiated_sp}->{confKey};
356 }
357  
358 # Check if IDP Initiated SSO is allowed
359 unless ( $self->spOptions->{$idp_initiated_sp}
360 ->{samlSPMetaDataOptionsEnableIDPInitiatedURL} )
361 {
362 return $self->_failAuthnRequest(
363 $req,
364 msg => (
365 "IDP Initiated SSO not allowed"
366 . " for SP $idp_initiated_spConfKey"
367 ),
368 userLogger => 1,
369 );
370 }
371  
372 $result =
373 $self->initIdpInitiatedAuthnRequest( $login,
374 $idp_initiated_sp );
375 unless ($result) {
376 return $self->_failAuthnRequest(
377 $req,
378 msg => (
379 "SSO: Fail to init IDP Initiated"
380 . " authentication request"
381 )
382 );
383 }
384  
385 # Force NameID Format
386 my $nameIDFormatKey =
387 $self->spOptions->{$idp_initiated_sp}
388 ->{samlSPMetaDataOptionsNameIDFormat} || "email";
389 eval {
390  
391 $login->request()
392 ->NameIDPolicy()
393 ->Format( $self->getNameIDFormat($nameIDFormatKey) );
394 };
395  
396 # Force AllowCreate to TRUE
397 eval { $login->request()->NameIDPolicy()->AllowCreate(1); };
398  
399 # Allow selection the AssertionConsumerServiceURL by the user
400 if ($idp_initiated_spDest) {
401 $login->request->AssertionConsumerServiceURL(
402 $idp_initiated_spDest);
403 }
404 }
405  
406 my $lasso_error;
407  
408 # Process authentication request
409 if ($artifact) {
410 $result = $self->processArtResponseMsg( $login, $request );
411 }
412 else {
413 ( $result, $lasso_error ) =
414 $self->processAuthnRequestMsgWithError( $login, $request );
415 }
416  
417 unless ($result) {
418 if ( $lasso_error ==
419 Lasso::Constants::SERVER_ERROR_PROVIDER_NOT_FOUND )
420 {
421 my $sp = eval { $login->remote_providerID() };
422 return $self->_failAuthnRequest(
423 $req,
424 msg => (
425 "SSO: Incoming entity ID $sp was not found"
426 . " in registered Service Providers metadata."
427 ),
428 res => PE_UNKNOWNPARTNER,
429 );
430 }
431 elsif ( $lasso_error ==
432 Lasso::Constants::PROFILE_ERROR_INVALID_PROTOCOLPROFILE )
433 {
434 if ( my $ACS =
435 eval { $login->request->AssertionConsumerServiceURL } )
436 {
437 $self->logger->error(
438 "Requested AssertionConsumerServiceURL $ACS"
439 . " might be missing from registered metadata" );
440 }
441 else {
442 $self->logger->error(
443 "Make sure AssertionConsumerServiceURL from the "
444 . " SAML requests is defined in registered metadata"
445 );
446 }
447  
448 return $self->_failAuthnRequest( $req,
449 msg => "SSO: Fail to process authentication request" );
450 }
451 else {
452 return $self->_failAuthnRequest( $req,
453 msg => "SSO: Fail to process authentication request" );
454 }
455 }
456  
457 # Get SP entityID
458 my $sp = $request ? $login->remote_providerID() : $idp_initiated_sp;
459 $self->logger->debug("Found entityID $sp in SAML message");
460  
461 # SP conf key
462 my $spConfKey = $self->spList->{$sp}->{confKey};
463 unless ($spConfKey) {
464 return $self->_failAuthnRequest(
465 $req,
466 msg => "$sp do not match any SP in configuration",
467 res => PE_UNKNOWNPARTNER,
468 logInfo => {
469 sp => $spConfKey,
470 entity_id => $sp,
471 },
472 userLogger => 1,
473 );
474 }
475 $self->logger->debug("$sp match $spConfKey SP in configuration");
476  
477 # Do we check signature?
478 my $checkSSOMessageSignature =
479 $self->spOptions->{$sp}
480 ->{samlSPMetaDataOptionsCheckSSOMessageSignature};
481  
482 if ($checkSSOMessageSignature) {
483  
484 $self->forceSignatureVerification($login);
485  
486 my $lasso_error;
487 if ($artifact) {
488 $result = $self->processArtResponseMsg( $login, $request );
489 }
490 else {
491 ( $result, $lasso_error ) =
492 $self->processAuthnRequestMsgWithError( $login,
493 $request );
494 }
495  
496 unless ($result) {
497 return $self->_failAuthnRequest(
498 $req,
499 msg => (
500 "Could not verify signature of "
501 . "incoming SSO request from $spConfKey"
502 ),
503 res => PE_SAML_SIGNATURE_ERROR,
504 logInfo => {
505 sp => $spConfKey,
506 entity_id => $sp,
507 },
508 );
509 }
510 else {
511 $self->logger->debug("Signature is valid");
512 }
513 }
514 else {
515 $self->logger->debug("Message signature will not be checked");
516 }
517  
518 # Hook must be run after processAuthnRequestMsg
519 my $h =
520 $self->p->processHook( $req, 'samlGotAuthnRequest', $login );
521 return $self->_failAuthnRequest(
522 $req,
523 msg => 'samlGotAuthnRequest hook failed',
524 res => $h,
525 logInfo => {
526 sp => $spConfKey,
527 entity_id => $sp,
528 },
529 ) if ( $h != PE_OK );
530  
531 # Set environment for rule/macro evaluation
532 $req->env->{llng_saml_sp} = $sp;
533 $req->env->{llng_saml_spconfkey} = $spConfKey;
534 if ( $login->request ) {
535 my $acs = $login->request->AssertionConsumerServiceURL;
536 if ($acs) {
537 $req->env->{llng_saml_acs} = $acs;
538 $self->logger->debug(
539 "Using AssertionConsumerServiceURL $acs");
540 }
541 }
542  
543 # Check access rule
544 if ( my $rule = $self->spRules->{$spConfKey} ) {
545 unless ( $rule->( $req, $req->sessionInfo ) ) {
546 return $self->_failAuthnRequest(
547 $req,
548 msg => (
549 'User '
550 . $req->sessionInfo->{ $self->conf->{whatToTrace}
551 }
552 . " is not authorized to access $spConfKey"
553 ),
554 res => PE_UNAUTHORIZEDPARTNER,
555 userLogger => 1,
556 logInfo => {
557 sp => $spConfKey,
558 entity_id => $sp,
559 },
560 );
561 }
562 }
563  
564 my $nameIDFormat;
565  
566 # Check NameID Policy in request
567 if ( $login->request()->NameIDPolicy ) {
568 $nameIDFormat = $login->request()->NameIDPolicy->Format();
569 $self->logger->debug(
570 "Get NameID format $nameIDFormat from request")
571 if defined($nameIDFormat);
572 }
573  
574 # Get default NameID Format from configuration
575 # Set to "email" if no value in configuration
576 my $nameIDFormatKey =
577 $self->spOptions->{$sp}->{samlSPMetaDataOptionsNameIDFormat}
578 || "email";
579  
580 # NameID unspecified is forced to default NameID format
581 if ( !$nameIDFormat
582 or $nameIDFormat eq $self->getNameIDFormat("unspecified")
583 or $self->spOptions->{$sp}
584 ->{samlSPMetaDataOptionsForceNameIDFormat} )
585 {
586 $nameIDFormat = $self->getNameIDFormat($nameIDFormatKey);
587  
588 # Update NameIDFormat in request
589 eval {
590 if ( !$login->request()->NameIDPolicy ) {
591  
592 # Create NameIDFormat object if it doesnt exist
593 $login->request()
594 ->NameIDPolicy( Lasso::Samlp2NameIDPolicy->new() );
595 }
596 $login->request()->NameIDPolicy()->Format($nameIDFormat);
597 };
598 if ($@) {
599 $self->logger->warn(
600 "Could not update NameIDPolicy in request: $@");
601 }
602 }
603  
604 # Force AllowCreate to TRUE for transient/persistent NameIDPolicy
605 if ( $login->request()->NameIDPolicy ) {
606 if ( $nameIDFormat eq $self->getNameIDFormat("transient")
607 or $nameIDFormat eq $self->getNameIDFormat("persistent") )
608 {
609 $self->logger->debug(
610 "Force AllowCreate flag in NameIDPolicy");
611 eval { $login->request()->NameIDPolicy()->AllowCreate(1); };
612 }
613 }
614  
615 # Validate request
616 unless ( $self->validateRequestMsg( $login, 1, 1 ) ) {
617 return $self->_failAuthnRequest(
618 $req,
619 msg => "Unable to validate SSO request message",
620 logInfo => {
621 sp => $spConfKey,
622 entity_id => $sp,
623 },
624 );
625 }
626  
627 $self->logger->debug("SSO: authentication request is valid");
628  
629 my $spAuthnLevel =
630 $self->spLevelRules->{$spConfKey}->( $req, $req->sessionInfo );
631  
632 # Get ForceAuthn flag
633 my $force_authn;
634  
635 eval { $force_authn = $login->request()->ForceAuthn(); };
636 if ($@) {
637 $self->logger->warn(
638 "Unable to get ForceAuthn flag, set it to false");
639 $force_authn = 0;
640 }
641  
642 $self->logger->debug(
643 "Found ForceAuthn flag with value $force_authn");
644  
645 # Force authentication if flag is on, or previous flag still active
646 if (
647 $force_authn
648 and (
649 time - $req->sessionInfo->{_lastAuthnUTime} >
650 $self->conf->{portalForceAuthnInterval} )
651 )
652 {
653  
654 $self->userLogger->info(
655 "SAML SP $spConfKey ask to refresh session of "
656 . $req->sessionInfo->{ $self->conf->{whatToTrace} } );
657  
658 # Replay authentication process
659 $req->pdata->{targetAuthnLevel} = $spAuthnLevel;
660 return $self->reAuth($req);
661 }
662  
663 # Check Destination (only in non proxy mode)
664 unless ( $req->data->{_proxiedRequest} ) {
665 if ( !$self->checkDestination( $login->request, $url ) ) {
666 return $self->_failAuthnRequest(
667 $req,
668 msg => "Invalid destination",
669 res => PE_SAML_DESTINATION_ERROR,
670 logInfo => {
671 sp => $spConfKey,
672 entity_id => $sp,
673 },
674 );
675 }
676 }
677  
678 # Check if we have sufficient auth level
679 my $authenticationLevel =
680 $req->{sessionInfo}->{authenticationLevel} || 0;
681 if ( $authenticationLevel < $spAuthnLevel ) {
682 $self->logger->debug(
683 "Insufficient authentication level for service $spConfKey"
684 . " (has: $authenticationLevel, want: $spAuthnLevel)" );
685  
686 # Reauth with sp auth level as target
687 $req->pdata->{targetAuthnLevel} = $spAuthnLevel;
688 return $self->upgradeAuth($req);
689 }
690  
691 $authn_context =
692 $self->authnLevel2authnContext($authenticationLevel);
693  
694 $self->logger->debug("Authentication context is $authn_context");
695  
696 # Get SP options notOnOrAfterTimeout
697 my $notOnOrAfterTimeout =
698 $self->spOptions->{$sp}
699 ->{samlSPMetaDataOptionsNotOnOrAfterTimeout};
700  
701 # Build Assertion
702 unless (
703 $self->buildAssertion(
704 $req, $login, $authn_context, $notOnOrAfterTimeout
705 )
706 )
707 {
708 return $self->_failAuthnRequest(
709 $req,
710 msg => "Unable to build assertion",
711 logInfo => {
712 sp => $spConfKey,
713 entity_id => $sp,
714 },
715 );
716 }
717  
718 $self->logger->debug("SSO: assertion is built");
719  
720 # Get session key associated with NameIDFormat
721 # Not for unspecified, transient, persistent, entity, encrypted
722 my $nameIDFormatConfiguration = {
723 $self->getNameIDFormat("email") => 'samlNameIDFormatMapEmail',
724 $self->getNameIDFormat("x509") => 'samlNameIDFormatMapX509',
725 $self->getNameIDFormat("windows") =>
726 'samlNameIDFormatMapWindows',
727 $self->getNameIDFormat("kerberos") =>
728 'samlNameIDFormatMapKerberos',
729 };
730  
731 my $nameIDSessionKey =
732 $nameIDFormatConfiguration->{$nameIDFormat}
733 ? $self->conf->{ $nameIDFormatConfiguration->{$nameIDFormat} }
734 : '';
735  
736 # Override default NameID Mapping
737 if (
738 $self->spOptions->{$sp}->{samlSPMetaDataOptionsNameIDSessionKey}
739 )
740 {
741 $nameIDSessionKey =
742 $self->spOptions->{$sp}
743 ->{samlSPMetaDataOptionsNameIDSessionKey};
744 }
745  
746 my $nameIDContent;
747 if ( $nameIDSessionKey
748 and $self->spMacros->{$spConfKey}->{$nameIDSessionKey} )
749 {
750 $nameIDContent =
751 $self->spMacros->{$spConfKey}->{$nameIDSessionKey}
752 ->( $req, $req->{sessionInfo} );
753 }
754 elsif ( $nameIDSessionKey
755 and ( defined $req->{sessionInfo}->{$nameIDSessionKey} ) )
756 {
757 $nameIDContent =
758 $self->p->getFirstValue(
759 $req->{sessionInfo}->{$nameIDSessionKey} );
760 }
761  
762 # Manage Entity NameID format
763 if ( $nameIDFormat eq $self->getNameIDFormat("entity") ) {
764 $nameIDContent = $self->getMetaDataURL( "samlEntityID", 0, 1 );
765 }
766  
767 # Manage Transient NameID format
768 if ( $nameIDFormat eq $self->getNameIDFormat("transient") ) {
769 eval {
770 my @assert = $login->response->Assertion;
771 $nameIDContent = $assert[0]->Subject->NameID->content;
772 };
773 }
774  
775 if ( $login->nameIdentifier ) {
776 $login->nameIdentifier->Format($nameIDFormat);
777 $login->nameIdentifier->content($nameIDContent)
778 if $nameIDContent;
779 }
780 else {
781 my $nameIdentifier = Lasso::Saml2NameID->new();
782 $nameIdentifier->Format($nameIDFormat);
783 $nameIdentifier->content($nameIDContent)
784 if $nameIDContent;
785 $login->nameIdentifier($nameIdentifier);
786 }
787  
788 $self->logger->debug(
789 "NameID Format is " . $login->nameIdentifier->Format );
790 $self->logger->debug( "NameID Content is "
791 . ( $login->nameIdentifier->content || "" ) );
792  
793 # Push attributes
794 my @attributes;
795 my %log_attributes;
796  
797 foreach ( keys %{ $self->spAttributes->{$sp} } ) {
798  
799 # Extract fields from exportedAttr value
800 my ( $mandatory, $name, $format, $friendly_name ) =
801 split( /;/, $self->spAttributes->{$sp}->{$_} );
802  
803 # Name is required
804 next unless $name;
805  
806 if ( $_ eq "__persistent_name_id" ) {
807  
808 my $value;
809  
810 # If a persistent nameID is returned as the NameID,
811 # reuse it as the attribute value
812 if ( $login->nameIdentifier->Format eq
813 $self->getNameIDFormat("persistent") )
814 {
815 $value = $login->nameIdentifier;
816  
817 }
818  
819 # Check whether the value is required or not
820 unless ( defined $value ) {
821 if ($mandatory) {
822 return $self->_failAuthnRequest(
823 $req,
824 msg => (
825 "Persistent NameID is required to set"
826 . " SAML $name attribute ($sp)"
827 ),
828 res => PE_ISSUERMISSINGREQATTR,
829 logInfo => {
830 sp => $spConfKey,
831 entity_id => $sp,
832 },
833 );
834 }
835 else {
836 $self->logger->debug(
837 "SAML2 attribute $name has no value"
838 . " but is not mandatory ($sp), skip it" );
839 next;
840 }
841 }
842  
843 $self->logger->debug( "SAML2 attribute $name will be set"
844 . " with persistent NameID" );
845  
846 # SAML2 attribute
847 my $attribute =
848 $self->createAttribute( $name, $format, $friendly_name );
849  
850 unless ($attribute) {
851 return $self->_failAuthnRequest(
852 $req,
853 msg => "Unable to create a new SAML attribute",
854 logInfo => {
855 sp => $spConfKey,
856 entity_id => $sp,
857 },
858 );
859 }
860  
861 my $saml2value = $self->createAttributeValue($value);
862  
863 unless ($saml2value) {
864 $self->checkLassoError($@);
865 return $self->_failAuthnRequest(
866 $req,
867 msg =>
868 "Unable to create a new SAML attribute value",
869 logInfo => {
870 sp => $spConfKey,
871 entity_id => $sp,
872 },
873 );
874 }
875  
876 $attribute->AttributeValue($saml2value);
877  
878 # Push attribute in attribute list
879 push @attributes, $attribute;
880  
881 # For logging
882 $log_attributes{ $friendly_name || $name } =
883 [ eval { $value->dump } ];
884  
885 }
886 else {
887 # Lookup attribute value in SP macros or session
888 my $value;
889 if ( $self->spMacros->{$spConfKey}->{$_} ) {
890 $value = $self->spMacros->{$spConfKey}->{$_}
891 ->( $req, $req->{sessionInfo} );
892 }
893 else {
894 $value = $req->{sessionInfo}->{$_};
895 }
896  
897 # Check whether the value is required or not
898 unless ( defined $value ) {
899 if ($mandatory) {
900 return $self->_failAuthnRequest(
901 $req,
902 msg => (
903 "Session key $_ is required to set"
904 . " SAML $name attribute ($sp)"
905 ),
906 res => PE_ISSUERMISSINGREQATTR,
907 logInfo => {
908 sp => $spConfKey,
909 entity_id => $sp,
910 },
911 );
912 }
913 else {
914 $self->logger->debug(
915 "SAML2 attribute $name has no value"
916 . " but is not mandatory ($sp), skip it" );
917 next;
918 }
919 }
920  
921 $self->logger->debug( "SAML2 attribute $name will be set"
922 . " with $_ session key ($sp)" );
923  
924 # SAML2 attribute
925 my $attribute =
926 $self->createAttribute( $name, $format, $friendly_name );
927  
928 unless ($attribute) {
929 return $self->_failAuthnRequest(
930 $req,
931 msg => "Unable to create a new SAML attribute",
932 logInfo => {
933 sp => $spConfKey,
934 entity_id => $sp,
935 },
936 );
937 }
938  
939 # Set attribute value(s)
940 my @values = split $self->conf->{multiValuesSeparator},
941 $value;
942 my @saml2values;
943  
944 foreach (@values) {
945  
946 # SAML2 attribute value
947 my $saml2value = $self->createAttributeValue( $_,
948 $self->spOptions->{$sp}
949 ->{samlSPMetaDataOptionsForceUTF8} );
950  
951 unless ($saml2value) {
952 $self->checkLassoError($@);
953 return $self->_failAuthnRequest(
954 $req,
955 msg =>
956 "Unable to create a new SAML attribute value",
957 logInfo => {
958 sp => $spConfKey,
959 entity_id => $sp,
960 },
961 );
962 }
963  
964 push @saml2values, $saml2value;
965  
966 $self->logger->debug("Push $_ in SAML attribute $name");
967  
968 }
969  
970 $attribute->AttributeValue(@saml2values);
971  
972 # Push attribute in attribute list
973 push @attributes, $attribute;
974  
975 # For logging
976 $log_attributes{ $friendly_name || $name } = [@values];
977 }
978 }
979  
980 # Get response assertion
981 my @response_assertions = $login->response->Assertion;
982  
983 unless ( $response_assertions[0] ) {
984 return $self->_failAuthnRequest(
985 $req,
986 msg => "Unable to get response assertion",
987 logInfo => {
988 sp => $spConfKey,
989 entity_id => $sp,
990 },
991 );
992 }
993  
994 # Rewrite Issuer with domain
995 if ($domain) {
996 my $original_issuer = $login->response->Issuer->content;
997 $self->logger->debug(
998 "Add domain $domain to Issuer $original_issuer");
999 my $new_issuer = $original_issuer . "?domain=$domain";
1000 $login->response->Issuer->content($new_issuer);
1001 $login->response->Assertion->Issuer->content($new_issuer);
1002 }
1003  
1004 # Set subject NameID
1005 $response_assertions[0]
1006 ->set_subject_name_id( $login->nameIdentifier );
1007  
1008 # Set basic conditions
1009 my $oneTimeUse =
1010 $self->spOptions->{$sp}->{samlSPMetaDataOptionsOneTimeUse} // 0;
1011  
1012 my $conditionNotOnOrAfter = $notOnOrAfterTimeout || "86400";
1013 eval {
1014 $response_assertions[0]
1015 ->set_basic_conditions( 60, $conditionNotOnOrAfter,
1016 $oneTimeUse );
1017 };
1018 if ($@) {
1019 $self->logger->debug("Basic conditions not set: $@");
1020 }
1021  
1022 # Create attribute statement
1023 if ( scalar @attributes ) {
1024  
1025 my $attribute_statement;
1026  
1027 eval {
1028 $attribute_statement =
1029 Lasso::Saml2AttributeStatement->new();
1030 };
1031 if ($@) {
1032 $self->checkLassoError($@);
1033 return $self->_failAuthnRequest(
1034 $req,
1035 msg => "Unable to create attribute statement",
1036 logInfo => {
1037 sp => $spConfKey,
1038 entity_id => $sp,
1039 },
1040 );
1041 }
1042  
1043 # Register attributes in attribute statement
1044 $attribute_statement->Attribute(@attributes);
1045  
1046 # Add attribute statement in response assertion
1047 my @attributes_statement = ($attribute_statement);
1048 $response_assertions[0]
1049 ->AttributeStatement(@attributes_statement);
1050 }
1051  
1052 # Get AuthnStatement
1053 my @authn_statements = $response_assertions[0]->AuthnStatement();
1054  
1055 # Set sessionIndex
1056 my $sessionIndexSession = $self->getSamlSession();
1057 if ( !$sessionIndexSession ) {
1058 return $self->_failAuthnRequest(
1059 $req,
1060 msg => "Unable to create SAML Session",
1061 res => PE_SAML_SESSION_ERROR,
1062 logInfo => {
1063 sp => $spConfKey,
1064 entity_id => $sp,
1065 },
1066 );
1067 }
1068  
1069 $sessionIndexSession->update(
1070 { '_utime' => time, '_saml_id' => $session_id } );
1071 my $sessionIndex = $sessionIndexSession->id;
1072  
1073 $authn_statements[0]->SessionIndex($sessionIndex);
1074  
1075 $self->logger->debug(
1076 "Set sessionIndex $sessionIndex (linked to session $session_id)"
1077 );
1078  
1079 # Set SessionNotOnOrAfter
1080 my $end_session_time = $time + $self->conf->{timeout};
1081  
1082 # If a timeout for the SP's session has been set, use it unless the
1083 # SSO session is already about to expire
1084 my $sessionNotOnOrAfterTimeout =
1085 $self->spOptions->{$sp}
1086 ->{samlSPMetaDataOptionsSessionNotOnOrAfterTimeout};
1087 if ( $sessionNotOnOrAfterTimeout
1088 and ( time + $sessionNotOnOrAfterTimeout < $end_session_time ) )
1089 {
1090  
1091 $end_session_time = time + $sessionNotOnOrAfterTimeout;
1092 }
1093  
1094 my $sessionNotOnOrAfter =
1095 $self->timestamp2samldate($end_session_time);
1096 $authn_statements[0]->SessionNotOnOrAfter($sessionNotOnOrAfter);
1097  
1098 $self->logger->debug(
1099 "Set sessionNotOnOrAfter $sessionNotOnOrAfter");
1100  
1101 # Register AuthnStatement in assertion
1102 $response_assertions[0]->AuthnStatement(@authn_statements);
1103  
1104 # Set response assertion
1105 $login->response->Assertion(@response_assertions);
1106  
1107 # Signature
1108 my $signSSOMessage =
1109 $self->spOptions->{$sp}->{samlSPMetaDataOptionsSignSSOMessage}
1110 // -1;
1111  
1112 if ( $signSSOMessage == 0 ) {
1113 $self->logger->debug("SSO response will not be signed");
1114 $self->disableSignature($login);
1115 }
1116 elsif ( $signSSOMessage == 1 ) {
1117 $self->logger->debug("SSO response will be signed");
1118 $self->forceSignature($login);
1119 }
1120 else {
1121 $self->logger->debug(
1122 "SSO response signature according to metadata");
1123 }
1124  
1125 $h =
1126 $self->p->processHook( $req, 'samlBuildAuthnResponse', $login );
1127 return $self->_failAuthnRequest(
1128 $req,
1129 msg => 'samlBuildAuthnResponse hook failed',
1130 res => $h,
1131 logInfo => {
1132 sp => $spConfKey,
1133 entity_id => $sp,
1134 },
1135 ) if ( $h != PE_OK );
1136  
1137 # Build SAML response
1138 $protocolProfile = $login->protocolProfile();
1139  
1140 # Artifact
1141 # Choose method
1142 if ( $artifact
1143 or $protocolProfile ==
1144 Lasso::Constants::LOGIN_PROTOCOL_PROFILE_BRWS_ART )
1145 {
1146 $artifact = 1;
1147 if ( $method == $self->getHttpMethod("post")
1148 || $method == $self->getHttpMethod("artifact-post") )
1149 {
1150 $artifact_method = $self->getHttpMethod("artifact-post");
1151  
1152 }
1153 else {
1154 $artifact_method = $self->getHttpMethod("artifact-get");
1155 }
1156 }
1157  
1158 if ( $protocolProfile ==
1159 Lasso::Constants::LOGIN_PROTOCOL_PROFILE_BRWS_ART )
1160 {
1161  
1162 # Build artifact message
1163 unless ( $self->buildArtifactMsg( $login, $artifact_method ) ) {
1164 return $self->_failAuthnRequest(
1165 $req,
1166 msg => "Unable to build SSO artifact response message",
1167 res => PE_SAML_ART_ERROR,
1168 logInfo => {
1169 sp => $spConfKey,
1170 entity_id => $sp,
1171 },
1172 );
1173 }
1174  
1175 $self->logger->debug("SSO: artifact response is built");
1176  
1177 # Get artifact ID and Content, and store them
1178 my $artifact_id = $login->get_artifact;
1179 my $artifact_message = $login->get_artifact_message;
1180  
1181 $self->storeArtifact( $artifact_id, $artifact_message,
1182 $session_id );
1183 }
1184  
1185 # No artifact
1186 else {
1187  
1188 unless ( $self->buildAuthnResponseMsg($login) ) {
1189 return $self->_failAuthnRequest(
1190 $req,
1191 msg => "Unable to build SSO response message",
1192 logInfo => {
1193 sp => $spConfKey,
1194 entity_id => $sp,
1195 },
1196 );
1197 }
1198  
1199 $self->logger->debug("SSO: authentication response is built");
1200  
1201 }
1202  
1203 # Save Identity and Session
1204 if ( $login->is_identity_dirty ) {
1205  
1206 # Update session
1207 $self->logger->debug("Save Lasso identity in session");
1208 $self->p->updatePersistentSession( $req,
1209 { $self->liDump => $login->get_identity->dump },
1210 undef, $session_id );
1211 }
1212  
1213 if ( $login->is_session_dirty ) {
1214 $self->logger->debug("Save Lasso session in session");
1215 $self->p->updateSession( $req,
1216 { $self->lsDump => $login->get_session->dump },
1217 $session_id );
1218 }
1219  
1220 # Keep SAML elements for later queries
1221 my $nameid = $login->nameIdentifier;
1222  
1223 $self->logger->debug( "Store NameID "
1224 . $nameid->dump
1225 . " and SessionIndex $sessionIndex for session $session_id" );
1226  
1227 my $infos;
1228  
1229 $infos->{type} = 'saml'; # Session type
1230 $infos->{_utime} = $time; # Creation time
1231 $infos->{_saml_id} = $session_id; # SSO session id
1232 $infos->{_nameID} = $nameid->dump; # SAML NameID
1233 $infos->{_sessionIndex} = $sessionIndex; # SAML SessionIndex
1234  
1235 my $samlSessionInfo = $self->getSamlSession( undef, $infos );
1236  
1237 if ( !$samlSessionInfo ) {
1238 return $self->_failAuthnRequest(
1239 $req,
1240 msg => "Could not get SAML session",
1241 res => PE_SAML_SESSION_ERROR,
1242 logInfo => {
1243 sp => $spConfKey,
1244 entity_id => $sp,
1245 },
1246 );
1247 }
1248  
1249 my $saml_session_id = $samlSessionInfo->id;
1250  
1251 $self->logger->debug(
1252 "Link session $session_id to SAML session $saml_session_id");
1253  
1254 $self->p->registerProtectedAppAccess( $req,
1255 $req->{sessionInfo}->{ $self->conf->{whatToTrace} },
1256 "saml:$spConfKey" );
1257  
1258 # Send SSO Response
1259  
1260 # Register IDP in Common Domain Cookie if needed
1261 if ( $self->conf->{samlCommonDomainCookieActivation}
1262 and $self->conf->{samlCommonDomainCookieWriter} )
1263 {
1264 my $cdc_idp = $self->getMetaDataURL( "samlEntityID", 0, 1 );
1265  
1266 $self->logger->debug(
1267 "Will register IDP $cdc_idp in Common Domain Cookie");
1268  
1269 # Redirection to CDC Writer page in a hidden iframe
1270 my $cdc_writer_url =
1271 $self->conf->{samlCommonDomainCookieWriter};
1272 $cdc_writer_url .= (
1273 $self->conf->{samlCommonDomainCookieWriter} =~ /\?/
1274 ? '&idp=' . $cdc_idp
1275 : '?url=' . $cdc_idp
1276 );
1277  
1278 my $cdc_iframe =
1279 qq'<iframe src="$cdc_writer_url"'
1280 . ' alt="Common Dommain Cookie" marginwidth="0"'
1281 . ' marginheight="0" scrolling="no" class="hiddenFrame"'
1282 . ' width="0" height="0" frameborder="0"></iframe>';
1283  
1284 $req->info(
1285 $self->loadTemplate(
1286 $req, 'simpleInfo',
1287 params => { trspan => 'updateCdc' }
1288 )
1289 . $cdc_iframe
1290 );
1291 }
1292  
1293 # log that a SAML authn response is build
1294 my $user = $req->{sessionInfo}->{ $self->conf->{whatToTrace} };
1295 my $nameIDLog = '';
1296 foreach my $format (qw(persistent transient)) {
1297 if ( $login->nameIdentifier->Format eq
1298 $self->getNameIDFormat($format) )
1299 {
1300 $nameIDLog =
1301 " with $format NameID " . $login->nameIdentifier->content;
1302 last;
1303 }
1304 }
1305 my $name_id_content = $login->nameIdentifier->content;
1306 my $attr_str = (
1307 %log_attributes
1308 ? ( " with attributes "
1309 . join( ',', sort( keys(%log_attributes) ) ) )
1310 : ""
1311 );
1312  
1313 # HTTP-POST
1314 if ( (
1315 !$artifact
1316 and $protocolProfile eq
1317 Lasso::Constants::LOGIN_PROTOCOL_PROFILE_BRWS_POST
1318 )
1319 or ( $artifact
1320 and $artifact_method ==
1321 $self->getHttpMethod("artifact-post") )
1322 )
1323 {
1324  
1325 $self->auditLog(
1326 $req,
1327 code => "ISSUER_SAML_LOGIN_SUCCESS",
1328 entity_id => $sp,
1329 sp => $spConfKey,
1330 message => (
1331 'User '
1332 . $req->sessionInfo->{ $self->conf->{whatToTrace} }
1333 . " is authorized to access $sp."
1334 . " SAML authentication response sent to"
1335 . " SAML SP $spConfKey for $user$nameIDLog$attr_str"
1336 ),
1337 user => $user,
1338 saml_name_id => $name_id_content,
1339 attributes => \%log_attributes,
1340 );
1341  
1342 # Use autosubmit form
1343 my $sso_url = $login->msg_url;
1344 my $sso_body = $login->msg_body;
1345  
1346 $req->postUrl($sso_url);
1347  
1348 if ( $artifact_method
1349 and $artifact_method ==
1350 $self->getHttpMethod("artifact-post") )
1351 {
1352 $req->{postFields} = { 'SAMLart' => $sso_body };
1353 }
1354 else {
1355 $req->{postFields} = { 'SAMLResponse' => $sso_body };
1356 }
1357  
1358 # RelayState
1359 if ($relaystate) {
1360 $req->{postFields}->{'RelayState'} =
1361 encode_entities($relaystate);
1362 $req->data->{safeHiddenFormValues}->{RelayState} = 1;
1363 }
1364  
1365 $req->steps( ['autoPost'] );
1366 return PE_OK;
1367 }
1368  
1369 # HTTP-REDIRECT
1370 if ( $protocolProfile eq
1371 Lasso::Constants::LOGIN_PROTOCOL_PROFILE_REDIRECT or $artifact )
1372 {
1373  
1374 $self->auditLog(
1375 $req,
1376 code => "ISSUER_SAML_LOGIN_SUCCESS",
1377 entity_id => $sp,
1378 sp => $spConfKey,
1379 message => (
1380 'User '
1381 . $req->sessionInfo->{ $self->conf->{whatToTrace} }
1382 . " is authorized to access $sp."
1383 . " SAML authentication response sent to"
1384 . " SAML SP $spConfKey for $user$nameIDLog$attr_str"
1385 ),
1386 user => $user,
1387 saml_name_id => $name_id_content,
1388 attributes => \%log_attributes,
1389 );
1390  
1391 # Redirect user to response URL
1392 my $sso_url = $login->msg_url;
1393 $self->logger->debug("Redirect user to $sso_url");
1394  
1395 $req->{urldc} = $sso_url;
1396 $req->mustRedirect(1);
1397 $req->steps( [] );
1398  
1399 return PE_OK;
1400 }
1401  
1402 }
1403  
1404 elsif ($response) {
1405 $self->logger->debug(
1406 "Authentication responses are not managed by this module");
1407 return PE_OK;
1408 }
1409  
1410 else {
1411  
1412 # No request or response
1413 # This should not happen
1414 $self->logger->debug("No request or response found");
1415 return PE_OK;
1416 }
1417  
1418 }
1419 $self->logger->debug("Not an issuer request $url");
1420 return PE_OK;
1421 }
1422  
1423 sub _failAuthnRequest {
1424 my ( $self, $req, %params ) = @_;
1425  
1426 my $reason = $params{'msg'} ? ": $params{'msg'}" : "";
1427 my $res = $params{res} || PE_SAML_SSO_ERROR;
1428 my $user = $req->sessionInfo->{ $self->conf->{whatToTrace} };
1429 my %logInfo = %{ $params{logInfo} || {} };
1430  
1431 $self->auditLog(
1432 $req,
1433 code => "ISSUER_SAML_LOGIN_FAILED",
1434 message => ( "SAML login failed" . $reason ),
1435 ( $params{'msg'} ? ( reason => $params{'msg'} ) : () ),
1436 portal_error => portalConsts->{$res},
1437 user => $user,
1438 %logInfo,
1439 );
1440  
1441 return $res;
1442 }
1443  
1444 sub artifactServer {
1445 my ( $self, $req ) = @_;
1446 $self->logger->debug( "URL "
1447 . $req->uri
1448 . " detected as an artifact resolution service URL" );
1449  
1450 # Artifact request are sent with SOAP trough POST
1451 my $art_request = $req->content;
1452 my $art_response;
1453  
1454 # Create Login object
1455 my $login = $self->createLogin( $self->lassoServer );
1456  
1457 # Process request message
1458 unless ( $self->processArtRequestMsg( $login, $art_request ) ) {
1459 return $self->p->sendError( $req,
1460 'Unable to process artifact request message', 400 );
1461 }
1462  
1463 # Check Destination
1464 unless ( $self->checkDestination( $login->request, $req->uri ) ) {
1465 return $self->p->sendError( $req, 'Bad request', 400 );
1466 }
1467  
1468 # Create artifact response
1469 unless ( $art_response = $self->createArtifactResponse( $req, $login ) ) {
1470 return $self->p->sendError( $req,
1471 "Unable to create artifact response message", 400 );
1472 }
1473  
1474 $self->{SOAPMessage} = $art_response;
1475  
1476 # Return SOAP message
1477 $self->logger->debug("Send SOAP Message: $art_response");
1478 return $self->p->sendBinaryResponse( $req, $art_response,
1479 type => 'text/xml' );
1480 }
1481  
1482 sub soapSloServer {
1483 my ( $self, $req ) = @_;
1484 my $url = $req->uri;
1485 my $request_method = $req->param('issuerMethod') || $req->method;
1486 my $content_type = $req->content_type();
1487  
1488 $self->logger->debug("URL $url detected as an SLO URL");
1489  
1490 # Check SAML Message
1491 my ( $request, $response, $method, $relaystate, $artifact ) =
1492 $self->checkMessage( $req, $url, $request_method, $content_type,
1493 "logout" );
1494  
1495 # Create Logout object
1496 my $logout = $self->createLogout( $self->lassoServer );
1497  
1498 # Ignore signature verification
1499 $self->disableSignatureVerification($logout);
1500  
1501 if ($request) {
1502  
1503 # Process logout request
1504 unless ( $self->processLogoutRequestMsg( $logout, $request ) ) {
1505 return $self->p->sendError( $req,
1506 "SLO: Fail to process logout request", 400 );
1507 }
1508  
1509 $self->logger->debug("SLO: Logout request is valid");
1510  
1511 my $h = $self->p->processHook( $req, 'samlGotLogoutRequest', $logout );
1512 if ( $h != PE_OK ) {
1513 return $self->p->sendError( $req,
1514 "SLO: samlGotLogoutRequest hook returned error", 400 );
1515 }
1516  
1517 # We accept only SOAP here
1518 unless ( $method eq $self->getHttpMethod('soap') ) {
1519 return $self->p->sendError( $req,
1520 "Only SOAP requests allowed here", 400 );
1521 }
1522  
1523 # Get SP entityID
1524 my $sp = $logout->remote_providerID();
1525  
1526 $self->logger->debug("Found entityID $sp in SAML message");
1527  
1528 # SP conf key
1529 my $spConfKey = $self->spList->{$sp}->{confKey};
1530  
1531 unless ($spConfKey) {
1532 return $self->p->sendError( $req,
1533 "$sp do not match any SP in configuration", 400 );
1534 }
1535  
1536 $self->logger->debug("$sp match $spConfKey SP in configuration");
1537  
1538 # Do we check signature?
1539 my $checkSLOMessageSignature =
1540 $self->spOptions->{$sp}
1541 ->{samlSPMetaDataOptionsCheckSLOMessageSignature};
1542  
1543 if ($checkSLOMessageSignature) {
1544  
1545 $self->forceSignatureVerification($logout);
1546  
1547 unless ( $self->processLogoutRequestMsg( $logout, $request ) ) {
1548 return $self->p->sendError( $req, "Signature is not valid",
1549 400 );
1550 }
1551 else {
1552 $self->logger->debug("Signature is valid");
1553 }
1554 }
1555 else {
1556 $self->logger->debug("Message signature will not be checked");
1557 }
1558  
1559 # Get SAML request
1560 my $saml_request = $logout->request();
1561 unless ($saml_request) {
1562 return $self->p->sendError( $req, "No SAML request found", 400 );
1563 }
1564  
1565 # Check Destination
1566 return $self->sendSLOSoapErrorResponse( $req, $logout, $method )
1567 unless ( $self->checkDestination( $saml_request, $url ) );
1568  
1569 # Get session index
1570 my $session_index;
1571 eval { $session_index = $logout->request()->SessionIndex; };
1572  
1573 # SLO requests without session index are not accepted in SOAP mode
1574 unless ( defined $session_index ) {
1575 $self->p->sendError( $req,
1576 "No session index in SLO request from $spConfKey SP", 400 );
1577 }
1578  
1579 # Get session index
1580 my $sessionIndexSession = $self->getSamlSession($session_index);
1581 return $self->p->sendError( $req, 'SAML session not found', 400 )
1582 unless $sessionIndexSession;
1583  
1584 my $local_session_id = $sessionIndexSession->data->{_saml_id};
1585  
1586 $sessionIndexSession->remove;
1587  
1588 $self->logger->debug( "Get session id $local_session_id"
1589 . " (from session index $session_index)" );
1590  
1591 # Open local session
1592 my $local_session = $self->p->getApacheSession($local_session_id);
1593  
1594 unless ($local_session) {
1595 return $self->p->sendError( $req, "No local session found", 400 );
1596 }
1597  
1598 # Load Session and Identity if they exist
1599 my $session = $local_session->data->{ $self->lsDump };
1600 my $identity = $local_session->data->{ $self->liDump };
1601  
1602 if ($session) {
1603 unless ( $self->setSessionFromDump( $logout, $session ) ) {
1604 return $self->p->sendError( $req,
1605 "Unable to load Lasso Session", 400 );
1606 }
1607 $self->logger->debug("Lasso Session loaded");
1608 }
1609  
1610 if ($identity) {
1611 unless ( $self->setIdentityFromDump( $logout, $identity ) ) {
1612 return $self->p->sendError( $req,
1613 "Unable to load Lasso Identity", 400 );
1614 }
1615 $self->logger->debug("Lasso Identity loaded");
1616 }
1617  
1618 # Close SAML sessions
1619 unless ( $self->deleteSAMLSecondarySessions($local_session_id) ) {
1620 return $self->p->sendError( $req, "Fail to delete SAML sessions",
1621 400 );
1622 }
1623  
1624 # Close local session
1625 unless ( $self->p->_deleteSession( $req, $local_session ) ) {
1626 return $self->p->sendError( $req,
1627 "Fail to delete session $local_session_id", 400 );
1628 }
1629  
1630 # Validate request if no previous error
1631 unless ( $self->validateLogoutRequest($logout) ) {
1632 return $self->p->sendError( $req, "SLO request is not valid", 400 );
1633 }
1634  
1635 # Try to send SLO request trough SOAP
1636 $self->resetProviderIdIndex($logout);
1637 while ( my $providerID = $self->getNextProviderId($logout) ) {
1638  
1639 # Send logout request
1640 my ( $rstatus, $rmethod, $rinfo ) =
1641 $self->sendLogoutRequestToProvider( $logout, $providerID,
1642 $self->getHttpMethod('soap'), 0 );
1643  
1644 if ($rstatus) {
1645 $self->logger->debug("SOAP SLO successful on $providerID");
1646 }
1647 else {
1648 $self->logger->debug("SOAP SLO error on $providerID");
1649 }
1650 }
1651  
1652 # Set RelayState
1653 if ($relaystate) {
1654 $logout->msg_relayState($relaystate);
1655 $self->logger->debug("Set $relaystate in RelayState");
1656 }
1657  
1658 # Signature
1659 my $signSLOMessage =
1660 $self->spOptions->{$sp}->{samlSPMetaDataOptionsSignSLOMessage} // 0;
1661  
1662 if ( $signSLOMessage == 0 ) {
1663 $self->logger->debug("SLO response will not be signed");
1664 $self->disableSignature($logout);
1665 }
1666 elsif ( $signSLOMessage == 1 ) {
1667 $self->logger->debug("SLO response will be signed");
1668 $self->forceSignature($logout);
1669 }
1670 else {
1671 $self->logger->debug(
1672 "SLO response signature according to metadata");
1673 }
1674  
1675 $h = $self->p->processHook( $req, 'samlBuildLogoutResponse', $logout );
1676 if ( $h != PE_OK ) {
1677 return $self->p->sendError( $req,
1678 "SLO: samlBuildLogoutResponse hook returned error", 400 );
1679 }
1680  
1681 # Send logout response
1682 unless ( $self->buildLogoutResponseMsg($logout) ) {
1683 $self->logger->error("Unable to build SLO response for $spConfKey");
1684 return $self->p->sendError( $req, 'Unable to build SLO response',
1685 400 );
1686 }
1687 my $slo_body = $logout->msg_body;
1688 return $self->p->sendBinaryResponse( $req, $slo_body,
1689 type => 'text/xml' );
1690 }
1691  
1692 }
1693  
1694 sub logout {
1695 my ( $self, $req ) = @_;
1696 return PE_OK if ( $req->data->{samlSLOCalled} );
1697  
1698 # Session ID
1699 my $session_id = $req->{sessionInfo}->{_session_id} || $req->id;
1700  
1701 # Close SAML sessions
1702 unless ( $self->deleteSAMLSecondarySessions($session_id) ) {
1703 $self->logger->error("Fail to delete SAML sessions");
1704 }
1705  
1706 # Create Logout object
1707 my $logout = $self->createLogout( $self->lassoServer );
1708  
1709 # Load Session and Identity if they exist
1710 my $session = $req->{sessionInfo}->{ $self->lsDump };
1711 my $identity = $req->{sessionInfo}->{ $self->liDump };
1712  
1713 if ($session) {
1714 unless ( $self->setSessionFromDump( $logout, $session ) ) {
1715 $self->logger->error("Unable to load Lasso Session");
1716 return PE_SLO_ERROR;
1717 }
1718 $self->logger->debug("Lasso Session loaded");
1719 }
1720  
1721 # No need to initiate logout requests on SP, if no SAML session is
1722 # available into the session.
1723 else {
1724 $self->logger->debug('No SAML session available into this session');
1725 return PE_OK;
1726 }
1727  
1728 if ($identity) {
1729 unless ( $self->setIdentityFromDump( $logout, $identity ) ) {
1730 $self->logger->error("Unable to load Lasso Identity");
1731 return PE_SLO_ERROR;
1732 }
1733 $self->logger->debug("Lasso Identity loaded");
1734 }
1735  
1736 # Proceed to logout on all others SP.
1737 # Verify that logout response is correctly sent. If we have to wait for
1738 # providers during HTTP-REDIRECT process, return PE_INFO to notify to wait
1739 # for them.
1740 # Redirect on logout page when all is done.
1741 if ( $self->sendLogoutRequestToProviders( $req, $logout ) ) {
1742 $req->urldc( $self->p->buildUrl( $req->portal, { logout => 1 } ) );
1743 return PE_OK;
1744 }
1745  
1746 return PE_OK;
1747 }
1748  
1749 sub sloRelaySoap {
1750 my ( $self, $req ) = @_;
1751 $self->logger->debug(
1752 "URL " . $req->uri . " detected as a SOAP relay service URL" );
1753  
1754 # Check if relay parameter is present (mandatory)
1755 my $relayID;
1756 unless ( $relayID = $req->param('relay') ) {
1757 $self->logger->error("No relayID detected");
1758 return $self->imgnok($req);
1759 }
1760  
1761 # Retrieve the corresponding data from samlStorage
1762 my $relayInfos = $self->getSamlSession($relayID);
1763 unless ($relayInfos) {
1764 $self->logger->warn("Could not get relay session $relayID");
1765 return $self->imgnok($req);
1766 }
1767  
1768 $self->logger->debug("Found relay session $relayID");
1769  
1770 # Rebuild the logout object
1771 my $logout;
1772 unless ( $logout = $self->createLogout( $self->lassoServer ) ) {
1773 $self->logger->error("Could not rebuild logout object");
1774 return $self->imgnok($req);
1775 }
1776  
1777 # Load Session and Identity if they exist
1778 my $session = $relayInfos->data->{ $self->lsDump };
1779 my $identity = $relayInfos->data->{ $self->liDump };
1780 my $providerID = $relayInfos->data->{_providerID};
1781 my $relayState = $relayInfos->data->{_relayState} // '';
1782 my $spConfKey = $self->spList->{$providerID}->{confKey};
1783  
1784 if ($session) {
1785 unless ( $self->setSessionFromDump( $logout, $session ) ) {
1786 $self->logger->error("Unable to load Lasso Session");
1787 return $self->imgnok($req);
1788 }
1789 $self->logger->debug("Lasso Session loaded");
1790 }
1791  
1792 if ($identity) {
1793 unless ( $self->setIdentityFromDump( $logout, $identity ) ) {
1794 $self->logger->error("Unable to load Lasso Identity");
1795 return $self->imgnok($req);
1796 }
1797 $self->logger->debug("Lasso Identity loaded");
1798 }
1799  
1800 # Send the logout request
1801 my ( $rstatus, $rmethod, $rinfo ) =
1802 $self->sendLogoutRequestToProvider( $req, $logout, $providerID,
1803 Lasso::Constants::HTTP_METHOD_SOAP,
1804 undef, $relayState );
1805 unless ($rstatus) {
1806 $self->logger->error(
1807 "Fail to process SOAP logout request to $providerID");
1808 return $self->imgnok($req);
1809 }
1810  
1811 # Store success status for this SLO request
1812 my $sloStatusSessionInfos =
1813 $self->getSamlSession( $relayState,
1814 { $spConfKey => 1, _utime => time() } );
1815  
1816 if ($sloStatusSessionInfos) {
1817 $self->logger->debug(
1818 "Store SLO status for $spConfKey in session $relayState");
1819 }
1820 else {
1821 $self->logger->warn(
1822 "Unable to store SLO status for $spConfKey in session $relayState");
1823 }
1824  
1825 # Delete relay session
1826 $relayInfos->remove();
1827  
1828 # SLO response is OK
1829 $self->logger->debug("Display OK status for SLO on $spConfKey");
1830 return $self->imgok($req);
1831 }
1832  
1833 sub sloRelayPost {
1834 my ( $self, $req ) = @_;
1835 $self->logger->debug(
1836 "URL " . $req->uri . " detected as a POST relay service URL" );
1837  
1838 # Check if relay parameter is present (mandatory)
1839 my $relayID;
1840 unless ( $relayID = $req->param('relay') ) {
1841 return $self->p->sendError( $req, 'No relayID detected' );
1842 }
1843  
1844 # Retrieve the corresponding data from samlStorage
1845 my $relayInfos = $self->getSamlSession($relayID);
1846 unless ($relayInfos) {
1847 return $self->p->sendError( $req,
1848 "Could not get relay session $relayID" );
1849 }
1850  
1851 $self->logger->debug("Found relay session $relayID");
1852  
1853 # Get data to build POST form
1854 $req->{postUrl} = $relayInfos->data->{url};
1855 $req->{postFields}->{'SAMLRequest'} = $relayInfos->data->{body};
1856  
1857 # RelayState
1858 if ( $relayInfos->data->{relayState} ) {
1859 $req->{postFields}->{'RelayState'} =
1860 encode_entities( $relayInfos->data->{relayState} );
1861 $req->data->{safeHiddenFormValues}->{RelayState} = 1;
1862 }
1863  
1864 # Delete relay session
1865 $relayInfos->remove();
1866 $req->frame(1);
1867 return $self->p->do( $req, ['autoPost'] );
1868 }
1869  
1870 sub sloRelayTerm {
1871 my ( $self, $req ) = @_;
1872 $self->logger->debug( "URL "
1873 . $req->uri
1874 . " detected as a SLO Termination relay service URL" );
1875  
1876 # Check if relay parameter is present (mandatory)
1877 my $relayID = $self->p->getHiddenFormValue( $req, 'relay', '', 0 )
1878 || $req->param('relay');
1879 unless ($relayID) {
1880 return $self->p->sendError( $req, 'No relayID detected' );
1881 }
1882  
1883 # Retrieve the corresponding data from samlStorage
1884 my $relayInfos = $self->getSamlSession($relayID);
1885 unless ($relayInfos) {
1886 return $self->p->sendError( $req,
1887 "Could not get relay session $relayID" );
1888 }
1889  
1890 $self->logger->debug("Found relay session $relayID");
1891  
1892 # Get data from relay session
1893 my $logout_dump = $relayInfos->data->{_logout};
1894 my $session_dump = $relayInfos->data->{_session};
1895 my $method = $relayInfos->data->{_method};
1896  
1897 unless ($logout_dump) {
1898 $self->logger->error("Could not get logout dump");
1899 return PE_SLO_ERROR;
1900 }
1901  
1902 # Rebuild Lasso::Logout object
1903 my $logout = $self->createLogout( $self->lassoServer, $logout_dump );
1904  
1905 unless ($logout) {
1906 $self->logger->error("Could not build Lasso::Logout");
1907 return PE_SLO_ERROR;
1908 }
1909  
1910 # Inject session
1911 unless ($session_dump) {
1912 $self->logger->error("Could not get session dump");
1913 return PE_SLO_ERROR;
1914 }
1915  
1916 unless ( $self->setSessionFromDump( $logout, $session_dump ) ) {
1917 $self->logger->error("Could not set session from dump");
1918 return PE_SLO_ERROR;
1919 }
1920  
1921 # Get Lasso::Session
1922 my $session = $logout->get_session();
1923  
1924 unless ($session) {
1925 $self->logger->error("Could not get session from logout");
1926 return PE_SLO_ERROR;
1927 }
1928  
1929 # Loop on assertions and remove them if SLO status is OK
1930 $self->resetProviderIdIndex($logout);
1931  
1932 while ( my $sp = $self->getNextProviderId($logout) ) {
1933  
1934 # Try to get SLO status from SLO session
1935 my $spConfKey = $self->spList->{$sp}->{confKey};
1936 my $status = $relayInfos->data->{$spConfKey};
1937  
1938 # Remove assertion if status is OK
1939 if ($status) {
1940 eval { $session->remove_assertion($sp); };
1941  
1942 if ($@) {
1943 $self->logger->warn("Unable to remove assertion for $sp");
1944 }
1945 else {
1946 $self->logger->debug("Assertion removed for $sp");
1947 }
1948 }
1949 else {
1950 $self->logger->debug(
1951 "SLO status was not ok for $sp, assertion not removed");
1952 }
1953 }
1954  
1955 # Reinject session
1956 unless ( $session->is_empty() ) {
1957 $self->setSessionFromDump( $logout, $session->dump );
1958 }
1959  
1960 # Delete relay session
1961 $relayInfos->remove();
1962  
1963 # Send SLO response
1964 if ( my $tmp =
1965 $self->sendLogoutResponseToServiceProvider( $req, $logout, $method ) )
1966 {
1967 return $tmp;
1968 }
1969 else {
1970 $self->logger->error("Fail to send SLO response");
1971 return PE_SLO_ERROR;
1972 }
1973  
1974 }
1975  
1976 sub authSloServer {
1977 my ( $self, $req ) = @_;
1978 $self->p->importHandlerData($req);
1979 return $self->sloServer($req);
1980 }
1981  
1982 sub sloResume {
1983 my ( $self, $req ) = @_;
1984  
1985 my $ResumeParams = $req->params('ResumeParams');
1986  
1987 unless ($ResumeParams) {
1988 $self->logger->error("Could not find resumption info");
1989 return PE_SLO_ERROR;
1990 }
1991  
1992 my $logoutContextSession = $self->getSamlSession($ResumeParams);
1993  
1994 unless ($logoutContextSession) {
1995 $self->logger->warn("Could not find logout context session");
1996 return PE_SLO_ERROR;
1997 }
1998  
1999 my $spConfKey = $logoutContextSession->data->{spConfKey};
2000 my $method = $logoutContextSession->data->{method};
2001 my $provider_nb = $logoutContextSession->data->{provider_nb};
2002 my $relayID = $logoutContextSession->data->{relayID};
2003  
2004 # Restore Lasso logout object from XML dump
2005 my $logout = $self->createLogout( $self->lassoServer,
2006 $logoutContextSession->data->{logout} );
2007  
2008 # Restore session info (for logout of other SPs)
2009 $req->setInfo( $logoutContextSession->data->{info} )
2010 if $logoutContextSession->data->{info};
2011  
2012 return $self->_finishSlo( $req, $logout, $method, $spConfKey,
2013 $provider_nb, $relayID );
2014 }
2015  
2016 sub _finishSlo {
2017 my ( $self, $req, $logout, $method, $spConfKey, $provider_nb, $relayID ) =
2018 @_;
2019  
2020 # Signature
2021 my $sp = $logout->remote_providerID;
2022 my $signSLOMessage = '';
2023 $signSLOMessage =
2024 $self->spOptions->{$sp}->{samlSPMetaDataOptionsSignSLOMessage}
2025 if $sp;
2026  
2027 unless ($signSLOMessage) {
2028 $self->logger->debug("Do not sign this SLO response");
2029 return $self->sendSLOErrorResponse( $req, $logout, $method )
2030 unless ( $self->disableSignature($logout) );
2031 }
2032  
2033 # If no waiting SP, return directly SLO response
2034 unless ($provider_nb) {
2035 return $self->sendLogoutResponseToServiceProvider( $req, $logout,
2036 $method );
2037 }
2038  
2039 # Else build SLO status relay URL and display info
2040 else {
2041 $req->{urldc} =
2042 $self->p->buildUrl( $req->portal, 'saml',
2043 'relaySingleLogoutTermination' );
2044 $self->p->setHiddenFormValue( $req, 'relay', $relayID, '', 0 );
2045 return $self->p->do( $req, [] );
2046 }
2047 }
2048  
2049 sub sloServer {
2050 my ( $self, $req ) = @_;
2051 my $url = $req->uri;
2052 my $request_method = $req->param('issuerMethod') || $req->method;
2053 my $content_type = $req->content_type();
2054 $self->logger->debug("URL $url detected as an SLO URL");
2055  
2056 # Check SAML Message
2057 my ( $request, $response, $method, $relaystate, $artifact ) =
2058 $self->checkMessage( $req, $url, $request_method, $content_type,
2059 "logout" );
2060  
2061 # Create Logout object
2062 my $logout = $self->createLogout( $self->lassoServer );
2063  
2064 # Ignore signature verification
2065 $self->disableSignatureVerification($logout);
2066  
2067 # Disable Content-Security-Policy header since logout can be embedded in
2068 # a frame
2069 $req->frame(1);
2070  
2071 if ($request) {
2072  
2073 # Process logout request
2074 unless ( $self->processLogoutRequestMsg( $logout, $request ) ) {
2075 return $self->p->sendError( $req,
2076 "SLO: Fail to process logout request", 400 );
2077 }
2078  
2079 $self->logger->debug("SLO: Logout request is valid");
2080  
2081 my $h = $self->p->processHook( $req, 'samlGotLogoutRequest', $logout );
2082 if ( $h != PE_OK ) {
2083 return $self->p->sendError( $req,
2084 "SLO: samlGotLogoutRequest hook returned error", 400 );
2085 }
2086  
2087 # Get SP entityID
2088 my $sp = $logout->remote_providerID();
2089 $req->env->{llng_saml_sp} = $sp;
2090  
2091 $self->logger->debug("Found entityID $sp in SAML message");
2092  
2093 # SP conf key
2094 my $spConfKey = $self->spList->{$sp}->{confKey};
2095  
2096 unless ($spConfKey) {
2097 return $self->p->sendError( $req,
2098 "$sp do not match any SP in configuration", 400 );
2099 }
2100  
2101 $self->logger->debug("$sp match $spConfKey SP in configuration");
2102 $req->env->{llng_saml_spconfkey} = $spConfKey;
2103  
2104 # Load Session and Identity if they exist
2105 my ( $session, $session_index, $identity, $local_session_id );
2106  
2107 eval { $session_index = $logout->request()->SessionIndex; };
2108  
2109 # SLO requests without session index can be accepted
2110 unless ( defined $session_index ) {
2111 $self->logger->warn(
2112 "No session index in SLO request from $spConfKey SP");
2113 }
2114  
2115 if ($session_index) {
2116 my $sessionIndexSession = $self->getSamlSession($session_index);
2117 return $self->p->doPE( $req, PE_SESSIONEXPIRED )
2118 unless $sessionIndexSession;
2119  
2120 $local_session_id = $sessionIndexSession->data->{_saml_id};
2121  
2122 $sessionIndexSession->remove;
2123  
2124 $self->logger->debug( "Get session id $local_session_id"
2125 . " (from session index $session_index)" );
2126 }
2127 else {
2128 $local_session_id = $req->id;
2129 $self->logger->debug(
2130 "Get session id $local_session_id (from cookie)");
2131 }
2132 if ( $req->{sessionInfo} ) {
2133 $session = $req->{sessionInfo}->{ $self->lsDump };
2134 $identity = $req->{sessionInfo}->{ $self->liDump };
2135 }
2136 unless ($session) {
2137  
2138 # Open local session
2139 my $local_session = $self->p->getApacheSession($local_session_id);
2140  
2141 unless ($local_session) {
2142 $self->logger->warn("No local session found");
2143 return $self->sendSLOErrorResponse( $req, $logout, $method );
2144 }
2145  
2146 # Load Session and Identity if they exist
2147 $session = $local_session->data->{ $self->lsDump };
2148 $identity = $local_session->data->{ $self->liDump };
2149  
2150 # Import user data in $req (for other "logout" subs)
2151 $req->id( $local_session->data->{_session_id} );
2152 $req->sessionInfo( $local_session->data );
2153 $req->user( $local_session->data->{ $self->conf->{whatToTrace} } );
2154 }
2155  
2156 if ($session) {
2157 unless ( $self->setSessionFromDump( $logout, $session ) ) {
2158 return $self->p->sendError( $req,
2159 "Unable to load Lasso Session", 400 );
2160 }
2161 $self->logger->debug("Lasso Session loaded");
2162 }
2163  
2164 if ($identity) {
2165 unless ( $self->setIdentityFromDump( $logout, $identity ) ) {
2166 return $self->p->sendError( $req,
2167 "Unable to load Lasso Identity", 400 );
2168 }
2169 $self->logger->debug("Lasso Identity loaded");
2170 }
2171  
2172 # Do we check signature?
2173 my $checkSLOMessageSignature =
2174 $self->spOptions->{$sp}
2175 ->{samlSPMetaDataOptionsCheckSLOMessageSignature};
2176  
2177 if ($checkSLOMessageSignature) {
2178  
2179 $self->forceSignatureVerification($logout);
2180  
2181 unless ( $self->processLogoutRequestMsg( $logout, $request ) ) {
2182 return $self->p->sendError( $req, "Signature is not valid",
2183 400 );
2184 }
2185 else {
2186 $self->logger->debug("Signature is valid");
2187 }
2188 }
2189 else {
2190 $self->logger->debug("Message signature will not be checked");
2191 }
2192  
2193 # Check Destination
2194 return $self->sendSLOErrorResponse( $req, $logout, $method )
2195 unless ( $self->checkDestination( $logout->request, $url ) );
2196  
2197 # Validate request if no previous error
2198 unless ( $self->validateLogoutRequest($logout) ) {
2199 return $self->p->sendError( $req, "SLO request is not valid", 400 );
2200 }
2201  
2202 # Set RelayState
2203 if ($relaystate) {
2204 $logout->msg_relayState($relaystate);
2205 $self->logger->debug("Set $relaystate in RelayState");
2206 }
2207  
2208 my $sloInfos;
2209 $sloInfos->{type} = 'sloStatus';
2210 $sloInfos->{_utime} = time;
2211 $sloInfos->{_logout} = $logout->dump;
2212 $sloInfos->{_session} =
2213 $logout->get_session() ? $logout->get_session()->dump : "";
2214 $sloInfos->{_method} = $method;
2215  
2216 # Create SLO status session and get ID
2217 my $sloStatusSessionInfo = $self->getSamlSession( undef, $sloInfos );
2218 my $relayID = $sloStatusSessionInfo->id;
2219  
2220 $self->logger->debug("Create relay session $relayID");
2221  
2222 # Prepare logout on all others SP
2223 my $provider_nb =
2224 $self->sendLogoutRequestToProviders( $req, $logout, $relayID );
2225  
2226 # Close SAML sessions
2227 unless ( $self->deleteSAMLSecondarySessions($local_session_id) ) {
2228 $self->logger->error("Fail to delete SAML sessions");
2229 }
2230  
2231 # Close local session
2232 # This flag is for logout() to say that SAML logout is already done
2233 $req->data->{samlSLOCalled} = 1;
2234  
2235 # This variable decides if we call the authLogout step
2236 # (which can redirect away)
2237 my $doAuthLogout = 0;
2238 my $logoutContextSession;
2239  
2240 # TODO: only propagation to SAML or OIDC issuers is supported
2241 # at the moment
2242 if ( $req->sessionInfo->{_lassoSessionDump}
2243 or $req->sessionInfo->{_oidc_OP} )
2244 {
2245  
2246 $doAuthLogout = 1;
2247  
2248 # In case we have to redirect to the IDP, save current state
2249 # to allow resumption. This needs to be done here because
2250 # issuerNextUrl will be put in the IdP logout's RelayState
2251 my $logoutInfos = {
2252 logout => $logout->dump,
2253 spConfKey => $spConfKey,
2254 method => $method,
2255 provider_nb => $provider_nb,
2256 relayID => $relayID,
2257 _utime => time(),
2258 };
2259 $logoutContextSession =
2260 $self->getSamlSession( undef, $logoutInfos );
2261 my $uri = URI->new(
2262 $self->p->buildUrl(
2263 $req->portal, 'saml', 'singleLogoutResume'
2264 )
2265 );
2266 $uri->query_param( ResumeParams => $logoutContextSession->id );
2267 $req->{issuerNextUrl} = $uri->as_string;
2268 }
2269  
2270 # We don't want info to interfere with the auth logout process
2271 my $savedInfo = $req->info;
2272 $req->setInfo('');
2273  
2274 # Launch normal logout and ignore errors
2275 my $tmp = $req->data->{nofail};
2276 $req->data->{nofail} = 1;
2277 $req->steps( [
2278 @{ $self->p->beforeLogout },
2279 ( $doAuthLogout ? 'authLogout' : () ),
2280 'deleteSession'
2281 ]
2282 );
2283 my $res = $self->p->process($req);
2284 $req->data->{nofail} = $tmp;
2285  
2286 if ( $res eq PE_REDIRECT ) {
2287  
2288 # Save session info (for logout of other SP)
2289 if ($savedInfo) {
2290 $logoutContextSession->update( { info => $savedInfo } );
2291 }
2292 return $self->p->doPE( $req, PE_REDIRECT );
2293 }
2294  
2295 $req->info($savedInfo);
2296  
2297 return $self->_finishSlo( $req, $logout, $method, $spConfKey,
2298 $provider_nb, $relayID );
2299 }
2300  
2301 elsif ($response) {
2302  
2303 # Process logout response
2304 my $result = $self->processLogoutResponseMsg( $logout, $response );
2305  
2306 unless ($result) {
2307 $self->logger->error("Fail to process logout response");
2308 $self->imgnok($req);
2309 }
2310  
2311 $self->logger->debug("Logout response is valid");
2312  
2313 my $h = $self->p->processHook( $req, 'samlGotLogoutResponse', $logout );
2314 $self->imgnok($req) if ( $h != PE_OK );
2315  
2316 # Check Destination
2317 $self->imgnok($req)
2318 unless ( $self->checkDestination( $logout->response, $url ) );
2319  
2320 # Get SP entityID
2321 my $sp = $logout->remote_providerID();
2322  
2323 $self->logger->debug("Found entityID $sp in SAML message");
2324  
2325 # SP conf key
2326 my $spConfKey = $self->spList->{$sp}->{confKey};
2327  
2328 unless ($spConfKey) {
2329 $self->logger->error("$sp do not match any SP in configuration");
2330 $self->imgnok($req);
2331 }
2332  
2333 $self->logger->debug("$sp match $spConfKey SP in configuration");
2334  
2335 # Do we check signature?
2336 my $checkSLOMessageSignature =
2337 $self->spOptions->{$sp}
2338 ->{samlSPMetaDataOptionsCheckSLOMessageSignature};
2339  
2340 if ($checkSLOMessageSignature) {
2341 unless ( $self->checkSignatureStatus($logout) ) {
2342 $self->logger->error( "Could not verify signature of"
2343 . " incoming SLO request from $spConfKey" );
2344 $self->imgnok($req);
2345 }
2346 else {
2347 $self->logger->debug("Signature is valid");
2348 }
2349 }
2350 else {
2351 $self->logger->debug("Message signature will not be checked");
2352 }
2353  
2354 # Store success status for this SLO request
2355 if ($relaystate) {
2356 my $sloStatusSessionInfos = $self->getSamlSession($relaystate);
2357  
2358 if ($sloStatusSessionInfos) {
2359 $sloStatusSessionInfos->update( { $spConfKey => 1 } );
2360 $self->logger->debug(
2361 "Store SLO status for $spConfKey in session $relaystate");
2362 }
2363 else {
2364 $self->logger->warn( "Unable to store SLO status for"
2365 . " $spConfKey in session $relaystate" );
2366 }
2367 }
2368 else {
2369 $self->logger->warn( "Unable to store SLO status for"
2370 . " $spConfKey because there is no RelayState" );
2371 }
2372  
2373 # SLO response is OK
2374 $self->logger->debug("Display OK status for SLO on $spConfKey");
2375 $self->imgok($req);
2376 }
2377  
2378 else {
2379  
2380 # No request or response
2381 # This should not happen
2382 return $self->p->sendError( $req, "No request or response found", 400 );
2383 }
2384 }
2385  
2386 sub attributeServer {
2387 my ( $self, $req, ) = @_;
2388 my $url = $req->uri;
2389 $self->logger->debug("URL $url detected as an attribute service URL");
2390  
2391 # Attribute request are sent with SOAP trough POST
2392 my $att_request = $req->content;
2393 my $att_response;
2394  
2395 # Process request
2396 my $query =
2397 $self->processAttributeRequest( $self->lassoServer, $att_request );
2398 unless ($query) {
2399 return $self->p->sendError( $req,
2400 "Unable to process attribute request", 400 );
2401 }
2402  
2403 # Get SP entityID
2404 my $sp = $query->remote_providerID();
2405  
2406 $self->logger->debug("Found entityID $sp in SAML message");
2407  
2408 # SP conf key
2409 my $spConfKey = $self->spList->{$sp}->{confKey};
2410  
2411 unless ($spConfKey) {
2412 return $self->p->sendError( $req,
2413 "$sp do not match any SP in configuration", 400 );
2414 }
2415  
2416 $self->logger->debug("$sp match $spConfKey SP in configuration");
2417  
2418 # Check Destination
2419 unless ( $self->checkDestination( $query->request, $url ) ) {
2420 return $self->p->sendError( $req, "Bad destination $url", 400 );
2421 }
2422  
2423 # Validate request
2424 unless ( $self->validateAttributeRequest($query) ) {
2425 return $self->p->sendError( $req, "Attribute request not valid", 400 );
2426 }
2427  
2428 # Get NameID
2429 my $name_id = $query->nameIdentifier();
2430  
2431 unless ($name_id) {
2432 $self->p->sendError( $req,
2433 "Fail to get NameID from attribute request", 400 );
2434 }
2435  
2436 my $user = $name_id->content();
2437  
2438 # Get sessionInfo for the given NameID
2439 my $sessionInfo;
2440  
2441 my $saml_sessions =
2442 Lemonldap::NG::Common::Apache::Session->searchOn( $self->amOpts,
2443 "_nameID", $name_id->dump );
2444  
2445 if (
2446 my @saml_sessions_keys =
2447 grep { $saml_sessions->{$_}->{_session_kind} eq $self->sessionKind }
2448 keys %$saml_sessions
2449 )
2450 {
2451  
2452 # Warning if more than one session found
2453 if ( $#saml_sessions_keys > 0 ) {
2454 $self->logger->warn(
2455 "More than one SAML session found for user $user");
2456 }
2457  
2458 # Take the first session
2459 my $saml_session = shift @saml_sessions_keys;
2460  
2461 # Get session
2462 $self->logger->debug(
2463 "Retrieve SAML session $saml_session for user $user");
2464  
2465 my $samlSessionInfo = $self->getSamlSession($saml_session);
2466  
2467 # Get real session
2468 my $real_session = $samlSessionInfo->data->{_saml_id};
2469  
2470 $self->logger->debug(
2471 "Retrieve real session $real_session for user $user");
2472  
2473 $sessionInfo = $self->p->getApacheSession($real_session);
2474  
2475 unless ($sessionInfo) {
2476 return $self->p->sendError( $req,
2477 "Cannot get session $real_session", 500 );
2478 }
2479  
2480 }
2481 else {
2482 return $self->p->sendError( $req,
2483 "No SAML session found for user $user", 400 );
2484 }
2485  
2486 # Get requested attributes
2487 my @requested_attributes;
2488 eval { @requested_attributes = $query->request()->Attribute(); };
2489 if ($@) {
2490 $self->checkLassoError($@);
2491 return $self->p->sendError( $req,
2492 "Unable to get requested attributes", 400 );
2493 }
2494  
2495 # Returned attributes
2496 my @returned_attributes;
2497  
2498 # Browse SP authorized attributes
2499 foreach ( keys %{ $self->spAttributes->{$sp} } ) {
2500 my $sp_attr = $_;
2501  
2502 # Extract fields from exportedAttr value
2503 my ( $mandatory, $name, $format, $friendly_name ) =
2504 split( /;/, $self->spAttributes->{$sp}->{$sp_attr} );
2505  
2506 foreach (@requested_attributes) {
2507 my $req_attr = $_;
2508 my $rname = $req_attr->Name();
2509 my $rformat = $req_attr->NameFormat();
2510 my $rfriendly_name = $req_attr->FriendlyName();
2511  
2512 # Skip if name does not match
2513 next unless ( $rname =~ /^$name$/ );
2514  
2515 # Check format and friendly name
2516 next if ( $rformat and $rformat !~ /^$format$/ );
2517 next
2518 if ( $rfriendly_name
2519 and $rfriendly_name !~ /^$friendly_name$/ );
2520  
2521 $self->logger->debug(
2522 "SP $spConfKey is authorized to access attribute $rname");
2523  
2524 $self->logger->debug(
2525 "Attribute $rname is linked to $sp_attr session key");
2526  
2527 # Check if values are given
2528 my $rvalue =
2529 $self->getAttributeValue( $rname, $rformat, $rfriendly_name,
2530 [$req_attr] );
2531  
2532 $self->logger->debug(
2533 "Some values are explicitly requested: $rvalue")
2534 if defined $rvalue;
2535  
2536 # Get session value
2537 if ( $sessionInfo->data->{$sp_attr} ) {
2538  
2539 my @values = split $self->conf->{multiValuesSeparator},
2540 $sessionInfo->data->{$sp_attr};
2541 my @saml2values;
2542  
2543 # SAML2 attribute
2544 my $ret_attr =
2545 $self->createAttribute( $rname, $rformat, $rfriendly_name );
2546  
2547 unless ($ret_attr) {
2548 return $self->p->sendError( $req,
2549 "Unable to create a new SAML attribute", 500 );
2550 }
2551  
2552 foreach (@values) {
2553  
2554 my $local_value = $_;
2555  
2556 # Check if values were set in requested attribute
2557 # In this case, only requested values can be returned
2558 if (
2559 $rvalue
2560 and !map( /^$local_value$/,
2561 split(
2562 $self->conf->{multiValuesSeparator}, $rvalue
2563 ) )
2564 )
2565 {
2566 $self->logger->warn( "$local_value value is not in"
2567 . " requested values, it will not be sent" );
2568 next;
2569 }
2570  
2571 # SAML2 attribute value
2572 my $saml2value = $self->createAttributeValue( $local_value,
2573 $self->spOptions->{$sp}
2574 ->{samlSPMetaDataOptionsForceUTF8} );
2575  
2576 unless ($saml2value) {
2577 return $self->p->sendError( $req,
2578 "Unable to create a new SAML attribute value",
2579 400 );
2580 }
2581  
2582 push @saml2values, $saml2value;
2583  
2584 $self->logger->debug(
2585 "Push $local_value in SAML attribute $name");
2586  
2587 }
2588  
2589 $ret_attr->AttributeValue(@saml2values);
2590  
2591 # Push attribute in attribute list
2592 push @returned_attributes, $ret_attr;
2593  
2594 }
2595 else {
2596 $self->logger->debug("No session value for $sp_attr");
2597 }
2598  
2599 }
2600  
2601 }
2602  
2603 # Create attribute statement
2604 if ( scalar @returned_attributes ) {
2605 my $attribute_statement;
2606  
2607 eval { $attribute_statement = Lasso::Saml2AttributeStatement->new(); };
2608 if ($@) {
2609 $self->checkLassoError($@);
2610 return $self->p->sendError( $req, 'An error occurs, see IdP logs',
2611 500 );
2612 }
2613  
2614 # Register attributes in attribute statement
2615 $attribute_statement->Attribute(@returned_attributes);
2616  
2617 # Create assetion
2618 my $assertion;
2619  
2620 eval { $assertion = Lasso::Saml2Assertion->new(); };
2621 if ($@) {
2622 $self->checkLassoError($@);
2623 return $self->p->sendError( $req, 'An error occurs, see IdP logs',
2624 500 );
2625 }
2626  
2627 # Add attribute statement in response assertion
2628 my @attributes_statement = ($attribute_statement);
2629 $assertion->AttributeStatement(@attributes_statement);
2630  
2631 # Set response assertion
2632 $query->response->Assertion( ($assertion) );
2633 }
2634  
2635 # Build response
2636 $att_response = $self->buildAttributeResponse($query);
2637  
2638 unless ($att_response) {
2639 $self->p->sendError( $req, "Unable to build attribute response", 500 );
2640 }
2641  
2642 return $self->p->sendBinaryResponse( $req, $att_response,
2643 type => 'text/xml' );
2644 }
2645  
2646 # LEGACY METHODS
2647 # Remove in 3.0
2648  
2649 sub imgok {
2650 my $self = shift;
2651 return $self->p->imgok(@_);
2652 }
2653  
2654 sub imgnok {
2655 my $self = shift;
2656 return $self->p->imgnok(@_);
2657 }
2658  
2659 sub sendImage {
2660 my $self = shift;
2661 return $self->p->sendImage(@_);
2662 }
2663  
2664 # INTERNAL METHODS
2665 # Normalize url to be tolerant to SAML Path
2666 # Usefull if SAML Path is a regex
2667 # @return normalized url
2668 sub normalize_url {
2669 my ( $self, $url, $samlPath, $metadataUrl ) = @_;
2670  
2671 my $initialPath = "";
2672 my $finalPath = "";
2673  
2674 # Get current (bad) path
2675 if ( $url =~ m/($samlPath)/ ) {
2676 $initialPath = $1;
2677 }
2678  
2679 # Get destination (good) path
2680 if ( $metadataUrl =~ m/($samlPath)/ ) {
2681 $finalPath = $1;
2682 }
2683  
2684 if ( $initialPath ne ""
2685 and $finalPath ne ""
2686 and $initialPath ne $finalPath )
2687 {
2688 $self->logger->debug(
2689 "Normalizing url path form $initialPath to $finalPath");
2690 $url =~ s/$initialPath/$finalPath/;
2691 }
2692  
2693 return $url;
2694 }
2695  
2696 1;
« blib/lib/Lemonldap/NG/Portal/Auth/SAML.pm ↑ Summary blib/lib/Lemonldap/NG/Portal/UserDB/Combination.pm »