083df26d72d78863dd5745cc5d73973bb589d4cc
[java-idp.git] / src / 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.util.ArrayList;
21
22 import javax.servlet.RequestDispatcher;
23 import javax.servlet.ServletException;
24 import javax.servlet.http.HttpServletRequest;
25 import javax.servlet.http.HttpSession;
26
27 import org.opensaml.common.SAMLObjectBuilder;
28 import org.opensaml.common.binding.decoding.SAMLMessageDecoder;
29 import org.opensaml.common.xml.SAMLConstants;
30 import org.opensaml.saml2.binding.AuthnResponseEndpointSelector;
31 import org.opensaml.saml2.core.AuthnContext;
32 import org.opensaml.saml2.core.AuthnContextClassRef;
33 import org.opensaml.saml2.core.AuthnContextDeclRef;
34 import org.opensaml.saml2.core.AuthnRequest;
35 import org.opensaml.saml2.core.AuthnStatement;
36 import org.opensaml.saml2.core.RequestedAuthnContext;
37 import org.opensaml.saml2.core.Response;
38 import org.opensaml.saml2.core.Statement;
39 import org.opensaml.saml2.core.StatusCode;
40 import org.opensaml.saml2.core.SubjectLocality;
41 import org.opensaml.saml2.metadata.AssertionConsumerService;
42 import org.opensaml.saml2.metadata.Endpoint;
43 import org.opensaml.saml2.metadata.EntityDescriptor;
44 import org.opensaml.saml2.metadata.IDPSSODescriptor;
45 import org.opensaml.saml2.metadata.SPSSODescriptor;
46 import org.opensaml.saml2.metadata.provider.MetadataProvider;
47 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
48 import org.opensaml.ws.message.decoder.MessageDecodingException;
49 import org.opensaml.ws.transport.http.HTTPInTransport;
50 import org.opensaml.ws.transport.http.HTTPOutTransport;
51 import org.opensaml.ws.transport.http.HttpServletRequestAdapter;
52 import org.opensaml.ws.transport.http.HttpServletResponseAdapter;
53 import org.opensaml.xml.io.MarshallingException;
54 import org.opensaml.xml.io.UnmarshallingException;
55 import org.opensaml.xml.security.SecurityException;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
60 import edu.internet2.middleware.shibboleth.common.relyingparty.ProfileConfiguration;
61 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
62 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.SSOConfiguration;
63 import edu.internet2.middleware.shibboleth.common.util.HttpHelper;
64 import edu.internet2.middleware.shibboleth.idp.authn.LoginContext;
65 import edu.internet2.middleware.shibboleth.idp.authn.Saml2LoginContext;
66
67 /** SAML 2.0 SSO request profile handler. */
68 public class SSOProfileHandler extends AbstractSAML2ProfileHandler {
69
70     /** Class logger. */
71     private final Logger log = LoggerFactory.getLogger(SSOProfileHandler.class);
72
73     /** Builder of AuthnStatement objects. */
74     private SAMLObjectBuilder<AuthnStatement> authnStatementBuilder;
75
76     /** Builder of AuthnContext objects. */
77     private SAMLObjectBuilder<AuthnContext> authnContextBuilder;
78
79     /** Builder of AuthnContextClassRef objects. */
80     private SAMLObjectBuilder<AuthnContextClassRef> authnContextClassRefBuilder;
81
82     /** Builder of AuthnContextDeclRef objects. */
83     private SAMLObjectBuilder<AuthnContextDeclRef> authnContextDeclRefBuilder;
84
85     /** Builder of SubjectLocality objects. */
86     private SAMLObjectBuilder<SubjectLocality> subjectLocalityBuilder;
87
88     /** URL of the authentication manager servlet. */
89     private String authenticationManagerPath;
90
91     /** URI of request decoder. */
92     private String decodingBinding;
93
94     /**
95      * Constructor.
96      * 
97      * @param authnManagerPath path to the authentication manager servlet
98      */
99     @SuppressWarnings("unchecked")
100     public SSOProfileHandler(String authnManagerPath) {
101         super();
102
103         authenticationManagerPath = authnManagerPath;
104
105         authnStatementBuilder = (SAMLObjectBuilder<AuthnStatement>) getBuilderFactory().getBuilder(
106                 AuthnStatement.DEFAULT_ELEMENT_NAME);
107         authnContextBuilder = (SAMLObjectBuilder<AuthnContext>) getBuilderFactory().getBuilder(
108                 AuthnContext.DEFAULT_ELEMENT_NAME);
109         authnContextClassRefBuilder = (SAMLObjectBuilder<AuthnContextClassRef>) getBuilderFactory().getBuilder(
110                 AuthnContextClassRef.DEFAULT_ELEMENT_NAME);
111         authnContextDeclRefBuilder = (SAMLObjectBuilder<AuthnContextDeclRef>) getBuilderFactory().getBuilder(
112                 AuthnContextDeclRef.DEFAULT_ELEMENT_NAME);
113         subjectLocalityBuilder = (SAMLObjectBuilder<SubjectLocality>) getBuilderFactory().getBuilder(
114                 SubjectLocality.DEFAULT_ELEMENT_NAME);
115     }
116
117     /** {@inheritDoc} */
118     public String getProfileId() {
119         return "urn:mace:shibboleth:2.0:idp:profiles:saml2:request:sso";
120     }
121
122     /** {@inheritDoc} */
123     public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
124         HttpServletRequest servletRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
125         HttpSession httpSession = servletRequest.getSession(true);
126
127         if (httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY) == null) {
128             performAuthentication(inTransport, outTransport);
129         } else {
130             completeAuthenticationRequest(inTransport, outTransport);
131         }
132     }
133
134     /**
135      * Creates a {@link Saml2LoginContext} an sends the request off to the AuthenticationManager to begin the process of
136      * authenticating the user.
137      * 
138      * @param inTransport inbound request transport
139      * @param outTransport outbound response transport
140      * 
141      * @throws ProfileException thrown if there is a problem creating the login context and transferring control to the
142      *             authentication manager
143      */
144     protected void performAuthentication(HTTPInTransport inTransport, HTTPOutTransport outTransport)
145             throws ProfileException {
146         HttpServletRequest servletRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
147
148         try {
149             SSORequestContext requestContext = decodeRequest(inTransport, outTransport);
150
151             String relyingPartyId = requestContext.getInboundMessageIssuer();
152             RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
153             ProfileConfiguration ssoConfig = rpConfig.getProfileConfiguration(SSOConfiguration.PROFILE_ID);
154             if (ssoConfig == null) {
155                 log.error("SAML 2 SSO profile is not configured for relying party "
156                         + requestContext.getInboundMessageIssuer());
157                 throw new ProfileException("SAML 2 SSO profile is not configured for relying party "
158                         + requestContext.getInboundMessageIssuer());
159             }
160
161             log.debug("Creating login context and transferring control to authentication engine");
162             Saml2LoginContext loginContext = new Saml2LoginContext(relyingPartyId, requestContext.getRelayState(),
163                     requestContext.getInboundSAMLMessage());
164             loginContext.setAuthenticationEngineURL(authenticationManagerPath);
165             loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(servletRequest));
166             if (loginContext.getRequestedAuthenticationMethods().size() == 0) {
167                 loginContext.getRequestedAuthenticationMethods().add(rpConfig.getDefaultAuthenticationMethod());
168             }
169
170             HttpSession httpSession = servletRequest.getSession();
171             httpSession.setAttribute(Saml2LoginContext.LOGIN_CONTEXT_KEY, loginContext);
172             RequestDispatcher dispatcher = servletRequest.getRequestDispatcher(authenticationManagerPath);
173             dispatcher.forward(servletRequest, ((HttpServletResponseAdapter) outTransport).getWrappedResponse());
174         } catch (MarshallingException e) {
175             log.error("Unable to marshall authentication request context");
176             throw new ProfileException("Unable to marshall authentication request context", e);
177         } catch (IOException ex) {
178             log.error("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
179             throw new ProfileException("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
180         } catch (ServletException ex) {
181             log.error("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
182             throw new ProfileException("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
183         }
184     }
185
186     /**
187      * Creates a response to the {@link AuthnRequest} and sends the user, with response in tow, back to the relying
188      * party after they've been authenticated.
189      * 
190      * @param inTransport inbound message transport
191      * @param outTransport outbound message transport
192      * 
193      * @throws ProfileException thrown if the response can not be created and sent back to the relying party
194      */
195     protected void completeAuthenticationRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
196             throws ProfileException {
197         HttpServletRequest servletRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
198         HttpSession httpSession = servletRequest.getSession();
199
200         Saml2LoginContext loginContext = (Saml2LoginContext) httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
201         httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
202
203         SSORequestContext requestContext = buildRequestContext(loginContext, inTransport, outTransport);
204
205         checkSamlVersion(requestContext);
206
207         Response samlResponse;
208         try {
209             if (loginContext.getPrincipalName() == null) {
210                 log.error("User's login context did not contain a principal, user considered unauthenticiated.");
211                 requestContext
212                         .setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.AUTHN_FAILED_URI, null));
213                 throw new ProfileException("User failed authentication");
214             }
215
216             resolveAttributes(requestContext);
217
218             ArrayList<Statement> statements = new ArrayList<Statement>();
219             statements.add(buildAuthnStatement(requestContext));
220             if (requestContext.getProfileConfiguration().includeAttributeStatement()
221                     && !requestContext.getPrincipalAttributes().isEmpty()) {
222                 requestContext.setRequestedAttributes(requestContext.getPrincipalAttributes().keySet());
223                 statements.add(buildAttributeStatement(requestContext));
224             }
225
226             samlResponse = buildResponse(requestContext, "urn:oasis:names:tc:SAML:2.0:cm:bearer", statements);
227         } catch (ProfileException e) {
228             samlResponse = buildErrorResponse(requestContext);
229         }
230
231         requestContext.setOutboundSAMLMessage(samlResponse);
232         requestContext.setOutboundSAMLMessageId(samlResponse.getID());
233         requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
234         encodeResponse(requestContext);
235         writeAuditLogEntry(requestContext);
236     }
237
238     /**
239      * Decodes an incoming request and stores the information in a created request context.
240      * 
241      * @param inTransport inbound transport
242      * @param outTransport outbound transport
243      * 
244      * @return request context with decoded information
245      * 
246      * @throws ProfileException thrown if the incomming message failed decoding
247      */
248     protected SSORequestContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
249             throws ProfileException {
250         log.debug("Decoding message with decoder binding {}", decodingBinding);
251
252         SSORequestContext requestContext = new SSORequestContext();
253         requestContext.setMetadataProvider(getMetadataProvider());
254         requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
255
256         requestContext.setCommunicationProfileId(SSOConfiguration.PROFILE_ID);
257         requestContext.setInboundMessageTransport(inTransport);
258         requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
259         requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
260
261         requestContext.setOutboundMessageTransport(outTransport);
262         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
263
264         try {
265             SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
266             requestContext.setMessageDecoder(decoder);
267             decoder.decode(requestContext);
268             return requestContext;
269         } catch (MessageDecodingException e) {
270             log.error("Error decoding authentication request message", e);
271             throw new ProfileException("Error decoding authentication request message", e);
272         } catch (SecurityException e) {
273             log.error("Message did not meet security requirements", e);
274             throw new ProfileException("Message did not meet security requirements", e);
275         }
276     }
277
278     /**
279      * Creates an authentication request context from the current environmental information.
280      * 
281      * @param loginContext current login context
282      * @param in inbound transport
283      * @param out outbount transport
284      * 
285      * @return created authentication request context
286      * 
287      * @throws ProfileException thrown if there is a problem creating the context
288      */
289     protected SSORequestContext buildRequestContext(Saml2LoginContext loginContext, HTTPInTransport in,
290             HTTPOutTransport out) throws ProfileException {
291         SSORequestContext requestContext = new SSORequestContext();
292
293         requestContext.setMessageDecoder(getMessageDecoders().get(getInboundBinding()));
294
295         requestContext.setLoginContext(loginContext);
296         requestContext.setPrincipalName(loginContext.getPrincipalName());
297         requestContext.setPrincipalAuthenticationMethod(loginContext.getAuthenticationMethod());
298         requestContext.setUserSession(getUserSession(in));
299         requestContext.setRelayState(loginContext.getRelayState());
300
301         requestContext.setInboundMessageTransport(in);
302         requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
303
304         try {
305             requestContext.setInboundMessage(loginContext.getAuthenticationRequest());
306             requestContext.setInboundSAMLMessage(loginContext.getAuthenticationRequest());
307             requestContext.setInboundSAMLMessageId(loginContext.getAuthenticationRequest().getID());
308         } catch (UnmarshallingException e) {
309             log.error("Unable to unmarshall authentication request context");
310             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
311                     "Error recovering request state"));
312             throw new ProfileException("Error recovering request state", e);
313         }
314
315         requestContext.setOutboundMessageTransport(out);
316         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
317
318         MetadataProvider metadataProvider = getMetadataProvider();
319         requestContext.setMetadataProvider(metadataProvider);
320
321         String relyingPartyId = loginContext.getRelyingPartyId();
322         requestContext.setInboundMessageIssuer(relyingPartyId);
323         try {
324             EntityDescriptor relyingPartyMetadata = metadataProvider.getEntityDescriptor(relyingPartyId);
325             if (relyingPartyMetadata != null) {
326                 requestContext.setPeerEntityMetadata(relyingPartyMetadata);
327                 requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
328                 requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata
329                         .getSPSSODescriptor(SAMLConstants.SAML20P_NS));
330             }
331         } catch (MetadataProviderException e) {
332             log.error("Unable to locate metadata for relying party");
333             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
334                     "Error locating relying party metadata"));
335             throw new ProfileException("Error locating relying party metadata");
336         }
337
338         RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
339         if (rpConfig == null) {
340             log.error("Unable to retrieve relying party configuration data for entity with ID {}", relyingPartyId);
341             throw new ProfileException("Unable to retrieve relying party configuration data for entity with ID "
342                     + relyingPartyId);
343         }
344         requestContext.setRelyingPartyConfiguration(rpConfig);
345
346         SSOConfiguration profileConfig = (SSOConfiguration) rpConfig
347                 .getProfileConfiguration(SSOConfiguration.PROFILE_ID);
348         requestContext.setProfileConfiguration(profileConfig);
349         requestContext.setOutboundMessageArtifactType(profileConfig.getOutboundArtifactType());
350         if (profileConfig.getSigningCredential() != null) {
351             requestContext.setOutboundSAMLMessageSigningCredential(profileConfig.getSigningCredential());
352         } else if (rpConfig.getDefaultSigningCredential() != null) {
353             requestContext.setOutboundSAMLMessageSigningCredential(rpConfig.getDefaultSigningCredential());
354         }
355         requestContext.setPeerEntityEndpoint(selectEndpoint(requestContext));
356
357         String assertingPartyId = rpConfig.getProviderId();
358         requestContext.setLocalEntityId(assertingPartyId);
359
360         try {
361             EntityDescriptor localEntityDescriptor = metadataProvider.getEntityDescriptor(assertingPartyId);
362             if (localEntityDescriptor != null) {
363                 requestContext.setLocalEntityMetadata(localEntityDescriptor);
364                 requestContext.setLocalEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
365                 requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
366                         .getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
367             }
368         } catch (MetadataProviderException e) {
369             log.error("Unable to locate metadata for asserting party");
370             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
371                     "Error locating asserting party metadata"));
372             throw new ProfileException("Error locating asserting party metadata");
373         }
374
375         return requestContext;
376     }
377
378     /**
379      * Creates an authentication statement for the current request.
380      * 
381      * @param requestContext current request context
382      * 
383      * @return constructed authentication statement
384      */
385     protected AuthnStatement buildAuthnStatement(SSORequestContext requestContext) {
386         Saml2LoginContext loginContext = requestContext.getLoginContext();
387
388         AuthnContext authnContext = buildAuthnContext(requestContext);
389
390         AuthnStatement statement = authnStatementBuilder.buildObject();
391         statement.setAuthnContext(authnContext);
392         statement.setAuthnInstant(loginContext.getAuthenticationInstant());
393
394         // TODO
395         statement.setSessionIndex(null);
396
397         if (loginContext.getAuthenticationDuration() > 0) {
398             statement.setSessionNotOnOrAfter(loginContext.getAuthenticationInstant().plus(
399                     loginContext.getAuthenticationDuration()));
400         }
401
402         statement.setSubjectLocality(buildSubjectLocality(requestContext));
403
404         return statement;
405     }
406
407     /**
408      * Creates an {@link AuthnContext} for a succesful authentication request.
409      * 
410      * @param requestContext current request
411      * 
412      * @return the built authn context
413      */
414     protected AuthnContext buildAuthnContext(SSORequestContext requestContext) {
415         AuthnContext authnContext = authnContextBuilder.buildObject();
416
417         Saml2LoginContext loginContext = requestContext.getLoginContext();
418         AuthnRequest authnRequest = requestContext.getInboundSAMLMessage();
419         RequestedAuthnContext requestedAuthnContext = authnRequest.getRequestedAuthnContext();
420         if (requestedAuthnContext != null) {
421             if (requestedAuthnContext.getAuthnContextClassRefs() != null) {
422                 for (AuthnContextClassRef classRef : requestedAuthnContext.getAuthnContextClassRefs()) {
423                     if (classRef.getAuthnContextClassRef().equals(loginContext.getAuthenticationMethod())) {
424                         AuthnContextClassRef ref = authnContextClassRefBuilder.buildObject();
425                         ref.setAuthnContextClassRef(loginContext.getAuthenticationMethod());
426                         authnContext.setAuthnContextClassRef(ref);
427                     }
428                 }
429             } else if (requestedAuthnContext.getAuthnContextDeclRefs() != null) {
430                 for (AuthnContextDeclRef declRef : requestedAuthnContext.getAuthnContextDeclRefs()) {
431                     if (declRef.getAuthnContextDeclRef().equals(loginContext.getAuthenticationMethod())) {
432                         AuthnContextDeclRef ref = authnContextDeclRefBuilder.buildObject();
433                         ref.setAuthnContextDeclRef(loginContext.getAuthenticationMethod());
434                         authnContext.setAuthnContextDeclRef(ref);
435                     }
436                 }
437             }
438         } else {
439             AuthnContextDeclRef ref = authnContextDeclRefBuilder.buildObject();
440             ref.setAuthnContextDeclRef(loginContext.getAuthenticationMethod());
441             authnContext.setAuthnContextDeclRef(ref);
442         }
443
444         return authnContext;
445     }
446
447     /**
448      * Constructs the subject locality for the authentication statement.
449      * 
450      * @param requestContext curent request context
451      * 
452      * @return subject locality for the authentication statement
453      */
454     protected SubjectLocality buildSubjectLocality(SSORequestContext requestContext) {
455         HTTPInTransport transport = (HTTPInTransport) requestContext.getInboundMessageTransport();
456         SubjectLocality subjectLocality = subjectLocalityBuilder.buildObject();
457         subjectLocality.setAddress(transport.getPeerAddress());
458         subjectLocality.setDNSName(transport.getPeerDomainName());
459
460         return subjectLocality;
461     }
462
463     /**
464      * Selects the appropriate endpoint for the relying party and stores it in the request context.
465      * 
466      * @param requestContext current request context
467      * 
468      * @return Endpoint selected from the information provided in the request context
469      */
470     protected Endpoint selectEndpoint(SSORequestContext requestContext) {
471         AuthnResponseEndpointSelector endpointSelector = new AuthnResponseEndpointSelector();
472         endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
473         endpointSelector.setMetadataProvider(getMetadataProvider());
474         endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
475         endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
476         endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
477         endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
478         return endpointSelector.selectEndpoint();
479     }
480
481     /** Represents the internal state of a SAML 2.0 SSO Request while it's being processed by the IdP. */
482     protected class SSORequestContext extends BaseSAML2ProfileRequestContext<AuthnRequest, Response, SSOConfiguration> {
483
484         /** Current login context. */
485         private Saml2LoginContext loginContext;
486
487         /**
488          * Gets the current login context.
489          * 
490          * @return current login context
491          */
492         public Saml2LoginContext getLoginContext() {
493             return loginContext;
494         }
495
496         /**
497          * Sets the current login context.
498          * 
499          * @param context current login context
500          */
501         public void setLoginContext(Saml2LoginContext context) {
502             loginContext = context;
503         }
504     }
505 }