SAML.pm 99.1 KB
Newer Older
Xavier Guimard's avatar
Xavier Guimard committed
1 2 3 4 5 6
package Lemonldap::NG::Portal::Lib::SAML;

use strict;
use Mouse;
use Lemonldap::NG::Common::Conf::SAML::Metadata;
use Lemonldap::NG::Common::Session;
7
use Lemonldap::NG::Common::UserAgent;
8
use Lemonldap::NG::Common::FormEncode;
Xavier Guimard's avatar
Xavier Guimard committed
9 10 11 12 13 14 15 16
use XML::Simple;
use MIME::Base64;
use String::Random;
use HTTP::Request;         # SOAP call
use POSIX qw(strftime);    # Convert SAML2 date into timestamp
use Time::Local;           # Convert SAML2 date into timestamp
use Encode;                # Encode attribute values
use URI;                   # Get metadata URL path
17 18 19 20 21
use Lemonldap::NG::Portal::Main::Constants qw(
  PE_OK
  PE_REDIRECT
  PE_SAML_SLO_ERROR
);
Xavier Guimard's avatar
Xavier Guimard committed
22

Xavier Guimard's avatar
Xavier Guimard committed
23
our $VERSION = '2.0.2';
Xavier Guimard's avatar
Xavier Guimard committed
24 25 26

# PROPERTIES

Xavier Guimard's avatar
Xavier Guimard committed
27 28 29
has lassoServer => ( is => 'rw' );
has spList      => ( is => 'rw', default => sub { {} } );
has idpList     => ( is => 'rw', default => sub { {} } );
Xavier Guimard's avatar
Xavier Guimard committed
30
has idpRules    => ( is => 'rw', default => sub { {} } );
31
has spRules     => ( is => 'rw', default => sub { {} } );
Xavier Guimard's avatar
Xavier Guimard committed
32

Xavier Guimard's avatar
Xavier Guimard committed
33 34 35
# return LWP::UserAgent object
has ua => (
    is      => 'rw',
Xavier Guimard's avatar
Xavier Guimard committed
36
    lazy    => 1,
Xavier Guimard's avatar
Xavier Guimard committed
37 38 39
    builder => sub {

        # TODO : LWP options to use a proxy for example
40
        my $ua = Lemonldap::NG::Common::UserAgent->new( $_[0]->{conf} );
Xavier Guimard's avatar
Xavier Guimard committed
41 42 43 44 45
        $ua->env_proxy();
        return $ua;
    }
);

46 47 48 49
# SAML storage
has aModule => ( is => 'rw' );
has amOpts  => ( is => 'rw' );

Xavier Guimard's avatar
Xavier Guimard committed
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
# INITIALIZATION

BEGIN {

    # Load Glib if available
    eval 'use Glib;';
    if ($@) {
        print STDERR
          "Glib Lasso messages will not be catched (require Glib module)\n";
        eval "use constant GLIB => 0";
    }
    else {
        eval "use constant GLIB => 1";
    }

    # Load Lasso.pm
    eval 'use Lasso;';
    if ($@) {
        print STDERR "Lasso.pm not loaded: $@";
        eval
'use constant LASSO => 0;use constant BADLASSO => 0;use constant LASSOTHINSESSIONS => 0';
    }
    else {
        no strict 'subs';
        eval 'use constant LASSO => 1';

        # Check Lasso version >= 2.3.0
        my $lasso_check_version_mode =
          eval 'Lasso::Constants::CHECK_VERSION_NUMERIC';
        my $check_version =
          Lasso::check_version( 2, 3, 0, $lasso_check_version_mode );
        unless ($check_version) {
            eval 'use constant BADLASSO => 1';
        }
        else {
            eval 'use constant BADLASSO => 0';
        }

        # Try to set thin-sessions flag
        eval 'Lasso::set_flag("thin-sessions");';
        if ($@) {
            eval 'use constant LASSOTHINSESSIONS => 0';
        }
        else {
            eval 'use constant LASSOTHINSESSIONS => 1';
        }
    }

}

sub init {
    my ($self) = @_;

103 104 105 106 107 108 109 110 111 112 113 114 115
    # Initialize SAML storage
    my $moduleOptions;
    if ( $self->conf->{samlStorage} ) {
        $moduleOptions = $self->conf->{samlStorageOptions} || {};
        $moduleOptions->{backend} = $self->conf->{samlStorage};
    }
    else {
        $moduleOptions = $self->conf->{globalStorageOptions} || {};
        $moduleOptions->{backend} = $self->conf->{globalStorage};
    }
    $self->aModule( $moduleOptions->{backend} );
    $self->amOpts($moduleOptions);

Xavier Guimard's avatar
Xavier Guimard committed
116 117
    # Check for Lasso errors/messages (see BEGIN)
    unless (LASSO) {
118
        $self->logger->error("Module Lasso not loaded (see below)");
Xavier Guimard's avatar
Xavier Guimard committed
119 120 121 122
        return 0;
    }

    if (BADLASSO) {
123
        $self->logger->error('Lasso version >= 2.3.0 required');
Xavier Guimard's avatar
Xavier Guimard committed
124 125 126 127
        return 0;
    }

    unless (LASSOTHINSESSIONS) {
128
        $self->logger->warn('Lasso thin-sessions flag could not be set');
Xavier Guimard's avatar
Xavier Guimard committed
129 130
    }
    else {
131
        $self->logger->debug('Lasso thin-sessions flag set');
Xavier Guimard's avatar
Xavier Guimard committed
132
    }
Xavier Guimard's avatar
Xavier Guimard committed
133 134 135 136 137
    if (GLIB) {
        Glib::Log->set_handler(
            "Lasso",
            [qw/ error critical warning message info debug /],
            sub {
138 139
                $self->logger->debug(
                    $_[0] . " error " . $_[1] . ": " . $_[2] );
Xavier Guimard's avatar
Xavier Guimard committed
140 141 142
            }
        );
    }
Xavier Guimard's avatar
Xavier Guimard committed
143 144 145

    # Conf initialization

Xavier Guimard's avatar
Xavier Guimard committed
146
    return 0 unless ( $self->lassoServer( $self->loadService ) );
Xavier Guimard's avatar
Xavier Guimard committed
147
    $self->addUnauthRoute(
148
        ( $self->{path} || 'saml' ) => { 'metadata' => { ':type' => 'metadata' }},
Xavier Guimard's avatar
Xavier Guimard committed
149 150 151
        ['GET']
    );
    $self->addAuthRoute(
152
        ( $self->{path} || 'saml' ) => { 'metadata' => { ':type' => 'metadata' }},
Xavier Guimard's avatar
Xavier Guimard committed
153 154 155
        ['GET']
    );
    return 1;
Xavier Guimard's avatar
Xavier Guimard committed
156
}
Xavier Guimard's avatar
Xavier Guimard committed
157

158 159
# METHODS

Xavier Guimard's avatar
Xavier Guimard committed
160 161 162 163
sub loadService {
    my ($self) = @_;

    # Check if certificate is available
Xavier Guimard's avatar
Xavier Guimard committed
164 165 166
    unless ($self->conf->{samlServicePublicKeySig}
        and $self->conf->{samlServicePrivateKeySig} )
    {
167 168
        $self->logger->error(
            'SAML private and public key not found in configuration');
Xavier Guimard's avatar
Xavier Guimard committed
169 170 171 172 173 174 175 176
        return 0;
    }

    my $serviceCertificate;
    if (    $self->conf->{samlServiceUseCertificateInResponse}
        and $self->conf->{samlServicePublicKeySig} =~ /CERTIFICATE/ )
    {
        $serviceCertificate = $self->conf->{samlServicePublicKeySig};
177
        $self->logger->debug('Certificate will be used in SAML responses');
Xavier Guimard's avatar
Xavier Guimard committed
178 179 180 181

    }

    # Get metadata from configuration
182
    $self->logger->debug("Get Metadata for this service");
Xavier Guimard's avatar
Xavier Guimard committed
183 184 185 186
    my $service_metadata = Lemonldap::NG::Common::Conf::SAML::Metadata->new();

    # Create Lasso server with service metadata
    my $server = $self->createServer(
187
        $service_metadata->serviceToXML( $self->conf, ''),
Xavier Guimard's avatar
Xavier Guimard committed
188 189
        $self->conf->{samlServicePrivateKeySig},
        $self->conf->{samlServicePrivateKeySigPwd},
Xavier Guimard's avatar
Xavier Guimard committed
190 191 192 193 194 195 196 197 198 199 200 201 202

        # use signature cert for encryption unless defined
        (
            $self->conf->{samlServicePrivateKeyEnc}
            ? (
                $self->conf->{samlServicePrivateKeyEnc},
                $self->conf->{samlServicePrivateKeyEncPwd}
              )
            : (
                $self->conf->{samlServicePrivateKeySig},
                $self->conf->{samlServicePrivateKeySigPwd}
            )
        ),
Xavier Guimard's avatar
Xavier Guimard committed
203 204 205
        $serviceCertificate
    );

206
    # Signature method
207
    my $method = $self->conf->{samlServiceSignatureMethod} || 'RSA_SHA1';
208 209 210
    $server->signature_method( $self->getSignatureMethod($method) );
    $self->logger->debug("Set $method as SAML server signature method ");

Xavier Guimard's avatar
Xavier Guimard committed
211 212
    # Log
    unless ($server) {
213
        $self->logger->error('Unable to create Lasso server');
Xavier Guimard's avatar
Xavier Guimard committed
214 215
        return 0;
    }
216
    $self->logger->debug("Service created");
Xavier Guimard's avatar
Xavier Guimard committed
217 218 219 220

    return $server;
}

Xavier Guimard's avatar
Xavier Guimard committed
221 222 223 224 225 226 227
sub loadIDPs {
    my ($self) = @_;

    # Check presence of at least one identity provider in configuration
    unless ( $self->conf->{samlIDPMetaDataXML}
        and keys %{ $self->conf->{samlIDPMetaDataXML} } )
    {
228
        $self->logger->debug("No IDP found in configuration");
Xavier Guimard's avatar
Xavier Guimard committed
229 230 231 232 233 234 235 236 237
    }

    # Load identity provider metadata
    # IDP metadata are listed in $self->{samlIDPMetaDataXML}
    # Each key is the IDP name
    # Build IDP list for later use in extractFormInfo
    $self->idpList( {} );

    foreach ( keys %{ $self->conf->{samlIDPMetaDataXML} } ) {
238
        $self->logger->debug("Get Metadata for IDP $_");
Xavier Guimard's avatar
Xavier Guimard committed
239 240 241 242 243 244

        my $idp_metadata =
          $self->conf->{samlIDPMetaDataXML}->{$_}->{samlIDPMetaDataXML};

        # Check metadata format
        if ( ref $idp_metadata eq "HASH" ) {
245
            $self->logger->error(
Xavier Guimard's avatar
Xavier Guimard committed
246 247
"Metadata for IDP $_ is in old format. Please reload them from Manager"
            );
248
            next;
Xavier Guimard's avatar
Xavier Guimard committed
249 250 251 252 253 254 255 256 257 258
        }

        if ( $self->conf->{samlMetadataForceUTF8} ) {
            $idp_metadata = encode( "utf8", $idp_metadata );
        }

        # Add this IDP to Lasso::Server
        my $result = $self->addIDP( $self->lassoServer, $idp_metadata );

        unless ($result) {
259
            $self->logger->error("Fail to use IDP $_ Metadata");
260
            next;
Xavier Guimard's avatar
Xavier Guimard committed
261 262 263
        }

        # Store IDP entityID and Organization Name
264 265
        my ( $tmp, $entityID ) =
          ( $idp_metadata =~ /entityID=(['"])(.+?)\1/si );
Xavier Guimard's avatar
Xavier Guimard committed
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
        my $name = $self->getOrganizationName( $self->lassoServer, $entityID )
          || ucfirst($_);
        $self->idpList->{$entityID}->{confKey} = $_;
        $self->idpList->{$entityID}->{name}    = $name;

        # Set encryption mode
        my $encryption_mode = $self->conf->{samlIDPMetaDataOptions}->{$_}
          ->{samlIDPMetaDataOptionsEncryptionMode};
        my $lasso_encryption_mode = $self->getEncryptionMode($encryption_mode);

        unless (
            $self->setProviderEncryptionMode(
                $self->lassoServer->get_provider($entityID),
                $lasso_encryption_mode
            )
          )
        {
283
            $self->logger->error(
Xavier Guimard's avatar
Xavier Guimard committed
284
                "Unable to set encryption mode $encryption_mode on IDP $_");
285
            next;
Xavier Guimard's avatar
Xavier Guimard committed
286
        }
287
        $self->logger->debug("Set encryption mode $encryption_mode on IDP $_");
Xavier Guimard's avatar
Xavier Guimard committed
288

289
        # Set display options
Xavier Guimard's avatar
Xavier Guimard committed
290 291 292 293 294 295
        $self->idpList->{$entityID}->{displayName} =
          $self->conf->{samlIDPMetaDataOptions}->{$_}
          ->{samlIDPMetaDataOptionsDisplayName};
        $self->idpList->{$entityID}->{icon} =
          $self->conf->{samlIDPMetaDataOptions}->{$_}
          ->{samlIDPMetaDataOptionsIcon};
296 297

        # Set rule
298 299 300
        my $cond = $self->conf->{samlIDPMetaDataOptions}->{$_}
          ->{samlIDPMetaDataOptionsResolutionRule};
        if ( length $cond ) {
Xavier Guimard's avatar
Xavier Guimard committed
301
            $cond = $self->p->HANDLER->substitute($cond);
302
            unless ( $cond = $self->p->HANDLER->buildSub($cond) ) {
303
                $self->logger->error( 'SAML IdP rule error: '
304
                      . $self->p->HANDLER->tsv->{jail}->error );
305
                next;
Xavier Guimard's avatar
Xavier Guimard committed
306 307 308
            }
            $self->idpRules->{$entityID} = $cond;
        }
Xavier Guimard's avatar
Xavier Guimard committed
309

310
        $self->logger->debug("IDP $_ added");
Xavier Guimard's avatar
Xavier Guimard committed
311 312 313 314 315 316 317 318 319 320 321
    }
    return 1;
}

sub loadSPs {
    my ($self) = @_;

    # Check presence of at least one service provider in configuration
    unless ( $self->conf->{samlSPMetaDataXML}
        and keys %{ $self->conf->{samlSPMetaDataXML} } )
    {
322
        $self->logger->debug("No SP found in configuration");
Xavier Guimard's avatar
Xavier Guimard committed
323 324 325 326 327 328 329 330 331
    }

    # Load service provider metadata
    # SP metadata are listed in $self->{samlSPMetaDataXML}
    # Each key is the SP name
    # Build SP list for later use in extractFormInfo
    $self->spList( {} );
    foreach ( keys %{ $self->conf->{samlSPMetaDataXML} } ) {

332
        $self->logger->debug("Get Metadata for SP $_");
Xavier Guimard's avatar
Xavier Guimard committed
333 334 335 336 337 338

        my $sp_metadata =
          $self->conf->{samlSPMetaDataXML}->{$_}->{samlSPMetaDataXML};

        # Check metadata format
        if ( ref $sp_metadata eq "HASH" ) {
339
            $self->logger->error(
Xavier Guimard's avatar
Xavier Guimard committed
340 341
"Metadata for SP $_ is in old format. Please reload them from Manager"
            );
342
            next;
Xavier Guimard's avatar
Xavier Guimard committed
343 344 345 346 347 348 349 350 351 352
        }

        if ( $self->conf->{samlMetadataForceUTF8} ) {
            $sp_metadata = encode( "utf8", $sp_metadata );
        }

        # Add this SP to Lasso::Server
        my $result = $self->addSP( $self->lassoServer, $sp_metadata );

        unless ($result) {
353
            $self->logger->error("Fail to use SP $_ Metadata");
354
            next;
Xavier Guimard's avatar
Xavier Guimard committed
355 356 357
        }

        # Store SP entityID and Organization Name
358
        my ( $tmp, $entityID ) = ( $sp_metadata =~ /entityID=(['"])(.+?)\1/si );
Xavier Guimard's avatar
Xavier Guimard committed
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
        my $name = $self->getOrganizationName( $self->lassoServer, $entityID )
          || ucfirst($_);
        $self->spList->{$entityID}->{confKey} = $_;
        $self->spList->{$entityID}->{name}    = $name;

        # Set encryption mode
        my $encryption_mode = $self->conf->{samlSPMetaDataOptions}->{$_}
          ->{samlSPMetaDataOptionsEncryptionMode};
        my $lasso_encryption_mode = $self->getEncryptionMode($encryption_mode);

        unless (
            $self->setProviderEncryptionMode(
                $self->lassoServer->get_provider($entityID),
                $lasso_encryption_mode
            )
          )
        {
376
            $self->logger->error(
Xavier Guimard's avatar
Xavier Guimard committed
377
                "Unable to set encryption mode $encryption_mode on SP $_");
378
            next;
Xavier Guimard's avatar
Xavier Guimard committed
379
        }
380
        $self->logger->debug("Set encryption mode $encryption_mode on SP $_");
Xavier Guimard's avatar
Xavier Guimard committed
381

382 383 384 385 386
        my $rule = $self->conf->{samlSPMetaDataOptions}->{$_}
          ->{samlSPMetaDataOptionsRule};
        if ( length $rule ) {
            $rule = $self->p->HANDLER->substitute($rule);
            unless ( $rule = $self->p->HANDLER->buildSub($rule) ) {
387
                $self->logger->error( 'SAML SP rule error: '
388
                      . $self->p->HANDLER->tsv->{jail}->error );
389
                next;
390 391 392 393
            }
            $self->spRules->{$entityID} = $rule;
        }

394
        $self->logger->debug("SP $_ added");
Xavier Guimard's avatar
Xavier Guimard committed
395 396 397 398 399
    }

    return 1;
}

Xavier Guimard's avatar
Xavier Guimard committed
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
# Check SAML requests and responses
sub checkMessage {
    my ( $self, $req, $url, $request_method, $content_type, $profile_type ) =
      @_;
    $profile_type ||= "login";

    # Create Profile object
    my $profile;
    $profile = $self->createLogin( $self->lassoServer )
      if ( $profile_type eq "login" );
    $profile = $self->createLogout( $self->lassoServer )
      if ( $profile_type eq "logout" );

    # Get relayState
    my $relaystate = $req->param('RelayState');
    my ( $method, $request, $response, $artifact, $message );

    # 2.1. HTTP REDIRECT
    if ( $request_method eq 'GET' ) {

        $method = Lasso::Constants::HTTP_METHOD_REDIRECT;
421
        $self->logger->debug("SAML method: HTTP-REDIRECT");
Xavier Guimard's avatar
Xavier Guimard committed
422 423 424 425 426

        if ( $req->param('SAMLResponse') ) {

            # Response in query string
            $response = $self->getQueryString($req);
427
            $self->logger->debug("HTTP-REDIRECT: SAML Response $response");
Xavier Guimard's avatar
Xavier Guimard committed
428 429 430 431 432 433 434

        }

        if ( $req->param('SAMLRequest') ) {

            # Request in query string
            $request = $self->getQueryString($req);
435
            $self->logger->debug("HTTP-REDIRECT: SAML Request $request");
Xavier Guimard's avatar
Xavier Guimard committed
436 437 438 439 440 441 442

        }

        if ( $req->param('SAMLart') ) {

            # Artifact in query string
            $artifact = $self->getQueryString($req);
443
            $self->logger->debug("HTTP-REDIRECT: SAML Artifact $artifact");
Xavier Guimard's avatar
Xavier Guimard committed
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466

            # Resolve Artifact
            $method = Lasso::Constants::HTTP_METHOD_ARTIFACT_GET;
            $message = $self->resolveArtifact( $profile, $artifact, $method );

            # Request or response ?
            if ( $message =~ /samlp:response/i ) {
                $response = $message;
            }
            else {
                $request = $message;
            }
        }

    }

    # 2.2. HTTP POST AND SOAP
    elsif ( $request_method =~ /^POST$/ ) {

        # 2.2.1. POST
        if ( $content_type !~ /xml/ ) {

            $method = Lasso::Constants::HTTP_METHOD_POST;
467
            $self->logger->debug("SAML method: HTTP-POST");
Xavier Guimard's avatar
Xavier Guimard committed
468 469 470 471 472

            if ( $req->param('SAMLResponse') ) {

                # Response in body part
                $response = $req->param('SAMLResponse');
Xavier Guimard's avatar
Xavier Guimard committed
473
                $response =~ s/ /+/gs;
474
                $self->logger->debug("HTTP-POST: SAML Response $response");
Xavier Guimard's avatar
Xavier Guimard committed
475 476 477 478 479 480 481

            }

            elsif ( $req->param('SAMLRequest') ) {

                # Request in body part
                $request = $req->param('SAMLRequest');
482
                $self->logger->debug("HTTP-POST: SAML Request $request");
Xavier Guimard's avatar
Xavier Guimard committed
483 484 485 486 487 488 489

            }

            elsif ( $req->param('SAMLart') ) {

                # Artifact in SAMLart param
                $artifact = $req->param('SAMLart');
490
                $self->logger->debug("HTTP-POST: SAML Artifact $artifact");
Xavier Guimard's avatar
Xavier Guimard committed
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512

                # Resolve Artifact
                $method = Lasso::Constants::HTTP_METHOD_ARTIFACT_POST;
                $message =
                  $self->resolveArtifact( $profile, $artifact, $method );

                # Request or response ?
                if ( $message =~ /samlp:response/i ) {
                    $response = $message;
                }
                else {
                    $request = $message;
                }

            }

        }

        # 2.2.2. SOAP
        else {

            $method = Lasso::Constants::HTTP_METHOD_SOAP;
513
            $self->logger->debug("SAML method: HTTP-SOAP");
Xavier Guimard's avatar
Xavier Guimard committed
514 515

            # SOAP is always a request
516
            $request = $req->content;
517
            $self->logger->debug("HTTP-SOAP: SAML Request $request");
Xavier Guimard's avatar
Xavier Guimard committed
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538

        }

    }

    # 4. Return values
    return ( $request, $response, $method, $relaystate, $artifact ? 1 : 0 );
}

## @method boolean checkLassoError(Lasso::Error error, string level)
# Log Lasso error code and message if this is actually a Lasso::Error with code > 0
# @param error Lasso error object
# @param level optional log level (debug by default)
# @return 1 if no error
sub checkLassoError {
    my ( $self, $error, $level ) = @_;
    $level ||= 'debug';

    # If $error is not a Lasso::Error object, display error string
    unless ( ref($error) and $error->isa("Lasso::Error") ) {
        return 1 unless $error;
539
        $self->p->lmLog( "Lasso error: $error", $level );
Xavier Guimard's avatar
Xavier Guimard committed
540 541 542 543 544
        return 0;
    }

    # Else check error code and error message
    if ( $error->{code} ) {
545
        $self->p->lmLog(
Xavier Guimard's avatar
Xavier Guimard committed
546 547 548 549 550 551 552 553 554 555
            "Lasso error code " . $error->{code} . ": " . $error->{message},
            $level );
        return 0;
    }

    return 1;
}

## @method Lasso::Server createServer(string metadata, string private_key, string private_key_password, string private_key_enc, string private_key_enc_password, string certificate)
# Load service metadata and create Lasso::Server object
Xavier Guimard's avatar
Xavier Guimard committed
556
# @param metadata SAML metadata
Xavier Guimard's avatar
Xavier Guimard committed
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
# @param private_key private key
# @param private_key_password optional private key password
# @param private_key_enc optional private key for encryption
# @param private_key_enc_password optional private key password for encryption
# @param certificate optional certificate
# @return Lasso::Server object
sub createServer {
    my ( $self, $metadata, $private_key, $private_key_password,
        $private_key_enc, $private_key_enc_password, $certificate )
      = @_;
    my $server;

    eval {
        $server = Lasso::Server::new_from_buffers( $metadata, $private_key,
            $private_key_password, $certificate );

        # Set private key for encryption
        if ($private_key_enc) {
            Lasso::Server::set_encryption_private_key_with_password( $server,
                $private_key_enc, $private_key_enc_password );
        }
    };

    if ($@) {
        $self->checkLassoError($@);
        return;
    }

    return $server;
}

## @method boolean addIDP(Lasso::Server server, string metadata, string public_key, string ca_cert_chain)
# Add IDP to an existing Lasso::Server
# @param server Lasso::Server object
# @param metadata IDP metadata
# @param public_key optional public key
# @param ca_cert_chain optional ca cert chain
# @return boolean result
sub addIDP {
    my ( $self, $server, $metadata, $public_key, $ca_cert_chain ) = @_;

    return 0 unless ( $server->isa("Lasso::Server") and defined $metadata );

    return $self->addProvider( $server, Lasso::Constants::PROVIDER_ROLE_IDP,
        $metadata, $public_key, $ca_cert_chain );
}

## @method boolean addSP(Lasso::Server server, string metadata, string public_key, string ca_cert_chain)
# Add SP to an existing Lasso::Server
# @param server Lasso::Server object
# @param metadata SP metadata
# @param public_key optional public key
# @param ca_cert_chain optional ca cert chain
# @return boolean result
sub addSP {
    my ( $self, $server, $metadata, $public_key, $ca_cert_chain ) = @_;

    return 0 unless ( $server->isa("Lasso::Server") and defined $metadata );

    return $self->addProvider( $server, Lasso::Constants::PROVIDER_ROLE_SP,
        $metadata, $public_key, $ca_cert_chain );
}

## @method boolean addAA(Lasso::Server server, string metadata, string public_key, string ca_cert_chain)
# Add Attribute Authority to an existing Lasso::Server
# @param server Lasso::Server object
# @param metadata AA metadata
# @param public_key optional public key
# @param ca_cert_chain optional ca cert chain
# @return boolean result
sub addAA {
    my ( $self, $server, $metadata, $public_key, $ca_cert_chain ) = @_;

    return 0 unless ( $server->isa("Lasso::Server") and defined $metadata );

    return $self->addProvider( $server,
        Lasso::Constants::PROVIDER_ROLE_ATTRIBUTE_AUTHORITY,
        $metadata, $public_key, $ca_cert_chain );
}

## @method boolean addProvider(Lasso::Server server, int role, string metadata, string public_key, string ca_cert_chain)
# Add provider to an existing Lasso::Server
# @param server Lasso::Server object
# @param role (IDP, SP or Both)
# @param metadata IDP metadata
# @param public_key optional public key
# @param ca_cert_chain optional ca cert chain
# @return boolean result
sub addProvider {
    my ( $self, $server, $role, $metadata, $public_key, $ca_cert_chain ) = @_;

    return 0
      unless ( $server->isa("Lasso::Server")
        and defined $role
        and defined $metadata );

    eval {
        Lasso::Server::add_provider_from_buffer( $server, $role, $metadata,
            $public_key, $ca_cert_chain );
    };

    return $self->checkLassoError($@);

}

## @method string getOrganizationName(Lasso::Server server, string idp)
# Return name of organization picked up from metadata
#@param server Lasso::Server object
#@param idp entity ID
#@return string organization name
sub getOrganizationName {
    my ( $self, $server, $idp ) = @_;
    my ( $provider, $node );

    # Get provider from server
    eval { $provider = Lasso::Server::get_provider( $server, $idp ); };

    if ($@) {
        $self->checkLassoError($@);
        return;
    }

    # Get organization node
    eval { $node = Lasso::Provider::get_organization($provider); };

    if ($@) {
        $self->checkLassoError($@);
        return;
    }

    # Return if node is empty
    return unless $node;

    # Extract organization name
    my $xs   = XML::Simple->new();
    my $data = $xs->XMLin($node);
    return $data->{OrganizationName}->{content};
}

## @method string getNextProviderId(Lasso::Logout logout)
# Returns the provider id from providerID_index in list of providerIDs in
# principal session with the exception of initial service provider ID.
# @param logout Lasso::Logout object
# @return string
sub getNextProviderId {
    my $self   = shift;
    my $logout = shift;
    my $providerId;

    eval { $providerId = Lasso::Logout::get_next_providerID($logout); };
    if ($@) {
        $self->checkLassoError($@);
        return;
    }

    return $providerId;
}

## @method boolean resetProviderIdIndex(Lasso::Logout logout)
# Reset the providerID_index attribute in Lasso::Logout object
# @param logout Lasso::Logout object
# @return boolean
sub resetProviderIdIndex {
    my $self   = shift;
    my $logout = shift;

    eval { Lasso::Logout::reset_providerID_index($logout); };
    return $self->checkLassoError($@);
}

## @method Lasso::Login createAuthnRequest(Lasso::Server server, string idp, int method, boolean forceAuthn, boolean isPassive, string nameIDFormat, boolean allowProxiedAuthn, boolean signSSOMessage, string requestedAuthnContext)
# Create authentication request for selected IDP
# @param server Lasso::Server object
# @param idp IDP entityID
# @param method HTTP method
# @param forceAuthn force authentication on IDP
# @param isPassive require passive authentication
# @param nameIDFormat SAML2 NameIDFormat
# @param allowProxiedAuthn allow proxy on IDP
# @param signSSOMessage sign request
# @param requestedAuthnContext authentication context
# @return Lasso::Login object
sub createAuthnRequest {
    my (
        $self,           $req,          $server,
        $idp,            $method,       $forceAuthn,
        $isPassive,      $nameIDFormat, $allowProxiedAuthn,
        $signSSOMessage, $requestedAuthnContext
    ) = @_;
    my $proxyCount;
    my $proxyRequestedAuthnContext;

    # Create Lasso Login
    my $login = $self->createLogin($server);

    unless ($login) {
753
        $self->logger->error('Unable to create Lasso login');
Xavier Guimard's avatar
Xavier Guimard committed
754 755 756 757 758
        return;
    }

    # Init authentication request
    unless ( $self->initAuthnRequest( $login, $idp, $method ) ) {
759 760
        $self->logger->error(
            "Could not initiate authentication request on $idp");
Xavier Guimard's avatar
Xavier Guimard committed
761 762 763 764
        return;
    }

    # Set RelayState
765
    if ( my $relaystate = $self->storeRelayState( $req, 'urldc' ) ) {
Xavier Guimard's avatar
Xavier Guimard committed
766
        $login->msg_relayState($relaystate);
767
        $self->logger->debug("Set $relaystate in RelayState");
Xavier Guimard's avatar
Xavier Guimard committed
768 769 770 771 772 773 774 775 776
    }

    # Customize request
    my $request = $login->request();

    # Maybe we are in IDP proxy mode (SAML request received on IDP side)
    # In this case:
    # * Check proxy conditions
    # * Forward some authn constraints
Xavier Guimard's avatar
Xavier Guimard committed
777
    if ( $req->data->{_proxiedSamlRequest} ) {
Xavier Guimard's avatar
Xavier Guimard committed
778

779
        $self->logger->debug("IDP Proxy mode detected");
Xavier Guimard's avatar
Xavier Guimard committed
780 781 782 783

        # Get ProxyCount value
        eval {
            $proxyCount =
Xavier Guimard's avatar
Xavier Guimard committed
784
              $req->data->{_proxiedSamlRequest}->Scoping()->ProxyCount();
Xavier Guimard's avatar
Xavier Guimard committed
785 786 787 788 789
        };

        # Deny request if ProxyCount eq 0
        if ( defined $proxyCount ) {

790 791
            $self->logger->debug(
                "Found proxyCount $proxyCount in proxied request");
Xavier Guimard's avatar
Xavier Guimard committed
792 793

            if ( $proxyCount eq 0 ) {
794 795
                $self->userLogger->error(
                    "SAML request cannot be proxied (ProxyCount 0)");
Xavier Guimard's avatar
Xavier Guimard committed
796 797 798 799 800
                return;
            }
            else {

                # Decrease ProxyCount
Xavier Guimard's avatar
Xavier Guimard committed
801
                my $scoping = $req->data->{_proxiedSamlRequest}->Scoping();
Xavier Guimard's avatar
Xavier Guimard committed
802 803 804 805 806 807
                $scoping->ProxyCount( $proxyCount-- );
                eval { $request->Scoping($scoping); };
            }
        }

        # isPassive
Xavier Guimard's avatar
Xavier Guimard committed
808
        eval { $isPassive = $req->data->{_proxiedSamlRequest}->IsPassive(); };
Xavier Guimard's avatar
Xavier Guimard committed
809 810

        # forceAuthn
Xavier Guimard's avatar
Xavier Guimard committed
811
        eval { $forceAuthn = $req->data->{_proxiedSamlRequest}->ForceAuthn(); };
Xavier Guimard's avatar
Xavier Guimard committed
812 813 814 815

        # requestedAuthnContext
        eval {
            $proxyRequestedAuthnContext =
Xavier Guimard's avatar
Xavier Guimard committed
816
              $req->data->{_proxiedSamlRequest}->RequestedAuthnContext();
Xavier Guimard's avatar
Xavier Guimard committed
817 818 819 820 821
        };
    }

    # NameIDFormat
    if ($nameIDFormat) {
822
        $self->logger->debug("Use NameIDFormat $nameIDFormat");
Xavier Guimard's avatar
Xavier Guimard committed
823 824 825 826 827 828 829 830
        $request->NameIDPolicy()->Format($nameIDFormat);
    }

    # Always allow NameID creation
    $request->NameIDPolicy()->AllowCreate(1);

    # Force authentication
    if ($forceAuthn) {
831
        $self->logger->debug("Force authentication on IDP");
Xavier Guimard's avatar
Xavier Guimard committed
832 833 834 835 836
        $request->ForceAuthn(1);
    }

    # Passive authentication
    if ($isPassive) {
837
        $self->logger->debug("Passive authentication on IDP");
Xavier Guimard's avatar
Xavier Guimard committed
838 839 840 841 842
        $request->IsPassive(1);
    }

    # Allow proxy
    unless ($allowProxiedAuthn) {
843
        $self->logger->debug("Do not allow this request to be proxied");
Xavier Guimard's avatar
Xavier Guimard committed
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860
        eval {
            my $proxyRestriction = Lasso::Saml2ProxyRestriction->new();
            $proxyRestriction->Audience($idp);
            $proxyRestriction->Count(0);
            my $conditions = $request->Conditions()
              || Lasso::Saml2Conditions->new();
            $conditions->ProxyRestriction($proxyRestriction);
            $request->Conditions($conditions);
        };
        if ($@) {
            $self->checkLassoError($@);
            return;
        }
    }

    # Signature
    if ( $signSSOMessage == 0 ) {
861
        $self->logger->debug("SSO request will not be signed");
Xavier Guimard's avatar
Xavier Guimard committed
862 863 864
        $self->disableSignature($login);
    }
    elsif ( $signSSOMessage == 1 ) {
865
        $self->logger->debug("SSO request will be signed");
Xavier Guimard's avatar
Xavier Guimard committed
866 867 868
        $self->forceSignature($login);
    }
    else {
869
        $self->logger->debug("SSO request signature according to metadata");
Xavier Guimard's avatar
Xavier Guimard committed
870 871 872 873
    }

    # Requested authentication context
    if ($proxyRequestedAuthnContext) {
874
        $self->logger->debug("Use RequestedAuthnContext from proxied request");
Xavier Guimard's avatar
Xavier Guimard committed
875 876 877
        $request->RequestedAuthnContext($proxyRequestedAuthnContext);
    }
    elsif ($requestedAuthnContext) {
878
        $self->logger->debug("Request $requestedAuthnContext context");
Xavier Guimard's avatar
Xavier Guimard committed
879 880 881 882 883 884 885 886 887 888 889 890 891 892
        eval {
            my $context = Lasso::Samlp2RequestedAuthnContext->new();
            $context->AuthnContextClassRef($requestedAuthnContext);
            $context->Comparison("minimum");
            $request->RequestedAuthnContext($context);
        };
        if ($@) {
            $self->checkLassoError($@);
            return;
        }
    }

    # Build authentication request
    unless ( $self->buildAuthnRequestMsg($login) ) {
893
        $self->logger->error("Could not build authentication request on $idp");
Xavier Guimard's avatar
Xavier Guimard committed
894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
        return;
    }

    # Artifact
    if (   $method == $self->getHttpMethod("artifact-get")
        or $method == $self->getHttpMethod("artifact-post") )
    {

        # Get artifact ID and Content, and store them
        my $artifact_id      = $login->get_artifact;
        my $artifact_message = $login->get_artifact_message;

        $self->storeArtifact( $artifact_id, $artifact_message );
    }
    return $login;
}

## @method Lasso::Login createLogin(Lasso::Server server, string dump)
# Create Lasso::Login object
# @param server Lasso::Server object
# @param dump optional XML dump
# @return Lasso::Login object
sub createLogin {
    my ( $self, $server, $dump ) = @_;
    my $login;

    if ($dump) {
        eval { $login = Lasso::Login::new_from_dump( $server, $dump ); };
    }
    else {
        eval { $login = Lasso::Login->new($server); };
    }

    if ($@) {
        $self->checkLassoError($@);
        return;
    }

    return $login;
}

## @method boolean initAuthnRequest(Lasso::Login login, string idp, int method)
# Init authentication request
# @param login Lasso::Login
# @param idp entityID
# @param method HTTP method
# @return boolean result
sub initAuthnRequest {
    my ( $self, $login, $idp, $method ) = @_;

    eval { Lasso::Login::init_authn_request( $login, $idp, $method ); };

    return $self->checkLassoError($@);
}

## @method boolean initIdpInitiatedAuthnRequest(Lasso::Login login, string idp)
# Init authentication request
# @param login Lasso::Login
# @param idp entityID
# @return boolean result
sub initIdpInitiatedAuthnRequest {
    my ( $self, $login, $idp ) = @_;

    eval { Lasso::Login::init_idp_initiated_authn_request( $login, $idp ); };

    return $self->checkLassoError($@);
}

## @method boolean buildAuthnRequestMsg(Lasso::Login login)
# Build authentication request message
# @param login Lasso::Login
# @return boolean result
sub buildAuthnRequestMsg {
    my ( $self, $login ) = @_;

    eval { Lasso::Login::build_authn_request_msg($login); };

    return $self->checkLassoError($@);
}

## @method boolean processAuthnRequestMsg(Lasso::Login login, string request)
# Process authentication request message
# @param login Lasso::Login object
# @param request SAML request
# @return result
sub processAuthnRequestMsg {
    my ( $self, $login, $request ) = @_;

    eval { Lasso::Login::process_authn_request_msg( $login, $request ); };

    return $self->checkLassoError($@);
}

## @method boolean validateRequestMsg(Lasso::Login login, boolean auth, boolean consent)
# Validate request message
# @param login Lasso::Login object
# @param auth is user authenticated?
# @param consent is consent obtained?
# @return result
sub validateRequestMsg {
    my ( $self, $login, $auth, $consent ) = @_;

    eval { Lasso::Login::validate_request_msg( $login, $auth, $consent ); };

    return $self->checkLassoError($@);
}

## @method boolean buildAuthnResponseMsg(Lasso::Login login)
# Build authentication response message
# @param login Lasso::Login object
# @return boolean result
sub buildAuthnResponseMsg {
    my ( $self, $login ) = @_;

    eval { Lasso::Login::build_authn_response_msg($login); };

    return $self->checkLassoError($@);
}

## @method boolean buildArtifactMsg(Lasso::Login login, int method)
# Build artifact message
# @param login Lasso::Login object
# @param method HTTP method
# @return boolean result
sub buildArtifactMsg {
    my ( $self, $login, $method ) = @_;

    eval { Lasso::Login::build_artifact_msg( $login, $method ); };

    return $self->checkLassoError($@);
}

## @method boolean buildAssertion(Lasso::Login login, string authn_context, int notOnOrAfterTimeout)
# Build assertion
# @param login Lasso::Login object
# @param authn_context SAML2 authentication context
# @param notOnOrAfterTimeout Timeout to apply to notOnOrAfter
# @return boolean result
sub buildAssertion {
    my ( $self, $req, $login, $authn_context, $notOnOrAfterTimeout ) = @_;
    $notOnOrAfterTimeout ||= $self->conf->{timeout};

    # Dates
    my $time                    = $req->sessionInfo->{_utime} || time();
    my $timeout                 = $time + $notOnOrAfterTimeout;
    my $authenticationInstant   = $self->timestamp2samldate($time);
    my $reauthenticateOnOrAfter = $self->timestamp2samldate($timeout);
    my $issued_time             = time;
    my $notBefore               = $self->timestamp2samldate($issued_time);
    my $notOnOrAfter =
      $self->timestamp2samldate( $issued_time + $notOnOrAfterTimeout );

    eval {
        Lasso::Login::build_assertion( $login, $authn_context,
            $authenticationInstant, $reauthenticateOnOrAfter, $notBefore,
            $notOnOrAfter );
    };

    return $self->checkLassoError($@);
}

## @method boolean processAuthnResponseMsg(Lasso::Login login, string response)
# Process authentication response message
# @param login Lasso::Login object
# @param response SAML response
# @return result
sub processAuthnResponseMsg {
    my ( $self, $login, $response ) = @_;

    eval { Lasso::Login::process_authn_response_msg( $login, $response ); };

    return $self->checkLassoError($@);
}

1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
# UNUSED
### @method Lasso::Saml2NameID getNameIdentifer(Lasso::Profile profile)
## Get NameID from Lasso Profile
## @param profile Lasso::Profile object
## @return result or NULL if error
#sub getNameIdentifier {
#    my ( $self, $profile ) = @_;
#    my $nameid;
#
#    eval { $nameid = Lasso::Profile::get_nameIdentifier($profile); };
#
#    if ($@) {
#        $self->checkLassoError($@);
#        return;
#    }
#
#    return $nameid;
#}

# UNUSED
### @method Lasso::Identity createIdentity(string dump)
## Create Lasso::Identity object
## @param dump optional Identity dump
## @return Lasso::Identity object
#sub createIdentity {
#    my ( $self, $dump ) = @_;
#    my $identity;
#
#    if ($dump) {
#        eval { $identity = Lasso::Identity::new_from_dump($dump); };
#    }
#    else {
#        eval { $identity = Lasso::Identity->new(); };
#    }
#
#    if ($@) {
#        $self->checkLassoError($@);
#        return;
#    }
#
#    return $identity;
#}

## UNUSED
### @method Lasso::Session createSession(string dump)
## Create Lasso::Session object
## @param dump optional Session dump
## @return Lasso::Session object
#sub createSession {
#    my ( $self, $dump ) = @_;
#    my $session;
#
#    if ($dump) {
#        eval { $session = Lasso::Session::new_from_dump($dump); };
#    }
#    else {
#        eval { $session = Lasso::Session->new(); };
#    }
#
#    if ($@) {
#        $self->checkLassoError($@);
#        return;
#    }
#
#    return $session;
#}
Xavier Guimard's avatar
Xavier Guimard committed
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172

## @method boolean acceptSSO(Lasso::Login login)
# Accept SSO from IDP
# @param login Lasso::Login object
# @return result
sub acceptSSO {
    my ( $self, $login ) = @_;

    eval { Lasso::Login::accept_sso($login); };

    return $self->checkLassoError($@);
}

## @method string storeRelayState(hashref infos)
# Store information in relayState database and return
# corresponding session_id
# @param infos HASH reference of information
sub storeRelayState {
    my ( $self, $req, @data ) = @_;

    # check if there are data to store
    my $infos;
    foreach (@data) {
        $infos->{$_} = $req->{$_} if $req->{$_};
    }
    return unless ($infos);

    # Session type
    $infos->{_type} = "relaystate";

    # Set _utime for session autoremove
    # Use default session timeout and relayState session timeout to compute it
    my $time    = time();
    my $timeout = $self->conf->{timeout};
    my $samlRelayStateTimeout =
      $self->conf->{samlRelayStateTimeout} || $timeout;

    $infos->{_utime} = $time + ( $samlRelayStateTimeout - $timeout );

1173 1174 1175
    # Create relaystate session and store infos in relaystate session
    my $samlSessionInfo = $self->getSamlSession( undef, $infos )
      or return undef;
Xavier Guimard's avatar
Xavier Guimard committed
1176 1177 1178 1179 1180 1181 1182 1183

    # Session ID
    my $relaystate_id = $samlSessionInfo->id;

    # Return session ID
    return $relaystate_id;
}

1184
## @method boolean extractRelayState(string relaystate, boolean relayStateURL)
Xavier Guimard's avatar
Xavier Guimard committed
1185 1186
# Extract RelayState information into $self
# @param relaystate Relay state value
1187
# @param relayStateURL Allow Relay state value to be the redirection URL
Xavier Guimard's avatar
Xavier Guimard committed
1188 1189
# @return result
sub extractRelayState {
1190
    my ( $self, $req, $relaystate, $relayStateURL ) = @_;
Xavier Guimard's avatar
Xavier Guimard committed
1191 1192

    return 0 unless $relaystate;
1193
    if ( $relayStateURL and $relaystate =~ /^https?:\/\// ) {
1194
        $self->logger->debug("RelayState is a redirection URL: $relaystate");
1195 1196 1197 1198
        $req->{urldc} = $relaystate;
        return 1;
    }
    else {
Xavier Guimard's avatar
Xavier Guimard committed
1199

1200 1201
        # Open relaystate session
        my $samlSessionInfo = $self->getSamlSession($relaystate);
Xavier Guimard's avatar
Xavier Guimard committed
1202

1203
        return 0 unless $samlSessionInfo;
Xavier Guimard's avatar
Xavier Guimard committed
1204

1205 1206 1207
        # Push values in $self
        foreach ( keys %{ $samlSessionInfo->data } ) {
            next if $_ =~ /(type|_session_id|_utime)/;
1208 1209
            if ( $_ eq 'issuerUrldc' ) {
                $req->urldc( $samlSessionInfo->data->{$_} );
1210 1211 1212 1213
            }
            else {
                $req->{$_} = $samlSessionInfo->data->{$_};
            }
1214 1215 1216 1217
        }

        # delete relaystate session
        if ( $samlSessionInfo->remove ) {
1218
            $self->logger->debug("Relaystate $relaystate was deleted");
1219 1220
        }
        else {
1221 1222
            $self->logger->error("Unable to delete relaystate $relaystate");
            $self->logger->error( $samlSessionInfo->error );
1223
        }
Xavier Guimard's avatar
Xavier Guimard committed
1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284

    }

    return 1;
}

## @method Lasso::Node getAssertion(Lasso::Login login)
# Get assertion in Lasso::Login object
# @param login Lasso::Login object
# @return assertion Lasso::Node object
sub getAssertion {
    my ( $self, $login ) = @_;
    my $assertion;

    eval { $assertion = Lasso::Login::get_assertion($login); };

    if ($@) {
        $self->checkLassoError($@);
        return;
    }

    return $assertion;
}

## @method string getAttributeValue(string name, string format, string friendly_name, arrayref attributes, boolean force_utf8)
# Get SAML attribute value corresponding to name, format and friendly_name
# Multivaluated values are separated by multiValuesSeparator
# If force_utf8 flag is set, value is encoded in UTF-8
# @param name SAML attribute name
# @param format optional SAML attribute format
# @param friendly_name optional SAML attribute friendly name
# @param attributes Attributes
# @param force_utf8 optional flag to force value in UTF-8
# @return attribute value
sub getAttributeValue {
    my ( $self, $name, $format, $friendly_name, $attributes, $force_utf8 ) = @_;
    my $value;

    # Loop on attributes
    foreach (@$attributes) {
        my $attr_name   = $_->Name();
        my $attr_format = $_->NameFormat();
        my $attr_fname  = $_->FriendlyName();

        # Skip if name does not correspond to attribute name
        next if ( $name ne $attr_name );

        # Verify format and friendly name if given
        next if ( $format        and $format ne $attr_format );
        next if ( $friendly_name and $friendly_name ne $attr_fname );

        # Attribute is found, return its content
        my @attr_values = $_->AttributeValue();

        foreach (@attr_values) {
            my $xs      = XML::Simple->new();
            my $data    = $xs->XMLin( $_->dump() );
            my $content = $data->{content};
            $value .= $content . $self->conf->{multiValuesSeparator}
              if $content;
        }
Xavier Guimard's avatar
Xavier Guimard committed
1285
        $value =~ s/$self->{conf}->{multiValuesSeparator}$//;
Xavier Guimard's avatar
Xavier Guimard committed
1286 1287 1288 1289 1290 1291 1292 1293 1294

        # Encode UTF-8 if force_utf8 flag
        $value = encode( "utf8", $value ) if $force_utf8;

    }

    return $value;
}

1295
## @method boolean validateConditions(Lasso::Saml2::Assertion assertion, string entityID, boolean checkTime, boolean checkAudience)
Xavier Guimard's avatar
Xavier Guimard committed
1296 1297 1298
# Validate conditions
# @param assertion SAML2 assertion
# @param entityID relying party entity ID
1299 1300
# @param checkTime Enable time conditions check
# @param checkAudience Enable audience conditions check
Xavier Guimard's avatar
Xavier Guimard committed
1301 1302
# @return result
sub validateConditions {
1303
    my ( $self, $assertion, $entityID, $checkTime, $checkAudience ) = @_;
Xavier Guimard's avatar
Xavier Guimard committed
1304 1305
    my $tolerance = 10;
    my $status;
1306 1307
    $checkTime     = 1 unless defined $checkTime;
    $checkAudience = 1 unless defined $checkAudience;
Xavier Guimard's avatar
Xavier Guimard committed
1308 1309

    # Time
1310 1311
    if ($checkTime) {
        eval {
1312
            $status = Lasso::Saml2Assertion::validate_time_checks( $assertion,
1313 1314
                $tolerance );
        };
Xavier Guimard's avatar
Xavier Guimard committed
1315

1316 1317 1318 1319
        if ($@) {
            $self->checkLassoError($@);
            return 0;
        }
Xavier Guimard's avatar
Xavier Guimard committed
1320

1321
        unless ( $status eq Lasso::Constants::SAML2_ASSERTION_VALID ) {
1322
            $self->logger->error("Time conditions validations result: $status");
1323 1324
            return 0;
        }
Xavier Guimard's avatar
Xavier Guimard committed
1325

1326
        $self->logger->debug("Time conditions validated");
1327 1328
    }
    else {
1329
        $self->logger->debug("Time conditions not checked");
1330
    }
Xavier Guimard's avatar
Xavier Guimard committed
1331 1332

    # Audience
1333 1334 1335 1336 1337
    if ($checkAudience) {
        eval {
            $status =
              Lasso::Saml2Assertion::validate_audience( $assertion, $entityID );
        };
Xavier Guimard's avatar
Xavier Guimard committed
1338

1339 1340 1341 1342
        if ($@) {
            $self->checkLassoError($@);
            return 0;
        }
Xavier Guimard's avatar
Xavier Guimard committed
1343

1344
        unless ( $status eq Lasso::Constants::SAML2_ASSERTION_VALID ) {
1345 1346
            $self->logger->error(
                "Audience conditions validations result: $status");
1347 1348
            return 0;
        }
Xavier Guimard's avatar
Xavier Guimard committed
1349

1350
        $self->logger->debug("Audience conditions validated");
1351 1352
    }
    else {
1353
        $self->logger->debug("Audience conditions not checked");
1354
    }
Xavier Guimard's avatar
Xavier Guimard committed
1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373

    return 1;
}

## @method Lasso::Logout createLogoutRequest(Lasso::Server server, string session_dump, int method, boolean signSLOMessage)
# Create logout request for selected entity
# @param server Lasso::Server object
# @param session_dump Lasso::Session dump
# @param method HTTP method
# @param signSLOMessage sign request
# @return Lasso::Login object
sub createLogoutRequest {
    my ( $self, $req, $server, $session_dump, $method, $signSLOMessage ) = @_;
    my $session;

    # Create Lasso Logout
    my $logout = $self->createLogout($server);

    unless ( $self->setSessionFromDump( $logout, $session_dump ) ) {
1374
        $self->logger->error("Could not fill Lasso::Logout with session dump");
Xavier Guimard's avatar
Xavier Guimard committed
1375 1376 1377 1378 1379
        return;
    }

    # Init logout request
    unless ( $self->initLogoutRequest( $logout, undef, $method ) ) {
1380
        $self->logger->error("Could not initiate logout request");
Xavier Guimard's avatar
Xavier Guimard committed
1381 1382 1383 1384 1385 1386
        return;
    }

    # Set RelayState
    if ( my $relaystate = $self->storeRelayState( $req, 'urldc' ) ) {
        $logout->msg_relayState($relaystate);
1387
        $self->logger->debug("Set $relaystate in RelayState");
Xavier Guimard's avatar
Xavier Guimard committed
1388 1389 1390 1391
    }

    # Signature
    if ( $signSLOMessage == 0 ) {
1392
        $self->logger->debug("SLO request will not be signed");
Xavier Guimard's avatar
Xavier Guimard committed
1393 1394 1395
        $self->disableSignature($logout);
    }
    elsif ( $signSLOMessage == 1 ) {
1396
        $self->logger->debug("SLO request will be signed");
Xavier Guimard's avatar
Xavier Guimard committed
1397 1398 1399
        $self->forceSignature($logout);
    }
    else {
1400
        $self->logger->debug("SLO request signature according to metadata");
Xavier Guimard's avatar
Xavier Guimard committed
1401 1402 1403 1404
    }

    # Build logout request
    unless ( $self->buildLogoutRequestMsg($logout) ) {
1405
        $self->logger->error("Could not build logout request");
Xavier Guimard's avatar
Xavier Guimard committed
1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470
        return;
    }

    return $logout;

}

## @method Lasso::Logout createLogout(Lasso::Server server, string dump)
# Create Lasso::Logout object
# @param server Lasso::Server object
# @param dump optional XML dump
# @return Lasso::Logout object
sub createLogout {
    my ( $self, $server, $dump ) = @_;
    my $logout;

    if ($dump) {
        eval { $logout = Lasso::Logout::new_from_dump( $server, $dump ); };
    }
    else {
        eval { $logout = Lasso::Logout->new($server); };
    }

    if ($@) {
        $self->checkLassoError($@);
        return;
    }

    return $logout;
}

## @method boolean initLogoutRequest(Lasso::Logout logout, string entityID, int method)
# Init logout request
# @param logout Lasso::Logout object
# @param entityID Entity ID
# @param method HTTP method
# @return result
sub initLogoutRequest {
    my ( $self, $logout, $entityID, $method ) = @_;

    eval { Lasso::Logout::init_request( $logout, $entityID, $method ); };

    return $self->checkLassoError($@);
}

## @method boolean buildLogoutRequestMsg(Lasso::Logout logout)
# Build logout request message
# @param logout Lasso::Logout object
# @return result
sub buildLogoutRequestMsg {
    my ( $self, $logout ) = @_;

    eval { Lasso::Logout::build_request_msg($logout); };

    return $self->checkLassoError($@);
}

## @method boolean setSessionFromDump(Lasso::Profile profile, string dump)
# Set session from dump in Lasso::Profile object
# @param profile Lasso::Profile object
# @param dump Lasso::Session XML dump
# @return result
sub setSessionFromDump {
    my ( $self, $profile, $dump ) = @_;

1471
    $self->logger->debug("Loading Session dump: $dump");
Xavier Guimard's avatar
Xavier Guimard committed
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498

    eval { Lasso::Profile::set_session_from_dump( $profile, $dump ); };

    return $self->checkLassoError($@);
}

## @method boolean setIdentityFromDump(Lasso::Profile profile, string dump)
# Set identity from dump in Lasso::Profile object
# @param profile Lasso::Profile object
# @param dump Lasso::Identity XML dump
# @return result
sub setIdentityFromDump {
    my ( $self, $profile, $dump ) = @_;

    eval { Lasso::Profile::set_identity_from_dump( $profile, $dump ); };

    return $self->checkLassoError($@);
}

## @method string getMetaDataURL(string key, int index)
# Get URL stored in a service metadata configuration key
# Replace #PORTAL# macro
# @param key Metadata configuration key
# @param index field index containing URL
# @param full Return full URL instead of path
# @return url
sub getMetaDataURL {
Xavier Guimard's avatar
Xavier Guimard committed
1499
    my ( $self, $key, $index, $full ) = @_;
Xavier Guimard's avatar
Xavier Guimard committed
1500 1501 1502
    $index = 3 unless defined $index;
    $full  = 0 unless defined $full;

1503
    return '' unless defined $self->conf->{$key};
Xavier Guimard's avatar
Xavier Guimard committed
1504

1505
    my $url = ( split( /;/, $self->conf->{$key} ) )[$index] || '';
Xavier Guimard's avatar
Xavier Guimard committed
1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521

    # Get portal value
    my $portal = $self->conf->{portal};
    $portal =~ s/\/$//;

    # Replace #PORTAL# macro
    $url =~ s/#PORTAL#/$portal/g;

    # Return Full URL
    return $url if $full;

    # Return only path
    my $uri = URI->new($url);
    return $uri->path();
}

1522 1523 1524 1525
sub getRouteFromMetaDataURL {
    my ( $self, $key, $index, $sub ) = @_;
    my $uri = $self->getMetaDataURL( $key, $index, 0 );
    unless ( $uri =~ m#^/\w# ) {
1526
        $self->logger->debug("$key has no index $index");
Xavier Guimard's avatar
Xavier Guimard committed
1527
        return ();
1528 1529 1530 1531 1532 1533 1534 1535 1536
    }
    my @t = grep /\w/, split( /\//, $uri );
    my $h = { pop(@t) => $sub };
    while ( my $s = pop @t ) {
        $h = { $s => $h };
    }
    return %$h;
}

Xavier Guimard's avatar
Xavier Guimard committed
1537
sub addRouteFromMetaDataURL {
1538
    my ( $self, @args ) = @_;
Xavier Guimard's avatar
Xavier Guimard committed
1539 1540
    $self->addAuthRouteFromMetaDataURL(@args);
    $self->addUnauthRouteFromMetaDataURL(@args);
1541 1542
}

Xavier Guimard's avatar
Xavier Guimard committed
1543
sub addAuthRouteFromMetaDataURL {
1544 1545 1546 1547 1548 1549
    my ( $self, $key, $index, $sub, $methods ) = @_;
    my %route = $self->getRouteFromMetaDataURL( $key, $index, $sub );
    return unless (%route);
    $self->addAuthRoute( %route, $methods );
}

Xavier Guimard's avatar
Xavier Guimard committed
1550
sub addUnauthRouteFromMetaDataURL {
1551 1552 1553 1554 1555 1556
    my ( $self, $key, $index, $sub, $methods ) = @_;
    my %route = $self->getRouteFromMetaDataURL( $key, $index, $sub );
    return unless (%route);
    $self->addUnauthRoute( %route, $methods );
}

Xavier Guimard's avatar
Xavier Guimard committed
1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589
## @method boolean processLogoutResponseMsg(Lasso::Logout logout, string response)
# Process logout response message
# @param logout Lasso::Logout object
# @param response SAML response
# @return result
sub processLogoutResponseMsg {
    my ( $self, $logout, $response ) = @_;

    eval { Lasso::Logout::process_response_msg( $logout, $response ); };

    return $self->checkLassoError($@);
}

## @method boolean processLogoutRequestMsg(Lasso::Logout logout, string request)
# Process logout request message
# @param logout Lasso::Logout object
# @param request SAML request
# @return result
sub processLogoutRequestMsg {
    my ( $self, $logout, $request ) = @_;

    # Process the request
    eval { Lasso::Logout::process_request_msg( $logout, $request ); };

    return 0 unless $self->checkLassoError($@);

    # Check NotOnOrAfter optional attribute
    my $notOnOrAfter;

    eval { $notOnOrAfter = $logout->request()->NotOnOrAfter(); };

    return 1 if ( $@ or !$notOnOrAfter );

1590
    $self->logger->debug("Found NotOnOrAfter $notOnOrAfter in logout request");
Xavier Guimard's avatar
Xavier Guimard committed
1591 1592 1593

    my $expirationTime = $self->samldate2timestamp($notOnOrAfter);

1594
    return ( time < $expirationTime );
Xavier Guimard's avatar
Xavier Guimard committed
1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627
}

## @method boolean validateLogoutRequest(Lasso::Logout logout)
# Validate logout request
# @param logout Lasso::Logout object
# @return result
sub validateLogoutRequest {
    my ( $self, $logout ) = @_;

    eval { Lasso::Logout::validate_request($logout); };

    return $self->checkLassoError($@);
}

## @method boolean buildLogoutResponseMsg(Lasso::Logout logout)
# Build logout response message
# @param logout Lasso::Logout object
# @return boolean result
sub buildLogoutResponseMsg {
    my ( $self, $logout ) = @_;

    eval { Lasso::Logout::build_response_msg($logout); };

    return $self->checkLassoError($@);
}

## @method boolean storeReplayProtection(string samlID, string samlData)
# Store ID of an SAML message in Replay Protection base
# @param samlID ID of SAML message
# @param samlData Optional data to store
# @return result
sub storeReplayProtection {
    my ( $self, $samlID, $samlData ) = @_;
1628 1629 1630 1631 1632
    my $infos = {
        type       => 'assertion',    # Session type
        _utime     => time(),         # Creation time
        _assert_id => $samlID,
    };
Xavier Guimard's avatar
Xavier Guimard committed
1633 1634 1635 1636 1637

    if ( defined $samlData && $samlData ) {
        $infos->{data} = $samlData;
    }

1638 1639
    my $samlSessionInfo = $self->getSamlSession( undef, $infos );
    return 0 unless $samlSessionInfo;
Xavier Guimard's avatar
Xavier Guimard committed
1640 1641 1642

    my $session_id = $samlSessionInfo->id;

1643 1644
    $self->logger->debug(
        "Keep request ID $samlID in assertion session $session_id");
Xavier Guimard's avatar
Xavier Guimard committed
1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656

    return 1;
}

## @method boolean replayProtection(string samlID)
# Check if SAML message do not correspond to a previously responded message
# @param samlID ID of initial SAML message
# @return result
sub replayProtection {
    my ( $self, $samlID ) = @_;

    unless ($samlID) {
1657 1658
        $self->userLogger->error(
            "Cannot verify replay because no SAML ID given");
Xavier Guimard's avatar
Xavier Guimard committed
1659 1660 1661
        return 0;
    }

1662 1663 1664
    my $sessions =
      Lemonldap::NG::Common::Apache::Session->searchOn( $self->amOpts,
        "_assert_id", $samlID );
Xavier Guimard's avatar
Xavier Guimard committed
1665

1666 1667 1668 1669 1670 1671
    if (
        my @keys =
        grep { $sessions->{$_}->{_session_kind} eq $self->sessionKind }
        keys %$sessions
      )
    {
Xavier Guimard's avatar
Xavier Guimard committed
1672 1673 1674

        # A session was found
        foreach (@keys) {
1675 1676
            next
              unless ( $sessions->{$_}->{_session_kind} eq $self->sessionKind );
Xavier Guimard's avatar
Xavier Guimard committed
1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689
            my $session = $_;
            my $result  = 1;

            # Delete it
            my $samlSessionInfo = $self->getSamlSession($_);

            return 0 unless $samlSessionInfo;

            if ( defined $samlSessionInfo->data->{data} ) {
                $result = $samlSessionInfo->data->{data};
            }

            if ( $samlSessionInfo->remove ) {
1690 1691
                $self->logger->debug(
"Assertion session $session (Message ID $samlID) was deleted"
Xavier Guimard's avatar
Xavier Guimard committed
1692 1693 1694 1695
                );
                return $result;
            }
            else {
1696 1697
                $self->logger->error(
"Unable to delete assertion session $session (Message ID $samlID)"
Xavier Guimard's avatar
Xavier Guimard committed
1698
                );
1699
                $self->logger->error( $samlSessionInfo->error );
Xavier Guimard's avatar
Xavier Guimard committed
1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729
                return 0;
            }
        }
    }

    return 0;
}

## @method string resolveArtifact(Lasso::Profile profile, string artifact, int method)
# Resolve artifact to get real SAML message
# @param profile Lasso::Profile object
# @param artifact Artifact message
# @param method HTTP method
# @return SAML message
sub resolveArtifact {
    my ( $self, $profile, $artifact, $method ) = @_;
    my $message;

    # Login profile
    if ( $profile->isa("Lasso::Login") ) {

        # Init request message
        eval { Lasso::Login::init_request( $profile, $artifact, $method ); };
        return unless $self->checkLassoError($@);

        # Build request message
        eval { Lasso::Login::build_request_msg($profile); };
        return unless $self->checkLassoError($@);

        unless ( $profile->msg_url ) {
1730
            $self->logger->error("No artifact resolution URL found");
Xavier Guimard's avatar
Xavier Guimard committed
1731 1732 1733 1734
            return;
        }

        my $request = HTTP::Request->new( 'POST' => $profile->msg_url );
1735
        $request->content_type('application/xml');
1736
        $request->header( Accept => 'application/xml' );
Xavier Guimard's avatar
Xavier Guimard committed
1737 1738
        $request->content( $profile->msg_body );

1739 1740
        $self->logger->debug(
            "Send message " . $profile->msg_body . " to " . $profile->msg_url );
Xavier Guimard's avatar
Xavier Guimard committed
1741 1742

        # SOAP call
Xavier Guimard's avatar
Xavier Guimard committed
1743
        my $soap_answer = $self->ua->request($request);
Xavier Guimard's avatar
Xavier Guimard committed
1744 1745
        if ( $soap_answer->code() == "200" ) {
            $message = $soap_answer->content();
1746
            $self->logger->debug("Get message $message");
Xavier Guimard's avatar
Xavier Guimard committed
1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761
        }
    }

    return $message;
}

## @method boolean storeArtifact(string id, string message, string session_id)
# Store artifact
# @param id Artifact ID
# @param message Artifact content
# @param session_id Session ID
# @return result
sub storeArtifact {
    my ( $self, $id, $message, $session_id ) = @_;

1762 1763 1764 1765 1766 1767
    my $infos = {
        type    => 'artifact',    # Session type
        _utime  => time(),        # Creation time
        _art_id => $id,
        message => $message,
    };
Xavier Guimard's avatar
Xavier Guimard committed
1768 1769
    $infos->{_saml_id} = $session_id if $session_id;

1770 1771
    my $samlSessionInfo = $self->getSamlSession( undef, $infos ) or return 0;
    return 0 unless $samlSessionInfo;
Xavier Guimard's avatar
Xavier Guimard committed
1772 1773 1774

    my $art_session_id = $samlSessionInfo->id;

1775
    $self->logger->debug("Keep artifact $id in session $art_session_id");
Xavier Guimard's avatar
Xavier Guimard committed
1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788

    return 1;
}

## @method hashRef loadArtifact(string id)
# Load artifact
# @param id Artifact ID
# @return Artifact session content
sub loadArtifact {
    my ( $self, $id ) = @_;
    my $art_session;

    unless ($id) {
1789
        $self->logger->error("Cannot load artifact because no id given");
Xavier Guimard's avatar
Xavier Guimard committed
1790 1791 1792
        return;
    }

1793 1794 1795
    my $sessions =
      Lemonldap::NG::Common::Apache::Session->searchOn( $self->amOpts,
        "_art_id", $id );
Xavier Guimard's avatar
Xavier Guimard committed
1796

1797 1798 1799 1800 1801 1802
    if (
        my @keys =
        grep { $sessions->{$_}->{_session_kind} eq $self->sessionKind }
        keys %$sessions
      )
    {
Xavier Guimard's avatar
Xavier Guimard committed
1803 1804 1805

        my $nb_sessions = $#keys + 1;

1806
        $self->logger->debug("Found $nb_sessions sessions for artifact $id");
Xavier Guimard's avatar
Xavier Guimard committed
1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825

        # There should only be 1 result
        return if ( $nb_sessions != 1 );

        my $session_id = shift @keys;
        my $session    = $session_id;

        # Open session
        my $samlSessionInfo = $self->getSamlSession($session_id);

        return unless $samlSessionInfo;

        # Get session contents
        foreach ( keys %{ $samlSessionInfo->data } ) {
            $art_session->{$_} = $samlSessionInfo->data->{$_};
        }

        # Delete session
        if ( $samlSessionInfo->remove ) {
1826 1827
            $self->logger->debug(
                "Artifact session $session (ID $id) was deleted");
Xavier Guimard's avatar
Xavier Guimard committed
1828 1829 1830 1831

            return $art_session;
        }
        else {
1832 1833 1834
            $self->logger->error(
                "Unable to delete artifact session $session (ID $id)");
            $self->logger->error( $samlSessionInfo->error );
Xavier Guimard's avatar
Xavier Guimard committed
1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846
            return;
        }
    }

    return;
}

## @method string createArtifactResponse(Lasso::Login login)
# Create artifact response
# @param login Lasso::Login object
# @return Artifact response
sub createArtifactResponse {
Xavier Guimard's avatar
Xavier Guimard committed
1847
    my ( $self, $req, $login ) = @_;
Xavier Guimard's avatar
Xavier Guimard committed
1848 1849 1850 1851 1852

    my $artifact_id = $login->assertionArtifact();

    # Load artifact message into login response
    my $art_session = $self->loadArtifact($artifact_id);
Xavier Guimard's avatar
Xavier Guimard committed
1853
    utf8::decode( $art_session->{message} );
Xavier Guimard's avatar
Xavier Guimard committed
1854 1855 1856
    eval { $login->set_artifact_message( $art_session->{message} ); };
    if ($@) {
        $self->checkLassoError($@);
1857
        $self->logger->error("Cannot load artifact message");
Xavier Guimard's avatar
Xavier Guimard committed
1858 1859 1860
        return;
    }

1861
    $self->logger->debug("Response loaded");
Xavier Guimard's avatar
Xavier Guimard committed
1862 1863 1864 1865

    # Try to get Lasso session
    my $session_id = $art_session->{_saml_id};
    if ($session_id) {
1866
        $self->logger->debug("Find session_id $session_id in artifact session");
Xavier Guimard's avatar
Xavier Guimard committed
1867

Xavier Guimard's avatar
Xavier Guimard committed
1868
        my $session = $self->p->getApacheSession($session_id);
Xavier Guimard's avatar
Xavier Guimard committed
1869
        unless ($session) {
1870
            $self->logger->error("Unable to open session $session_id");
Xavier Guimard's avatar
Xavier Guimard committed
1871 1872 1873
            return;
        }

1874
        my $lassoSession = $session->data->{ $self->lsDump };
Xavier Guimard's avatar
Xavier Guimard committed
1875 1876 1877

        if ($lassoSession) {
            unless ( $self->setSessionFromDump( $login, $lassoSession ) ) {
1878
                $self->logger->error("Unable to load Lasso Session");
Xavier Guimard's avatar
Xavier Guimard committed
1879 1880
                return;
            }
1881
            $self->logger->debug("Lasso Session loaded");
Xavier Guimard's avatar
Xavier Guimard committed
1882 1883 1884 1885
        }

    }
    else {
1886
        $self->logger->debug("No session_id in artifact session");
Xavier Guimard's avatar
Xavier Guimard committed
1887 1888 1889 1890 1891 1892
    }

    # Build artifact response
    eval { Lasso::Login::build_response_msg($login); };
    if ($@) {
        $self->checkLassoError($@);
1893
        $self->logger->error("Cannot build artifact response");
Xavier Guimard's avatar
Xavier Guimard committed
1894 1895
        return;
    }
1896
    $self->logger->debug("Artifact response built");
Xavier Guimard's avatar
Xavier Guimard committed
1897 1898 1899

    # Store Lasso session if session opened
    if ( $session_id and $login->is_session_dirty ) {
1900
        $self->logger->debug("Save Lasso session in session");
Xavier Guimard's avatar
Xavier Guimard committed
1901
        $self->updateSession( $req,
1902
            { $self->lsDump => $login->get_session->dump }, $session_id );
Xavier Guimard's avatar
Xavier Guimard committed
1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951