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