Moving Shibboleth constants down to java-shib-common. Seems to more naturally belong...
[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.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.AssertionConsumerService;
44 import org.opensaml.saml2.metadata.Endpoint;
45 import org.opensaml.saml2.metadata.RoleDescriptor;
46 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
47 import org.opensaml.xml.util.DatatypeHelper;
48
49 import edu.internet2.middleware.shibboleth.common.ShibbolethConstants;
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         if (getRelyingPartyConfiguration(loginContext.getRelyingPartyId()) == null) {
148             log.error("Shibboleth SSO profile is not configured for relying party " + loginContext.getRelyingPartyId());
149             throw new ProfileException("Shibboleth SSO profile is not configured for relying party "
150                     + loginContext.getRelyingPartyId());
151         }
152
153         httpSession.setAttribute(LoginContext.LOGIN_CONTEXT_KEY, loginContext);
154
155         try {
156             RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(authenticationManagerPath);
157             dispatcher.forward(httpRequest, httpResponse);
158             return;
159         } catch (IOException ex) {
160             log.error("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
161             throw new ProfileException("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
162         } catch (ServletException ex) {
163             log.error("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
164             throw new ProfileException("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
165         }
166     }
167
168     /**
169      * Creates a response to the Shibboleth SSO and sends the user, with response in tow, back to the relying party
170      * after they've been authenticated.
171      * 
172      * @param request current request
173      * @param response current response
174      * 
175      * @throws ProfileException thrown if the response can not be created and sent back to the relying party
176      */
177     protected void completeAuthenticationRequest(ProfileRequest<ServletRequest> request,
178             ProfileResponse<ServletResponse> response) throws ProfileException {
179         HttpSession httpSession = ((HttpServletRequest) request.getRawRequest()).getSession(true);
180
181         ShibbolethSSOLoginContext loginContext = (ShibbolethSSOLoginContext) httpSession
182                 .getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
183         httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
184
185         ShibbolethSSORequestContext requestContext = buildRequestContext(loginContext, request, response);
186
187         Response samlResponse;
188         try {
189             if (!loginContext.isPrincipalAuthenticated()) {
190                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "User failed authentication"));
191                 throw new ProfileException("User failed authentication");
192             }
193
194             ArrayList<Statement> statements = new ArrayList<Statement>();
195             statements.add(buildAuthenticationStatement(requestContext));
196             if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
197                 statements
198                         .add(buildAttributeStatement(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:sender-vouches"));
199             }
200
201             samlResponse = buildResponse(requestContext, statements);
202         } catch (ProfileException e) {
203             samlResponse = buildErrorResponse(requestContext);
204         }
205
206         requestContext.setSamlResponse(samlResponse);
207         encodeResponse(requestContext);
208         writeAuditLogEntry(requestContext);
209     }
210
211     /**
212      * Creates a login context from the incoming HTTP request.
213      * 
214      * @param request current HTTP request
215      * 
216      * @return the constructed login context
217      * 
218      * @throws ProfileException thrown if the incomming request did not contain a providerId, shire, and target
219      *             parameter
220      */
221     protected ShibbolethSSOLoginContext buildLoginContext(HttpServletRequest request) throws ProfileException {
222         ShibbolethSSOLoginContext loginContext = new ShibbolethSSOLoginContext();
223
224         try {
225             String providerId = DatatypeHelper.safeTrimOrNullString(request.getParameter("providerId"));
226             if (providerId == null) {
227                 log.error("No providerId parameter in Shibboleth SSO request");
228                 throw new ProfileException("No providerId parameter in Shibboleth SSO request");
229             }
230             loginContext.setRelyingParty(URLDecoder.decode(providerId, "UTF-8"));
231
232             RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(providerId);
233             if (rpConfig == null) {
234                 log.error("No relying party configuration available for " + providerId);
235                 throw new ProfileException("No relying party configuration available for " + providerId);
236             }
237             loginContext.getRequestedAuthenticationMethods().add(rpConfig.getDefaultAuthenticationMethod());
238
239             String acs = DatatypeHelper.safeTrimOrNullString(request.getParameter("shire"));
240             if (acs == null) {
241                 log.error("No shire parameter in Shibboleth SSO request");
242                 throw new ProfileException("No shire parameter in Shibboleth SSO request");
243             }
244             loginContext.setSpAssertionConsumerService(URLDecoder.decode(acs, "UTF-8"));
245
246             String target = DatatypeHelper.safeTrimOrNullString(request.getParameter("target"));
247             if (target == null) {
248                 log.error("No target parameter in Shibboleth SSO request");
249                 throw new ProfileException("No target parameter in Shibboleth SSO request");
250             }
251             loginContext.setSpTarget(URLDecoder.decode(target, "UTF-8"));
252         } catch (UnsupportedEncodingException e) {
253             // UTF-8 encoding required to be supported by all JVMs.
254         }
255
256         loginContext.setAuthenticationEngineURL(authenticationManagerPath);
257         loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(request));
258         return loginContext;
259     }
260
261     /**
262      * Creates an authentication request context from the current environmental information.
263      * 
264      * @param loginContext current login context
265      * @param request current request
266      * @param response current response
267      * 
268      * @return created authentication request context
269      * 
270      * @throws ProfileException thrown if asserting and relying party metadata can not be located
271      */
272     protected ShibbolethSSORequestContext buildRequestContext(ShibbolethSSOLoginContext loginContext,
273             ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response) throws ProfileException {
274         ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext(request, response);
275
276         requestContext.setLoginContext(loginContext);
277
278         requestContext.setPrincipalName(loginContext.getPrincipalName());
279
280         requestContext.setPrincipalAuthenticationMethod(loginContext.getAuthenticationMethod());
281
282         String relyingPartyId = loginContext.getRelyingPartyId();
283
284         requestContext.setRelyingPartyId(relyingPartyId);
285
286         populateRelyingPartyData(requestContext);
287         
288         populateAssertingPartyData(requestContext);
289         
290         return requestContext;
291     }
292
293     /**
294      * Populates the relying party entity and role metadata and relying party configuration data.
295      * 
296      * @param requestContext current request context with relying party ID populated
297      * 
298      * @throws ProfileException thrown if metadata can not be located for the relying party
299      */
300     protected void populateRelyingPartyData(ShibbolethSSORequestContext requestContext) throws ProfileException {
301         try {
302             requestContext.setRelyingPartyMetadata(getMetadataProvider().getEntityDescriptor(
303                     requestContext.getRelyingPartyId()));
304
305             RoleDescriptor relyingPartyRole = requestContext.getRelyingPartyMetadata().getSPSSODescriptor(
306                     ShibbolethConstants.SAML11P_NS);
307
308             if (relyingPartyRole == null) {
309                 relyingPartyRole = requestContext.getRelyingPartyMetadata()
310                         .getSPSSODescriptor(ShibbolethConstants.SAML10P_NS);
311                 if (relyingPartyRole == null) {
312                     throw new MetadataProviderException("Unable to locate SPSSO role descriptor for entity "
313                             + requestContext.getRelyingPartyId());
314                 }
315             }
316             requestContext.setRelyingPartyRoleMetadata(relyingPartyRole);
317
318             RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(requestContext.getRelyingPartyId());
319             requestContext.setRelyingPartyConfiguration(rpConfig);
320
321             requestContext.setProfileConfiguration((ShibbolethSSOConfiguration) rpConfig
322                     .getProfileConfiguration(ShibbolethSSOConfiguration.PROFILE_ID));
323
324         } catch (MetadataProviderException e) {
325             log.error("Unable to locate metadata for relying party " + requestContext.getRelyingPartyId());
326             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
327                     "Unable to locate metadata for relying party " + requestContext.getRelyingPartyId()));
328             throw new ProfileException("Unable to locate metadata for relying party "
329                     + requestContext.getRelyingPartyId());
330         }
331     }
332
333     /**
334      * Populates the asserting party entity and role metadata.
335      * 
336      * @param requestContext current request context with relying party configuration populated
337      * 
338      * @throws ProfileException thrown if metadata can not be located for the asserting party
339      */
340     protected void populateAssertingPartyData(ShibbolethSSORequestContext requestContext) throws ProfileException {
341         String assertingPartyId = requestContext.getRelyingPartyConfiguration().getProviderId();
342
343         try {
344             requestContext.setAssertingPartyId(assertingPartyId);
345
346             requestContext.setAssertingPartyMetadata(getMetadataProvider().getEntityDescriptor(assertingPartyId));
347
348             RoleDescriptor assertingPartyRole = requestContext.getAssertingPartyMetadata().getIDPSSODescriptor(
349                     ShibbolethConstants.SHIB_SSO_PROFILE_URI);
350             if (assertingPartyRole == null) {
351                 throw new MetadataProviderException("Unable to locate IDPSSO role descriptor for entity "
352                         + assertingPartyId);
353             }
354             requestContext.setAssertingPartyRoleMetadata(assertingPartyRole);
355         } catch (MetadataProviderException e) {
356             log.error("Unable to locate metadata for asserting party " + assertingPartyId);
357             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
358                     "Unable to locate metadata for relying party " + assertingPartyId));
359             throw new ProfileException("Unable to locate metadata for relying party " + assertingPartyId);
360         }
361     }
362
363     /**
364      * Builds the authentication statement for the authenticated principal.
365      * 
366      * @param requestContext current request context
367      * 
368      * @return the created statement
369      * 
370      * @throws ProfileException thrown if the authentication statement can not be created
371      */
372     protected AuthenticationStatement buildAuthenticationStatement(ShibbolethSSORequestContext requestContext)
373             throws ProfileException {
374         ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
375
376         AuthenticationStatement statement = getAuthenticationStatementBuilder().buildObject();
377         statement.setAuthenticationInstant(loginContext.getAuthenticationInstant());
378         statement.setAuthenticationMethod(loginContext.getAuthenticationMethod());
379
380         // TODO
381         statement.setSubjectLocality(null);
382
383         Subject statementSubject = buildSubject(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:sender-vouches");
384         statement.setSubject(statementSubject);
385
386         return statement;
387     }
388
389     /**
390      * Encodes the request's SAML response and writes it to the servlet response.
391      * 
392      * @param requestContext current request context
393      * 
394      * @throws ProfileException thrown if no message encoder is registered for this profiles binding
395      */
396     protected void encodeResponse(ShibbolethSSORequestContext requestContext) throws ProfileException {
397         if (log.isDebugEnabled()) {
398             log.debug("Encoding response to SAML request from relying party " + requestContext.getRelyingPartyId());
399         }
400
401         BasicEndpointSelector endpointSelector = new BasicEndpointSelector();
402         endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
403         endpointSelector.setMetadataProvider(getMetadataProvider());
404         endpointSelector.setRelyingParty(requestContext.getRelyingPartyMetadata());
405         endpointSelector.setRelyingPartyRole(requestContext.getRelyingPartyRoleMetadata());
406         endpointSelector.setSamlRequest(requestContext.getSamlRequest());
407         endpointSelector.getSupportedIssuerBindings().addAll(getMessageEncoderFactory().getEncoderBuilders().keySet());
408         Endpoint relyingPartyEndpoint = endpointSelector.selectEndpoint();
409
410         if (relyingPartyEndpoint == null) {
411             log.error("Unable to determine endpoint, from metadata, for relying party "
412                     + requestContext.getRelyingPartyId() + " acting in SPSSO role");
413             throw new ProfileException("Unable to determine endpoint, from metadata, for relying party "
414                     + requestContext.getRelyingPartyId() + " acting in SPSSO role");
415         }
416
417         MessageEncoder<ServletResponse> encoder = getMessageEncoderFactory().getMessageEncoder(
418                 relyingPartyEndpoint.getBinding());
419
420         super.populateMessageEncoder(encoder);
421         ProfileResponse<ServletResponse> profileResponse = requestContext.getProfileResponse();
422         encoder.setResponse(profileResponse.getRawResponse());
423         encoder.setSamlMessage(requestContext.getSamlResponse());
424         requestContext.setMessageEncoder(encoder);
425
426         try {
427             encoder.encode();
428         } catch (BindingException e) {
429             throw new ProfileException("Unable to encode response to relying party: "
430                     + requestContext.getRelyingPartyId(), e);
431         }
432     }
433
434     /** Represents the internal state of a Shibboleth SSO Request while it's being processed by the IdP. */
435     protected class ShibbolethSSORequestContext extends
436             SAML1ProfileRequestContext<SAMLObject, Response, ShibbolethSSOConfiguration> {
437
438         /** Current login context. */
439         private ShibbolethSSOLoginContext loginContext;
440
441         /**
442          * Constructor.
443          * 
444          * @param request current profile request
445          * @param response current profile response
446          */
447         public ShibbolethSSORequestContext(ProfileRequest<ServletRequest> request,
448                 ProfileResponse<ServletResponse> response) {
449             super(request, response);
450         }
451
452         /**
453          * Gets the current login context.
454          * 
455          * @return current login context
456          */
457         public ShibbolethSSOLoginContext getLoginContext() {
458             return loginContext;
459         }
460
461         /**
462          * Sets the current login context.
463          * 
464          * @param context current login context
465          */
466         public void setLoginContext(ShibbolethSSOLoginContext context) {
467             loginContext = context;
468         }
469     }
470 }