fetch attributes so that the name ID can be constructed properly
[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     /**
98      * Convenience method for getting the SAML 1 AuthenticationStatement builder.
99      * 
100      * @return SAML 1 AuthenticationStatement builder
101      */
102     public SAMLObjectBuilder<AuthenticationStatement> getAuthenticationStatementBuilder() {
103         return authnStatementBuilder;
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             ArrayList<Statement> statements = new ArrayList<Statement>();
202             statements.add(buildAttributeStatement(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:sender-vouches"));
203             statements.add(buildAuthenticationStatement(requestContext));
204             if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
205                 // TODO support this
206             }
207
208             samlResponse = buildResponse(requestContext, statements);
209         } catch (ProfileException e) {
210             samlResponse = buildErrorResponse(requestContext);
211         }
212
213         requestContext.setSamlResponse(samlResponse);
214         encodeResponse(requestContext);
215         writeAuditLogEntry(requestContext);
216     }
217
218     /**
219      * Creates a login context from the incoming HTTP request.
220      * 
221      * @param request current HTTP request
222      * 
223      * @return the constructed login context
224      * 
225      * @throws ProfileException thrown if the incomming request did not contain a providerId, shire, and target
226      *             parameter
227      */
228     protected ShibbolethSSOLoginContext buildLoginContext(HttpServletRequest request) throws ProfileException {
229         ShibbolethSSOLoginContext loginContext = new ShibbolethSSOLoginContext();
230
231         try {
232             String providerId = DatatypeHelper.safeTrimOrNullString(request.getParameter("providerId"));
233             if (providerId == null) {
234                 log.error("No providerId parameter in Shibboleth SSO request");
235                 throw new ProfileException("No providerId parameter in Shibboleth SSO request");
236             }
237             loginContext.setRelyingParty(URLDecoder.decode(providerId, "UTF-8"));
238
239             RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(providerId);
240             if (rpConfig == null) {
241                 log.error("No relying party configuration available for " + providerId);
242                 throw new ProfileException("No relying party configuration available for " + providerId);
243             }
244             loginContext.getRequestedAuthenticationMethods().add(rpConfig.getDefaultAuthenticationMethod());
245
246             String acs = DatatypeHelper.safeTrimOrNullString(request.getParameter("shire"));
247             if (acs == null) {
248                 log.error("No shire parameter in Shibboleth SSO request");
249                 throw new ProfileException("No shire parameter in Shibboleth SSO request");
250             }
251             loginContext.setSpAssertionConsumerService(URLDecoder.decode(acs, "UTF-8"));
252
253             String target = DatatypeHelper.safeTrimOrNullString(request.getParameter("target"));
254             if (target == null) {
255                 log.error("No target parameter in Shibboleth SSO request");
256                 throw new ProfileException("No target parameter in Shibboleth SSO request");
257             }
258             loginContext.setSpTarget(URLDecoder.decode(target, "UTF-8"));
259         } catch (UnsupportedEncodingException e) {
260             // UTF-8 encoding required to be supported by all JVMs.
261         }
262
263         loginContext.setAuthenticationEngineURL(authenticationManagerPath);
264         loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(request));
265         return loginContext;
266     }
267
268     /**
269      * Creates an authentication request context from the current environmental information.
270      * 
271      * @param loginContext current login context
272      * @param request current request
273      * @param response current response
274      * 
275      * @return created authentication request context
276      * 
277      * @throws ProfileException thrown if asserting and relying party metadata can not be located
278      */
279     protected ShibbolethSSORequestContext buildRequestContext(ShibbolethSSOLoginContext loginContext,
280             ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response) throws ProfileException {
281         ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext(request, response);
282
283         requestContext.setLoginContext(loginContext);
284
285         requestContext.setPrincipalName(loginContext.getPrincipalName());
286
287         requestContext.setPrincipalAuthenticationMethod(loginContext.getAuthenticationMethod());
288
289         String relyingPartyId = loginContext.getRelyingPartyId();
290
291         requestContext.setRelyingPartyId(relyingPartyId);
292
293         populateRelyingPartyData(requestContext);
294
295         populateAssertingPartyData(requestContext);
296
297         return requestContext;
298     }
299
300     /**
301      * Populates the relying party entity and role metadata and relying party configuration data.
302      * 
303      * @param requestContext current request context with relying party ID populated
304      * 
305      * @throws ProfileException thrown if metadata can not be located for the relying party
306      */
307     protected void populateRelyingPartyData(ShibbolethSSORequestContext requestContext) throws ProfileException {
308         try {
309             requestContext.setRelyingPartyMetadata(getMetadataProvider().getEntityDescriptor(
310                     requestContext.getRelyingPartyId()));
311
312             RoleDescriptor relyingPartyRole = requestContext.getRelyingPartyMetadata().getSPSSODescriptor(
313                     ShibbolethConstants.SAML11P_NS);
314
315             if (relyingPartyRole == null) {
316                 relyingPartyRole = requestContext.getRelyingPartyMetadata().getSPSSODescriptor(
317                         ShibbolethConstants.SAML10P_NS);
318                 if (relyingPartyRole == null) {
319                     throw new MetadataProviderException("Unable to locate SPSSO role descriptor for entity "
320                             + requestContext.getRelyingPartyId());
321                 }
322             }
323             requestContext.setRelyingPartyRoleMetadata(relyingPartyRole);
324
325             RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(requestContext.getRelyingPartyId());
326             requestContext.setRelyingPartyConfiguration(rpConfig);
327
328             requestContext.setProfileConfiguration((ShibbolethSSOConfiguration) rpConfig
329                     .getProfileConfiguration(ShibbolethSSOConfiguration.PROFILE_ID));
330
331         } catch (MetadataProviderException e) {
332             log.error("Unable to locate metadata for relying party " + requestContext.getRelyingPartyId());
333             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
334                     "Unable to locate metadata for relying party " + requestContext.getRelyingPartyId()));
335             throw new ProfileException("Unable to locate metadata for relying party "
336                     + requestContext.getRelyingPartyId());
337         }
338     }
339
340     /**
341      * Populates the asserting party entity and role metadata.
342      * 
343      * @param requestContext current request context with relying party configuration populated
344      * 
345      * @throws ProfileException thrown if metadata can not be located for the asserting party
346      */
347     protected void populateAssertingPartyData(ShibbolethSSORequestContext requestContext) throws ProfileException {
348         String assertingPartyId = requestContext.getRelyingPartyConfiguration().getProviderId();
349
350         try {
351             requestContext.setAssertingPartyId(assertingPartyId);
352
353             requestContext.setAssertingPartyMetadata(getMetadataProvider().getEntityDescriptor(assertingPartyId));
354
355             RoleDescriptor assertingPartyRole = requestContext.getAssertingPartyMetadata().getIDPSSODescriptor(
356                     ShibbolethConstants.SHIB_SSO_PROFILE_URI);
357             if (assertingPartyRole == null) {
358                 throw new MetadataProviderException("Unable to locate IDPSSO role descriptor for entity "
359                         + assertingPartyId);
360             }
361             requestContext.setAssertingPartyRoleMetadata(assertingPartyRole);
362         } catch (MetadataProviderException e) {
363             log.error("Unable to locate metadata for asserting party " + assertingPartyId);
364             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
365                     "Unable to locate metadata for relying party " + assertingPartyId));
366             throw new ProfileException("Unable to locate metadata for relying party " + assertingPartyId);
367         }
368     }
369
370     /**
371      * Builds the authentication statement for the authenticated principal.
372      * 
373      * @param requestContext current request context
374      * 
375      * @return the created statement
376      * 
377      * @throws ProfileException thrown if the authentication statement can not be created
378      */
379     protected AuthenticationStatement buildAuthenticationStatement(ShibbolethSSORequestContext requestContext)
380             throws ProfileException {
381         ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
382
383         AuthenticationStatement statement = getAuthenticationStatementBuilder().buildObject();
384         statement.setAuthenticationInstant(loginContext.getAuthenticationInstant());
385         statement.setAuthenticationMethod(loginContext.getAuthenticationMethod());
386
387         statement.setSubjectLocality(buildSubjectLocality(requestContext));
388
389         Subject statementSubject = buildSubject(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:sender-vouches");
390         statement.setSubject(statementSubject);
391
392         return statement;
393     }
394
395     /**
396      * Constructs the subject locality for the authentication statement.
397      * 
398      * @param requestContext curent request context
399      * 
400      * @return subject locality for the authentication statement
401      */
402     protected SubjectLocality buildSubjectLocality(ShibbolethSSORequestContext requestContext) {
403         SubjectLocality subjectLocality = subjectLocalityBuilder.buildObject();
404
405         ShibbolethSSOConfiguration profileConfig = requestContext.getProfileConfiguration();
406         HttpServletRequest httpRequest = (HttpServletRequest) requestContext.getProfileRequest().getRawRequest();
407
408         if (profileConfig.getLocalityAddress() != null) {
409             subjectLocality.setIPAddress(profileConfig.getLocalityAddress());
410         } else {
411             subjectLocality.setIPAddress(httpRequest.getLocalAddr());
412         }
413
414         if (profileConfig.getLocalityDNSName() != null) {
415             subjectLocality.setDNSAddress(profileConfig.getLocalityDNSName());
416         } else {
417             subjectLocality.setDNSAddress(httpRequest.getLocalName());
418         }
419
420         return subjectLocality;
421     }
422
423     /**
424      * Encodes the request's SAML response and writes it to the servlet response.
425      * 
426      * @param requestContext current request context
427      * 
428      * @throws ProfileException thrown if no message encoder is registered for this profiles binding
429      */
430     protected void encodeResponse(ShibbolethSSORequestContext requestContext) throws ProfileException {
431         if (log.isDebugEnabled()) {
432             log.debug("Encoding response to SAML request from relying party " + requestContext.getRelyingPartyId());
433         }
434
435         Endpoint relyingPartyEndpoint;
436
437         BasicEndpointSelector endpointSelector = new BasicEndpointSelector();
438         endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
439         endpointSelector.setMetadataProvider(getMetadataProvider());
440         endpointSelector.setRelyingParty(requestContext.getRelyingPartyMetadata());
441         endpointSelector.setRelyingPartyRole(requestContext.getRelyingPartyRoleMetadata());
442         endpointSelector.setSamlRequest(requestContext.getSamlRequest());
443         endpointSelector.getSupportedIssuerBindings().addAll(getMessageEncoderFactory().getEncoderBuilders().keySet());
444         relyingPartyEndpoint = endpointSelector.selectEndpoint();
445
446         if (relyingPartyEndpoint == null) {
447             log.error("Unable to determine endpoint, from metadata, for relying party "
448                     + requestContext.getRelyingPartyId() + " acting in SPSSO role");
449             throw new ProfileException("Unable to determine endpoint, from metadata, for relying party "
450                     + requestContext.getRelyingPartyId() + " acting in SPSSO role");
451         }
452
453         MessageEncoder<ServletResponse> encoder = getMessageEncoderFactory().getMessageEncoder(
454                 relyingPartyEndpoint.getBinding());
455         encoder.setRelyingPartyEndpoint(relyingPartyEndpoint);
456         super.populateMessageEncoder(encoder);
457         ProfileResponse<ServletResponse> profileResponse = requestContext.getProfileResponse();
458         encoder.setResponse(profileResponse.getRawResponse());
459         encoder.setSamlMessage(requestContext.getSamlResponse());
460         requestContext.setMessageEncoder(encoder);
461
462         try {
463             encoder.encode();
464         } catch (BindingException e) {
465             throw new ProfileException("Unable to encode response to relying party: "
466                     + requestContext.getRelyingPartyId(), e);
467         }
468     }
469
470     /** Represents the internal state of a Shibboleth SSO Request while it's being processed by the IdP. */
471     protected class ShibbolethSSORequestContext extends
472             SAML1ProfileRequestContext<Request, Response, ShibbolethSSOConfiguration> {
473
474         /** Current login context. */
475         private ShibbolethSSOLoginContext loginContext;
476
477         /**
478          * Constructor.
479          * 
480          * @param request current profile request
481          * @param response current profile response
482          */
483         public ShibbolethSSORequestContext(ProfileRequest<ServletRequest> request,
484                 ProfileResponse<ServletResponse> response) {
485             super(request, response);
486         }
487
488         /**
489          * Gets the current login context.
490          * 
491          * @return current login context
492          */
493         public ShibbolethSSOLoginContext getLoginContext() {
494             return loginContext;
495         }
496
497         /**
498          * Sets the current login context.
499          * 
500          * @param context current login context
501          */
502         public void setLoginContext(ShibbolethSSOLoginContext context) {
503             loginContext = context;
504         }
505     }
506 }