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