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