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