Properly handle case where authentication fails and control is handed back to profile...
[java-idp.git] / src / main / java / edu / internet2 / middleware / shibboleth / idp / profile / saml2 / SSOProfileHandler.java
1 /*
2  * Copyright 2007 University Corporation for Advanced Internet Development, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package edu.internet2.middleware.shibboleth.idp.profile.saml2;
18
19 import java.io.IOException;
20 import java.io.StringReader;
21 import java.util.ArrayList;
22
23 import javax.servlet.ServletContext;
24 import javax.servlet.http.HttpServletRequest;
25 import javax.servlet.http.HttpServletResponse;
26
27 import org.joda.time.DateTime;
28 import org.joda.time.DateTimeZone;
29 import org.opensaml.Configuration;
30 import org.opensaml.common.SAMLObjectBuilder;
31 import org.opensaml.common.binding.decoding.SAMLMessageDecoder;
32 import org.opensaml.common.xml.SAMLConstants;
33 import org.opensaml.saml2.binding.AuthnResponseEndpointSelector;
34 import org.opensaml.saml2.core.AttributeStatement;
35 import org.opensaml.saml2.core.AuthnContext;
36 import org.opensaml.saml2.core.AuthnContextClassRef;
37 import org.opensaml.saml2.core.AuthnContextDeclRef;
38 import org.opensaml.saml2.core.AuthnRequest;
39 import org.opensaml.saml2.core.AuthnStatement;
40 import org.opensaml.saml2.core.NameID;
41 import org.opensaml.saml2.core.NameIDPolicy;
42 import org.opensaml.saml2.core.RequestedAuthnContext;
43 import org.opensaml.saml2.core.Response;
44 import org.opensaml.saml2.core.Statement;
45 import org.opensaml.saml2.core.StatusCode;
46 import org.opensaml.saml2.core.Subject;
47 import org.opensaml.saml2.core.SubjectLocality;
48 import org.opensaml.saml2.metadata.AffiliateMember;
49 import org.opensaml.saml2.metadata.AffiliationDescriptor;
50 import org.opensaml.saml2.metadata.AssertionConsumerService;
51 import org.opensaml.saml2.metadata.Endpoint;
52 import org.opensaml.saml2.metadata.EntityDescriptor;
53 import org.opensaml.saml2.metadata.IDPSSODescriptor;
54 import org.opensaml.saml2.metadata.SPSSODescriptor;
55 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
56 import org.opensaml.util.URLBuilder;
57 import org.opensaml.ws.message.decoder.MessageDecodingException;
58 import org.opensaml.ws.transport.http.HTTPInTransport;
59 import org.opensaml.ws.transport.http.HTTPOutTransport;
60 import org.opensaml.ws.transport.http.HttpServletRequestAdapter;
61 import org.opensaml.ws.transport.http.HttpServletResponseAdapter;
62 import org.opensaml.xml.io.MarshallingException;
63 import org.opensaml.xml.io.Unmarshaller;
64 import org.opensaml.xml.io.UnmarshallingException;
65 import org.opensaml.xml.security.SecurityException;
66 import org.opensaml.xml.util.DatatypeHelper;
67 import org.slf4j.Logger;
68 import org.slf4j.LoggerFactory;
69 import org.w3c.dom.Element;
70
71 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
72 import edu.internet2.middleware.shibboleth.common.profile.provider.BaseSAMLProfileRequestContext;
73 import edu.internet2.middleware.shibboleth.common.relyingparty.ProfileConfiguration;
74 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
75 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.SAMLMDRelyingPartyConfigurationManager;
76 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.SSOConfiguration;
77 import edu.internet2.middleware.shibboleth.common.util.HttpHelper;
78 import edu.internet2.middleware.shibboleth.idp.authn.PassiveAuthenticationException;
79 import edu.internet2.middleware.shibboleth.idp.authn.Saml2LoginContext;
80 import edu.internet2.middleware.shibboleth.idp.session.Session;
81 import edu.internet2.middleware.shibboleth.idp.util.HttpServletHelper;
82
83 /** SAML 2.0 SSO request profile handler. */
84 public class SSOProfileHandler extends AbstractSAML2ProfileHandler {
85
86     /** Class logger. */
87     private final Logger log = LoggerFactory.getLogger(SSOProfileHandler.class);
88
89     /** Builder of AuthnStatement objects. */
90     private SAMLObjectBuilder<AuthnStatement> authnStatementBuilder;
91
92     /** Builder of AuthnContext objects. */
93     private SAMLObjectBuilder<AuthnContext> authnContextBuilder;
94
95     /** Builder of AuthnContextClassRef objects. */
96     private SAMLObjectBuilder<AuthnContextClassRef> authnContextClassRefBuilder;
97
98     /** Builder of AuthnContextDeclRef objects. */
99     private SAMLObjectBuilder<AuthnContextDeclRef> authnContextDeclRefBuilder;
100
101     /** Builder of SubjectLocality objects. */
102     private SAMLObjectBuilder<SubjectLocality> subjectLocalityBuilder;
103
104     /** Builder of Endpoint objects. */
105     private SAMLObjectBuilder<Endpoint> endpointBuilder;
106
107     /** URL of the authentication manager Servlet. */
108     private String authenticationManagerPath;
109
110     /**
111      * Constructor.
112      * 
113      * @param authnManagerPath path to the authentication manager Servlet
114      */
115     @SuppressWarnings("unchecked")
116     public SSOProfileHandler(String authnManagerPath) {
117         super();
118
119         if (DatatypeHelper.isEmpty(authnManagerPath)) {
120             throw new IllegalArgumentException("Authentication manager path may not be null");
121         }
122         if (authnManagerPath.startsWith("/")) {
123             authenticationManagerPath = authnManagerPath;
124         } else {
125             authenticationManagerPath = "/" + authnManagerPath;
126         }
127
128         authnStatementBuilder = (SAMLObjectBuilder<AuthnStatement>) getBuilderFactory().getBuilder(
129                 AuthnStatement.DEFAULT_ELEMENT_NAME);
130         authnContextBuilder = (SAMLObjectBuilder<AuthnContext>) getBuilderFactory().getBuilder(
131                 AuthnContext.DEFAULT_ELEMENT_NAME);
132         authnContextClassRefBuilder = (SAMLObjectBuilder<AuthnContextClassRef>) getBuilderFactory().getBuilder(
133                 AuthnContextClassRef.DEFAULT_ELEMENT_NAME);
134         authnContextDeclRefBuilder = (SAMLObjectBuilder<AuthnContextDeclRef>) getBuilderFactory().getBuilder(
135                 AuthnContextDeclRef.DEFAULT_ELEMENT_NAME);
136         subjectLocalityBuilder = (SAMLObjectBuilder<SubjectLocality>) getBuilderFactory().getBuilder(
137                 SubjectLocality.DEFAULT_ELEMENT_NAME);
138         endpointBuilder = (SAMLObjectBuilder<Endpoint>) getBuilderFactory().getBuilder(
139                 AssertionConsumerService.DEFAULT_ELEMENT_NAME);
140     }
141
142     /** {@inheritDoc} */
143     public String getProfileId() {
144         return SSOConfiguration.PROFILE_ID;
145     }
146
147     /** {@inheritDoc} */
148     public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
149         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
150         HttpServletResponse httpResponse = ((HttpServletResponseAdapter) outTransport).getWrappedResponse();
151         ServletContext servletContext = httpRequest.getSession().getServletContext();
152
153         Saml2LoginContext loginContext = (Saml2LoginContext) HttpServletHelper.getLoginContext(getStorageService(),
154                 servletContext, httpRequest);
155         if (loginContext == null) {
156             log.debug("Incoming request does not contain a login context, processing as first leg of request");
157             performAuthentication(inTransport, outTransport);
158         }else if(loginContext.isPrincipalAuthenticated() || loginContext.getAuthenticationFailure() != null){
159             log.debug("Incoming request contains a login context, processing as second leg of request");
160             HttpServletHelper.unbindLoginContext(getStorageService(), servletContext, httpRequest, httpResponse);
161             completeAuthenticationRequest(loginContext, inTransport, outTransport);
162         }else {
163             log.debug("Incoming request contained a login context but principal was not authenticated, processing as first leg of request");
164             performAuthentication(inTransport, outTransport);            
165         }
166     }
167
168     /**
169      * Creates a {@link Saml2LoginContext} an sends the request off to the AuthenticationManager to begin the process of
170      * authenticating the user.
171      * 
172      * @param inTransport inbound request transport
173      * @param outTransport outbound response transport
174      * 
175      * @throws ProfileException thrown if there is a problem creating the login context and transferring control to the
176      *             authentication manager
177      */
178     protected void performAuthentication(HTTPInTransport inTransport, HTTPOutTransport outTransport)
179             throws ProfileException {
180         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
181         HttpServletResponse httpResponse = ((HttpServletResponseAdapter) outTransport).getWrappedResponse();
182
183         SSORequestContext requestContext = new SSORequestContext();
184
185         try {
186             decodeRequest(requestContext, inTransport, outTransport);
187
188             String relyingPartyId = requestContext.getInboundMessageIssuer();
189             RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
190             ProfileConfiguration ssoConfig = rpConfig.getProfileConfiguration(getProfileId());
191             if (ssoConfig == null) {
192                 String msg = "SAML 2 SSO profile is not configured for relying party "
193                         + requestContext.getInboundMessageIssuer();
194                 log.warn(msg);
195                 throw new ProfileException(msg);
196             }
197
198             log.debug("Creating login context and transferring control to authentication engine");
199             Saml2LoginContext loginContext = new Saml2LoginContext(relyingPartyId, requestContext.getRelayState(),
200                     requestContext.getInboundSAMLMessage());
201             loginContext.setAuthenticationEngineURL(authenticationManagerPath);
202             loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(httpRequest));
203             loginContext.setDefaultAuthenticationMethod(rpConfig.getDefaultAuthenticationMethod());
204
205             HttpServletHelper.bindLoginContext(loginContext, getStorageService(), httpRequest.getSession()
206                     .getServletContext(), httpRequest, httpResponse);
207
208             URLBuilder urlBuilder = HttpServletHelper.getServletContextUrl(httpRequest);
209             urlBuilder.setPath(urlBuilder.getPath() + authenticationManagerPath);
210             String authnEngineUrl = urlBuilder.buildURL();
211             log.debug("Redirecting user to authentication engine at {}", authnEngineUrl);
212             httpResponse.sendRedirect(authnEngineUrl);
213         } catch (MarshallingException e) {
214             log.error("Unable to marshall authentication request context");
215             throw new ProfileException("Unable to marshall authentication request context", e);
216         } catch (IOException ex) {
217             log.error("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
218             throw new ProfileException("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
219         }
220     }
221
222     /**
223      * Creates a response to the {@link AuthnRequest} and sends the user, with response in tow, back to the relying
224      * party after they've been authenticated.
225      * 
226      * @param loginContext login context for this request
227      * @param inTransport inbound message transport
228      * @param outTransport outbound message transport
229      * 
230      * @throws ProfileException thrown if the response can not be created and sent back to the relying party
231      */
232     protected void completeAuthenticationRequest(Saml2LoginContext loginContext, HTTPInTransport inTransport,
233             HTTPOutTransport outTransport) throws ProfileException {
234         SSORequestContext requestContext = buildRequestContext(loginContext, inTransport, outTransport);
235
236         Response samlResponse;
237         try {
238             checkSamlVersion(requestContext);
239             checkNameIDPolicy(requestContext);
240
241             if (loginContext.getAuthenticationFailure() != null) {
242                 if (loginContext.getAuthenticationFailure() instanceof PassiveAuthenticationException) {
243                     requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.NO_PASSIVE_URI,
244                             null));
245                 } else {
246                     requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.AUTHN_FAILED_URI,
247                             null));
248                 }
249                 throw new ProfileException("Authentication failure", loginContext.getAuthenticationFailure());
250             }
251
252             if (requestContext.getSubjectNameIdentifier() != null) {
253                 log
254                         .debug("Authentication request contained a subject with a name identifier, resolving principal from NameID");
255                 resolvePrincipal(requestContext);
256                 String requestedPrincipalName = requestContext.getPrincipalName();
257                 if (!DatatypeHelper.safeEquals(loginContext.getPrincipalName(), requestedPrincipalName)) {
258                     log
259                             .warn(
260                                     "Authentication request identified principal {} but authentication mechanism identified principal {}",
261                                     requestedPrincipalName, loginContext.getPrincipalName());
262                     requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.AUTHN_FAILED_URI,
263                             null));
264                     throw new ProfileException("User failed authentication");
265                 }
266             }
267
268             resolveAttributes(requestContext);
269
270             ArrayList<Statement> statements = new ArrayList<Statement>();
271             statements.add(buildAuthnStatement(requestContext));
272             if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
273                 AttributeStatement attributeStatement = buildAttributeStatement(requestContext);
274                 if (attributeStatement != null) {
275                     requestContext.setReleasedAttributes(requestContext.getAttributes().keySet());
276                     statements.add(attributeStatement);
277                 }
278             }
279
280             samlResponse = buildResponse(requestContext, "urn:oasis:names:tc:SAML:2.0:cm:bearer", statements);
281         } catch (ProfileException e) {
282             samlResponse = buildErrorResponse(requestContext);
283         }
284
285         requestContext.setOutboundSAMLMessage(samlResponse);
286         requestContext.setOutboundSAMLMessageId(samlResponse.getID());
287         requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
288         encodeResponse(requestContext);
289         writeAuditLogEntry(requestContext);
290     }
291
292     /**
293      * Decodes an incoming request and stores the information in a created request context.
294      * 
295      * @param inTransport inbound transport
296      * @param outTransport outbound transport
297      * @param requestContext request context to which decoded information should be added
298      * 
299      * @throws ProfileException thrown if the incoming message failed decoding
300      */
301     protected void decodeRequest(SSORequestContext requestContext, HTTPInTransport inTransport,
302             HTTPOutTransport outTransport) throws ProfileException {
303         if (log.isDebugEnabled()) {
304             log.debug("Decoding message with decoder binding '{}'", getInboundMessageDecoder(requestContext)
305                     .getBindingURI());
306         }
307
308         requestContext.setCommunicationProfileId(getProfileId());
309
310         requestContext.setMetadataProvider(getMetadataProvider());
311         requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
312
313         requestContext.setCommunicationProfileId(getProfileId());
314         requestContext.setInboundMessageTransport(inTransport);
315         requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
316         requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
317
318         requestContext.setOutboundMessageTransport(outTransport);
319         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
320
321         try {
322             SAMLMessageDecoder decoder = getInboundMessageDecoder(requestContext);
323             requestContext.setMessageDecoder(decoder);
324             decoder.decode(requestContext);
325             log.debug("Decoded request from relying party '{}'", requestContext.getInboundMessageIssuer());
326
327             if (!(requestContext.getInboundSAMLMessage() instanceof AuthnRequest)) {
328                 log.warn("Incomming message was not a AuthnRequest, it was a '{}'", requestContext
329                         .getInboundSAMLMessage().getClass().getName());
330                 requestContext.setFailureStatus(buildStatus(StatusCode.REQUESTER_URI, null,
331                         "Invalid SAML AuthnRequest message."));
332                 throw new ProfileException("Invalid SAML AuthnRequest message.");
333             }
334         } catch (MessageDecodingException e) {
335             String msg = "Error decoding authentication request message";
336             log.warn(msg, e);
337             throw new ProfileException(msg, e);
338         } catch (SecurityException e) {
339             String msg = "Message did not meet security requirements";
340             log.warn(msg, e);
341             throw new ProfileException(msg, e);
342         }
343     }
344
345     /**
346      * Checks to see, if present, if the affiliation associated with the SPNameQualifier given in the AuthnRequest
347      * NameIDPolicy lists the inbound message issuer as a member.
348      * 
349      * @param requestContext current request context
350      * 
351      * @throws ProfileException thrown if there the request is not a member of the affiliation or if there was a problem
352      *             determining membership
353      */
354     protected void checkNameIDPolicy(SSORequestContext requestContext) throws ProfileException {
355         AuthnRequest request = requestContext.getInboundSAMLMessage();
356
357         NameIDPolicy nameIdPolcy = request.getNameIDPolicy();
358         if (nameIdPolcy == null) {
359             return;
360         }
361
362         String spNameQualifier = DatatypeHelper.safeTrimOrNullString(nameIdPolcy.getSPNameQualifier());
363         if (spNameQualifier == null) {
364             return;
365         }
366
367         log.debug("Checking if message issuer is a member of affiliation '{}'", spNameQualifier);
368         try {
369             EntityDescriptor affiliation = getMetadataProvider().getEntityDescriptor(spNameQualifier);
370             if (affiliation != null) {
371                 AffiliationDescriptor affiliationDescriptor = affiliation.getAffiliationDescriptor();
372                 if (affiliationDescriptor != null && affiliationDescriptor.getMembers() != null) {
373                     for (AffiliateMember member : affiliationDescriptor.getMembers()) {
374                         if (DatatypeHelper.safeEquals(member.getID(), requestContext.getInboundMessageIssuer())) {
375                             return;
376                         }
377                     }
378                 }
379             }
380
381             requestContext.setFailureStatus(buildStatus(StatusCode.REQUESTER_URI, StatusCode.INVALID_NAMEID_POLICY_URI,
382                     "Invalid SPNameQualifier for this request"));
383             throw new ProfileException("Relying party '" + requestContext.getInboundMessageIssuer()
384                     + "' is not a member of the affiliation " + spNameQualifier);
385         } catch (MetadataProviderException e) {
386             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Internal service error"));
387             log.error("Error looking up metadata for affiliation", e);
388             throw new ProfileException("Relying party '" + requestContext.getInboundMessageIssuer()
389                     + "' is not a member of the affiliation " + spNameQualifier);
390         }
391     }
392
393     /**
394      * Creates an authentication request context from the current environmental information.
395      * 
396      * @param loginContext current login context
397      * @param in inbound transport
398      * @param out outbount transport
399      * 
400      * @return created authentication request context
401      * 
402      * @throws ProfileException thrown if there is a problem creating the context
403      */
404     protected SSORequestContext buildRequestContext(Saml2LoginContext loginContext, HTTPInTransport in,
405             HTTPOutTransport out) throws ProfileException {
406         SSORequestContext requestContext = new SSORequestContext();
407         requestContext.setCommunicationProfileId(getProfileId());
408
409         requestContext.setMessageDecoder(getInboundMessageDecoder(requestContext));
410
411         requestContext.setLoginContext(loginContext);
412
413         requestContext.setInboundMessageTransport(in);
414         requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
415
416         requestContext.setOutboundMessageTransport(out);
417         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
418
419         requestContext.setMetadataProvider(getMetadataProvider());
420
421         String relyingPartyId = loginContext.getRelyingPartyId();
422         requestContext.setPeerEntityId(relyingPartyId);
423         requestContext.setInboundMessageIssuer(relyingPartyId);
424
425         populateRequestContext(requestContext);
426
427         return requestContext;
428     }
429
430     /** {@inheritDoc} */
431     protected void populateRelyingPartyInformation(BaseSAMLProfileRequestContext requestContext)
432             throws ProfileException {
433         super.populateRelyingPartyInformation(requestContext);
434
435         EntityDescriptor relyingPartyMetadata = requestContext.getPeerEntityMetadata();
436         if (relyingPartyMetadata != null) {
437             requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
438             requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata.getSPSSODescriptor(SAMLConstants.SAML20P_NS));
439         }
440     }
441
442     /** {@inheritDoc} */
443     protected void populateAssertingPartyInformation(BaseSAMLProfileRequestContext requestContext)
444             throws ProfileException {
445         super.populateAssertingPartyInformation(requestContext);
446
447         EntityDescriptor localEntityDescriptor = requestContext.getLocalEntityMetadata();
448         if (localEntityDescriptor != null) {
449             requestContext.setLocalEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
450             requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
451                     .getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
452         }
453     }
454
455     /**
456      * Populates the request context with information from the inbound SAML message.
457      * 
458      * This method requires the the following request context properties to be populated: login context
459      * 
460      * This methods populates the following request context properties: inbound saml message, relay state, inbound saml
461      * message ID, subject name identifier
462      * 
463      * @param requestContext current request context
464      * 
465      * @throws ProfileException thrown if the inbound SAML message or subject identifier is null
466      */
467     protected void populateSAMLMessageInformation(BaseSAMLProfileRequestContext requestContext) throws ProfileException {
468         SSORequestContext ssoRequestContext = (SSORequestContext) requestContext;
469         try {
470             Saml2LoginContext loginContext = ssoRequestContext.getLoginContext();
471             requestContext.setRelayState(loginContext.getRelayState());
472
473             AuthnRequest authnRequest = deserializeRequest(loginContext.getAuthenticationRequest());
474             requestContext.setInboundMessage(authnRequest);
475             requestContext.setInboundSAMLMessage(authnRequest);
476             requestContext.setInboundSAMLMessageId(authnRequest.getID());
477
478             Subject authnSubject = authnRequest.getSubject();
479             if (authnSubject != null) {
480                 requestContext.setSubjectNameIdentifier(authnSubject.getNameID());
481             }
482         } catch (UnmarshallingException e) {
483             log.error("Unable to unmarshall authentication request context");
484             ssoRequestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
485                     "Error recovering request state"));
486             throw new ProfileException("Error recovering request state", e);
487         }
488     }
489
490     /**
491      * Creates an authentication statement for the current request.
492      * 
493      * @param requestContext current request context
494      * 
495      * @return constructed authentication statement
496      */
497     protected AuthnStatement buildAuthnStatement(SSORequestContext requestContext) {
498         Saml2LoginContext loginContext = requestContext.getLoginContext();
499
500         AuthnContext authnContext = buildAuthnContext(requestContext);
501
502         AuthnStatement statement = authnStatementBuilder.buildObject();
503         statement.setAuthnContext(authnContext);
504         statement.setAuthnInstant(loginContext.getAuthenticationInstant());
505
506         Session session = getUserSession(requestContext.getInboundMessageTransport());
507         if (session != null) {
508             statement.setSessionIndex(session.getSessionID());
509         }
510
511         long maxSPSessionLifetime = requestContext.getProfileConfiguration().getMaximumSPSessionLifetime();
512         if (maxSPSessionLifetime > 0) {
513             DateTime lifetime = new DateTime(DateTimeZone.UTC).plus(maxSPSessionLifetime);
514             log.debug("Explicitly setting SP session expiration time to '{}'", lifetime.toString());
515             statement.setSessionNotOnOrAfter(lifetime);
516         }
517
518         statement.setSubjectLocality(buildSubjectLocality(requestContext));
519
520         return statement;
521     }
522
523     /**
524      * Creates an {@link AuthnContext} for a successful authentication request.
525      * 
526      * @param requestContext current request
527      * 
528      * @return the built authn context
529      */
530     protected AuthnContext buildAuthnContext(SSORequestContext requestContext) {
531         AuthnContext authnContext = authnContextBuilder.buildObject();
532
533         Saml2LoginContext loginContext = requestContext.getLoginContext();
534         AuthnRequest authnRequest = requestContext.getInboundSAMLMessage();
535         RequestedAuthnContext requestedAuthnContext = authnRequest.getRequestedAuthnContext();
536         if (requestedAuthnContext != null) {
537             if (requestedAuthnContext.getAuthnContextClassRefs() != null) {
538                 for (AuthnContextClassRef classRef : requestedAuthnContext.getAuthnContextClassRefs()) {
539                     if (classRef.getAuthnContextClassRef().equals(loginContext.getAuthenticationMethod())) {
540                         AuthnContextClassRef ref = authnContextClassRefBuilder.buildObject();
541                         ref.setAuthnContextClassRef(loginContext.getAuthenticationMethod());
542                         authnContext.setAuthnContextClassRef(ref);
543                     }
544                 }
545             } else if (requestedAuthnContext.getAuthnContextDeclRefs() != null) {
546                 for (AuthnContextDeclRef declRef : requestedAuthnContext.getAuthnContextDeclRefs()) {
547                     if (declRef.getAuthnContextDeclRef().equals(loginContext.getAuthenticationMethod())) {
548                         AuthnContextDeclRef ref = authnContextDeclRefBuilder.buildObject();
549                         ref.setAuthnContextDeclRef(loginContext.getAuthenticationMethod());
550                         authnContext.setAuthnContextDeclRef(ref);
551                     }
552                 }
553             }
554         }
555
556         if (authnContext.getAuthnContextClassRef() == null || authnContext.getAuthnContextDeclRef() == null) {
557             AuthnContextClassRef ref = authnContextClassRefBuilder.buildObject();
558             ref.setAuthnContextClassRef(loginContext.getAuthenticationMethod());
559             authnContext.setAuthnContextClassRef(ref);
560         }
561
562         return authnContext;
563     }
564
565     /**
566      * Constructs the subject locality for the authentication statement.
567      * 
568      * @param requestContext curent request context
569      * 
570      * @return subject locality for the authentication statement
571      */
572     protected SubjectLocality buildSubjectLocality(SSORequestContext requestContext) {
573         HTTPInTransport transport = (HTTPInTransport) requestContext.getInboundMessageTransport();
574         SubjectLocality subjectLocality = subjectLocalityBuilder.buildObject();
575         subjectLocality.setAddress(transport.getPeerAddress());
576
577         return subjectLocality;
578     }
579
580     /** {@inheritDoc} */
581     protected String getRequiredNameIDFormat(BaseSAMLProfileRequestContext requestContext) {
582         String requiredNameFormat = null;
583         AuthnRequest authnRequest = (AuthnRequest) requestContext.getInboundSAMLMessage();
584         NameIDPolicy nameIdPolicy = authnRequest.getNameIDPolicy();
585         if (nameIdPolicy != null) {
586             requiredNameFormat = DatatypeHelper.safeTrimOrNullString(nameIdPolicy.getFormat());
587             // Check for unspec'd or encryption formats, which aren't relevant for this section of code.
588             if (requiredNameFormat != null
589                     && (NameID.ENCRYPTED.equals(requiredNameFormat) || NameID.UNSPECIFIED.equals(requiredNameFormat))) {
590                 requiredNameFormat = null;
591             }
592         }
593
594         return requiredNameFormat;
595     }
596
597     /** {@inheritDoc} */
598     protected NameID buildNameId(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
599         NameID nameId = super.buildNameId(requestContext);
600         if (nameId != null) {
601             AuthnRequest authnRequest = (AuthnRequest) requestContext.getInboundSAMLMessage();
602             NameIDPolicy nameIdPolicy = authnRequest.getNameIDPolicy();
603             if (nameIdPolicy != null) {
604                 String spNameQualifier = DatatypeHelper.safeTrimOrNullString(nameIdPolicy.getSPNameQualifier());
605                 if (spNameQualifier != null) {
606                     nameId.setSPNameQualifier(spNameQualifier);
607                 } else {
608                     nameId.setSPNameQualifier(requestContext.getInboundMessageIssuer());
609                 }
610             }
611         }
612
613         return nameId;
614     }
615
616     /**
617      * Selects the appropriate endpoint for the relying party and stores it in the request context.
618      * 
619      * @param requestContext current request context
620      * 
621      * @return Endpoint selected from the information provided in the request context
622      */
623     protected Endpoint selectEndpoint(BaseSAMLProfileRequestContext requestContext) {
624         AuthnRequest authnRequest = ((SSORequestContext) requestContext).getInboundSAMLMessage();
625
626         Endpoint endpoint = null;
627         if (requestContext.getRelyingPartyConfiguration().getRelyingPartyId() == SAMLMDRelyingPartyConfigurationManager.ANONYMOUS_RP_NAME) {
628             if (authnRequest.getAssertionConsumerServiceURL() != null) {
629                 endpoint = endpointBuilder.buildObject();
630                 endpoint.setLocation(authnRequest.getAssertionConsumerServiceURL());
631                 if (authnRequest.getProtocolBinding() != null) {
632                     endpoint.setBinding(authnRequest.getProtocolBinding());
633                 } else {
634                     endpoint.setBinding(getSupportedOutboundBindings().get(0));
635                 }
636                 log
637                         .warn(
638                                 "Generating endpoint for anonymous relying party self-identified as '{}', ACS url '{}' and binding '{}'",
639                                 new Object[] { requestContext.getInboundMessageIssuer(), endpoint.getLocation(),
640                                         endpoint.getBinding(), });
641             } else {
642                 log.warn("Unable to generate endpoint for anonymous party.  No ACS url provided.");
643             }
644         } else {
645             AuthnResponseEndpointSelector endpointSelector = new AuthnResponseEndpointSelector();
646             endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
647             endpointSelector.setMetadataProvider(getMetadataProvider());
648             endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
649             endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
650             endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
651             endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
652             endpoint = endpointSelector.selectEndpoint();
653         }
654
655         return endpoint;
656     }
657
658     /**
659      * Deserailizes an authentication request from a string.
660      * 
661      * @param request request to deserialize
662      * 
663      * @return the request XMLObject
664      * 
665      * @throws UnmarshallingException thrown if the request can no be deserialized and unmarshalled
666      */
667     protected AuthnRequest deserializeRequest(String request) throws UnmarshallingException {
668         try {
669             Element requestElem = getParserPool().parse(new StringReader(request)).getDocumentElement();
670             Unmarshaller unmarshaller = Configuration.getUnmarshallerFactory().getUnmarshaller(requestElem);
671             return (AuthnRequest) unmarshaller.unmarshall(requestElem);
672         } catch (Exception e) {
673             throw new UnmarshallingException("Unable to read serialized authentication request");
674         }
675     }
676
677     /** Represents the internal state of a SAML 2.0 SSO Request while it's being processed by the IdP. */
678     protected class SSORequestContext extends BaseSAML2ProfileRequestContext<AuthnRequest, Response, SSOConfiguration> {
679
680         /** Current login context. */
681         private Saml2LoginContext loginContext;
682
683         /**
684          * Gets the current login context.
685          * 
686          * @return current login context
687          */
688         public Saml2LoginContext getLoginContext() {
689             return loginContext;
690         }
691
692         /**
693          * Sets the current login context.
694          * 
695          * @param context current login context
696          */
697         public void setLoginContext(Saml2LoginContext context) {
698             loginContext = context;
699         }
700     }
701 }