f812b5d0158168b40d942c714f83b8d49cb3c148
[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.io.UnsupportedEncodingException;
21 import java.net.URLDecoder;
22 import java.util.ArrayList;
23
24 import javax.servlet.RequestDispatcher;
25 import javax.servlet.ServletException;
26 import javax.servlet.ServletRequest;
27 import javax.servlet.ServletResponse;
28 import javax.servlet.http.HttpServletRequest;
29 import javax.servlet.http.HttpServletResponse;
30 import javax.servlet.http.HttpSession;
31
32 import org.apache.log4j.Logger;
33 import org.opensaml.common.SAMLObject;
34 import org.opensaml.common.SAMLObjectBuilder;
35 import org.opensaml.common.binding.BasicEndpointSelector;
36 import org.opensaml.common.binding.BindingException;
37 import org.opensaml.common.binding.encoding.MessageEncoder;
38 import org.opensaml.common.xml.SAMLConstants;
39 import org.opensaml.log.XMLObjectRenderer;
40 import org.opensaml.saml1.core.AuthenticationStatement;
41 import org.opensaml.saml1.core.Response;
42 import org.opensaml.saml1.core.Statement;
43 import org.opensaml.saml1.core.StatusCode;
44 import org.opensaml.saml1.core.Subject;
45 import org.opensaml.saml2.metadata.AssertionConsumerService;
46 import org.opensaml.saml2.metadata.Endpoint;
47 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
48 import org.opensaml.xml.util.DatatypeHelper;
49
50 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
51 import edu.internet2.middleware.shibboleth.common.profile.ProfileRequest;
52 import edu.internet2.middleware.shibboleth.common.profile.ProfileResponse;
53 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
54 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml1.ShibbolethSSOConfiguration;
55 import edu.internet2.middleware.shibboleth.common.util.HttpHelper;
56 import edu.internet2.middleware.shibboleth.idp.authn.LoginContext;
57 import edu.internet2.middleware.shibboleth.idp.authn.ShibbolethSSOLoginContext;
58
59 /** Shibboleth SSO request profile handler. */
60 public class ShibbolethSSOProfileHandler extends AbstractSAML1ProfileHandler {
61
62     /** Class logger. */
63     private final Logger log = Logger.getLogger(ShibbolethSSOProfileHandler.class);
64
65     /** Builder of AuthenticationStatement objects. */
66     private SAMLObjectBuilder<AuthenticationStatement> authnStatementBuilder;
67
68     /** URL of the authentication manager servlet. */
69     private String authenticationManagerPath;
70
71     /**
72      * Constructor.
73      * 
74      * @param authnManagerPath path to the authentication manager servlet
75      * 
76      * @throws IllegalArgumentException thrown if either the authentication manager path or encoding binding URI are
77      *             null or empty
78      */
79     public ShibbolethSSOProfileHandler(String authnManagerPath) {
80         if (DatatypeHelper.isEmpty(authnManagerPath)) {
81             throw new IllegalArgumentException("Authentication manager path may not be null");
82         }
83
84         authenticationManagerPath = authnManagerPath;
85
86         authnStatementBuilder = (SAMLObjectBuilder<AuthenticationStatement>) getBuilderFactory().getBuilder(
87                 AuthenticationStatement.DEFAULT_ELEMENT_NAME);
88     }
89
90     /**
91      * Convenience method for getting the SAML 1 AuthenticationStatement builder.
92      * 
93      * @return SAML 1 AuthenticationStatement builder
94      */
95     public SAMLObjectBuilder<AuthenticationStatement> getAuthenticationStatementBuilder() {
96         return authnStatementBuilder;
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(ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response)
106             throws ProfileException {
107         
108         if(response.getRawResponse().isCommitted()){
109             log.error("HTTP Response already committed");
110         }
111
112         if (log.isDebugEnabled()) {
113             log.debug("Processing incomming request");
114         }
115         HttpSession httpSession = ((HttpServletRequest) request.getRawRequest()).getSession(true);
116         if (httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY) == null) {
117             if (log.isDebugEnabled()) {
118                 log.debug("User session does not contain a login context, processing as first leg of request");
119             }
120             performAuthentication(request, response);
121         } else {
122             if (log.isDebugEnabled()) {
123                 log.debug("User session contains a login context, processing as second leg of request");
124             }
125             completeAuthenticationRequest(request, response);
126         }
127     }
128
129     /**
130      * Creates a {@link LoginContext} an sends the request off to the AuthenticationManager to begin the process of
131      * authenticating the user.
132      * 
133      * @param request current request
134      * @param response current response
135      * 
136      * @throws ProfileException thrown if there is a problem creating the login context and transferring control to the
137      *             authentication manager
138      */
139     protected void performAuthentication(ProfileRequest<ServletRequest> request,
140             ProfileResponse<ServletResponse> response) throws ProfileException {
141
142         HttpServletRequest httpRequest = (HttpServletRequest) request.getRawRequest();
143         HttpServletResponse httpResponse = (HttpServletResponse) response.getRawResponse();
144         HttpSession httpSession = httpRequest.getSession(true);
145
146         LoginContext loginContext = buildLoginContext(httpRequest);
147         httpSession.setAttribute(LoginContext.LOGIN_CONTEXT_KEY, loginContext);
148
149         try {
150             RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(authenticationManagerPath);
151             dispatcher.forward(httpRequest, httpResponse);
152             return;
153         } catch (IOException ex) {
154             log.error("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
155             throw new ProfileException("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
156         } catch (ServletException ex) {
157             log.error("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
158             throw new ProfileException("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
159         }
160     }
161
162     /**
163      * Creates a response to the Shibboleth SSO and sends the user, with response in tow, back to the relying party
164      * after they've been authenticated.
165      * 
166      * @param request current request
167      * @param response current response
168      * 
169      * @throws ProfileException thrown if the response can not be created and sent back to the relying party
170      */
171     protected void completeAuthenticationRequest(ProfileRequest<ServletRequest> request,
172             ProfileResponse<ServletResponse> response) throws ProfileException {
173         HttpSession httpSession = ((HttpServletRequest) request.getRawRequest()).getSession(true);
174
175         ShibbolethSSOLoginContext loginContext = (ShibbolethSSOLoginContext) httpSession
176                 .getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
177         httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
178
179         ShibbolethSSORequestContext requestContext = buildRequestContext(loginContext, request, response);
180
181         Response samlResponse;
182         try {
183             if (!loginContext.isPrincipalAuthenticated()) {
184                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "User failed authentication"));
185                 throw new ProfileException("User failed authentication");
186             }
187
188             ArrayList<Statement> statements = new ArrayList<Statement>();
189             statements.add(buildAuthenticationStatement(requestContext));
190             if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
191                 statements
192                         .add(buildAttributeStatement(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:sender-vouches"));
193             }
194
195             samlResponse = buildResponse(requestContext, statements);
196         } catch (ProfileException e) {
197             samlResponse = buildErrorResponse(requestContext);
198         }
199
200         requestContext.setSamlResponse(samlResponse);
201         encodeResponse(requestContext);
202         writeAuditLogEntry(requestContext);
203     }
204
205     /**
206      * Creates a login context from the incoming HTTP request.
207      * 
208      * @param request current HTTP request
209      * 
210      * @return the constructed login context
211      * 
212      * @throws ProfileException thrown if the incomming request did not contain a providerId, shire, and target
213      *             parameter
214      */
215     protected ShibbolethSSOLoginContext buildLoginContext(HttpServletRequest request) throws ProfileException {
216         ShibbolethSSOLoginContext loginContext = new ShibbolethSSOLoginContext();
217
218         try {
219             String providerId = DatatypeHelper.safeTrimOrNullString(request.getParameter("providerId"));
220             if (providerId == null) {
221                 log.error("No providerId parameter in Shibboleth SSO request");
222                 throw new ProfileException("No providerId parameter in Shibboleth SSO request");
223             }
224             loginContext.setRelyingParty(URLDecoder.decode(providerId, "UTF-8"));
225
226             RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(providerId);
227             if (rpConfig == null) {
228                 log.error("No relying party configuration available for " + providerId);
229                 throw new ProfileException("No relying party configuration available for " + providerId);
230             }
231             loginContext.getRequestedAuthenticationMethods().add(rpConfig.getDefaultAuthenticationMethod());
232
233             String acs = DatatypeHelper.safeTrimOrNullString(request.getParameter("shire"));
234             if (acs == null) {
235                 log.error("No shire parameter in Shibboleth SSO request");
236                 throw new ProfileException("No shire parameter in Shibboleth SSO request");
237             }
238             loginContext.setSpAssertionConsumerService(URLDecoder.decode(acs, "UTF-8"));
239
240             String target = DatatypeHelper.safeTrimOrNullString(request.getParameter("target"));
241             if (target == null) {
242                 log.error("No target parameter in Shibboleth SSO request");
243                 throw new ProfileException("No target parameter in Shibboleth SSO request");
244             }
245             loginContext.setSpTarget(URLDecoder.decode(target, "UTF-8"));
246         } catch (UnsupportedEncodingException e) {
247             // UTF-8 encoding required to be supported by all JVMs.
248         }
249
250         loginContext.setAuthenticationEngineURL(authenticationManagerPath);
251         loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(request));
252         return loginContext;
253     }
254
255     /**
256      * Creates an authentication request context from the current environmental information.
257      * 
258      * @param loginContext current login context
259      * @param request current request
260      * @param response current response
261      * 
262      * @return created authentication request context
263      * 
264      * @throws ProfileException thrown if asserting and relying party metadata can not be located
265      */
266     protected ShibbolethSSORequestContext buildRequestContext(ShibbolethSSOLoginContext loginContext,
267             ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response) throws ProfileException {
268         ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext(request, response);
269
270         requestContext.setLoginContext(loginContext);
271
272         requestContext.setPrincipalName(loginContext.getPrincipalName());
273
274         requestContext.setPrincipalAuthenticationMethod(loginContext.getAuthenticationMethod());
275
276         String relyingPartyId = loginContext.getRelyingPartyId();
277
278         requestContext.setRelyingPartyId(relyingPartyId);
279
280         try {
281
282             requestContext.setRelyingPartyMetadata(getMetadataProvider().getEntityDescriptor(
283                     requestContext.getRelyingPartyId()));
284
285             requestContext.setRelyingPartyRoleMetadata(requestContext.getRelyingPartyMetadata().getSPSSODescriptor(
286                     SAMLConstants.SAML1P_NS));
287
288             RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
289             requestContext.setRelyingPartyConfiguration(rpConfig);
290
291             requestContext.setAssertingPartyId(requestContext.getRelyingPartyConfiguration().getProviderId());
292
293             requestContext.setAssertingPartyMetadata(getMetadataProvider().getEntityDescriptor(
294                     requestContext.getAssertingPartyId()));
295
296             requestContext.setAssertingPartyRoleMetadata(requestContext.getAssertingPartyMetadata()
297                     .getIDPSSODescriptor(SAMLConstants.SAML1P_NS));
298
299             requestContext.setProfileConfiguration((ShibbolethSSOConfiguration) rpConfig
300                     .getProfileConfiguration(ShibbolethSSOConfiguration.PROFILE_ID));
301
302             return requestContext;
303         } catch (MetadataProviderException e) {
304             log.error("Unable to locate metadata for asserting or relying party");
305             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Error locating party metadata"));
306             throw new ProfileException("Error locating party metadata");
307         }
308     }
309
310     /**
311      * Builds the authentication statement for the authenticated principal.
312      * 
313      * @param requestContext current request context
314      * 
315      * @return the created statement
316      * 
317      * @throws ProfileException thrown if the authentication statement can not be created
318      */
319     protected AuthenticationStatement buildAuthenticationStatement(ShibbolethSSORequestContext requestContext)
320             throws ProfileException {
321         ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
322
323         AuthenticationStatement statement = getAuthenticationStatementBuilder().buildObject();
324         statement.setAuthenticationInstant(loginContext.getAuthenticationInstant());
325         statement.setAuthenticationMethod(loginContext.getAuthenticationMethod());
326
327         // TODO
328         statement.setSubjectLocality(null);
329
330         Subject statementSubject = buildSubject(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:sender-vouches");
331         statement.setSubject(statementSubject);
332
333         return statement;
334     }
335
336     /**
337      * Encodes the request's SAML response and writes it to the servlet response.
338      * 
339      * @param requestContext current request context
340      * 
341      * @throws ProfileException thrown if no message encoder is registered for this profiles binding
342      */
343     protected void encodeResponse(ShibbolethSSORequestContext requestContext) throws ProfileException {
344         if (log.isDebugEnabled()) {
345             log.debug("Encoding response to SAML request from relying party " + requestContext.getRelyingPartyId());
346         }
347
348         BasicEndpointSelector endpointSelector = new BasicEndpointSelector();
349         endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
350         endpointSelector.setMetadataProvider(getMetadataProvider());
351         endpointSelector.setRelyingParty(requestContext.getRelyingPartyMetadata());
352         endpointSelector.setRelyingPartyRole(requestContext.getRelyingPartyRoleMetadata());
353         endpointSelector.setSamlRequest(requestContext.getSamlRequest());
354         endpointSelector.getSupportedIssuerBindings().addAll(getMessageEncoderFactory().getEncoderBuilders().keySet());
355         Endpoint relyingPartyEndpoint = endpointSelector.selectEndpoint();
356
357         if (relyingPartyEndpoint == null) {
358             log.error("Unable to determine endpoint, from metadata, for relying party "
359                     + requestContext.getRelyingPartyId() + " acting in SPSSO role");
360             throw new ProfileException("Unable to determine endpoint, from metadata, for relying party "
361                     + requestContext.getRelyingPartyId() + " acting in SPSSO role");
362         }
363
364         MessageEncoder<ServletResponse> encoder = getMessageEncoderFactory().getMessageEncoder(
365                 relyingPartyEndpoint.getBinding());
366
367         super.populateMessageEncoder(encoder);
368         ProfileResponse<ServletResponse> profileResponse = requestContext.getProfileResponse();
369         encoder.setResponse(profileResponse.getRawResponse());
370         encoder.setSamlMessage(requestContext.getSamlResponse());
371         requestContext.setMessageEncoder(encoder);
372
373         try {
374             encoder.encode();
375         } catch (BindingException e) {
376             throw new ProfileException("Unable to encode response to relying party: "
377                     + requestContext.getRelyingPartyId(), e);
378         }
379     }
380
381     /** Represents the internal state of a Shibboleth SSO Request while it's being processed by the IdP. */
382     protected class ShibbolethSSORequestContext extends
383             SAML1ProfileRequestContext<SAMLObject, Response, ShibbolethSSOConfiguration> {
384
385         /** Current login context. */
386         private ShibbolethSSOLoginContext loginContext;
387
388         /**
389          * Constructor.
390          * 
391          * @param request current profile request
392          * @param response current profile response
393          */
394         public ShibbolethSSORequestContext(ProfileRequest<ServletRequest> request,
395                 ProfileResponse<ServletResponse> response) {
396             super(request, response);
397         }
398
399         /**
400          * Gets the current login context.
401          * 
402          * @return current login context
403          */
404         public ShibbolethSSOLoginContext getLoginContext() {
405             return loginContext;
406         }
407
408         /**
409          * Sets the current login context.
410          * 
411          * @param context current login context
412          */
413         public void setLoginContext(ShibbolethSSOLoginContext context) {
414             loginContext = context;
415         }
416     }
417 }