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

filter: Statementstmt 21.4% 70 / 327 Branchbran 1.8% 2 / 108 Conditioncond 0.0% 0 / 38 MC/DCmcdc 0.0% 0 / 20 Subroutinesub 60.5% 23 / 38 Podpod n/a totaltotal 17.8% 95 / 531 CC 75 SCAR 47.3
CC
75
Cov
15%
load_sp_metadata
342.0
checkMessage
272.0
load_idp_metadata
90.0
CRAP 112.8
« blib/lib/Lemonldap/NG/Portal/Auth/LDAP.pm ↑ Summary blib/lib/Lemonldap/NG/Portal/Plugins/OIDC/DynamicRegistration.pm »
1 package Lemonldap::NG::Portal::Lib::SAML;
2  
3 3 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 3 ▶use Mouse;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 3 ▶use Lemonldap::NG::Common::Conf::SAML::Metadata;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 3 ▶use Lemonldap::NG::Common::Session;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 3 ▶use Lemonldap::NG::Common::UserAgent;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 3 ▶use Lemonldap::NG::Common::FormEncode;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 3 ▶use HTML::Entities qw(decode_entities encode_entities);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 3 ▶use XML::LibXML;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 3 ▶use MIME::Base64;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 3 ▶use HTTP::Request; # SOAP call
Subroutine BEGIN: called CC=1 SCAR=0.0
13 3 ▶use POSIX qw(strftime); # Convert SAML2 date into timestamp
Subroutine BEGIN: called CC=1 SCAR=0.0
14 3 ▶use Time::Local; # Convert SAML2 date into timestamp
Subroutine BEGIN: called CC=1 SCAR=0.0
15 3 ▶use Encode; # Encode attribute values
Subroutine BEGIN: called CC=1 SCAR=0.0
16 3 ▶use URI; # Get metadata URL path
Subroutine BEGIN: called CC=1 SCAR=0.0
17 3 ▶use Lemonldap::NG::Portal::Main::Constants qw(
Subroutine BEGIN: called CC=1 SCAR=0.0
18 PE_OK
19 PE_REDIRECT
20 PE_LOGOUT_OK
21 PE_SLO_ERROR
22 3 );
23  
24 with 'Lemonldap::NG::Portal::Lib::LazyLoadedConfiguration';
25  
26 our $VERSION = '2.23.0';
27  
28 # PROPERTIES
29  
30 has lassoServer => ( is => 'rw' );
31 has idpList => ( is => 'rw', default => sub { {} } );
32 has idpRules => ( is => 'rw', default => sub { {} } );
33 has idpAttributes => ( is => 'rw', default => sub { {} } );
34 has idpOptions => ( is => 'rw', default => sub { {} } );
35 has spList => ( is => 'rw', default => sub { {} } );
36 has spRules => ( is => 'rw', default => sub { {} } );
37 has spLevelRules => ( is => 'rw', default => sub { {} } );
38 has spMacros => ( is => 'rw', default => sub { {} } );
39 has spAttributes => ( is => 'rw', default => sub { {} } );
40 has spOptions => ( is => 'rw', default => sub { {} } );
41  
42 # XML parser
43 has parser => (
44 is => 'rw',
45 builder => sub {
46 return XML::LibXML->new( load_ext_dtd => 0, expand_entities => 0 );
47 }
48 );
49  
50 # return LWP::UserAgent object
51 has ua => (
52 is => 'rw',
53 lazy => 1,
54 builder => sub {
55  
56 # TODO : LWP options to use a proxy for example
57 my $ua = Lemonldap::NG::Common::UserAgent->new( $_[0]->{conf} );
58 $ua->env_proxy();
59 return $ua;
60 }
61 );
62  
63 # SAML storage
64 has aModule => ( is => 'rw' );
65 has amOpts => ( is => 'rw' );
66  
67 # INITIALIZATION
68  
69 3 ▶BEGIN {
Subroutine BEGIN: called CC=5 SCAR=19.6
70  
71 # Load Glib if available
72 0 ▶ eval 'use Glib;';
Subroutine BEGIN: called CC=1 SCAR=1.2
73 3 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) { } 3 0 3
74 3 print STDERR
75 "Glib Lasso messages will not be catched (require Glib module)\n";
76 3 ▶ eval "use constant GLIB => 0";
Subroutine BEGIN: called CC=1 SCAR=0.0
77 }
78 else {
79 0 eval "use constant GLIB => 1";
80 }
81  
82 # Load Lasso.pm
83 0 ▶ eval 'use Lasso;';
Subroutine BEGIN: called CC=1 SCAR=1.2
84 3 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) { } 3 0 3
85 3 print STDERR "Lasso.pm not loaded: $@";
86 eval
87 3 ▶'use constant LASSO => 0;use constant BADLASSO => 0;use constant LASSOTHINSESSIONS => 0';
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
88 }
89 else {
90 3 ▶ no strict 'subs';
Subroutine BEGIN: called CC=1 SCAR=0.0
91 0 eval 'use constant LASSO => 1';
92  
93 # Check Lasso version >= 2.3.0
94 0 my $lasso_check_version_mode =
95 eval 'Lasso::Constants::CHECK_VERSION_NUMERIC';
96 0 my $check_version =
97 Lasso::check_version( 2, 3, 0, $lasso_check_version_mode );
98 0 ▶ unless ($check_version) {
Branch: 1 branch
BranchTrueFalseTotal
if ($check_version) { } 0 0 0
99 0 eval 'use constant BADLASSO => 1';
100 }
101 else {
102 0 eval 'use constant BADLASSO => 0';
103 }
104  
105 # Try to set thin-sessions flag
106 0 eval 'Lasso::set_flag("thin-sessions");';
107 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) { } 0 0 0
108 0 eval 'use constant LASSOTHINSESSIONS => 0';
109 }
110 else {
111 0 eval 'use constant LASSOTHINSESSIONS => 1';
112 }
113 }
114  
115 }
116  
117 0 ▶sub init {
Subroutine init: not called CC=7 SCAR=40.3
118 0 my ($self) = @_;
119  
120 # Initialize SAML storage
121 0 my $moduleOptions;
122 0 ▶ if ( $self->conf->{samlStorage} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->conf->{'samlStorage'}) { } 0 0 0
123 0 ▶ $moduleOptions = $self->conf->{samlStorageOptions} || {};
Condition0%0/2
$self->conf->{'samlStorageOptions'} || {}
l!l
00
MC/DC0%0/1
$self->conf->{'samlStorageOptions'} || {}
$self->conf->{'samlStorageOptions'}
Truth table0%0/2
A
A= $self->conf->{'samlStorageOptions'}
Aresult
11
00
124 0 $moduleOptions->{backend} = $self->conf->{samlStorage};
125 }
126 else {
127 0 ▶ $moduleOptions = $self->conf->{globalStorageOptions} || {};
Condition0%0/2
$self->conf->{'globalStorageOptions'} || {}
l!l
00
MC/DC0%0/1
$self->conf->{'globalStorageOptions'} || {}
$self->conf->{'globalStorageOptions'}
Truth table0%0/2
A
A= $self->conf->{'globalStorageOptions'}
Aresult
11
00
128 0 $moduleOptions->{backend} = $self->conf->{globalStorage};
129 }
130 0 $self->aModule( $moduleOptions->{backend} );
131 0 $self->amOpts($moduleOptions);
132  
133 # Check for Lasso errors/messages (see BEGIN)
134 0 unless (LASSO) {
135 0 $self->logger->error("Module Lasso not loaded (see below)");
136 0 return 0;
137 }
138  
139 0 if (BADLASSO) {
140 $self->logger->error('Lasso version >= 2.3.0 required');
141 return 0;
142 }
143  
144 0 unless (LASSOTHINSESSIONS) {
145 0 $self->logger->warn('Lasso thin-sessions flag could not be set');
146 }
147 else {
148 $self->logger->debug('Lasso thin-sessions flag set');
149 }
150 0 if (GLIB) {
151 Glib::Log->set_handler(
152 "Lasso",
153 [qw/ error critical warning message info debug /],
154 0 ▶ sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
155 0 $self->logger->debug(
156 $_[0] . " error " . $_[1] . ": " . $_[2] );
157 }
158 );
159 }
160  
161 # Conf initialization
162  
163 0 ▶ return 0 unless ( $self->lassoServer( $self->loadService ) );
Branch: 1 branch
BranchTrueFalseTotal
unless $self->lassoServer($self->loadService) 0 0 0
164 $self->addUnauthRoute(
165 0 ▶ ( $self->{path} || 'saml' ) =>
Condition0%0/2
$self->{'path'} || 'saml'
l!l
00
MC/DC0%0/1
$self->{'path'} || 'saml'
$self->{'path'}
Truth table0%0/2
A
A= $self->{'path'}
Aresult
11
00
166 { 'metadata' => { ':type' => 'metadata' } },
167 ['GET']
168 );
169 $self->addAuthRoute(
170 0 ▶ ( $self->{path} || 'saml' ) =>
Condition0%0/2
$self->{'path'} || 'saml'
l!l
00
MC/DC0%0/1
$self->{'path'} || 'saml'
$self->{'path'}
Truth table0%0/2
A
A= $self->{'path'}
Aresult
11
00
171 { 'metadata' => { ':type' => 'metadata' } },
172 ['GET']
173 );
174 0 return 1;
175 }
176  
177 # METHODS
178  
179 0 ▶sub loadService {
Subroutine loadService: not called CC=6 SCAR=37.4
180 0 my ($self) = @_;
181  
182 # Check if certificate is available
183 0 my $signing_key =
184 $self->get_private_key( $self->_get_default_signing_key_name );
185 0 ▶ unless ($signing_key) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($signing_key) 0 0 0
186 0 $self->logger->error(
187 'SAML private and public key not found in configuration');
188 0 return 0;
189 }
190  
191 0 my $serviceCertificate;
192 0 ▶ if ( $self->conf->{samlServiceUseCertificateInResponse}
Branch: 1 branch
BranchTrueFalseTotal
if ($self->conf->{"samlServiceUseCertificateInResponse"} and $signing_key->{"public"} =~ /CERTIFICATE/) 0 0 0
Condition0%0/3
$self->conf->{"samlServiceUseCertificateInResponse"} and $signing_key->{"public"} =~ /CERTIFICATE/
!ll&&!rl&&r
000
MC/DC0%0/2
$self->conf->{"samlServiceUseCertificateInResponse"} and $signing_key->{"public"} =~ /CERTIFICATE/
$self->conf->{"samlServiceUseCertificateInResponse"} $signing_key->{"public"} =~ /CERTIFICATE/
Truth table0%0/3
A and B
A= $self->conf->{"samlServiceUseCertificateInResponse"}B= $signing_key->{"public"} =~ /CERTIFICATE/
ABresult
0X0
100
111
193 and $signing_key->{public} =~ /CERTIFICATE/ )
194 {
195 0 $serviceCertificate = $signing_key->{public};
196 0 $self->logger->debug('Certificate will be used in SAML responses');
197  
198 }
199  
200 # Get metadata from configuration
201 0 $self->logger->debug("Get Metadata for this service");
202 0 my $metadata = $self->_get_metadata_xml( undef, "all" );
203  
204 0 $self->logger->debug("Create Lasso server");
205  
206 0 my $encryption_key =
207 $self->get_private_key( $self->_get_default_encryption_key_name );
208  
209 # Create Lasso server with service metadata
210 my $server = $self->createServer(
211 $metadata,
212 $signing_key->{private},
213 $signing_key->{password},
214  
215 # use signature cert for encryption unless defined
216 (
217 $encryption_key
218 ? ( $encryption_key->{private}, $encryption_key->{password}, )
219 : ( $signing_key->{private}, $signing_key->{password}, )
220 0 ▶ ),
Branch: 1 branch
BranchTrueFalseTotal
$encryption_key ? : 0 0 0
221 $serviceCertificate
222 );
223  
224 0 ▶ unless ($server) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($server) 0 0 0
225 0 $self->logger->error('Unable to create Lasso server');
226 0 return 0;
227 }
228  
229 # Signature method
230 0 my $method = $self->getDefaultSignatureMethod();
231 0 $server->signature_method( $self->getSignatureMethod($method) );
232 0 $self->logger->debug("Set $method as SAML server signature method ");
233  
234 # Log
235 0 $self->logger->debug("Service created");
236  
237 0 return $server;
238 }
239  
240 0 ▶sub loadIDPs {
Subroutine loadIDPs: not called CC=2 SCAR=17.9
241 0 my ($self) = @_;
242  
243 # Load identity provider metadata
244 # IDP metadata are listed in $self->{samlIDPMetaDataXML}
245 # Each key is the IDP name
246 # Build IDP list for later use in extractFormInfo
247 0 foreach ( keys %{ $self->conf->{samlIDPMetaDataXML} } ) {
248 0 $self->loadIDP($_);
249 }
250 0 return 1;
251 }
252  
253 0 ▶sub loadIDP {
Subroutine loadIDP: not called CC=3 SCAR=24.8
254 0 my ( $self, $idpConfKey ) = @_;
255  
256 0 $self->logger->debug("Get Metadata for IDP $idpConfKey");
257  
258 # If XML metadata has been set in conf, load this provider from conf
259 my $idp_metadata =
260 0 $self->conf->{samlIDPMetaDataXML}->{$idpConfKey}->{samlIDPMetaDataXML};
261 0 ▶ if ($idp_metadata) {
Branch: 1 branch
BranchTrueFalseTotal
if ($idp_metadata) 0 0 0
262 0 ▶ if ( $self->load_idp_from_conf( $idpConfKey, $idp_metadata ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->load_idp_from_conf($idpConfKey, $idp_metadata)) { } 0 0 0
263 0 $self->logger->debug("IDP $idpConfKey added");
264 }
265 else {
266 0 $self->logger->warn("Ignoring IDP $idpConfKey");
267 }
268 }
269 }
270  
271 0 ▶sub load_idp_from_conf {
Subroutine load_idp_from_conf: not called CC=3 SCAR=24.8
272 0 my ( $self, $idpConfKey, $idp_metadata ) = @_;
273  
274 # Check metadata format
275 0 ▶ if ( ref $idp_metadata eq "HASH" ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $idp_metadata eq "HASH") 0 0 0
276 0 $self->logger->error(
277 "Metadata for IDP $idpConfKey is in old format. Please reload them from Manager"
278 );
279 0 return;
280 }
281  
282 0 ▶ if ( $self->conf->{samlMetadataForceUTF8} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->conf->{"samlMetadataForceUTF8"}) 0 0 0
283 0 $idp_metadata = encode( "utf8", $idp_metadata );
284 }
285  
286 # Store IDP entityID and Organization Name
287 0 my ( $tmp, $entityID ) = ( $idp_metadata =~ /entityID=(['"])(.+?)\1/si );
288  
289 # Decode HTML entities from entityID
290 # TODO: see Lasso comment above
291 0 decode_entities($entityID);
292  
293 return $self->load_idp_metadata(
294 $idpConfKey,
295 $idp_metadata,
296 $entityID,
297 $self->conf->{samlIDPMetaDataExportedAttributes}->{$idpConfKey},
298 0 $self->conf->{samlIDPMetaDataOptions}->{$idpConfKey},
299 );
300 }
301  
302 0 ▶sub load_idp_metadata {
Subroutine load_idp_metadata: not called CC=9 SCAR=45.0
303 0 my ( $self, $idpConfKey, $idp_metadata, $entityID, $attributes, $options )
304 = @_;
305  
306 # Add this IDP to Lasso::Server
307 0 my $result = $self->addIDP( $self->lassoServer, $idp_metadata );
308  
309 0 ▶ unless ($result) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($result) 0 0 0
310 0 $self->logger->error("Fail to use IDP $idpConfKey Metadata");
311 0 return;
312 }
313  
314 0 ▶ my $name = $self->getOrganizationName( $self->lassoServer, $entityID )
Condition0%0/3
$self->getOrganizationName($self->lassoServer, $entityID) || ucfirst $idpConfKey
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->getOrganizationName($self->lassoServer, $entityID) || ucfirst $idpConfKey
$self->getOrganizationName($self->lassoServer, $entityID) ucfirst $idpConfKey
Truth table0%0/3
A || B
A= $self->getOrganizationName($self->lassoServer, $entityID)B= ucfirst $idpConfKey
ABresult
1X1
011
000
315 || ucfirst($idpConfKey);
316 0 $self->idpList->{$entityID}->{confKey} = $idpConfKey;
317 0 $self->idpList->{$entityID}->{name} = $name;
318  
319 # Set encryption mode
320 my $encryption_mode =
321 0 ▶ $options->{samlIDPMetaDataOptionsEncryptionMode} || "none";
Condition0%0/2
$options->{'samlIDPMetaDataOptionsEncryptionMode'} || 'none'
l!l
00
MC/DC0%0/1
$options->{'samlIDPMetaDataOptionsEncryptionMode'} || 'none'
$options->{'samlIDPMetaDataOptionsEncryptionMode'}
Truth table0%0/2
A
A= $options->{'samlIDPMetaDataOptionsEncryptionMode'}
Aresult
11
00
322 0 my $lasso_encryption_mode = $self->getEncryptionMode($encryption_mode);
323  
324 0 ▶ unless (
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->setProviderEncryptionMode($self->lassoServer->get_provider($entityID), $lasso_encryption_mode)) 0 0 0
325 $self->setProviderEncryptionMode(
326 $self->lassoServer->get_provider($entityID),
327 $lasso_encryption_mode
328 )
329 )
330 {
331 0 $self->logger->error(
332 "Unable to set encryption mode $encryption_mode on IDP $idpConfKey"
333 );
334 0 delete $self->idpList->{$entityID};
335 0 return;
336 }
337 $self->logger->debug(
338 0 "Set encryption mode $encryption_mode on IDP $idpConfKey");
339  
340 # Set signature method if overridden
341 0 my $signature_method = $options->{samlIDPMetaDataOptionsSignatureMethod};
342 0 my $signature_key = $options->{samlIDPMetaDataOptionsSignatureKey};
343 0 $self->_override_signature_or_key( $entityID, "IDP $idpConfKey",
344 $signature_method, $signature_key );
345  
346 # Set display options
347 $self->idpList->{$entityID}->{displayName} =
348 0 $options->{samlIDPMetaDataOptionsDisplayName};
349 $self->idpList->{$entityID}->{icon} =
350 0 $options->{samlIDPMetaDataOptionsIcon};
351 $self->idpList->{$entityID}->{tooltip} =
352 0 $options->{samlIDPMetaDataOptionsTooltip};
353 $self->idpList->{$entityID}->{order} =
354 0 $options->{samlIDPMetaDataOptionsSortNumber};
355  
356 # Set rule
357 0 my $cond = $options->{samlIDPMetaDataOptionsResolutionRule};
358 0 ▶ if ( length $cond ) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $cond) 0 0 0
359 0 $cond = $self->p->HANDLER->substitute($cond);
360 0 ▶ unless ( $cond = $self->p->HANDLER->buildSub($cond) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($cond = $self->p->HANDLER->buildSub($cond)) 0 0 0
361 $self->logger->error( 'SAML IdP rule error: '
362 0 . $self->p->HANDLER->tsv->{jail}->error );
363 0 delete $self->idpList->{$entityID};
364 0 return;
365 }
366 0 $self->idpRules->{$entityID} = $cond;
367 }
368  
369 0 ▶ $self->idpAttributes->{$entityID} = { %{ $attributes || {} } };
Condition0%0/2
$attributes || {}
l!l
00
MC/DC0%0/1
$attributes || {}
$attributes
Truth table0%0/2
A
A= $attributes
Aresult
11
00
370 0 ▶ $self->idpOptions->{$entityID} = { %{ $options || {} } };
Condition0%0/2
$options || {}
l!l
00
MC/DC0%0/1
$options || {}
$options
Truth table0%0/2
A
A= $options
Aresult
11
00
371  
372 0 return 1;
373 }
374  
375 0 ▶sub loadSPs {
Subroutine loadSPs: not called CC=2 SCAR=17.9
376 0 my ($self) = @_;
377  
378 # Load service provider metadata
379 # SP metadata are listed in $self->{samlSPMetaDataXML}
380 # Each key is the SP name
381 # Build SP list for later use in extractFormInfo
382 0 foreach ( keys %{ $self->conf->{samlSPMetaDataXML} } ) {
383 0 $self->loadSP($_);
384 }
385 0 return 1;
386 }
387  
388 # This loads either a single SP or a federation
389 0 ▶sub loadSP {
Subroutine loadSP: not called CC=2 SCAR=17.9
390 0 my ( $self, $spConfKey ) = @_;
391  
392 0 $self->logger->debug("Get Metadata for SP $spConfKey");
393  
394 # If XML metadata has been set in conf, load this provider from conf
395 my $sp_metadata =
396 0 $self->conf->{samlSPMetaDataXML}->{$spConfKey}->{samlSPMetaDataXML};
397 0 ▶ if ($sp_metadata) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sp_metadata) 0 0 0
398 0 $self->load_sp_from_conf( $spConfKey, $sp_metadata );
399 0 $self->logger->debug("SP $spConfKey added");
400 }
401 }
402  
403 0 ▶sub load_sp_from_conf {
Subroutine load_sp_from_conf: not called CC=3 SCAR=24.8
404 0 my ( $self, $spConfKey, $sp_metadata ) = @_;
405  
406 # Check metadata format
407 0 ▶ if ( ref $sp_metadata eq "HASH" ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $sp_metadata eq "HASH") 0 0 0
408 0 $self->logger->error(
409 "Metadata for SP $spConfKey is in old format. Please reload them from Manager"
410 );
411 0 return;
412 }
413  
414 0 ▶ if ( $self->conf->{samlMetadataForceUTF8} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->conf->{"samlMetadataForceUTF8"}) 0 0 0
415 0 $sp_metadata = encode( "utf8", $sp_metadata );
416 }
417  
418 # Get SP entityID
419 # TODO: when Lasso issue #35061 is fixed in all distros,
420 # we could load the metadata into a new LassoProvider, extract the
421 # parsed-and-decoded entityID from this Provider, and then add the
422 # Provider into the server with $server->add_provider2, instead of
423 # extracting and decoding HTML entities ourselves here
424 0 my ( $tmp, $entityID ) = ( $sp_metadata =~ /entityID=(['"])(.+?)\1/si );
425 0 decode_entities($entityID);
426  
427 return $self->load_sp_metadata(
428 $spConfKey,
429 $sp_metadata,
430 $entityID,
431 $self->conf->{samlSPMetaDataExportedAttributes}->{$spConfKey},
432 $self->conf->{samlSPMetaDataOptions}->{$spConfKey},
433 0 $self->conf->{samlSPMetaDataMacros}->{$spConfKey},
434 );
435 }
436  
437 0 ▶sub load_sp_metadata {
Subroutine load_sp_metadata: not called CC=18 SCAR=58.3
438 0 my ( $self, $spConfKey, $sp_metadata, $entityID, $attributes, $options,
439 $macros )
440 = @_;
441  
442 0 my $valid = 1;
443  
444 # Check if SP is activated
445 0 ▶ unless ( $options->{samlSPMetaDataOptionsActivation} // 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($options->{"samlSPMetaDataOptionsActivation"} // 1) 0 0 0
Condition0%0/2
$options->{"samlSPMetaDataOptionsActivation"} // 1
l!l
00
MC/DC0%0/1
$options->{"samlSPMetaDataOptionsActivation"} // 1
$options->{"samlSPMetaDataOptionsActivation"}
Truth table0%0/2
A
A= $options->{"samlSPMetaDataOptionsActivation"}
Aresult
11
00
446 0 $self->logger->debug("SP $spConfKey deactivated");
447 0 return 0;
448 }
449  
450 # Access Rule
451 0 my $rule = $options->{samlSPMetaDataOptionsRule};
452 0 ▶ if ( length $rule ) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $rule) 0 0 0
453 0 $rule = $self->p->buildRule( $rule, "access rule for SP $spConfKey" );
454 0 ▶ unless ($rule) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($rule) 0 0 0
455 0 $valid = 0;
456 }
457 }
458  
459 # Required authentication level rule
460 my $levelrule =
461 $options->{samlSPMetaDataOptionsAuthnLevel}
462 || $self->conf->{defaultAuthnLevel}
463 0 ▶ || 0;
Condition0%0/5
$options->{'samlSPMetaDataOptionsAuthnLevel'} || $self->conf->{'defaultAuthnLevel'} || 0
l!l
00
$options->{"samlSPMetaDataOptionsAuthnLevel"} or $self->conf->{"defaultAuthnLevel"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$options->{'samlSPMetaDataOptionsAuthnLevel'} || $self->conf->{'defaultAuthnLevel'} || 0
$options->{"samlSPMetaDataOptionsAuthnLevel"} $self->conf->{"defaultAuthnLevel"}
Truth table0%0/3
A or B
A= $options->{"samlSPMetaDataOptionsAuthnLevel"}B= $self->conf->{"defaultAuthnLevel"}
ABresult
1X1
011
000
464 0 $levelrule = $self->p->buildRule( $levelrule,
465 "Required authentication level rule for SP $spConfKey" );
466 0 ▶ unless ($levelrule) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($levelrule) 0 0 0
467 0 $valid = 0;
468 }
469  
470 # Load per-SP macros
471 0 my $compiledMacros = {};
472 0 for my $macroAttr ( keys %{$macros} ) {
473 0 my $macroRule = $macros->{$macroAttr};
474 0 ▶ if ( length $macroRule ) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $macroRule) 0 0 0
475 0 $macroRule = $self->p->HANDLER->substitute($macroRule);
476 0 ▶ if ( $macroRule = $self->p->HANDLER->buildSub($macroRule) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($macroRule = $self->p->HANDLER->buildSub($macroRule)) { } 0 0 0
477 0 $compiledMacros->{$macroAttr} = $macroRule;
478 }
479 else {
480 0 $valid = 0;
481 $self->logger->error(
482 "Error processing macro $macroAttr for SAML SP $spConfKey"
483 0 . $self->p->HANDLER->tsv->{jail}->error );
484 }
485 }
486 }
487  
488 0 ▶ if ($valid) {
Branch: 1 branch
BranchTrueFalseTotal
if ($valid) { } 0 0 0
489 0 $self->spRules->{$spConfKey} = $rule;
490 0 $self->spLevelRules->{$spConfKey} = $levelrule;
491 0 $self->spMacros->{$spConfKey} = $compiledMacros;
492 }
493 else {
494 0 $self->logger->error(
495 "SAML SP $spConfKey has errors and will be ignored");
496 0 return;
497 }
498  
499 0 ▶ $self->spAttributes->{$entityID} = { %{ $attributes || {} } };
Condition0%0/2
$attributes || {}
l!l
00
MC/DC0%0/1
$attributes || {}
$attributes
Truth table0%0/2
A
A= $attributes
Aresult
11
00
500  
501 0 ▶ $self->spOptions->{$entityID} = { %{ $options || {} } };
Condition0%0/2
$options || {}
l!l
00
MC/DC0%0/1
$options || {}
$options
Truth table0%0/2
A
A= $options
Aresult
11
00
502  
503 # Add this SP to Lasso::Server
504 0 my $result = $self->addSP( $self->lassoServer, $sp_metadata );
505  
506 0 ▶ unless ($result) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($result) 0 0 0
507 0 $self->logger->error("Fail to use SP $spConfKey Metadata");
508 0 return;
509 }
510  
511 # Store Org name
512 0 ▶ my $name = $self->getOrganizationName( $self->lassoServer, $entityID )
Condition0%0/3
$self->getOrganizationName($self->lassoServer, $entityID) || ucfirst $spConfKey
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->getOrganizationName($self->lassoServer, $entityID) || ucfirst $spConfKey
$self->getOrganizationName($self->lassoServer, $entityID) ucfirst $spConfKey
Truth table0%0/3
A || B
A= $self->getOrganizationName($self->lassoServer, $entityID)B= ucfirst $spConfKey
ABresult
1X1
011
000
513 || ucfirst($spConfKey);
514 0 $self->spList->{$entityID}->{confKey} = $spConfKey;
515 0 $self->spList->{$entityID}->{name} = $name;
516  
517 # Set encryption mode
518 my $encryption_mode =
519 0 ▶ $options->{samlSPMetaDataOptionsEncryptionMode} || "none";
Condition0%0/2
$options->{'samlSPMetaDataOptionsEncryptionMode'} || 'none'
l!l
00
MC/DC0%0/1
$options->{'samlSPMetaDataOptionsEncryptionMode'} || 'none'
$options->{'samlSPMetaDataOptionsEncryptionMode'}
Truth table0%0/2
A
A= $options->{'samlSPMetaDataOptionsEncryptionMode'}
Aresult
11
00
520 0 my $lasso_encryption_mode = $self->getEncryptionMode($encryption_mode);
521  
522 0 ▶ unless (
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->setProviderEncryptionMode($self->lassoServer->get_provider($entityID), $lasso_encryption_mode)) 0 0 0
523 $self->setProviderEncryptionMode(
524 $self->lassoServer->get_provider($entityID),
525 $lasso_encryption_mode
526 )
527 )
528 {
529 0 $self->logger->error(
530 "Unable to set encryption mode $encryption_mode on SP $spConfKey");
531 0 return;
532 }
533 $self->logger->debug(
534 0 "Set encryption mode $encryption_mode on SP $spConfKey");
535  
536 # Set signature method if overridden
537 0 my $signature_method = $options->{samlSPMetaDataOptionsSignatureMethod};
538 0 my $signature_key = $options->{samlSPMetaDataOptionsSignatureKey};
539 0 $self->_override_signature_or_key( $entityID, "SP $spConfKey",
540 $signature_method, $signature_key );
541 }
542  
543 0 ▶sub lazy_load_message {
Subroutine lazy_load_message: not called CC=3 SCAR=24.8
544 0 my ( $self, $message ) = @_;
545 0 ▶ return unless $message;
Branch: 1 branch
BranchTrueFalseTotal
unless $message 0 0 0
546 0 my $entityID = $self->getIssuer($message);
547 0 ▶ if ($entityID) {
Branch: 1 branch
BranchTrueFalseTotal
if ($entityID) 0 0 0
548 0 $self->logger->debug("Found entityID $entityID in message");
549 0 return $self->lazy_load_entityid($entityID);
550 }
551 }
552  
553 0 ▶sub lazy_load_entityid {
Subroutine lazy_load_entityid: not called CC=3 SCAR=24.8
554 0 my ( $self, $entityID ) = @_;
555 0 ▶ return unless $entityID;
Branch: 1 branch
BranchTrueFalseTotal
unless $entityID 0 0 0
556 0 my $provider = $self->lassoServer->get_provider($entityID);
557 0 ▶ unless ($provider) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($provider) 0 0 0
558 0 $self->logger->debug("Lazy loading provider $entityID");
559  
560 0 return $self->lazy_load_config($entityID);
561 }
562 }
563  
564 0 ▶sub load_config {
Subroutine load_config: not called CC=7 SCAR=40.3
565 0 my ( $self, $entityID ) = @_;
566  
567 0 my $config = {};
568 0 my $res = $self->p->processHook( {}, 'getSamlConfig', $entityID, $config );
569 0 ▶ if ( $res != PE_OK ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($res != 0) 0 0 0
570 0 return;
571 }
572  
573 0 my $info;
574 0 ▶ if ( $config->{sp_metadata} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($config->{"sp_metadata"}) 0 0 0
575 0 $info->{sp_confKey} = $config->{sp_confKey};
576 $self->load_sp_metadata(
577 $config->{sp_confKey}, $config->{sp_metadata},
578 $entityID, $config->{sp_attributes},
579 $config->{sp_options}, $config->{sp_macros},
580 0 );
581  
582 }
583  
584 0 ▶ if ( $config->{idp_metadata} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($config->{"idp_metadata"}) 0 0 0
585 0 $info->{idp_confKey} = $config->{idp_confKey};
586 0 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if ($self->load_idp_metadata($config->{'idp_confKey'}, $config->{'idp_metadata'}, $entityID, $config->{'idp_attributes'}, $config->{'idp_options'})) { } 0 0 0
587 $self->load_idp_metadata(
588 $config->{idp_confKey}, $config->{idp_metadata},
589 $entityID, $config->{idp_attributes},
590 $config->{idp_options}
591 )
592 )
593 {
594 0 $self->logger->debug("IDP $config->{idp_confKey} added from hook");
595 }
596 else {
597 0 $self->logger->warn("Ignoring IDP $config->{idp_confKey}");
598 }
599 }
600 0 my $ttl = $config->{ttl};
601 0 ▶ return { ( $ttl ? ( ttl => $ttl ) : () ),
Branch: 2 branches
BranchTrueFalseTotal
$ttl ? : 0 0 0
$info ? : 0 0 0
602 ( $info ? ( info => $info ) : () ) };
603 }
604  
605 # This method returns the configuration info for the given provider
606 # Returns a hashref or undef
607  
608 # Check SAML requests and responses
609 0 ▶sub checkMessage {
Subroutine checkMessage: not called CC=16 SCAR=56.1
610 0 my ( $self, $req, $url, $request_method, $content_type, $profile_type ) =
611 @_;
612 0 ▶ $profile_type ||= "login";
Condition0%0/2
$profile_type ||= "login"
l!l
00
MC/DC0%0/1
$profile_type ||= "login"
$profile_type
Truth table0%0/2
A
A= $profile_type
Aresult
11
00
613  
614 # Create Profile object
615 0 my $profile;
616 0 ▶ $profile = $self->createLogin( $self->lassoServer )
Branch: 1 branch
BranchTrueFalseTotal
if $profile_type eq "login" 0 0 0
617 if ( $profile_type eq "login" );
618 0 ▶ $profile = $self->createLogout( $self->lassoServer )
Branch: 1 branch
BranchTrueFalseTotal
if $profile_type eq "logout" 0 0 0
619 if ( $profile_type eq "logout" );
620  
621 # Get relayState
622 0 my $relaystate = $req->param('RelayState');
623 0 my ( $method, $request, $response, $artifact, $message );
624  
625 # 2.1. HTTP REDIRECT
626 0 ▶ if ( $request_method eq 'GET' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($request_method eq 'GET') { } 0 0 0
elsif ($request_method =~ /^POST$/) { } 0 0 0
627  
628 0 $method = Lasso::Constants::HTTP_METHOD_REDIRECT;
629 0 $self->logger->debug("SAML method: HTTP-REDIRECT");
630  
631 0 ▶ if ( $req->param('SAMLResponse') ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($req->param("SAMLResponse")) 0 0 0
632  
633 # Response in query string
634 0 $response = $self->getQueryString($req);
635 0 $self->logger->debug("HTTP-REDIRECT: SAML Response $response");
636  
637 }
638  
639 0 ▶ if ( $req->param('SAMLRequest') ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($req->param("SAMLRequest")) 0 0 0
640  
641 # Request in query string
642 0 $request = $self->getQueryString($req);
643 0 $self->logger->debug("HTTP-REDIRECT: SAML Request $request");
644  
645 }
646  
647 0 ▶ if ( $req->param('SAMLart') ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($req->param("SAMLart")) 0 0 0
648  
649 # Artifact in query string
650 0 $artifact = $self->getQueryString($req);
651 0 $self->logger->debug("HTTP-REDIRECT: SAML Artifact $artifact");
652  
653 # Resolve Artifact
654 0 $method = Lasso::Constants::HTTP_METHOD_ARTIFACT_GET;
655 0 $message = $self->resolveArtifact( $profile, $artifact, $method );
656  
657 # Request or response ?
658 0 ▶ if ( $self->_isArtifactSamlResponse($message) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_isArtifactSamlResponse($message)) { } 0 0 0
659 0 $response = $message;
660 }
661 else {
662 0 $request = $message;
663 }
664 }
665  
666 }
667  
668 # 2.2. HTTP POST AND SOAP
669 elsif ( $request_method =~ /^POST$/ ) {
670  
671 # 2.2.1. POST
672 0 ▶ if ( $content_type !~ /xml/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $content_type =~ /xml/) { } 0 0 0
673  
674 0 $method = Lasso::Constants::HTTP_METHOD_POST;
675 0 $self->logger->debug("SAML method: HTTP-POST");
676  
677 0 ▶ if ( $req->param('SAMLResponse') ) {
Branch: 3 branches
BranchTrueFalseTotal
if ($req->param('SAMLResponse')) { } 0 0 0
elsif ($req->param('SAMLRequest')) { } 0 0 0
elsif ($req->param('SAMLart')) { } 0 0 0
678  
679 # Response in body part
680 0 $response = $req->param('SAMLResponse');
681 0 $response =~ s/ /+/gs;
682 0 $self->logger->debug("HTTP-POST: SAML Response $response");
683  
684 }
685  
686 elsif ( $req->param('SAMLRequest') ) {
687  
688 # Request in body part
689 0 $request = $req->param('SAMLRequest');
690 0 $self->logger->debug("HTTP-POST: SAML Request $request");
691  
692 }
693  
694 elsif ( $req->param('SAMLart') ) {
695  
696 # Artifact in SAMLart param
697 0 $artifact = $req->param('SAMLart');
698 0 $self->logger->debug("HTTP-POST: SAML Artifact $artifact");
699  
700 # Resolve Artifact
701 0 $method = Lasso::Constants::HTTP_METHOD_ARTIFACT_POST;
702 0 $message =
703 $self->resolveArtifact( $profile, $artifact, $method );
704  
705 # Request or response ?
706 0 ▶ if ( $self->_isArtifactSamlResponse($message) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_isArtifactSamlResponse($message)) { } 0 0 0
707 0 $response = $message;
708 }
709 else {
710 0 $request = $message;
711 }
712  
713 }
714  
715 }
716  
717 # 2.2.2. SOAP
718 else {
719  
720 0 $method = Lasso::Constants::HTTP_METHOD_SOAP;
721 0 $self->logger->debug("SAML method: HTTP-SOAP");
722  
723 # SOAP is always a request
724 0 $request = $req->content;
725 0 $self->logger->debug("HTTP-SOAP: SAML Request $request");
726  
727 }
728  
729 }
730  
731 # 4. Return values
732 0 ▶ return ( $request, $response, $method, $relaystate, $artifact ? 1 : 0 );
Branch: 1 branch
BranchTrueFalseTotal
$artifact ? : 0 0 0
733 }
734  
735 sub _isArtifactSamlResponse {
736 my ( $self, $message ) = @_;
737  
738 my $type = eval {
739 my $resp = Lasso::Samlp2ArtifactResponse->new;
740 $resp->init_from_message($message);
741 $resp->any->get_name;
742 };
743  
744 if ($@) {
745 $self->logger->warn("Could not detect type of Artifact response");
746 return;
747 }
748  
749 $self->logger->debug("Artifact response type is $type");
750 if ( $type eq "Response" ) {
751 return 1;
752 }
753 else {
754 return 0;
755 }
756 }
757  
758 ## @method boolean checkLassoError(Lasso::Error error, string level)
759 # Log Lasso error code and message if this is actually a Lasso::Error with code > 0
760 # @param error Lasso error object
761 # @param level optional log level (debug by default)
762 # @return 1 if no error
763 sub checkLassoError {
764 my ( $self, $error, $level ) = @_;
765 my ( $lasso_result, $lasso_error_code ) =
766 $self->getLassoError( $error, $level );
767 return $lasso_result;
768 }
769  
770 ## @method boolean getLassoError(Lasso::Error error, string level)
771 # Log Lasso error code and message if this is actually a Lasso::Error with code > 0
772 # @param error Lasso error object
773 # @param level optional log level (debug by default)
774 # @return (success status, lasso error code)
775 sub getLassoError {
776 my ( $self, $error, $level ) = @_;
777 $level ||= 'error';
778  
779 # If $error is not a Lasso::Error object, display error string
780 unless ( ref($error) and $error->isa("Lasso::Error") ) {
781 return ( 1, undef ) unless $error;
782 $self->p->lmLog( "Lasso error: $error", $level );
783 return ( 0, undef );
784 }
785  
786 # Else check error code and error message
787 if ( $error->{code} ) {
788 $self->p->lmLog(
789 "Lasso error code " . $error->{code} . ": " . $error->{message},
790 $level );
791 return ( 0, $error->{code} );
792 }
793  
794 return ( 1, undef );
795 }
796  
797 ## @method Lasso::Server createServer(string metadata, string private_key, string private_key_password, string private_key_enc, string private_key_enc_password, string certificate)
798 # Load service metadata and create Lasso::Server object
799 # @param metadata SAML metadata
800 # @param private_key private key
801 # @param private_key_password optional private key password
802 # @param private_key_enc optional private key for encryption
803 # @param private_key_enc_password optional private key password for encryption
804 # @param certificate optional certificate
805 # @return Lasso::Server object
806 sub createServer {
807 my ( $self, $metadata, $private_key, $private_key_password,
808 $private_key_enc, $private_key_enc_password, $certificate )
809 = @_;
810 my $server;
811  
812 # https://dev.entrouvert.org/issues/51415
813 my $save_env = $ENV{'SSL_CERT_FILE'};
814 $ENV{'SSL_CERT_FILE'} = "/dev/null";
815  
816 eval {
817 $server = Lasso::Server::new_from_buffers( $metadata, $private_key,
818 $private_key_password, $certificate );
819  
820 # Set private key for encryption
821 if ( $server && $private_key_enc ) {
822 Lasso::Server::set_encryption_private_key_with_password( $server,
823 $private_key_enc, $private_key_enc_password );
824 }
825 };
826  
827 if ( defined $save_env ) {
828 $ENV{'SSL_CERT_FILE'} = $save_env;
829 }
830 else {
831 delete $ENV{'SSL_CERT_FILE'};
832 }
833  
834 if ($@) {
835 $self->checkLassoError($@);
836 return;
837 }
838  
839 return $server;
840 }
841  
842 ## @method boolean addIDP(Lasso::Server server, string metadata, string public_key, string ca_cert_chain)
843 # Add IDP to an existing Lasso::Server
844 # @param server Lasso::Server object
845 # @param metadata IDP metadata
846 # @param public_key optional public key
847 # @param ca_cert_chain optional ca cert chain
848 # @return boolean result
849 sub addIDP {
850 my ( $self, $server, $metadata, $public_key, $ca_cert_chain ) = @_;
851  
852 return 0 unless ( $server->isa("Lasso::Server") and defined $metadata );
853  
854 return $self->addProvider( $server, Lasso::Constants::PROVIDER_ROLE_IDP,
855 $metadata, $public_key, $ca_cert_chain );
856 }
857  
858 ## @method boolean addSP(Lasso::Server server, string metadata, string public_key, string ca_cert_chain)
859 # Add SP to an existing Lasso::Server
860 # @param server Lasso::Server object
861 # @param metadata SP metadata
862 # @param public_key optional public key
863 # @param ca_cert_chain optional ca cert chain
864 # @return boolean result
865 sub addSP {
866 my ( $self, $server, $metadata, $public_key, $ca_cert_chain ) = @_;
867  
868 return 0 unless ( $server->isa("Lasso::Server") and defined $metadata );
869  
870 return $self->addProvider( $server, Lasso::Constants::PROVIDER_ROLE_SP,
871 $metadata, $public_key, $ca_cert_chain );
872 }
873  
874 ## @method boolean addAA(Lasso::Server server, string metadata, string public_key, string ca_cert_chain)
875 # Add Attribute Authority to an existing Lasso::Server
876 # @param server Lasso::Server object
877 # @param metadata AA metadata
878 # @param public_key optional public key
879 # @param ca_cert_chain optional ca cert chain
880 # @return boolean result
881 sub addAA {
882 my ( $self, $server, $metadata, $public_key, $ca_cert_chain ) = @_;
883  
884 return 0 unless ( $server->isa("Lasso::Server") and defined $metadata );
885  
886 return $self->addProvider( $server,
887 Lasso::Constants::PROVIDER_ROLE_ATTRIBUTE_AUTHORITY,
888 $metadata, $public_key, $ca_cert_chain );
889 }
890  
891 ## @method boolean addProvider(Lasso::Server server, int role, string metadata, string public_key, string ca_cert_chain)
892 # Add provider to an existing Lasso::Server
893 # @param server Lasso::Server object
894 # @param role (IDP, SP or Both)
895 # @param metadata IDP metadata
896 # @param public_key optional public key
897 # @param ca_cert_chain optional ca cert chain
898 # @return boolean result
899 sub addProvider {
900 my ( $self, $server, $role, $metadata, $public_key, $ca_cert_chain ) = @_;
901  
902 return 0
903 unless ( $server->isa("Lasso::Server")
904 and defined $role
905 and defined $metadata );
906  
907 # https://dev.entrouvert.org/issues/51415
908 my $save_env = $ENV{'SSL_CERT_FILE'};
909 $ENV{'SSL_CERT_FILE'} = "/dev/null";
910  
911 eval {
912 Lasso::Server::add_provider_from_buffer( $server, $role, $metadata,
913 $public_key, $ca_cert_chain );
914 };
915  
916 if ( defined $save_env ) {
917 $ENV{'SSL_CERT_FILE'} = $save_env;
918 }
919 else {
920 delete $ENV{'SSL_CERT_FILE'};
921 }
922  
923 return $self->checkLassoError($@);
924 }
925  
926 ## @method string getOrganizationName(Lasso::Server server, string idp)
927 # Return name of organization picked up from metadata
928 #@param server Lasso::Server object
929 #@param idp entity ID
930 #@return string organization name
931 sub getOrganizationName {
932 my ( $self, $server, $idp ) = @_;
933 my ( $provider, $node );
934  
935 # Get provider from server
936 eval { $provider = Lasso::Server::get_provider( $server, $idp ); };
937  
938 if ($@) {
939 $self->checkLassoError($@);
940 return;
941 }
942  
943 # Get organization node
944 eval { $node = Lasso::Provider::get_organization($provider); };
945  
946 if ($@) {
947 $self->checkLassoError($@);
948 return;
949 }
950  
951 # Return if node is empty
952 return unless $node;
953  
954 # Extract organization name
955 my $data = eval { $self->parser->parse_string($node)->documentElement };
956 if ( my $exception = $@ ) {
957 $self->logger->warn("Could not parse Organization for $idp: $@");
958 }
959 return unless $data;
960 return $data->getElementsByTagNameNS(
961 "urn:oasis:names:tc:SAML:2.0:metadata",
962 'OrganizationName' )->string_value;
963 }
964  
965 ## @method string getNextProviderId(Lasso::Logout logout)
966 # Returns the provider id from providerID_index in list of providerIDs in
967 # principal session with the exception of initial service provider ID.
968 # @param logout Lasso::Logout object
969 # @return string
970 sub getNextProviderId {
971 my $self = shift;
972 my $logout = shift;
973 my $providerId;
974  
975 eval { $providerId = Lasso::Logout::get_next_providerID($logout); };
976 if ($@) {
977 $self->checkLassoError($@);
978 return;
979 }
980  
981 return $providerId;
982 }
983  
984 ## @method boolean resetProviderIdIndex(Lasso::Logout logout)
985 # Reset the providerID_index attribute in Lasso::Logout object
986 # @param logout Lasso::Logout object
987 # @return boolean
988 sub resetProviderIdIndex {
989 my $self = shift;
990 my $logout = shift;
991  
992 eval { Lasso::Logout::reset_providerID_index($logout); };
993 return $self->checkLassoError($@);
994 }
995  
996 ## @method Lasso::Login createAuthnRequest(Lasso::Server server, string idp, int method, boolean forceAuthn, boolean isPassive, string nameIDFormat, boolean allowProxiedAuthn, boolean signSSOMessage, string requestedAuthnContext)
997 # Create authentication request for selected IDP
998 # @param server Lasso::Server object
999 # @param idp IDP entityID
1000 # @param method HTTP method
1001 # @param forceAuthn force authentication on IDP
1002 # @param isPassive require passive authentication
1003 # @param nameIDFormat SAML2 NameIDFormat
1004 # @param allowProxiedAuthn allow proxy on IDP // Not used anymore but kept to avoid API break
1005 # @param signSSOMessage sign request
1006 # @param requestedAuthnContext authentication context
1007 # @return Lasso::Login object
1008 sub createAuthnRequest {
1009 my (
1010 $self, $req, $server,
1011 $idp, $method, $forceAuthn,
1012 $isPassive, $nameIDFormat, $allowProxiedAuthn,
1013 $signSSOMessage, $requestedAuthnContext
1014 ) = @_;
1015 my $proxyCount;
1016 my $proxyRequestedAuthnContext;
1017  
1018 # Create Lasso Login
1019 my $login = $self->createLogin($server);
1020  
1021 unless ($login) {
1022 $self->logger->error('Unable to create Lasso login');
1023 return;
1024 }
1025  
1026 # Init authentication request
1027 unless ( $self->initAuthnRequest( $login, $idp, $method ) ) {
1028 $self->logger->error(
1029 "Could not initiate authentication request on $idp");
1030 return;
1031 }
1032  
1033 # Set RelayState
1034 if ( my $relaystate = $self->storeRelayState( $req, 'urldc' ) ) {
1035 $login->msg_relayState($relaystate);
1036 $self->logger->debug("Set $relaystate in RelayState");
1037 }
1038  
1039 # Customize request
1040 my $request = $login->request();
1041  
1042 # Maybe we are in IDP proxy mode (SAML request received on IDP side)
1043 # In this case:
1044 # * Check proxy conditions
1045 # * Forward some authn constraints
1046 if ( $req->data->{_proxiedSamlRequest} ) {
1047  
1048 $self->logger->debug("IDP Proxy mode detected");
1049  
1050 # Get ProxyCount value
1051 eval {
1052 $proxyCount =
1053 $req->data->{_proxiedSamlRequest}->Scoping()->ProxyCount();
1054 };
1055  
1056 # Deny request if ProxyCount eq 0
1057 if ( defined $proxyCount ) {
1058  
1059 $self->logger->debug(
1060 "Found proxyCount $proxyCount in proxied request");
1061  
1062 if ( $proxyCount eq 0 ) {
1063 $self->userLogger->error(
1064 "SAML request cannot be proxied (ProxyCount 0)");
1065 return;
1066 }
1067 else {
1068  
1069 # Decrease ProxyCount
1070 my $scoping = $req->data->{_proxiedSamlRequest}->Scoping();
1071 $scoping->ProxyCount( $proxyCount-- );
1072 eval { $request->Scoping($scoping); };
1073 }
1074 }
1075  
1076 # isPassive
1077 eval { $isPassive = $req->data->{_proxiedSamlRequest}->IsPassive(); };
1078  
1079 # forceAuthn
1080 eval { $forceAuthn = $req->data->{_proxiedSamlRequest}->ForceAuthn(); };
1081  
1082 # requestedAuthnContext
1083 eval {
1084 $proxyRequestedAuthnContext =
1085 $req->data->{_proxiedSamlRequest}->RequestedAuthnContext();
1086 };
1087 }
1088  
1089 # NameIDFormat
1090 if ($nameIDFormat) {
1091 $self->logger->debug("Use NameIDFormat $nameIDFormat");
1092 $request->NameIDPolicy()->Format($nameIDFormat);
1093 }
1094  
1095 # Always allow NameID creation
1096 $request->NameIDPolicy()->AllowCreate(1);
1097  
1098 # Force authentication
1099 if ($forceAuthn) {
1100 $self->logger->debug("Force authentication on IDP");
1101 $request->ForceAuthn(1);
1102 }
1103  
1104 # Passive authentication
1105 if ($isPassive) {
1106 $self->logger->debug("Passive authentication on IDP");
1107 $request->IsPassive(1);
1108 }
1109  
1110 # Signature
1111 if ( $signSSOMessage == 0 ) {
1112 $self->logger->debug("SSO request will not be signed");
1113 $self->disableSignature($login);
1114 }
1115 elsif ( $signSSOMessage == 1 ) {
1116 $self->logger->debug("SSO request will be signed");
1117 $self->forceSignature($login);
1118 }
1119 else {
1120 $self->logger->debug("SSO request signature according to metadata");
1121 }
1122  
1123 # Requested authentication context
1124 if ($proxyRequestedAuthnContext) {
1125 $self->logger->debug("Use RequestedAuthnContext from proxied request");
1126 $request->RequestedAuthnContext($proxyRequestedAuthnContext);
1127 }
1128 elsif ($requestedAuthnContext) {
1129 $self->logger->debug("Request $requestedAuthnContext context");
1130 eval {
1131 my $context = Lasso::Samlp2RequestedAuthnContext->new();
1132 $context->AuthnContextClassRef($requestedAuthnContext);
1133 $context->Comparison("minimum");
1134 $request->RequestedAuthnContext($context);
1135 };
1136 if ($@) {
1137 $self->checkLassoError($@);
1138 return;
1139 }
1140 }
1141  
1142 # Call samlGenerateAuthnRequest hook
1143 my $h =
1144 $self->p->processHook( $req, 'samlGenerateAuthnRequest', $idp, $login );
1145 return if ( $h != PE_OK );
1146  
1147 # Build authentication request
1148 unless ( $self->buildAuthnRequestMsg($login) ) {
1149 $self->logger->error("Could not build authentication request on $idp");
1150 return;
1151 }
1152  
1153 # Artifact
1154 if ( $method == $self->getHttpMethod("artifact-get")
1155 or $method == $self->getHttpMethod("artifact-post") )
1156 {
1157  
1158 # Get artifact ID and Content, and store them
1159 my $artifact_id = $login->get_artifact;
1160 my $artifact_message = $login->get_artifact_message;
1161  
1162 $self->storeArtifact( $artifact_id, $artifact_message );
1163 }
1164 return $login;
1165 }
1166  
1167 ## @method Lasso::Login createLogin(Lasso::Server server, string dump)
1168 # Create Lasso::Login object
1169 # @param server Lasso::Server object
1170 # @param dump optional XML dump
1171 # @return Lasso::Login object
1172 sub createLogin {
1173 my ( $self, $server, $dump ) = @_;
1174 my $login;
1175  
1176 if ($dump) {
1177 eval { $login = Lasso::Login::new_from_dump( $server, $dump ); };
1178 }
1179 else {
1180 eval { $login = Lasso::Login->new($server); };
1181 }
1182  
1183 if ($@) {
1184 $self->checkLassoError($@);
1185 return;
1186 }
1187  
1188 return $login;
1189 }
1190  
1191 ## @method boolean initAuthnRequest(Lasso::Login login, string idp, int method)
1192 # Init authentication request
1193 # @param login Lasso::Login
1194 # @param idp entityID
1195 # @param method HTTP method
1196 # @return boolean result
1197 sub initAuthnRequest {
1198 my ( $self, $login, $idp, $method ) = @_;
1199  
1200 eval { Lasso::Login::init_authn_request( $login, $idp, $method ); };
1201  
1202 return $self->checkLassoError($@);
1203 }
1204  
1205 ## @method boolean initIdpInitiatedAuthnRequest(Lasso::Login login, string idp)
1206 # Init authentication request
1207 # @param login Lasso::Login
1208 # @param idp entityID
1209 # @return boolean result
1210 sub initIdpInitiatedAuthnRequest {
1211 my ( $self, $login, $idp ) = @_;
1212  
1213 eval { Lasso::Login::init_idp_initiated_authn_request( $login, $idp ); };
1214  
1215 return $self->checkLassoError($@);
1216 }
1217  
1218 ## @method boolean buildAuthnRequestMsg(Lasso::Login login)
1219 # Build authentication request message
1220 # @param login Lasso::Login
1221 # @return boolean result
1222 sub buildAuthnRequestMsg {
1223 my ( $self, $login ) = @_;
1224  
1225 eval { Lasso::Login::build_authn_request_msg($login); };
1226  
1227 return $self->checkLassoError($@);
1228 }
1229  
1230 ## @method boolean processAuthnRequestMsg(Lasso::Login login, string request)
1231 # Process authentication request message
1232 # processAuthnRequestMsgWithError is preferred, but this function is kept for
1233 # API compatibility in 2.0
1234 # @param login Lasso::Login object
1235 # @param request SAML request
1236 # @return result
1237 sub processAuthnRequestMsg {
1238 my ( $self, $login, $request, $level ) = @_;
1239  
1240 $self->lazy_load_message($request);
1241  
1242 eval { Lasso::Login::process_authn_request_msg( $login, $request ); };
1243  
1244 return $self->checkLassoError( $@, $level );
1245 }
1246  
1247 ## @method boolean processAuthnRequestMsgWithError(Lasso::Login login, string request)
1248 # Process authentication request message
1249 # @param login Lasso::Login object
1250 # @param request SAML request
1251 # @return result, Lasso error code
1252 sub processAuthnRequestMsgWithError {
1253 my ( $self, $login, $request, $level ) = @_;
1254  
1255 $self->lazy_load_message($request);
1256  
1257 eval { Lasso::Login::process_authn_request_msg( $login, $request ); };
1258  
1259 return $self->getLassoError( $@, $level );
1260 }
1261  
1262 ## @method boolean validateRequestMsg(Lasso::Login login, boolean auth, boolean consent)
1263 # Validate request message
1264 # @param login Lasso::Login object
1265 # @param auth is user authenticated?
1266 # @param consent is consent obtained?
1267 # @return result
1268 sub validateRequestMsg {
1269 my ( $self, $login, $auth, $consent ) = @_;
1270  
1271 eval { Lasso::Login::validate_request_msg( $login, $auth, $consent ); };
1272  
1273 return $self->checkLassoError($@);
1274 }
1275  
1276 ## @method boolean buildAuthnResponseMsg(Lasso::Login login)
1277 # Build authentication response message
1278 # @param login Lasso::Login object
1279 # @return boolean result
1280 sub buildAuthnResponseMsg {
1281 my ( $self, $login ) = @_;
1282  
1283 eval { Lasso::Login::build_authn_response_msg($login); };
1284  
1285 return $self->checkLassoError($@);
1286 }
1287  
1288 ## @method boolean buildArtifactMsg(Lasso::Login login, int method)
1289 # Build artifact message
1290 # @param login Lasso::Login object
1291 # @param method HTTP method
1292 # @return boolean result
1293 sub buildArtifactMsg {
1294 my ( $self, $login, $method ) = @_;
1295  
1296 eval { Lasso::Login::build_artifact_msg( $login, $method ); };
1297  
1298 return $self->checkLassoError($@);
1299 }
1300  
1301 ## @method boolean buildAssertion(Lasso::Login login, string authn_context, int notOnOrAfterTimeout)
1302 # Build assertion
1303 # @param login Lasso::Login object
1304 # @param authn_context SAML2 authentication context
1305 # @param notOnOrAfterTimeout Timeout to apply to notOnOrAfter
1306 # @return boolean result
1307 sub buildAssertion {
1308 my ( $self, $req, $login, $authn_context, $notOnOrAfterTimeout ) = @_;
1309 $notOnOrAfterTimeout ||= $self->conf->{timeout};
1310  
1311 # Dates
1312 my $time = $req->sessionInfo->{_utime} || time();
1313 my $timeout = $time + $notOnOrAfterTimeout;
1314 my $authenticationInstant = $self->timestamp2samldate($time);
1315 my $reauthenticateOnOrAfter = $self->timestamp2samldate($timeout);
1316 my $issued_time = time;
1317 my $notBefore = $self->timestamp2samldate($issued_time);
1318 my $notOnOrAfter =
1319 $self->timestamp2samldate( $issued_time + $notOnOrAfterTimeout );
1320  
1321 eval {
1322 Lasso::Login::build_assertion( $login, $authn_context,
1323 $authenticationInstant, $reauthenticateOnOrAfter, $notBefore,
1324 $notOnOrAfter );
1325 };
1326  
1327 return $self->checkLassoError($@);
1328 }
1329  
1330 ## @method boolean processAuthnResponseMsg(Lasso::Login login, string response)
1331 # Process authentication response message
1332 # @param login Lasso::Login object
1333 # @param response SAML response
1334 # @return result
1335 sub processAuthnResponseMsg {
1336 my ( $self, $login, $response ) = @_;
1337  
1338 $self->lazy_load_message($response);
1339  
1340 eval { Lasso::Login::process_authn_response_msg( $login, $response ); };
1341  
1342 return $self->checkLassoError($@);
1343 }
1344  
1345 # UNUSED
1346 ### @method Lasso::Saml2NameID getNameIdentifer(Lasso::Profile profile)
1347 ## Get NameID from Lasso Profile
1348 ## @param profile Lasso::Profile object
1349 ## @return result or NULL if error
1350 #sub getNameIdentifier {
1351 # my ( $self, $profile ) = @_;
1352 # my $nameid;
1353 #
1354 # eval { $nameid = Lasso::Profile::get_nameIdentifier($profile); };
1355 #
1356 # if ($@) {
1357 # $self->checkLassoError($@);
1358 # return;
1359 # }
1360 #
1361 # return $nameid;
1362 #}
1363  
1364 # UNUSED
1365 ### @method Lasso::Identity createIdentity(string dump)
1366 ## Create Lasso::Identity object
1367 ## @param dump optional Identity dump
1368 ## @return Lasso::Identity object
1369 #sub createIdentity {
1370 # my ( $self, $dump ) = @_;
1371 # my $identity;
1372 #
1373 # if ($dump) {
1374 # eval { $identity = Lasso::Identity::new_from_dump($dump); };
1375 # }
1376 # else {
1377 # eval { $identity = Lasso::Identity->new(); };
1378 # }
1379 #
1380 # if ($@) {
1381 # $self->checkLassoError($@);
1382 # return;
1383 # }
1384 #
1385 # return $identity;
1386 #}
1387  
1388 ## UNUSED
1389 ### @method Lasso::Session createSession(string dump)
1390 ## Create Lasso::Session object
1391 ## @param dump optional Session dump
1392 ## @return Lasso::Session object
1393 #sub createSession {
1394 # my ( $self, $dump ) = @_;
1395 # my $session;
1396 #
1397 # if ($dump) {
1398 # eval { $session = Lasso::Session::new_from_dump($dump); };
1399 # }
1400 # else {
1401 # eval { $session = Lasso::Session->new(); };
1402 # }
1403 #
1404 # if ($@) {
1405 # $self->checkLassoError($@);
1406 # return;
1407 # }
1408 #
1409 # return $session;
1410 #}
1411  
1412 ## @method boolean acceptSSO(Lasso::Login login)
1413 # Accept SSO from IDP
1414 # @param login Lasso::Login object
1415 # @return result
1416 sub acceptSSO {
1417 my ( $self, $login ) = @_;
1418  
1419 eval { Lasso::Login::accept_sso($login); };
1420  
1421 return $self->checkLassoError($@);
1422 }
1423  
1424 ## @method string getIssuer(string msg)
1425 # Get issuer from message
1426 # @param msg SAML message
1427 # @return issuer
1428 sub getIssuer {
1429 my ( $self, $message ) = @_;
1430  
1431 # Work around lasso bug (https://dev.entrouvert.org/issues/97575)
1432 $message =~ s/&RelayState=$//g;
1433 my $issuer = eval { Lasso::profile_get_issuer($message) };
1434 if ($@) {
1435 $self->logger->debug("lasso_profile_get_issuer: $@");
1436 }
1437 if ( !$issuer ) {
1438 $self->logger->debug(
1439 "lasso_profile_get_issuer could not find entityID"
1440 . " in incoming message" );
1441 return;
1442 }
1443 return $issuer;
1444 }
1445  
1446 ## @method string storeRelayState(hashref infos)
1447 # Store information in relayState database and return
1448 # corresponding session_id
1449 # @param infos HASH reference of information
1450 sub storeRelayState {
1451 my ( $self, $req, @data ) = @_;
1452  
1453 # check if there are data to store
1454 my $infos;
1455 foreach (@data) {
1456 $infos->{$_} = $req->{$_} if $req->{$_};
1457 }
1458 return unless ($infos);
1459  
1460 # Session type
1461 $infos->{_type} = "relaystate";
1462  
1463 # Set _utime for session autoremove
1464 # Use default session timeout and relayState session timeout to compute it
1465 my $time = time();
1466 my $timeout = $self->conf->{timeout};
1467 my $samlRelayStateTimeout =
1468 $self->conf->{samlRelayStateTimeout} || $timeout;
1469  
1470 $infos->{_utime} = $time + ( $samlRelayStateTimeout - $timeout );
1471  
1472 # Create relaystate session and store infos in relaystate session
1473 my $samlSessionInfo = $self->getSamlSession( undef, $infos )
1474 or return undef;
1475  
1476 # Session ID
1477 my $relaystate_id = $samlSessionInfo->id;
1478  
1479 # Return session ID
1480 return $relaystate_id;
1481 }
1482  
1483 ## @method boolean extractRelayState(string relaystate, boolean relayStateURL)
1484 # Extract RelayState information into $self
1485 # @param relaystate Relay state value
1486 # @param relayStateURL Allow Relay state value to be the redirection URL
1487 # @return result
1488 sub extractRelayState {
1489 my ( $self, $req, $relaystate, $relayStateURL ) = @_;
1490  
1491 return 0 unless $relaystate;
1492 if ( $relayStateURL and $relaystate =~ /^https?:\/\// ) {
1493 $self->logger->debug("RelayState is a redirection URL: $relaystate");
1494 $req->{urldc} = $relaystate;
1495 return 1;
1496 }
1497 else {
1498  
1499 # Open relaystate session
1500 my $samlSessionInfo = $self->getSamlSession($relaystate);
1501  
1502 return 0 unless $samlSessionInfo;
1503  
1504 # Push values in $self
1505 foreach ( keys %{ $samlSessionInfo->data } ) {
1506 next if $_ =~ /(type|_session_id|_utime|issuerNextUrl)/;
1507 $req->{$_} = $samlSessionInfo->data->{$_};
1508 }
1509  
1510 # issuerNextUrl has priority over urldc if both are set
1511 if ( $samlSessionInfo->data->{issuerNextUrl} ) {
1512 $req->urldc( $samlSessionInfo->data->{issuerNextUrl} );
1513 }
1514  
1515 # delete relaystate session
1516 if ( $samlSessionInfo->remove ) {
1517 $self->logger->debug("Relaystate $relaystate was deleted");
1518 }
1519 else {
1520 $self->logger->error("Unable to delete relaystate $relaystate");
1521 $self->logger->error( $samlSessionInfo->error );
1522 }
1523  
1524 }
1525  
1526 return 1;
1527 }
1528  
1529 ## @method Lasso::Node getAssertion(Lasso::Login login)
1530 # Get assertion in Lasso::Login object
1531 # @param login Lasso::Login object
1532 # @return assertion Lasso::Node object
1533 sub getAssertion {
1534 my ( $self, $login ) = @_;
1535 my $assertion;
1536  
1537 eval { $assertion = Lasso::Login::get_assertion($login); };
1538  
1539 if ($@) {
1540 $self->checkLassoError($@);
1541 return;
1542 }
1543  
1544 return $assertion;
1545 }
1546  
1547 ## @method string getAttributeValue(string name, string format, string friendly_name, arrayref attributes, boolean force_utf8)
1548 # Get SAML attribute value corresponding to name, format and friendly_name
1549 # Multivaluated values are separated by multiValuesSeparator
1550 # If force_utf8 flag is set, value is encoded in UTF-8
1551 # @param name SAML attribute name
1552 # @param format optional SAML attribute format
1553 # @param friendly_name optional SAML attribute friendly name
1554 # @param attributes Attributes
1555 # @param force_utf8 optional flag to force value in UTF-8
1556 # @return attribute value
1557 sub getAttributeValue {
1558 my ( $self, $name, $format, $friendly_name, $attributes, $force_utf8 ) = @_;
1559 my $value;
1560  
1561 # Loop on attributes
1562 foreach (@$attributes) {
1563 my $attr_name = $_->Name();
1564 my $attr_format = $_->NameFormat();
1565 my $attr_fname = $_->FriendlyName();
1566  
1567 # Skip if name does not correspond to attribute name
1568 next if ( $name ne $attr_name );
1569  
1570 # Verify format and friendly name if given
1571 next if ( $format and $format ne $attr_format );
1572 next if ( $friendly_name and $friendly_name ne $attr_fname );
1573  
1574 # Attribute is found, return its content
1575 my @attr_values = $_->AttributeValue();
1576  
1577 $value = join(
1578 $self->{conf}->{multiValuesSeparator},
1579 map {
1580 eval { $_->any->content }
1581 || ()
1582 } @attr_values
1583 );
1584 }
1585  
1586 return $value;
1587 }
1588  
1589 ## @method boolean validateConditions(Lasso::Saml2::Assertion assertion, string entityID, boolean checkTime, boolean checkAudience)
1590 # Validate conditions
1591 # @param assertion SAML2 assertion
1592 # @param entityID relying party entity ID
1593 # @param checkTime Enable time conditions check
1594 # @param checkAudience Enable audience conditions check
1595 # @return result
1596 sub validateConditions {
1597 my ( $self, $assertion, $entityID, $checkTime, $checkAudience ) = @_;
1598 my $tolerance = 10;
1599 my $status;
1600 $checkTime = 1 unless defined $checkTime;
1601 $checkAudience = 1 unless defined $checkAudience;
1602  
1603 # Time
1604 if ($checkTime) {
1605 eval {
1606 $status = Lasso::Saml2Assertion::validate_time_checks( $assertion,
1607 $tolerance );
1608 };
1609  
1610 if ($@) {
1611 $self->checkLassoError($@);
1612 return 0;
1613 }
1614  
1615 unless ( $status eq Lasso::Constants::SAML2_ASSERTION_VALID ) {
1616 $self->logger->error("Time conditions validation failed ($status)");
1617 return 0;
1618 }
1619  
1620 $self->logger->debug("Time conditions validated");
1621 }
1622 else {
1623 $self->logger->debug("Time conditions not checked");
1624 }
1625  
1626 # Audience
1627 if ($checkAudience) {
1628 eval {
1629 $status =
1630 Lasso::Saml2Assertion::validate_audience( $assertion, $entityID );
1631 };
1632  
1633 if ($@) {
1634 $self->checkLassoError($@);
1635 return 0;
1636 }
1637  
1638 unless ( $status eq Lasso::Constants::SAML2_ASSERTION_VALID ) {
1639 $self->logger->error(
1640 "Audience conditions validations result: $status");
1641 return 0;
1642 }
1643  
1644 $self->logger->debug("Audience conditions validated");
1645 }
1646 else {
1647 $self->logger->debug("Audience conditions not checked");
1648 }
1649  
1650 return 1;
1651 }
1652  
1653 ## @method Lasso::Logout createLogoutRequest(Lasso::Server server, string session_dump, int method, boolean signSLOMessage)
1654 # Create logout request for selected entity
1655 # @param server Lasso::Server object
1656 # @param session_dump Lasso::Session dump
1657 # @param method HTTP method
1658 # @param signSLOMessage sign request
1659 # @return Lasso::Login object
1660 sub createLogoutRequest {
1661 my ( $self, $req, $server, $session_dump, $method, $signSLOMessage ) = @_;
1662 my $session;
1663  
1664 # Create Lasso Logout
1665 my $logout = $self->createLogout($server);
1666  
1667 unless ( $self->setSessionFromDump( $logout, $session_dump ) ) {
1668 $self->logger->error("Could not fill Lasso::Logout with session dump");
1669 return;
1670 }
1671  
1672 # Init logout request
1673 unless ( $self->initLogoutRequest( $logout, undef, $method ) ) {
1674 $self->logger->error("Could not initiate logout request");
1675 return;
1676 }
1677  
1678 # Set RelayState
1679 if ( my $relaystate =
1680 $self->storeRelayState( $req, 'urldc', 'issuerNextUrl' ) )
1681 {
1682 $logout->msg_relayState($relaystate);
1683 $self->logger->debug("Set $relaystate in RelayState");
1684 }
1685  
1686 # Signature
1687 if ( $signSLOMessage == 0 ) {
1688 $self->logger->debug("SLO request will not be signed");
1689 $self->disableSignature($logout);
1690 }
1691 elsif ( $signSLOMessage == 1 ) {
1692 $self->logger->debug("SLO request will be signed");
1693 $self->forceSignature($logout);
1694 }
1695 else {
1696 $self->logger->debug("SLO request signature according to metadata");
1697 }
1698  
1699 # Build logout request
1700 unless ( $self->buildLogoutRequestMsg($logout) ) {
1701 $self->logger->error("Could not build logout request");
1702 return;
1703 }
1704  
1705 return $logout;
1706  
1707 }
1708  
1709 ## @method Lasso::Logout createLogout(Lasso::Server server, string dump)
1710 # Create Lasso::Logout object
1711 # @param server Lasso::Server object
1712 # @param dump optional XML dump
1713 # @return Lasso::Logout object
1714 sub createLogout {
1715 my ( $self, $server, $dump ) = @_;
1716 my $logout;
1717  
1718 if ($dump) {
1719 eval { $logout = Lasso::Logout::new_from_dump( $server, $dump ); };
1720 }
1721 else {
1722 eval { $logout = Lasso::Logout->new($server); };
1723 }
1724  
1725 if ($@) {
1726 $self->checkLassoError($@);
1727 return;
1728 }
1729  
1730 return $logout;
1731 }
1732  
1733 ## @method boolean initLogoutRequest(Lasso::Logout logout, string entityID, int method)
1734 # Init logout request
1735 # @param logout Lasso::Logout object
1736 # @param entityID Entity ID
1737 # @param method HTTP method
1738 # @return result
1739 sub initLogoutRequest {
1740 my ( $self, $logout, $entityID, $method ) = @_;
1741  
1742 eval { Lasso::Logout::init_request( $logout, $entityID, $method ); };
1743  
1744 return $self->checkLassoError($@);
1745 }
1746  
1747 ## @method boolean buildLogoutRequestMsg(Lasso::Logout logout)
1748 # Build logout request message
1749 # @param logout Lasso::Logout object
1750 # @return result
1751 sub buildLogoutRequestMsg {
1752 my ( $self, $logout ) = @_;
1753  
1754 eval { Lasso::Logout::build_request_msg($logout); };
1755  
1756 return $self->checkLassoError($@);
1757 }
1758  
1759 ## @method boolean setSessionFromDump(Lasso::Profile profile, string dump)
1760 # Set session from dump in Lasso::Profile object
1761 # @param profile Lasso::Profile object
1762 # @param dump Lasso::Session XML dump
1763 # @return result
1764 sub setSessionFromDump {
1765 my ( $self, $profile, $dump ) = @_;
1766  
1767 $self->logger->debug("Loading Session dump: $dump") if $dump;
1768  
1769 eval { Lasso::Profile::set_session_from_dump( $profile, $dump ); };
1770  
1771 return $self->checkLassoError($@);
1772 }
1773  
1774 ## @method boolean setIdentityFromDump(Lasso::Profile profile, string dump)
1775 # Set identity from dump in Lasso::Profile object
1776 # @param profile Lasso::Profile object
1777 # @param dump Lasso::Identity XML dump
1778 # @return result
1779 sub setIdentityFromDump {
1780 my ( $self, $profile, $dump ) = @_;
1781  
1782 eval { Lasso::Profile::set_identity_from_dump( $profile, $dump ); };
1783  
1784 return $self->checkLassoError($@);
1785 }
1786  
1787 ## @method string getMetaDataURL(string key, int index)
1788 # Get URL stored in a service metadata configuration key
1789 # Replace #PORTAL# macro
1790 # @param key Metadata configuration key
1791 # @param index field index containing URL
1792 # @param full Return full URL instead of path
1793 # @return url
1794 sub getMetaDataURL {
1795 my ( $self, $key, $index, $full ) = @_;
1796 $index = 3 unless defined $index;
1797 $full = 0 unless defined $full;
1798  
1799 return '' unless defined $self->conf->{$key};
1800  
1801 my $url = ( split( /;/, $self->conf->{$key} ) )[$index] || '';
1802  
1803 # Get default portal value
1804 my $portal = $self->p->buildUrl;
1805 $portal =~ s/\/$//;
1806  
1807 # Replace #PORTAL# macro
1808 $url =~ s/#PORTAL#/$portal/g;
1809  
1810 # Return Full URL
1811 return $url if $full;
1812  
1813 # Return only path
1814 my $uri = URI->new($url);
1815 return $uri->path();
1816 }
1817  
1818 sub getRouteFromMetaDataURL {
1819 my ( $self, $key, $index, $sub ) = @_;
1820 my $uri = $self->getMetaDataURL( $key, $index, 0 );
1821 unless ( $uri =~ m#^/\w# ) {
1822 $self->logger->debug("$key has no index $index");
1823 return ();
1824 }
1825 my @t = grep /\w/, split( /\//, $uri );
1826 my $h = { pop(@t) => $sub };
1827 while ( my $s = pop @t ) {
1828 $h = { $s => $h };
1829 }
1830 return %$h;
1831 }
1832  
1833 sub addRouteFromMetaDataURL {
1834 my ( $self, @args ) = @_;
1835 $self->addAuthRouteFromMetaDataURL(@args);
1836 $self->addUnauthRouteFromMetaDataURL(@args);
1837 }
1838  
1839 sub addAuthRouteFromMetaDataURL {
1840 my ( $self, $key, $index, $sub, $methods ) = @_;
1841 my %route = $self->getRouteFromMetaDataURL( $key, $index, $sub );
1842 return unless (%route);
1843 $self->addAuthRoute( %route, $methods );
1844 }
1845  
1846 sub addUnauthRouteFromMetaDataURL {
1847 my ( $self, $key, $index, $sub, $methods ) = @_;
1848 my %route = $self->getRouteFromMetaDataURL( $key, $index, $sub );
1849 return unless (%route);
1850 $self->addUnauthRoute( %route, $methods );
1851 }
1852  
1853 ## @method boolean processLogoutResponseMsg(Lasso::Logout logout, string response)
1854 # Process logout response message
1855 # @param logout Lasso::Logout object
1856 # @param response SAML response
1857 # @return result
1858 sub processLogoutResponseMsg {
1859 my ( $self, $logout, $response ) = @_;
1860  
1861 $self->lazy_load_message($response);
1862  
1863 eval { Lasso::Logout::process_response_msg( $logout, $response ); };
1864  
1865 return $self->checkLassoError($@);
1866 }
1867  
1868 ## @method boolean processLogoutRequestMsg(Lasso::Logout logout, string request)
1869 # Process logout request message
1870 # @param logout Lasso::Logout object
1871 # @param request SAML request
1872 # @return result
1873 sub processLogoutRequestMsg {
1874 my ( $self, $logout, $request ) = @_;
1875  
1876 $self->lazy_load_message($request);
1877  
1878 # Process the request
1879 eval { Lasso::Logout::process_request_msg( $logout, $request ); };
1880  
1881 return 0 unless $self->checkLassoError($@);
1882  
1883 # Check NotOnOrAfter optional attribute
1884 my $notOnOrAfter;
1885  
1886 eval { $notOnOrAfter = $logout->request()->NotOnOrAfter(); };
1887  
1888 return 1 if ( $@ or !$notOnOrAfter );
1889  
1890 $self->logger->debug("Found NotOnOrAfter $notOnOrAfter in logout request");
1891  
1892 my $expirationTime = $self->samldate2timestamp($notOnOrAfter);
1893  
1894 return ( time < $expirationTime );
1895 }
1896  
1897 ## @method boolean validateLogoutRequest(Lasso::Logout logout)
1898 # Validate logout request
1899 # @param logout Lasso::Logout object
1900 # @return result
1901 sub validateLogoutRequest {
1902 my ( $self, $logout ) = @_;
1903  
1904 eval { Lasso::Logout::validate_request($logout); };
1905  
1906 return $self->checkLassoError($@);
1907 }
1908  
1909 ## @method boolean buildLogoutResponseMsg(Lasso::Logout logout)
1910 # Build logout response message
1911 # @param logout Lasso::Logout object
1912 # @return boolean result
1913 sub buildLogoutResponseMsg {
1914 my ( $self, $logout ) = @_;
1915  
1916 eval { Lasso::Logout::build_response_msg($logout); };
1917  
1918 return $self->checkLassoError($@);
1919 }
1920  
1921 ## @method boolean storeReplayProtection(string samlID, string samlData)
1922 # Store ID of an SAML message in Replay Protection base
1923 # @param samlID ID of SAML message
1924 # @param samlData Optional data to store
1925 # @return result
1926 sub storeReplayProtection {
1927 my ( $self, $samlID, $samlData ) = @_;
1928 my $infos = {
1929 type => 'assertion', # Session type
1930 _utime => time(), # Creation time
1931 _assert_id => $samlID,
1932 };
1933  
1934 if ( defined $samlData && $samlData ) {
1935 $infos->{data} = $samlData;
1936 }
1937  
1938 my $samlSessionInfo = $self->getSamlSession( undef, $infos );
1939 return 0 unless $samlSessionInfo;
1940  
1941 my $session_id = $samlSessionInfo->id;
1942  
1943 $self->logger->debug(
1944 "Keep request ID $samlID in assertion session $session_id");
1945  
1946 return 1;
1947 }
1948  
1949 ## @method boolean replayProtection(string samlID)
1950 # Check if SAML message do not correspond to a previously responded message
1951 # @param samlID ID of initial SAML message
1952 # @return result
1953 sub replayProtection {
1954 my ( $self, $samlID ) = @_;
1955  
1956 unless ($samlID) {
1957 $self->userLogger->error(
1958 "Cannot verify replay because no SAML ID given");
1959 return 0;
1960 }
1961  
1962 my $sessions =
1963 Lemonldap::NG::Common::Apache::Session->searchOn( $self->amOpts,
1964 "_assert_id", $samlID );
1965  
1966 if (
1967 my @keys =
1968 grep { $sessions->{$_}->{_session_kind} eq $self->sessionKind }
1969 keys %$sessions
1970 )
1971 {
1972  
1973 # A session was found
1974 foreach (@keys) {
1975 next
1976 unless ( $sessions->{$_}->{_session_kind} eq $self->sessionKind );
1977 my $session = $_;
1978 my $result = 1;
1979  
1980 # Delete it
1981 my $samlSessionInfo = $self->getSamlSession($_);
1982  
1983 return 0 unless $samlSessionInfo;
1984  
1985 if ( defined $samlSessionInfo->data->{data} ) {
1986 $result = $samlSessionInfo->data->{data};
1987 }
1988  
1989 if ( $samlSessionInfo->remove ) {
1990 $self->logger->debug(
1991 "Assertion session $session (Message ID $samlID) was deleted"
1992 );
1993 return $result;
1994 }
1995 else {
1996 $self->logger->error(
1997 "Unable to delete assertion session $session (Message ID $samlID)"
1998 );
1999 $self->logger->error( $samlSessionInfo->error );
2000 return 0;
2001 }
2002 }
2003 }
2004 else {
2005 $self->logger->warn(
2006 "No assertion session found for request ID " . $samlID );
2007 }
2008  
2009 return 0;
2010 }
2011  
2012 ## @method string resolveArtifact(Lasso::Profile profile, string artifact, int method)
2013 # Resolve artifact to get real SAML message
2014 # @param profile Lasso::Profile object
2015 # @param artifact Artifact message
2016 # @param method HTTP method
2017 # @return SAML message
2018 sub resolveArtifact {
2019 my ( $self, $profile, $artifact, $method ) = @_;
2020 my $message;
2021  
2022 # Login profile
2023 if ( $profile->isa("Lasso::Login") ) {
2024  
2025 # Init request message
2026 eval { Lasso::Login::init_request( $profile, $artifact, $method ); };
2027 return unless $self->checkLassoError($@);
2028  
2029 # Build request message
2030 eval { Lasso::Login::build_request_msg($profile); };
2031 return unless $self->checkLassoError($@);
2032  
2033 unless ( $profile->msg_url ) {
2034 $self->logger->error("No artifact resolution URL found");
2035 return;
2036 }
2037  
2038 my $request = HTTP::Request->new( 'POST' => $profile->msg_url );
2039 $request->content_type('text/xml');
2040 $request->header( Accept => 'text/xml' );
2041 $request->content( $profile->msg_body );
2042  
2043 $self->logger->debug(
2044 "Send message " . $profile->msg_body . " to " . $profile->msg_url );
2045  
2046 # SOAP call
2047 my $soap_answer = $self->ua->request($request);
2048 if ( $soap_answer->code() == "200" ) {
2049 $message = $soap_answer->content();
2050 $self->logger->debug("Get message $message");
2051 }
2052 else {
2053 $self->logger->error(
2054 "Error while sending message: " . $soap_answer->status_line );
2055 }
2056 }
2057  
2058 return $message;
2059 }
2060  
2061 ## @method boolean storeArtifact(string id, string message, string session_id)
2062 # Store artifact
2063 # @param id Artifact ID
2064 # @param message Artifact content
2065 # @param session_id Session ID
2066 # @return result
2067 sub storeArtifact {
2068 my ( $self, $id, $message, $session_id ) = @_;
2069  
2070 my $infos = {
2071 type => 'artifact', # Session type
2072 _utime => time(), # Creation time
2073 _art_id => $id,
2074 message => $message,
2075 };
2076 $infos->{_saml_id} = $session_id if $session_id;
2077  
2078 my $samlSessionInfo = $self->getSamlSession( undef, $infos ) or return 0;
2079 return 0 unless $samlSessionInfo;
2080  
2081 my $art_session_id = $samlSessionInfo->id;
2082  
2083 $self->logger->debug("Keep artifact $id in session $art_session_id");
2084  
2085 return 1;
2086 }
2087  
2088 ## @method hashRef loadArtifact(string id)
2089 # Load artifact
2090 # @param id Artifact ID
2091 # @return Artifact session content
2092 sub loadArtifact {
2093 my ( $self, $id ) = @_;
2094 my $art_session;
2095  
2096 unless ($id) {
2097 $self->logger->error("Cannot load artifact because no id given");
2098 return;
2099 }
2100  
2101 my $sessions =
2102 Lemonldap::NG::Common::Apache::Session->searchOn( $self->amOpts,
2103 "_art_id", $id );
2104  
2105 if (
2106 my @keys =
2107 grep { $sessions->{$_}->{_session_kind} eq $self->sessionKind }
2108 keys %$sessions
2109 )
2110 {
2111  
2112 my $nb_sessions = $#keys + 1;
2113  
2114 $self->logger->debug("Found $nb_sessions sessions for artifact $id");
2115  
2116 # There should only be 1 result
2117 return if ( $nb_sessions != 1 );
2118  
2119 my $session_id = shift @keys;
2120 my $session = $session_id;
2121  
2122 # Open session
2123 my $samlSessionInfo = $self->getSamlSession($session_id);
2124  
2125 return unless $samlSessionInfo;
2126  
2127 # Get session contents
2128 foreach ( keys %{ $samlSessionInfo->data } ) {
2129 $art_session->{$_} = $samlSessionInfo->data->{$_};
2130 }
2131  
2132 # Delete session
2133 if ( $samlSessionInfo->remove ) {
2134 $self->logger->debug(
2135 "Artifact session $session (ID $id) was deleted");
2136  
2137 return $art_session;
2138 }
2139 else {
2140 $self->logger->error(
2141 "Unable to delete artifact session $session (ID $id)");
2142 $self->logger->error( $samlSessionInfo->error );
2143 return;
2144 }
2145 }
2146  
2147 return;
2148 }
2149  
2150 ## @method string createArtifactResponse(Lasso::Login login)
2151 # Create artifact response
2152 # @param login Lasso::Login object
2153 # @return Artifact response
2154 sub createArtifactResponse {
2155 my ( $self, $req, $login ) = @_;
2156  
2157 my $artifact_id = $login->assertionArtifact();
2158  
2159 # Load artifact message into login response
2160 my $art_session = $self->loadArtifact($artifact_id);
2161 utf8::decode( $art_session->{message} );
2162 eval { $login->set_artifact_message( $art_session->{message} ); };
2163 if ($@) {
2164 $self->checkLassoError($@);
2165 $self->logger->error("Cannot load artifact message");
2166 return;
2167 }
2168  
2169 $self->logger->debug("Response loaded");
2170  
2171 # Try to get Lasso session
2172 my $session_id = $art_session->{_saml_id};
2173 if ($session_id) {
2174 $self->logger->debug("Find session_id $session_id in artifact session");
2175  
2176 my $session = $self->p->getApacheSession($session_id);
2177 unless ($session) {
2178 $self->logger->error("Unable to open session $session_id");
2179 return;
2180 }
2181  
2182 my $lassoSession = $session->data->{ $self->lsDump };
2183  
2184 if ($lassoSession) {
2185 unless ( $self->setSessionFromDump( $login, $lassoSession ) ) {
2186 $self->logger->error("Unable to load Lasso Session");
2187 return;
2188 }
2189 $self->logger->debug("Lasso Session loaded");
2190 }
2191  
2192 }
2193 else {
2194 $self->logger->debug("No session_id in artifact session");
2195 }
2196  
2197 # Build artifact response
2198 eval { Lasso::Login::build_response_msg($login); };
2199 if ($@) {
2200 $self->checkLassoError($@);
2201 $self->logger->error("Cannot build artifact response");
2202 return;
2203 }
2204 $self->logger->debug("Artifact response built");
2205  
2206 # Store Lasso session if session opened
2207 if ( $session_id and $login->is_session_dirty ) {
2208 $self->logger->debug("Save Lasso session in session");
2209 $self->updateSession( $req,
2210 { $self->lsDump => $login->get_session->dump }, $session_id );
2211 }
2212  
2213 # Return artifact message
2214 return $login->msg_body;
2215 }
2216  
2217 ## @method boolean processArtRequestMsg(Lasso::Profile profile, string request)
2218 # Process artifact request message
2219 # @param profile Lasso::Profile object
2220 # @param request SAML request
2221 # @return result
2222 sub processArtRequestMsg {
2223 my ( $self, $profile, $request ) = @_;
2224  
2225 # Login profile
2226 if ( $profile->isa("Lasso::Login") ) {
2227  
2228 eval { Lasso::Login::process_request_msg( $profile, $request ); };
2229 return $self->checkLassoError($@);
2230  
2231 }
2232  
2233 return 0;
2234 }
2235  
2236 ## @method boolean processArtResponseMsg(Lasso::Profile profile, string response)
2237 # Process artifact response message
2238 # @param profile Lasso::Profile object
2239 # @param response SAML response
2240 # @return result
2241 sub processArtResponseMsg {
2242 my ( $self, $profile, $response ) = @_;
2243  
2244 # Login profile
2245 if ( $profile->isa("Lasso::Login") ) {
2246  
2247 eval { Lasso::Login::process_response_msg( $profile, $response ); };
2248 return $self->checkLassoError($@);
2249  
2250 }
2251  
2252 return 0;
2253 }
2254  
2255 ## @method string sendSOAPMessage(string endpoint, string message)
2256 # Send SOAP message and get response
2257 # @param endpoint SOAP End Point
2258 # @param message SOAP message
2259 # @return SOAP response
2260 sub sendSOAPMessage {
2261 my ( $self, $endpoint, $message ) = @_;
2262 my $response;
2263  
2264 my $request = HTTP::Request->new( 'POST' => $endpoint );
2265 $request->content_type('text/xml');
2266 $request->header( Accept => 'text/xml' );
2267 $request->content($message);
2268  
2269 $self->logger->debug("Send SOAP message $message to $endpoint");
2270  
2271 # SOAP call
2272 my $soap_answer = $self->ua()->request($request);
2273 if ( $soap_answer->code() == "200" ) {
2274 $response = $soap_answer->content();
2275 $self->logger->debug("Get response $response");
2276 }
2277 else {
2278 $self->logger->debug("No response to SOAP request");
2279 return;
2280 }
2281  
2282 return $response;
2283 }
2284  
2285 ## @method Lasso::AssertionQuery createAssertionQuery(Lasso::Server server)
2286 # Create a new assertion query
2287 # @param server Lasso::Server object
2288 # @return assertion query
2289 sub createAssertionQuery {
2290 my ( $self, $server ) = @_;
2291 my $query;
2292  
2293 # Create assertion query
2294 eval { $query = Lasso::AssertionQuery->new($server); };
2295 if ($@) {
2296 $self->checkLassoError($@);
2297 return;
2298 }
2299  
2300 return $query;
2301 }
2302  
2303 ## @method Lasso::AssertionQuery createAttributeRequest(Lasso::Server server, string idp, hashref attributes, Lasso::Saml2NameID nameid)
2304 # Create an attribute request
2305 # @param server Lasso::Server object
2306 # @param idp IDP entityID
2307 # @param attributes List of requested attributes
2308 # @param nameid Subject NameID
2309 # @return attribute request
2310 sub createAttributeRequest {
2311 my ( $self, $server, $idp, $attributes, $nameid ) = @_;
2312 my $query;
2313  
2314 # Create assertion query
2315 return unless ( $query = $self->createAssertionQuery($server) );
2316  
2317 $self->logger->debug("Assertion query created");
2318  
2319 # Init request
2320 my $method = Lasso::Constants::HTTP_METHOD_SOAP;
2321 my $type = Lasso::Constants::ASSERTION_QUERY_REQUEST_TYPE_ATTRIBUTE;
2322 eval {
2323 Lasso::AssertionQuery::init_request( $query, $idp, $method, $type );
2324 };
2325 if ($@) {
2326 $self->checkLassoError($@);
2327 return;
2328 }
2329  
2330 $self->logger->debug("Assertion query request initiated");
2331  
2332 # Set NameID
2333 eval { $query->request()->Subject()->NameID($nameid); };
2334 if ($@) {
2335 $self->checkLassoError($@);
2336 return;
2337 }
2338  
2339 $self->logger->debug(
2340 "Set NameID " . $nameid->dump . " in assertion query" );
2341  
2342 # Store attributes in request
2343 my @requested_attributes;
2344 foreach ( keys %$attributes ) {
2345  
2346 # Create SAML2 Attribute
2347 my $attribute;
2348  
2349 eval { $attribute = Lasso::Saml2Attribute->new(); };
2350 if ($@) {
2351 $self->checkLassoError($@);
2352 return;
2353 }
2354  
2355 # Set attribute properties
2356 my ( $mandatory, $name, $format, $friendly_name ) =
2357 split( /;/, $attributes->{$_} );
2358  
2359 $attribute->Name($name) if defined $name;
2360 $attribute->NameFormat($format) if defined $format;
2361 $attribute->FriendlyName($friendly_name) if defined $friendly_name;
2362  
2363 # Store attribute
2364 push @requested_attributes, $attribute;
2365 }
2366  
2367 # Set attributes in request
2368 eval { $query->request()->Attribute(@requested_attributes); };
2369 if ($@) {
2370 $self->checkLassoError($@);
2371 return;
2372 }
2373  
2374 # Build message
2375 eval { Lasso::AssertionQuery::build_request_msg($query); };
2376 if ($@) {
2377 $self->checkLassoError($@);
2378 return;
2379 }
2380  
2381 # Return query
2382 return $query;
2383 }
2384  
2385 ## @method boolean validateAttributeRequest(Lasso::AssertionQuery query)
2386 # Validate an attribute request
2387 # @param query Lasso::AssertionQuery object
2388 # @return result
2389 sub validateAttributeRequest {
2390 my ( $self, $query ) = @_;
2391  
2392 eval { Lasso::AssertionQuery::validate_request($query); };
2393  
2394 return $self->checkLassoError($@);
2395 }
2396  
2397 ## @method Lasso::AssertionQuery processAttributeRequest(Lasso::Server server, string request)
2398 # Process an attribute request
2399 # @param server Lasso::Server object
2400 # @param request Request content
2401 # @return assertion query
2402 sub processAttributeRequest {
2403 my ( $self, $server, $request ) = @_;
2404 my $query;
2405  
2406 # Create assertion query
2407 return unless ( $query = $self->createAssertionQuery($server) );
2408  
2409 $self->logger->debug("Assertion query created");
2410  
2411 # Process response
2412 eval { Lasso::AssertionQuery::process_request_msg( $query, $request ); };
2413 if ($@) {
2414 $self->checkLassoError($@);
2415 return;
2416 }
2417  
2418 $self->logger->debug("Attribute request is valid");
2419  
2420 return $query;
2421 }
2422  
2423 ## @method string buildAttributeResponse(Lasso::AssertionQuery query)
2424 # Build attribute response
2425 # @param query Lasso::AssertionQuery object
2426 # @return attribute response
2427 sub buildAttributeResponse {
2428 my ( $self, $query ) = @_;
2429  
2430 eval { Lasso::AssertionQuery::build_response_msg($query); };
2431  
2432 if ($@) {
2433 $self->checkLassoError($@);
2434 return;
2435 }
2436  
2437 return $query->msg_body;
2438 }
2439  
2440 ## @method Lasso::AssertionQuery processAttributeResponse(Lasso::Server server, string response)
2441 # Process an attribute response
2442 # @param server Lasso::Server object
2443 # @param response Response content
2444 # @return assertion query
2445 sub processAttributeResponse {
2446 my ( $self, $server, $response ) = @_;
2447 my $query;
2448  
2449 # Create assertion query
2450 return unless ( $query = $self->createAssertionQuery($server) );
2451  
2452 $self->logger->debug("Assertion query created");
2453  
2454 # Process response
2455 eval { Lasso::AssertionQuery::process_response_msg( $query, $response ); };
2456 if ($@) {
2457 $self->checkLassoError($@);
2458 return;
2459 }
2460  
2461 $self->logger->debug("Attribute response is valid");
2462  
2463 return $query;
2464 }
2465  
2466 ## @method string getNameIDFormat(string format)
2467 # Convert configuration string into SAML2 NameIDFormat string
2468 # @param format configuration string
2469 # @return SAML2 NameIDFormat string
2470 sub getNameIDFormat {
2471 my ( $self, $format ) = @_;
2472  
2473 return Lasso::Constants::SAML2_NAME_IDENTIFIER_FORMAT_UNSPECIFIED
2474 if ( $format =~ /unspecified/i );
2475 return Lasso::Constants::SAML2_NAME_IDENTIFIER_FORMAT_EMAIL
2476 if ( $format =~ /email/i );
2477 return Lasso::Constants::SAML2_NAME_IDENTIFIER_FORMAT_X509
2478 if ( $format =~ /x509/i );
2479 return Lasso::Constants::SAML2_NAME_IDENTIFIER_FORMAT_WINDOWS
2480 if ( $format =~ /windows/i );
2481 return Lasso::Constants::SAML2_NAME_IDENTIFIER_FORMAT_KERBEROS
2482 if ( $format =~ /kerberos/i );
2483 return Lasso::Constants::SAML2_NAME_IDENTIFIER_FORMAT_ENTITY
2484 if ( $format =~ /entity/i );
2485 return Lasso::Constants::SAML2_NAME_IDENTIFIER_FORMAT_PERSISTENT
2486 if ( $format =~ /persistent/i );
2487 return Lasso::Constants::SAML2_NAME_IDENTIFIER_FORMAT_TRANSIENT
2488 if ( $format =~ /transient/i );
2489 return Lasso::Constants::SAML2_NAME_IDENTIFIER_FORMAT_ENCRYPTED
2490 if ( $format =~ /encrypted/i );
2491  
2492 return;
2493 }
2494  
2495 ## @method int getHttpMethod(string method)
2496 # Convert configuration string into Lasso HTTP Method integer
2497 # @param method configuration string
2498 # @return Lasso HTTP Method integer
2499 sub getHttpMethod {
2500 my ( $self, $method ) = @_;
2501  
2502 $method ||= '';
2503 return Lasso::Constants::HTTP_METHOD_POST
2504 if ( $method =~ /^(http)?[-_]?post$/i );
2505 return Lasso::Constants::HTTP_METHOD_REDIRECT
2506 if ( $method =~ /^(http)?[-_]?redirect$/i );
2507 return Lasso::Constants::HTTP_METHOD_SOAP
2508 if ( $method =~ /^(http)?[-_]?soap$/i );
2509 return Lasso::Constants::HTTP_METHOD_ARTIFACT_GET
2510 if ( $method =~ /^(artifact)[-_]get$/i );
2511 return Lasso::Constants::HTTP_METHOD_ARTIFACT_POST
2512 if ( $method =~ /^(artifact)[-_]post$/i );
2513  
2514 return;
2515 }
2516  
2517 ## @method int getHttpMethodString(int method)
2518 # Convert configuration Lasso HTTP Method integer into string
2519 # @param method Lasso HTTP Method
2520 # @return method string
2521 sub getHttpMethodString {
2522 my ( $self, $method ) = @_;
2523  
2524 return "POST" if ( $method == Lasso::Constants::HTTP_METHOD_POST );
2525 return "REDIRECT"
2526 if ( $method == Lasso::Constants::HTTP_METHOD_REDIRECT );
2527 return "SOAP" if ( $method == Lasso::Constants::HTTP_METHOD_SOAP );
2528 return "ARTIFACT GET"
2529 if ( $method == Lasso::Constants::HTTP_METHOD_ARTIFACT_GET );
2530 return "ARTIFACT POST"
2531 if ( $method == Lasso::Constants::HTTP_METHOD_ARTIFACT_POST );
2532  
2533 return "UNDEFINED";
2534 }
2535 ## @method int getFirstHttpMethod(Lasso::Server server, string entityID, int protocolType)
2536 # Find a suitable HTTP method for an entity with a given protocol
2537 # @param server Lasso::Server object
2538 # @param entityID entity ID
2539 # @param protocolType Lasso protocol type
2540 # @return Lasso HTTP Method
2541 sub getFirstHttpMethod {
2542 my ( $self, $server, $entityID, $protocolType ) = @_;
2543 my $entity_provider;
2544 my $method;
2545  
2546 # Get Lasso::Provider object
2547 eval {
2548 $entity_provider = Lasso::Server::get_provider( $server, $entityID );
2549 };
2550 if ($@) {
2551 $self->checkLassoError($@);
2552 return;
2553 }
2554  
2555 # Find HTTP method
2556 eval {
2557 $method =
2558 Lasso::Provider::get_first_http_method( $server, $entity_provider,
2559 $protocolType );
2560 };
2561 if ($@) {
2562 $self->checkLassoError($@);
2563 return;
2564 }
2565  
2566 return $method;
2567 }
2568  
2569 ## @method boolean disableSignature(Lasso::Profile profile)
2570 # Modify Lasso signature hint to disable signature
2571 # @param profile Lasso profile object
2572 # @return result
2573 sub disableSignature {
2574 my ( $self, $profile ) = @_;
2575  
2576 eval {
2577 Lasso::Profile::set_signature_hint( $profile,
2578 Lasso::Constants::PROFILE_SIGNATURE_HINT_FORBID );
2579 };
2580  
2581 return $self->checkLassoError($@);
2582 }
2583  
2584 ## @method boolean forceSignature(Lasso::Profile profile)
2585 # Modify Lasso signature hint to force signature
2586 # @param profile Lasso profile object
2587 # @return result
2588 sub forceSignature {
2589 my ( $self, $profile ) = @_;
2590  
2591 eval {
2592 Lasso::Profile::set_signature_hint( $profile,
2593 Lasso::Constants::PROFILE_SIGNATURE_HINT_FORCE );
2594 };
2595  
2596 return $self->checkLassoError($@);
2597 }
2598  
2599 ## @method boolean disableSignatureVerification(Lasso::Profile profile)
2600 # Modify Lasso signature hint to disable signature verification
2601 # @param profile Lasso profile object
2602 # @return result
2603 sub disableSignatureVerification {
2604 my ( $self, $profile ) = @_;
2605  
2606 eval {
2607 Lasso::Profile::set_signature_verify_hint( $profile,
2608 Lasso::Constants::PROFILE_SIGNATURE_VERIFY_HINT_IGNORE );
2609 };
2610  
2611 return $self->checkLassoError($@);
2612 }
2613  
2614 ## @method boolean forceSignatureVerification(Lasso::Profile profile)
2615 # Modify Lasso signature hint to force signature verification
2616 # @param profile Lasso profile object
2617 # @return result
2618 sub forceSignatureVerification {
2619 my ( $self, $profile ) = @_;
2620  
2621 eval {
2622 Lasso::Profile::set_signature_verify_hint( $profile,
2623 Lasso::Constants::PROFILE_SIGNATURE_VERIFY_HINT_MAYBE );
2624 };
2625  
2626 return $self->checkLassoError($@);
2627 }
2628  
2629 ## @method string getAuthnContext(string context)
2630 # Convert configuration string into SAML2 AuthnContextClassRef string
2631 # @param context configuration string
2632 # @return SAML2 AuthnContextClassRef string
2633 sub getAuthnContext {
2634 my ( $self, $context ) = @_;
2635  
2636 return Lasso::Constants::SAML2_AUTHN_CONTEXT_KERBEROS
2637 if ( $context =~ /^kerberos$/i );
2638 return Lasso::Constants::SAML2_AUTHN_CONTEXT_PASSWORD_PROTECTED_TRANSPORT
2639 if ( $context =~ /^password[-_ ]protected[-_ ]transport$/i );
2640 return Lasso::Constants::SAML2_AUTHN_CONTEXT_PASSWORD
2641 if ( $context =~ /^password$/i );
2642 return Lasso::Constants::SAML2_AUTHN_CONTEXT_X509
2643 if ( $context =~ /^x509$/i );
2644 return Lasso::Constants::SAML2_AUTHN_CONTEXT_TLS_CLIENT
2645 if ( $context =~ /^tls[-_ ]client$/i );
2646 return Lasso::Constants::SAML2_AUTHN_CONTEXT_UNSPECIFIED
2647 if ( $context =~ /^unspecified$/i );
2648  
2649 return;
2650 }
2651  
2652 ## @method string timestamp2samldate(string timestamp)
2653 # Convert timestamp into SAML2 date format
2654 # @param timestamp UNIX timestamp
2655 # @return SAML2 date
2656 sub timestamp2samldate {
2657 my ( $self, $timestamp ) = @_;
2658  
2659 my @t = gmtime($timestamp);
2660 my $samldate = strftime( "%Y-%m-%dT%TZ", @t );
2661  
2662 $self->logger->debug(
2663 "Convert timestamp $timestamp in SAML2 date: $samldate");
2664  
2665 return $samldate;
2666 }
2667  
2668 ## @method string samldate2timestamp(string samldate)
2669 # Convert SAML2 date format into timestamp
2670 # @param samldate SAML2 date format
2671 # @return UNIX timestamp
2672 sub samldate2timestamp {
2673 my ( $self, $samldate ) = @_;
2674  
2675 my ( $year, $mon, $mday, $hour, $min, $sec, $msec, $ztime ) = ( $samldate =~
2676 /(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d+)?(Z)?/ );
2677  
2678 my $timestamp =
2679 timegm( $sec, $min, $hour, $mday, $mon - 1, $year - 1900, 0 );
2680  
2681 $self->logger->debug(
2682 "Convert SAML2 date $samldate in timestamp: $timestamp");
2683  
2684 return $timestamp;
2685 }
2686  
2687 ## @pmethod int sendLogoutResponseToServiceProvider(Lasso::Logout $logout, int $method)
2688 # Send logout response issue from a logout request.
2689 # @param $logout Lasso Logout object
2690 # @param $method Method to use
2691 # @return boolean False if failed.
2692 sub sendLogoutResponseToServiceProvider {
2693 my ( $self, $req, $logout, $method ) = @_;
2694  
2695 # Logout response
2696 unless ( $self->buildLogoutResponseMsg($logout) ) {
2697 $self->logger->warn( "Could not build a logout response for provider "
2698 . $logout->remote_providerID
2699 . ", staying on portal" );
2700 return $self->p->doPE( $req, PE_LOGOUT_OK );
2701 }
2702  
2703 # Send response depending on request method
2704 # HTTP-REDIRECT
2705 if ( $method == Lasso::Constants::HTTP_METHOD_REDIRECT ) {
2706  
2707 # Redirect user to response URL
2708 my $slo_url = $logout->msg_url;
2709 return $self->p->sendRedirection( $req, URI->new($slo_url)->as_string );
2710 }
2711  
2712 # HTTP-POST
2713 elsif ( $method == Lasso::Constants::HTTP_METHOD_POST ) {
2714  
2715 # Use autosubmit form
2716 my $slo_url = $logout->msg_url;
2717 my $slo_body = $logout->msg_body;
2718 my $relaystate = $logout->msg_relayState;
2719  
2720 # TODO: insert postUrl in $req
2721 $req->postUrl($slo_url);
2722 $req->{postFields} = { 'SAMLResponse' => $slo_body };
2723  
2724 # RelayState
2725 if ($relaystate) {
2726 $req->{postFields}->{'RelayState'} = encode_entities($relaystate);
2727 $req->data->{safeHiddenFormValues}->{RelayState} = 1;
2728 }
2729  
2730 return $self->p->do( $req, ['autoPost'] );
2731 }
2732 elsif ( $method == Lasso::Constants::HTTP_METHOD_SOAP ) {
2733 return $self->sendSLOSoapErrorResponse( $req, $logout, $method );
2734 }
2735 return $self->p->sendError( $req,
2736 "Lasso method '$method' should not be handle here...", 400 );
2737 }
2738  
2739 ## @pmethod int sendLogoutRequestToProvider(Lasso::Logout $logout, string $providerID, int $method, boolean $relay, string $relayState)
2740 # Send a logout request to a provider
2741 # If information have to be displayed to users, such as iframe to send
2742 # HTTP-Redirect or HTTP-POST logout request, then $self->{_info} will be
2743 # updated.
2744 # @param $logout Lasso Logout object
2745 # @param $providerID The concerned service provider
2746 # @param $method The method used to send the logout request
2747 # @param $relay If SOAP method, build a relay logout request
2748 # @param $relayState Relay State for SLO status
2749 # @return int Number of concerned providers.
2750 sub sendLogoutRequestToProvider {
2751 my ( $self, $req, $logout, $providerID, $method, $relay, $relayState ) = @_;
2752 my $server = $self->lassoServer;
2753 my $info;
2754  
2755 # Test if provider is mentionned
2756 if ( !$providerID ) {
2757 return ( 0, undef, undef );
2758 }
2759  
2760 # Lazy load provider
2761 $self->lazy_load_entityid($providerID);
2762  
2763 my $type = defined $self->spList->{$providerID} ? "SP" : "IDP";
2764  
2765 # Find EntityID in spList or idpList
2766 unless ( defined $self->{ lc($type) . 'List' }->{$providerID} ) {
2767 $self->logger->error("$providerID does not match any known $type");
2768 return ( 0, undef, undef );
2769 }
2770  
2771 # Get Provider Name and Conf Key from EntityID
2772 my $providerName =
2773 $self->{ lc($type) . 'List' }->{$providerID}->{name};
2774 my $confKey =
2775 $self->{ lc($type) . 'List' }->{$providerID}->{confKey};
2776  
2777 # Get first HTTP method
2778 my $protocolType = Lasso::Constants::MD_PROTOCOL_TYPE_SINGLE_LOGOUT;
2779 if ( !$method ) {
2780 $method =
2781 $self->getFirstHttpMethod( $server, $providerID, $protocolType );
2782 }
2783  
2784 # Fix a default value for the relay parameter
2785 $relay = 0 unless ( defined $relay );
2786  
2787 # Signature
2788 my $signSLOMessage =
2789 $self->{ lc($type) . 'Options' }->{$providerID}
2790 ->{ 'saml' . $type . 'MetaDataOptionsSignSLOMessage' } // -1;
2791  
2792 if ( $signSLOMessage == 0 ) {
2793 $self->logger->debug("SLO request will not be signed");
2794 $self->disableSignature($logout);
2795 }
2796 elsif ( $signSLOMessage == 1 ) {
2797 $self->logger->debug("SLO request will be signed");
2798 $self->forceSignature($logout);
2799 }
2800 else {
2801 $self->logger->debug("SLO request signature according to metadata");
2802 }
2803  
2804 # Relay State
2805 if ($relayState) {
2806 eval { $logout->msg_relayState($relayState); };
2807 if ($@) {
2808 $self->logger->error(
2809 "Unable to set Relay State $relayState in SLO request for $confKey"
2810 );
2811 return ( 0, $method, undef );
2812 }
2813 $self->logger->debug('Relay state set');
2814 }
2815  
2816 # Skip SLO if no method found (#2746)
2817 unless ( defined $method and $method != -1 ) {
2818 $self->logger->debug("No HTTP SLO method found for $providerID");
2819 return ( 0, $method, undef );
2820 }
2821  
2822 # Initiate the logout request
2823 unless ( $self->initLogoutRequest( $logout, $providerID, $method ) ) {
2824 $self->logger->error("Initiate logout request failed for $providerID");
2825 return ( 0, $method, undef );
2826 }
2827  
2828 # Build request message
2829 unless ( $self->buildLogoutRequestMsg($logout) ) {
2830 $self->logger->error("Build logout request failed for $providerID");
2831 return ( 0, $method, undef );
2832 }
2833  
2834 $self->logger->debug("Request built for $providerID");
2835  
2836 # Keep message ID in memory to prevent replay
2837 my $samlID = $logout->request()->ID;
2838 unless ( $self->storeReplayProtection($samlID) ) {
2839 $self->logger->error("Unable to store message ID");
2840 return ( 0, $method, undef );
2841 }
2842  
2843 # Get portal value
2844 my $portal = $self->p->buildUrl;
2845 $portal =~ s/\/$//;
2846  
2847 # Send logout request to the provider depending of the request method
2848 # HTTP-REDIRECT
2849 if ( $method == Lasso::Constants::HTTP_METHOD_REDIRECT ) {
2850  
2851 $self->logger->debug(
2852 "Send HTTP-REDIRECT logout request to $providerID");
2853  
2854 # Redirect user to response URL
2855 my $slo_url = $logout->msg_url;
2856  
2857 # Create iFrame
2858 $info .= $self->loadTemplate(
2859 $req,
2860 'samlSpLogout',
2861 params => {
2862 url => $slo_url,
2863 name => $providerName,
2864 }
2865 );
2866 }
2867  
2868 # HTTP-POST
2869 elsif ( $method == Lasso::Constants::HTTP_METHOD_POST ) {
2870  
2871 $self->logger->debug("Build POST relay logout request to $providerID");
2872  
2873 my $infos;
2874  
2875 # Store infos
2876 $infos->{type} = 'relay';
2877 $infos->{_utime} = time;
2878 $infos->{url} = $logout->msg_url;
2879 $infos->{body} = $logout->msg_body;
2880 $infos->{relayState} = $logout->msg_relayState;
2881  
2882 # Create a new relay session
2883 my $relayInfos = $self->getSamlSession( undef, $infos );
2884  
2885 my $relayID = $relayInfos->id;
2886  
2887 # Build the URL that could be used to play this logout request
2888 my $slo_url =
2889 $portal
2890 . '/saml/relaySingleLogoutPOST?'
2891 . build_urlencoded( relay => $relayID );
2892  
2893 # Create iFrame
2894 $info .= $self->loadTemplate(
2895 $req,
2896 'samlSpLogout',
2897 params => {
2898 url => $slo_url,
2899 name => $providerName,
2900 }
2901 );
2902 $req->data->{cspChildSrc}->{ $self->p->cspGetHost( $logout->msg_url ) }
2903 = 1;
2904 }
2905  
2906 # HTTP-SOAP
2907 elsif ( $method == Lasso::Constants::HTTP_METHOD_SOAP ) {
2908  
2909 # Build a relay request, to be used after SLO process is done
2910 if ($relay) {
2911  
2912 $self->logger->debug(
2913 "Build SOAP relay logout request for $providerID");
2914  
2915 my $infos;
2916 $infos->{type} = 'relay';
2917 $infos->{_utime} = time;
2918 $infos->{ $self->lsDump } = $req->sessionInfo->{ $self->lsDump };
2919 $infos->{ $self->liDump } = $req->sessionInfo->{ $self->liDump };
2920 $infos->{_providerID} = $providerID;
2921 $infos->{_relayState} = $logout->msg_relayState;
2922  
2923 # Create a new relay session
2924 my $relayInfos = $self->getSamlSession( undef, $infos );
2925  
2926 my $relayID = $relayInfos->id;
2927  
2928 # Build the URL that could be used to play this logout request
2929 my $slo_url =
2930 $portal
2931 . '/saml/relaySingleLogoutSOAP?'
2932 . build_urlencoded( relay => $relayID );
2933  
2934 # Display information to the user
2935 $info .= $self->loadTemplate(
2936 $req,
2937 'samlSpSoapLogout',
2938 params => {
2939 imgUrl => $slo_url,
2940 name => $providerName,
2941 }
2942 );
2943 }
2944  
2945 # Send the request directly
2946 else {
2947  
2948 $self->logger->debug("Send SOAP logout request to $providerID");
2949  
2950 my $slo_url = $logout->msg_url;
2951 my $slo_body = $logout->msg_body;
2952  
2953 # Send SOAP request and manage response
2954 my $sp_response = $self->sendSOAPMessage( $slo_url, $slo_body );
2955  
2956 unless ($sp_response) {
2957 $self->logger->error("No logout response to SOAP request");
2958 return ( 0, $method, undef );
2959 }
2960  
2961 # Process logout response
2962 my $sp_result =
2963 $self->processLogoutResponseMsg( $logout, $sp_response );
2964  
2965 unless ($sp_result) {
2966 $self->logger->error("Fail to process logout response");
2967 return ( 0, $method, undef );
2968 }
2969  
2970 if ($relayState) {
2971  
2972 # Store success status for this SLO request
2973 my $sloStatusSessionInfos = $self->getSamlSession($relayState);
2974  
2975 if ($sloStatusSessionInfos) {
2976 $sloStatusSessionInfos->update( { $confKey => 1 } );
2977 $self->logger->debug(
2978 "Store SLO status for $confKey in session $relayState");
2979 }
2980 else {
2981 $self->logger->warn(
2982 "Unable to store SLO status for $confKey in session $relayState"
2983 );
2984 }
2985 }
2986  
2987 $self->logger->debug("Logout response is valid");
2988  
2989 }
2990  
2991 }
2992  
2993 return ( 1, $method, $info );
2994  
2995 }
2996  
2997 ## @pmethod int sendLogoutRequestToProviders(Lasso::Logout logout, string relayState )
2998 # Send logout response issue from a logout request to all other
2999 # providers. If information have to be displayed to users, such as
3000 # iframe to send HTTP-Redirect or HTTP-POST logout request, then
3001 # $self->{_info} will be updated.
3002 # @param logout Lasso Logout object
3003 # @param relayState Relay State for SLO status
3004 # @return int Number of concerned providers.
3005 sub sendLogoutRequestToProviders {
3006 my ( $self, $req, $logout, $relayState ) = @_;
3007 my $server = $self->lassoServer;
3008 my $providersCount = 0;
3009 my $content = '';
3010  
3011 # Reset providerID into Lasso::Logout object
3012 $self->resetProviderIdIndex($logout);
3013  
3014 # Foreach SP found in session, get it from configuration, and send the
3015 # appropriate logout request (HTTP,POST,SOAP).
3016 while ( my $providerID = $self->getNextProviderId($logout) ) {
3017  
3018 # Send logout request
3019 my ( $rstatus, $rmethod, $rinfo ) =
3020 $self->sendLogoutRequestToProvider( $req, $logout, $providerID,
3021 undef, 1, $relayState );
3022  
3023 next unless ($rstatus);
3024  
3025 # Count providers that have to be request by HTTP redirect
3026 $providersCount++;
3027  
3028 # Add information if necessary
3029 if ($rinfo) {
3030 $content .= $rinfo;
3031 }
3032  
3033 }
3034  
3035 # Print some information to the user.
3036 $req->info(
3037 $self->loadTemplate(
3038 $req, 'samlSpsLogout', params => { content => $content }
3039 )
3040 ) if $providersCount;
3041  
3042 return $providersCount;
3043 }
3044  
3045 ## @method boolean checkSignatureStatus(Lasso::Profile profile)
3046 # Check signature status
3047 # @param profile Lasso::Profile object
3048 # @return result
3049 sub checkSignatureStatus {
3050 my ( $self, $profile ) = @_;
3051  
3052 eval { Lasso::Profile::get_signature_status($profile); };
3053  
3054 return $self->checkLassoError($@);
3055 }
3056  
3057 ## @method int authnContext2authnLevel(string authnContext)
3058 # Return authentication level corresponding to authnContext
3059 # @param authnContext SAML authentication context
3060 # return authentication level
3061 sub authnContext2authnLevel {
3062 my ( $self, $authnContext ) = @_;
3063  
3064 # Standard contexts
3065 return $self->conf->{samlAuthnContextMapPassword}
3066 if ( $authnContext eq $self->getAuthnContext("password") );
3067 return $self->conf->{samlAuthnContextMapPasswordProtectedTransport}
3068 if (
3069 $authnContext eq $self->getAuthnContext("password-protected-transport")
3070 );
3071 return $self->conf->{samlAuthnContextMapKerberos}
3072 if ( $authnContext eq $self->getAuthnContext("kerberos") );
3073 return $self->conf->{samlAuthnContextMapTLSClient}
3074 if ( $authnContext eq $self->getAuthnContext("tls-client") );
3075  
3076 # Extras contexts
3077 if ( defined $self->conf->{samlAuthnContextMapExtra}
3078 and defined $self->conf->{samlAuthnContextMapExtra}->{$authnContext} )
3079 {
3080 return $self->conf->{samlAuthnContextMapExtra}->{$authnContext};
3081 }
3082  
3083 return 0;
3084 }
3085  
3086 ## @method int authnLevel2authnContext(int authnLevel)
3087 # Return SAML authentication context corresponding to authnLevel
3088 # @param authnLevel internal authentication level
3089 # return SAML authentication context
3090 sub authnLevel2authnContext {
3091 my ( $self, $authnLevel ) = @_;
3092  
3093 # Standard contexts
3094 return $self->getAuthnContext("password")
3095 if ( $authnLevel == $self->conf->{samlAuthnContextMapPassword} );
3096 return $self->getAuthnContext("password-protected-transport")
3097 if ( $authnLevel ==
3098 $self->conf->{samlAuthnContextMapPasswordProtectedTransport} );
3099 return $self->getAuthnContext("kerberos")
3100 if ( $authnLevel == $self->conf->{samlAuthnContextMapKerberos} );
3101 return $self->getAuthnContext("tls-client")
3102 if ( $authnLevel == $self->conf->{samlAuthnContextMapTLSClient} );
3103  
3104 # Extras contexts
3105 if ( defined $self->conf->{samlAuthnContextMapExtra} ) {
3106 foreach
3107 my $authnContext ( keys %{ $self->conf->{samlAuthnContextMapExtra} } )
3108 {
3109 return $authnContext
3110 if ( $authnLevel ==
3111 $self->conf->{samlAuthnContextMapExtra}->{$authnContext} );
3112 }
3113 }
3114  
3115 return $self->getAuthnContext("unspecified");
3116 }
3117  
3118 ## @method boolean checkDestination(Lasso::Node message, string url)
3119 # If SAML Destination attribute is present, check it
3120 # @param message SAML request or response
3121 # @param url Requested URL
3122 # @return Result
3123 sub checkDestination {
3124 my ( $self, $message, $url ) = @_;
3125 my $destination;
3126  
3127 # Read Destination
3128 eval { $destination = $message->Destination(); };
3129  
3130 # Ok if no Destination
3131 if ( $@ or !$destination ) {
3132 $self->logger->debug("No Destination in SAML message");
3133 return 1;
3134 }
3135  
3136 $self->logger->debug("Destination $destination found in SAML message");
3137  
3138 # Retrieve full URL
3139 my $portal = $self->p->buildUrl;
3140 $portal =~ s#^(https?://[^/]+)/.*#$1#; # remove path of portal URL
3141 $url = $portal . $url;
3142 $url =~ s/\?.*//;
3143  
3144 # Compare Destination and URL
3145 if ( $destination eq $url ) {
3146 $self->logger->debug("Destination match URL $url");
3147 return 1;
3148 }
3149  
3150 $self->logger->error("Destination does not match URL $url");
3151 return 0;
3152 }
3153  
3154 ## @method hashref getSamlSession(string id)
3155 # Try to recover the SAML session corresponding to id and return session
3156 # If id is set to undef, return a new session
3157 # @param id session reference
3158 # @return Lemonldap::NG::Common::Session object
3159 sub getSamlSession {
3160 my ( $self, $id, $info ) = @_;
3161  
3162 my $samlSession = Lemonldap::NG::Common::Session->new( {
3163 storageModule => $self->aModule,
3164 storageModuleOptions => $self->amOpts,
3165 cacheModule => $self->conf->{localSessionStorage},
3166 cacheModuleOptions => $self->conf->{localSessionStorageOptions},
3167 id => $id,
3168 kind => $self->sessionKind,
3169 ( $info ? ( info => $info ) : () ),
3170 }
3171 );
3172  
3173 if ( $samlSession->error ) {
3174 if ($id) {
3175 $self->userLogger->warn("SAML session $id not found");
3176 }
3177 else {
3178 $self->logger->error("Unable to create new SAML session");
3179 $self->logger->error( $samlSession->error );
3180 }
3181 return undef;
3182 }
3183  
3184 return $samlSession;
3185 }
3186  
3187 ## @method Lasso::Saml2Attribute createAttribute(string name, string format, string friendly_name)
3188 # Create a new SAML attribute
3189 # @param name Attribute name
3190 # @param format optional Attribute format
3191 # @param friendly_name optional Attribute friendly name
3192 # @return SAML attribute
3193 sub createAttribute {
3194 my ( $self, $name, $format, $friendly_name ) = @_;
3195 my $attribute;
3196  
3197 # Name is required
3198 return unless defined $name;
3199  
3200 # SAML2 attribute
3201 eval { $attribute = Lasso::Saml2Attribute->new(); };
3202 if ($@) {
3203 $self->checkLassoError($@);
3204 return;
3205 }
3206  
3207 # Default values
3208 $friendly_name ||= $name;
3209 $format ||= Lasso::Constants::SAML2_ATTRIBUTE_NAME_FORMAT_BASIC;
3210  
3211 # Set attribute properties
3212 $attribute->Name($name);
3213 $attribute->NameFormat($format);
3214 $attribute->FriendlyName($friendly_name);
3215  
3216 return $attribute;
3217 }
3218  
3219 ## @method Lasso::Saml2AttributeValue createAttributeValue(value, force_utf8)
3220 # Create a new SAML attribute value
3221 # @param value Value to store (string or Lasso::Node)
3222 # @param force_utf8 set to 1 to decode UTF8 value
3223 # @return SAML attribute value
3224 sub createAttributeValue {
3225 my ( $self, $value, $force_utf8 ) = @_;
3226 my $saml2value;
3227 $force_utf8 = 1 unless defined($force_utf8);
3228  
3229 # Value is required
3230 return unless defined $value;
3231  
3232 # SAML2 attribute value
3233 eval { $saml2value = Lasso::Saml2AttributeValue->new(); };
3234 if ($@) {
3235 $self->checkLassoError($@);
3236 return;
3237 }
3238  
3239 my $content = $value;
3240  
3241 # If a string was provided, wrap it in a TextNode
3242 if ( !ref($content) ) {
3243  
3244 # Decode UTF-8
3245 $self->logger->debug("Decode UTF8 value $value") if $force_utf8;
3246 $value = decode( "utf8", $value ) if $force_utf8;
3247 $self->logger->debug("Create attribute value $value");
3248  
3249 eval { $content = Lasso::MiscTextNode->new(); };
3250 if ($@) {
3251 $self->checkLassoError($@);
3252 return;
3253 }
3254 $content->text_child(1);
3255 $content->content($value);
3256 }
3257  
3258 $saml2value->any($content);
3259  
3260 return $saml2value;
3261 }
3262  
3263 ## @method int getEncryptionMode(string encryption_mode)
3264 # Return Lasso encryption mode
3265 # @param encryption_mode Encryption mode string
3266 # @return Lasso encryption mode
3267 sub getEncryptionMode {
3268 my ( $self, $encryption_mode ) = @_;
3269  
3270 return Lasso::Constants::ENCRYPTION_MODE_NAMEID
3271 if ( $encryption_mode =~ /^nameid$/i );
3272 return Lasso::Constants::ENCRYPTION_MODE_ASSERTION
3273 if ( $encryption_mode =~ /^assertion$/i );
3274 return Lasso::Constants::ENCRYPTION_MODE_NONE;
3275 }
3276  
3277 ## @method boolean setProviderEncryptionMode(Lasso::Provider provider, int encryption_mode)
3278 # Set encryption mode on a provider
3279 # @param provider Lasso::Provider object
3280 # @param encryption_mode Lasso encryption mode
3281 # @return result
3282 sub setProviderEncryptionMode {
3283 my ( $self, $provider, $encryption_mode ) = @_;
3284  
3285 eval {
3286 Lasso::Provider::set_encryption_mode( $provider, $encryption_mode );
3287 };
3288  
3289 return $self->checkLassoError($@);
3290  
3291 }
3292  
3293 ## @method boolean updateSAMLSecondarySessions(string old_session_id, string new_session_id)
3294 # Update _saml_id of secondary sessions when the session ID is changed (upgrade)
3295 sub updateSAMLSecondarySessions {
3296 my ( $self, $req, $old_session_id, $new_session_id ) = @_;
3297  
3298 # Find SAML sessions
3299 my $saml_sessions =
3300 Lemonldap::NG::Common::Apache::Session->searchOn( $self->amOpts,
3301 "_saml_id", $old_session_id );
3302  
3303 if (
3304 my @saml_sessions_keys =
3305 grep { $saml_sessions->{$_}->{_session_kind} eq $self->sessionKind }
3306 keys %$saml_sessions
3307 )
3308 {
3309  
3310 foreach my $saml_session (@saml_sessions_keys) {
3311  
3312 # Get session
3313 $self->logger->debug("Retrieve SAML session $saml_session");
3314  
3315 my $samlSessionInfo = $self->getSamlSession($saml_session);
3316  
3317 # Update session
3318 if ($samlSessionInfo) {
3319 $samlSessionInfo->update( { '_saml_id' => $new_session_id } );
3320 }
3321 }
3322 }
3323 return;
3324 }
3325  
3326 ## @method boolean deleteSAMLSecondarySessions(string session_id)
3327 # Find and delete SAML sessions bounded to a primary session
3328 # @param session_id Primary session ID
3329 # @return result
3330 sub deleteSAMLSecondarySessions {
3331 my ( $self, $session_id ) = @_;
3332 my $result = 1;
3333  
3334 # Find SAML sessions
3335 my $saml_sessions =
3336 Lemonldap::NG::Common::Apache::Session->searchOn( $self->amOpts,
3337 "_saml_id", $session_id );
3338  
3339 if (
3340 my @saml_sessions_keys =
3341 grep { $saml_sessions->{$_}->{_session_kind} eq $self->sessionKind }
3342 keys %$saml_sessions
3343 )
3344 {
3345  
3346 foreach my $saml_session (@saml_sessions_keys) {
3347  
3348 # Get session
3349 $self->logger->debug("Retrieve SAML session $saml_session");
3350  
3351 my $samlSessionInfo = $self->getSamlSession($saml_session);
3352  
3353 # Delete session
3354 if ( $samlSessionInfo->remove ) {
3355 $self->logger->debug("SAML session $saml_session deleted");
3356 }
3357 else {
3358 $self->logger->error(
3359 "Unable to delete SAML session $saml_session");
3360 $self->logger->error( $samlSessionInfo->error );
3361 $result = 0;
3362 }
3363 }
3364 }
3365 elsif ($session_id) {
3366 $self->logger->debug("No SAML session found for session $session_id");
3367 }
3368  
3369 return $result;
3370 }
3371  
3372 ## @method void sendSLOErrorResponse(Lasso::Logout logout, string method)
3373 # Send an SLO error response
3374 # @param logout Lasso::Logout object
3375 # @param method HTTP method
3376 sub sendSLOErrorResponse {
3377 my ( $self, $req, $logout, $method ) = @_;
3378  
3379 # Load empty session
3380 my $session =
3381 '<Session xmlns="http://www.entrouvert.org/namespaces/lasso/0.0"/>';
3382  
3383 unless ( $self->setSessionFromDump( $logout, $session ) ) {
3384 return $self->p->sendError( $req,
3385 "Could not set empty session in logout object", 500 );
3386 }
3387  
3388 # Send invalidated SLO response
3389 return $self->sendLogoutResponseToServiceProvider( $req, $logout, $method );
3390 }
3391  
3392 ## @method void sendSLOSoapErrorResponse(Lasso::Logout logout, string method)
3393 # Send an SLO error response
3394 # @param logout Lasso::Logout object
3395 # @param method HTTP method
3396 # @return PSGI response
3397 sub sendSLOSoapErrorResponse {
3398 my ( $self, $req, $logout, $method ) = @_;
3399  
3400 # Load empty session
3401 my $session =
3402 '<Session xmlns="http://www.entrouvert.org/namespaces/lasso/0.0"/>';
3403  
3404 unless ( $self->setSessionFromDump( $logout, $session ) ) {
3405 return $self->p->sendError( $req,
3406 "Could not set empty session in logout object" );
3407 }
3408 my $slo_body = $logout->msg_body;
3409 $self->logger->debug("SOAP response $slo_body");
3410 return $self->p->sendBinaryResponse( $req, $slo_body, type => 'text/xml' );
3411 }
3412  
3413 ## @method string getQueryString()
3414 # Return query string with or without CGI query_string() method
3415 # @return query string
3416 sub getQueryString {
3417 my ( $self, $req ) = @_;
3418  
3419 my $query_string;
3420  
3421 if ( $self->conf->{samlUseQueryStringSpecific} ) {
3422 my @pairs =
3423 split( /&/, $req->param('issuerQuery') || $req->query_string );
3424 $query_string = join( ';', @pairs );
3425  
3426 }
3427 else {
3428 # TODO: verify this
3429 $query_string = $req->param('issuerQuery') || $req->query_string;
3430 }
3431  
3432 return $query_string;
3433 }
3434  
3435 sub importRealSession {
3436 my ( $self, $req, $ssoSession ) = @_;
3437 $req->sessionInfo( $ssoSession->data );
3438 $req->id( $ssoSession->id );
3439 $req->user( $ssoSession->data->{ $self->conf->{whatToTrace} } );
3440 }
3441  
3442 sub _get_metadata_xml {
3443 my ( $self, $req_or_undef, $type, $sp, $idp ) = @_;
3444  
3445 require Lemonldap::NG::Common::Conf::SAML::Metadata;
3446  
3447 my @signing_keys;
3448 if ($sp) {
3449 $self->lazy_load_entityid($sp);
3450 if ( my $key_list =
3451 $self->spOptions->{$sp}->{samlSPMetaDataOptionsSignatureKey} )
3452 {
3453 @signing_keys = $self->_get_keys_from_config($key_list);
3454 }
3455  
3456 }
3457 elsif ($idp) {
3458 $self->lazy_load_entityid($idp);
3459 if ( my $key_list =
3460 $self->idpOptions->{$idp}->{samlIDPMetaDataOptionsSignatureKey} )
3461 {
3462 @signing_keys = $self->_get_keys_from_config($key_list);
3463 }
3464 }
3465 if ( !@signing_keys ) {
3466 @signing_keys =
3467 $self->_get_keys_from_config( $self->conf->{samlServiceSignatureKey}
3468 || "default-saml-sig" );
3469 }
3470  
3471 my @encryption_keys =
3472 $self->_get_keys_from_config( $self->conf->{samlServiceEncryptionKey}
3473 || "default-saml-enc" );
3474  
3475 if ( my $metadata = Lemonldap::NG::Common::Conf::SAML::Metadata->new() ) {
3476 my $portal =
3477 $req_or_undef
3478 ? $req_or_undef->portal
3479 : $self->p->HANDLER->tsv->{portal}->();
3480 return $metadata->serviceToXML(
3481 $self->conf,
3482 $type,
3483 portal => $portal,
3484 signing_keys => \@signing_keys,
3485 (
3486 @encryption_keys ? ( encryption_keys => \@encryption_keys ) : ()
3487 ),
3488 );
3489 }
3490 return;
3491 }
3492  
3493 sub _get_keys_from_config {
3494 my ( $self, $list_of_keys ) = @_;
3495 my @keys;
3496  
3497 if ($list_of_keys) {
3498 for my $key_id ( split( /\s*,\s*/, $list_of_keys ) ) {
3499 my $key = $self->get_public_key($key_id);
3500 if ($key) {
3501 push @keys, $key;
3502 }
3503 else {
3504 $self->logger->debug("Could not publish $key_id in metadata");
3505 }
3506 }
3507 }
3508 return @keys;
3509 }
3510  
3511 sub metadata {
3512 my ( $self, $req ) = @_;
3513 my $type = $req->param('type') || 'all';
3514 my $idp = $req->param('idp');
3515 my $sp = $req->param('sp');
3516 if ( my $metadata = $self->_get_metadata_xml( $req, $type, $sp, $idp ) ) {
3517 return $self->p->sendTextResponse( $req, $metadata,
3518 type => 'application/xml' );
3519 }
3520 return $self->p->sendError( $req, 'Unable to build Metadata', 500 );
3521 }
3522  
3523 ## @method int getSignatureMethod(string signature_method)
3524 # Return Lasso signature method
3525 # @param signature_method Signature method string
3526 # @return Lasso signature method
3527 sub getSignatureMethod {
3528 my ( $self, $signature_method ) = @_;
3529  
3530 $signature_method ||= $self->getDefaultSignatureMethod();
3531  
3532 if ( my $const =
3533 Lasso::Constants->can( "SIGNATURE_METHOD_" . uc($signature_method) ) )
3534 {
3535 return $const->();
3536 }
3537 else {
3538 return 0;
3539 }
3540 }
3541  
3542 sub getDefaultSignatureMethod {
3543 my ($self) = @_;
3544  
3545 my $signature_method =
3546 $self->conf->{samlServiceSignatureMethod} || 'RSA_SHA1';
3547 return $signature_method;
3548 }
3549  
3550 ## @method boolean setProviderSignatureMethod(Lasso::Provider provider, int signature_method)
3551 # Set signature method on a provider
3552 # @param provider Lasso::Provider object
3553 # @param signature_method Lasso signature method
3554 # @return result
3555 sub setProviderSignatureMethod {
3556 my ( $self, $provider, $signature_method ) = @_;
3557  
3558 my $key = $self->get_private_key( $self->_get_default_signing_key_name );
3559 return $self->setProviderSignatureOptions( $provider, $signature_method,
3560 $key );
3561 }
3562  
3563 sub setProviderSignatureOptions {
3564 my ( $self, $provider, $signature_method, $key ) = @_;
3565  
3566 # We have to use an intermediate variable to avoid interferences between
3567 # Lasso binding and tied hashes (#3105)
3568 my $priv = $key->{private};
3569 my $pass = $key->{password};
3570 my $cert = $key->{public};
3571  
3572 eval {
3573 my $key = Lasso::Key::new_for_signature_from_file( $priv, $pass,
3574 $signature_method, $cert, );
3575 $provider->set_server_signing_key($key);
3576 };
3577  
3578 return $self->checkLassoError($@);
3579 }
3580  
3581 sub _override_signature_or_key {
3582 my ( $self, $entityID, $log_description, $signature_method,
3583 $signature_key_list )
3584 = @_;
3585 if ( $signature_method or $signature_key_list ) {
3586 $signature_key_list //= "";
3587 my $signature_key = ( split( /\s*,\s*/, $signature_key_list ) )[0];
3588  
3589 $signature_method ||= $self->getDefaultSignatureMethod;
3590 my $lasso_signature_method =
3591 $self->getSignatureMethod($signature_method);
3592  
3593 $signature_key ||= $self->_get_default_signing_key_name;
3594 my $key = $self->get_private_key($signature_key);
3595  
3596 # Fallback to default key if custom key was not found
3597 if ( !$key ) {
3598 $signature_key = $self->_get_default_signing_key_name;
3599 $key = $self->get_private_key($signature_key);
3600 }
3601  
3602 $self->logger->debug( "Setting signature key $signature_key"
3603 . " and signature method $signature_method"
3604 . " on $log_description" );
3605  
3606 unless (
3607 $self->setProviderSignatureOptions(
3608 $self->lassoServer->get_provider($entityID),
3609 $lasso_signature_method, $key
3610 )
3611 )
3612 {
3613 $self->logger->error(
3614 "Unable to set signature options on $log_description");
3615 return;
3616 }
3617 }
3618 }
3619  
3620 # The default signing key is the first key listed in samlServiceSignatureKey, with
3621 # fallback to default-saml-sig
3622 sub _get_default_signing_key_name {
3623 my ($self) = @_;
3624 my @key_list =
3625 split( /\s*,\s*/, ( $self->conf->{samlServiceSignatureKey} || "" ) );
3626  
3627 return ( $key_list[0] || "default-saml-sig" );
3628 }
3629  
3630 # The default encryption key is the first key listed in samlServiceEncryptionKey, with
3631 # fallback to default-saml-enc
3632 sub _get_default_encryption_key_name {
3633 my ($self) = @_;
3634 my @key_list =
3635 split( /\s*,\s*/, ( $self->conf->{samlServiceEncryptionKey} || "" ) );
3636  
3637 return ( $key_list[0] || "default-saml-enc" );
3638 }
3639  
3640 1;
3641  
3642 __END__
« blib/lib/Lemonldap/NG/Portal/Auth/LDAP.pm ↑ Summary blib/lib/Lemonldap/NG/Portal/Plugins/OIDC/DynamicRegistration.pm »