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