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