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