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