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