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