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