Drive relying party endpoint selection off of metadata
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / idp / profile / saml2 / SSOProfileHandler.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.saml2;
18
19 import java.io.IOException;
20 import java.util.ArrayList;
21
22 import javax.servlet.RequestDispatcher;
23 import javax.servlet.ServletException;
24 import javax.servlet.ServletRequest;
25 import javax.servlet.ServletResponse;
26 import javax.servlet.http.HttpServletRequest;
27 import javax.servlet.http.HttpSession;
28
29 import org.apache.log4j.Logger;
30 import org.opensaml.common.SAMLObjectBuilder;
31 import org.opensaml.common.binding.BindingException;
32 import org.opensaml.common.binding.decoding.MessageDecoder;
33 import org.opensaml.common.binding.encoding.MessageEncoder;
34 import org.opensaml.common.binding.security.SAMLSecurityPolicy;
35 import org.opensaml.common.xml.SAMLConstants;
36 import org.opensaml.saml2.binding.AuthnResponseEndpointSelector;
37 import org.opensaml.saml2.core.AuthnContext;
38 import org.opensaml.saml2.core.AuthnContextClassRef;
39 import org.opensaml.saml2.core.AuthnContextDeclRef;
40 import org.opensaml.saml2.core.AuthnRequest;
41 import org.opensaml.saml2.core.AuthnStatement;
42 import org.opensaml.saml2.core.RequestedAuthnContext;
43 import org.opensaml.saml2.core.Response;
44 import org.opensaml.saml2.core.Statement;
45 import org.opensaml.saml2.core.StatusCode;
46 import org.opensaml.saml2.core.Subject;
47 import org.opensaml.saml2.metadata.AssertionConsumerService;
48 import org.opensaml.saml2.metadata.Endpoint;
49 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
50 import org.opensaml.ws.security.SecurityPolicyException;
51 import org.opensaml.xml.io.MarshallingException;
52 import org.opensaml.xml.io.UnmarshallingException;
53
54 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
55 import edu.internet2.middleware.shibboleth.common.profile.ProfileRequest;
56 import edu.internet2.middleware.shibboleth.common.profile.ProfileResponse;
57 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
58 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.SSOConfiguration;
59 import edu.internet2.middleware.shibboleth.idp.authn.LoginContext;
60 import edu.internet2.middleware.shibboleth.idp.authn.Saml2LoginContext;
61
62 /** SAML 2.0 SSO request profile handler. */
63 public class SSOProfileHandler extends AbstractSAML2ProfileHandler {
64
65     /** Class logger. */
66     private final Logger log = Logger.getLogger(SSOProfileHandler.class);
67
68     /** Builder of AuthnStatement objects. */
69     private SAMLObjectBuilder<AuthnStatement> authnStatementBuilder;
70
71     /** Builder of AuthnContext objects. */
72     private SAMLObjectBuilder<AuthnContext> authnContextBuilder;
73
74     /** Builder of AuthnContextClassRef objects. */
75     private SAMLObjectBuilder<AuthnContextClassRef> authnContextClassRefBuilder;
76
77     /** Builder of AuthnContextDeclRef objects. */
78     private SAMLObjectBuilder<AuthnContextDeclRef> authnContextDeclRefBuilder;
79
80     /** URL of the authentication manager servlet. */
81     private String authenticationManagerPath;
82
83     /** URI of request decoder. */
84     private String decodingBinding;
85
86     /**
87      * Constructor.
88      * 
89      * @param authnManagerPath path to the authentication manager servlet
90      * @param decoder URI of the request decoder to use
91      */
92     @SuppressWarnings("unchecked")
93     public SSOProfileHandler(String authnManagerPath, String decoder) {
94         super();
95
96         if (authnManagerPath == null || decoder == null) {
97             throw new IllegalArgumentException("AuthN manager path or decoding bindings URI may not be null");
98         }
99
100         authenticationManagerPath = authnManagerPath;
101         decodingBinding = decoder;
102
103         authnStatementBuilder = (SAMLObjectBuilder<AuthnStatement>) getBuilderFactory().getBuilder(
104                 AuthnStatement.DEFAULT_ELEMENT_NAME);
105         authnContextBuilder = (SAMLObjectBuilder<AuthnContext>) getBuilderFactory().getBuilder(
106                 AuthnContext.DEFAULT_ELEMENT_NAME);
107         authnContextClassRefBuilder = (SAMLObjectBuilder<AuthnContextClassRef>) getBuilderFactory().getBuilder(
108                 AuthnContextClassRef.DEFAULT_ELEMENT_NAME);
109         authnContextDeclRefBuilder = (SAMLObjectBuilder<AuthnContextDeclRef>) getBuilderFactory().getBuilder(
110                 AuthnContextDeclRef.DEFAULT_ELEMENT_NAME);
111     }
112
113     /**
114      * Convenience method for getting the SAML 2 AuthnStatement builder.
115      * 
116      * @return SAML 2 AuthnStatement builder
117      */
118     public SAMLObjectBuilder<AuthnStatement> getAuthnStatementBuilder() {
119         return authnStatementBuilder;
120     }
121
122     /**
123      * Convenience method for getting the SAML 2 AuthnContext builder.
124      * 
125      * @return SAML 2 AuthnContext builder
126      */
127     public SAMLObjectBuilder<AuthnContext> getAuthnContextBuilder() {
128         return authnContextBuilder;
129     }
130
131     /**
132      * Convenience method for getting the SAML 2 AuthnContextClassRef builder.
133      * 
134      * @return SAML 2 AuthnContextClassRef builder
135      */
136     public SAMLObjectBuilder<AuthnContextClassRef> getAuthnContextClassRefBuilder() {
137         return authnContextClassRefBuilder;
138     }
139
140     /**
141      * Convenience method for getting the SAML 2 AuthnContextDeclRef builder.
142      * 
143      * @return SAML 2 AuthnContextDeclRef builder
144      */
145     public SAMLObjectBuilder<AuthnContextDeclRef> getAuthnContextDeclRefBuilder() {
146         return authnContextDeclRefBuilder;
147     }
148
149     /** {@inheritDoc} */
150     public String getProfileId() {
151         return "urn:mace:shibboleth:2.0:idp:profiles:saml2:request:sso";
152     }
153
154     /** {@inheritDoc} */
155     public void processRequest(ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response)
156             throws ProfileException {
157
158         HttpSession httpSession = ((HttpServletRequest) request.getRawRequest()).getSession(true);
159         if (httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY) == null) {
160             performAuthentication(request, response);
161         } else {
162             completeAuthenticationRequest(request, response);
163         }
164     }
165
166     /**
167      * Creates a {@link Saml2LoginContext} an sends the request off to the AuthenticationManager to begin the process of
168      * authenticating the user.
169      * 
170      * @param request current request
171      * @param response current response
172      * 
173      * @throws ProfileException thrown if there is a problem creating the login context and transferring control to the
174      *             authentication manager
175      */
176     protected void performAuthentication(ProfileRequest<ServletRequest> request,
177             ProfileResponse<ServletResponse> response) throws ProfileException {
178         HttpServletRequest httpRequest = (HttpServletRequest) request.getRawRequest();
179
180         AuthnRequest authnRequest = null;
181         try {
182             MessageDecoder<ServletRequest> decoder = decodeRequest(request);
183             SAMLSecurityPolicy securityPolicy = decoder.getSecurityPolicy();
184
185             String relyingParty = securityPolicy.getIssuer();
186             authnRequest = (AuthnRequest) decoder.getSAMLMessage();
187
188             Saml2LoginContext loginContext = new Saml2LoginContext(relyingParty, authnRequest);
189             loginContext.setAuthenticationEngineURL(authenticationManagerPath);
190             loginContext.setProfileHandlerURL(httpRequest.getRequestURI());
191
192             HttpSession httpSession = httpRequest.getSession();
193             httpSession.setAttribute(Saml2LoginContext.LOGIN_CONTEXT_KEY, loginContext);
194             RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(authenticationManagerPath);
195             dispatcher.forward(httpRequest, response.getRawResponse());
196         } catch (MarshallingException e) {
197             log.error("Unable to marshall authentication request context");
198             throw new ProfileException("Unable to marshall authentication request context", e);
199         } catch (IOException ex) {
200             log.error("Error forwarding SAML 2 AuthnRequest " + authnRequest.getID() + " to AuthenticationManager", ex);
201             throw new ProfileException("Error forwarding SAML 2 AuthnRequest " + authnRequest.getID()
202                     + " to AuthenticationManager", ex);
203         } catch (ServletException ex) {
204             log.error("Error forwarding SAML 2 AuthnRequest " + authnRequest.getID() + " to AuthenticationManager", ex);
205             throw new ProfileException("Error forwarding SAML 2 AuthnRequest " + authnRequest.getID()
206                     + " to AuthenticationManager", ex);
207         }
208     }
209
210     /**
211      * Creates a response to the {@link AuthnRequest} and sends the user, with response in tow, back to the relying
212      * party after they've been authenticated.
213      * 
214      * @param request current request
215      * @param response current response
216      * 
217      * @throws ProfileException thrown if the response can not be created and sent back to the relying party
218      */
219     protected void completeAuthenticationRequest(ProfileRequest<ServletRequest> request,
220             ProfileResponse<ServletResponse> response) throws ProfileException {
221
222         HttpSession httpSession = ((HttpServletRequest) request.getRawRequest()).getSession(true);
223
224         Saml2LoginContext loginContext = (Saml2LoginContext) httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
225         httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
226
227         SSORequestContext requestContext = buildRequestContext(loginContext, request, response);
228
229         checkSamlVersion(requestContext);
230
231         Response samlResponse;
232         try {
233             if (!loginContext.isPrincipalAuthenticated()) {
234                 requestContext
235                         .setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.AUTHN_FAILED_URI, null));
236                 throw new ProfileException("User failed authentication");
237             }
238
239             ArrayList<Statement> statements = new ArrayList<Statement>();
240             statements.add(buildAuthnStatement(requestContext));
241             if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
242                 statements.add(buildAttributeStatement(requestContext));
243             }
244
245             Subject assertionSubject = buildSubject(requestContext, "urn:oasis:names:tc:SAML:2.0:cm:bearer");
246
247             samlResponse = buildResponse(requestContext, assertionSubject, statements);
248         } catch (ProfileException e) {
249             samlResponse = buildErrorResponse(requestContext);
250         }
251
252         requestContext.setSamlResponse(samlResponse);
253         encodeResponse(requestContext);
254         writeAuditLogEntry(requestContext);
255     }
256
257     /**
258      * Creates an appropriate message decoder, populates it, and decodes the incoming request.
259      * 
260      * @param request current request
261      * 
262      * @return message decoder containing the decoded message and other stateful information
263      * 
264      * @throws ProfileException thrown if the incomming message failed decoding
265      */
266     protected MessageDecoder<ServletRequest> decodeRequest(ProfileRequest<ServletRequest> request)
267             throws ProfileException {
268         MessageDecoder<ServletRequest> decoder = getMessageDecoderFactory().getMessageDecoder(decodingBinding);
269         if (decoder == null) {
270             log.error("No request decoder was registered for binding type: " + decodingBinding);
271             throw new ProfileException("No request decoder was registered for binding type: " + decodingBinding);
272         }
273
274         populateMessageDecoder(decoder);
275         decoder.setRequest(request.getRawRequest());
276         try {
277             decoder.decode();
278             return decoder;
279         } catch (BindingException e) {
280             log.error("Error decoding authentication request message", e);
281             throw new ProfileException("Error decoding authentication request message", e);
282         } catch (SecurityPolicyException e) {
283             log.error("Message did not meet security policy requirements", e);
284             throw new ProfileException("Message did not meet security policy requirements", e);
285         }
286     }
287
288     /**
289      * Creates an authentication request context from the current environmental information.
290      * 
291      * @param loginContext current login context
292      * @param request current request
293      * @param response current response
294      * 
295      * @return created authentication request context
296      * 
297      * @throws ProfileException thrown if there is a problem creating the context
298      */
299     protected SSORequestContext buildRequestContext(Saml2LoginContext loginContext,
300             ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response) throws ProfileException {
301         SSORequestContext requestContext = new SSORequestContext(request, response);
302
303         try {
304             requestContext.setMessageDecoder(getMessageDecoderFactory().getMessageDecoder(decodingBinding));
305
306             requestContext.setLoginContext(loginContext);
307
308             String relyingPartyId = loginContext.getRelyingPartyId();
309             AuthnRequest authnRequest = loginContext.getAuthenticationRequest();
310
311             requestContext.setRelyingPartyId(relyingPartyId);
312
313             requestContext.setRelyingPartyMetadata(getMetadataProvider().getEntityDescriptor(relyingPartyId));
314
315             requestContext.setRelyingPartyRoleMetadata(requestContext.getRelyingPartyMetadata().getSPSSODescriptor(
316                     SAMLConstants.SAML20P_NS));
317
318             RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
319             requestContext.setRelyingPartyConfiguration(rpConfig);
320
321             requestContext.setAssertingPartyId(requestContext.getRelyingPartyConfiguration().getProviderId());
322
323             requestContext.setAssertingPartyMetadata(getMetadataProvider().getEntityDescriptor(
324                     requestContext.getAssertingPartyId()));
325
326             requestContext.setAssertingPartyRoleMetadata(requestContext.getRelyingPartyMetadata().getIDPSSODescriptor(
327                     SAMLConstants.SAML20P_NS));
328
329             requestContext.setPrincipalName(loginContext.getPrincipalName());
330
331             requestContext.setProfileConfiguration((SSOConfiguration) rpConfig
332                     .getProfileConfiguration(SSOConfiguration.PROFILE_ID));
333
334             requestContext.setSamlRequest(authnRequest);
335
336             return requestContext;
337         } catch (UnmarshallingException e) {
338             log.error("Unable to unmarshall authentication request context");
339             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
340                     "Error recovering request state"));
341             throw new ProfileException("Error recovering request state", e);
342         } catch (MetadataProviderException e) {
343             log.error("Unable to locate metadata for asserting or relying party");
344             requestContext
345                     .setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error locating party metadata"));
346             throw new ProfileException("Error locating party metadata");
347         }
348     }
349
350     /**
351      * Creates an authentication statement for the current request.
352      * 
353      * @param requestContext current request context
354      * 
355      * @return constructed authentication statement
356      */
357     protected AuthnStatement buildAuthnStatement(SSORequestContext requestContext) {
358         Saml2LoginContext loginContext = requestContext.getLoginContext();
359
360         AuthnContext authnContext = buildAuthnContext(requestContext);
361
362         AuthnStatement statement = getAuthnStatementBuilder().buildObject();
363         statement.setAuthnContext(authnContext);
364         statement.setAuthnInstant(loginContext.getAuthenticationInstant());
365
366         // TODO
367         statement.setSessionIndex(null);
368
369         if (loginContext.getAuthenticationDuration() > 0) {
370             statement.setSessionNotOnOrAfter(loginContext.getAuthenticationInstant().plus(
371                     loginContext.getAuthenticationDuration()));
372         }
373
374         // TODO
375         statement.setSubjectLocality(null);
376
377         return statement;
378     }
379
380     /**
381      * Creates an {@link AuthnContext} for a succesful authentication request.
382      * 
383      * @param requestContext current request
384      * 
385      * @return the built authn context
386      */
387     protected AuthnContext buildAuthnContext(SSORequestContext requestContext) {
388         AuthnContext authnContext = getAuthnContextBuilder().buildObject();
389
390         Saml2LoginContext loginContext = requestContext.getLoginContext();
391         AuthnRequest authnRequest = requestContext.getSamlRequest();
392         RequestedAuthnContext requestedAuthnContext = authnRequest.getRequestedAuthnContext();
393         if (requestedAuthnContext != null) {
394             if (requestedAuthnContext.getAuthnContextClassRefs() != null) {
395                 for (AuthnContextClassRef classRef : requestedAuthnContext.getAuthnContextClassRefs()) {
396                     if (classRef.getAuthnContextClassRef().equals(loginContext.getAuthenticationMethod())) {
397                         AuthnContextClassRef ref = getAuthnContextClassRefBuilder().buildObject();
398                         ref.setAuthnContextClassRef(loginContext.getAuthenticationMethod());
399                         authnContext.setAuthnContextClassRef(ref);
400                     }
401                 }
402             } else if (requestedAuthnContext.getAuthnContextDeclRefs() != null) {
403                 for (AuthnContextDeclRef declRef : requestedAuthnContext.getAuthnContextDeclRefs()) {
404                     if (declRef.getAuthnContextDeclRef().equals(loginContext.getAuthenticationMethod())) {
405                         AuthnContextDeclRef ref = getAuthnContextDeclRefBuilder().buildObject();
406                         ref.setAuthnContextDeclRef(loginContext.getAuthenticationMethod());
407                         authnContext.setAuthnContextDeclRef(ref);
408                     }
409                 }
410             }
411         } else {
412             AuthnContextDeclRef ref = getAuthnContextDeclRefBuilder().buildObject();
413             ref.setAuthnContextDeclRef(loginContext.getAuthenticationMethod());
414             authnContext.setAuthnContextDeclRef(ref);
415         }
416
417         return authnContext;
418     }
419
420     /**
421      * Encodes the request's SAML response and writes it to the servlet response.
422      * 
423      * @param requestContext current request context
424      * 
425      * @throws ProfileException thrown if no message encoder is registered for this profiles binding
426      */
427     protected void encodeResponse(SSORequestContext requestContext) throws ProfileException {
428         if (log.isDebugEnabled()) {
429             log.debug("Encoding response to SAML request " + requestContext.getSamlRequest().getID()
430                     + " from relying party " + requestContext.getRelyingPartyId());
431         }
432         AuthnResponseEndpointSelector endpointSelector = new AuthnResponseEndpointSelector();
433         endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
434         endpointSelector.setMetadataProvider(getMetadataProvider());
435         endpointSelector.setRelyingParty(requestContext.getRelyingPartyMetadata());
436         endpointSelector.setRelyingPartyRole(requestContext.getRelyingPartyRoleMetadata());
437         endpointSelector.setSamlRequest(requestContext.getSamlRequest());
438         endpointSelector.getSupportedIssuerBindings().addAll(getMessageEncoderFactory().getEncoderBuilders().keySet());
439         Endpoint relyingPartyEndpoint = endpointSelector.selectEndpoint();
440
441         MessageEncoder<ServletResponse> encoder = getMessageEncoderFactory().getMessageEncoder(
442                 relyingPartyEndpoint.getBinding());
443         if (encoder == null) {
444             log.error("No response encoder was registered for binding type: " + relyingPartyEndpoint.getBinding());
445             throw new ProfileException("No response encoder was registered for binding type: "
446                     + relyingPartyEndpoint.getBinding());
447         }
448
449         super.populateMessageEncoder(encoder);
450         encoder.setIssuer(requestContext.getAssertingPartyId());
451         encoder.setRelyingParty(requestContext.getRelyingPartyMetadata());
452         encoder.setRelyingPartyEndpoint(relyingPartyEndpoint);
453         encoder.setRelyingPartyRole(requestContext.getRelyingPartyRoleMetadata());
454         encoder.setResponse(requestContext.getProfileResponse().getRawResponse());
455         encoder.setSamlMessage(requestContext.getSamlResponse());
456         requestContext.setMessageEncoder(encoder);
457
458         try {
459             encoder.encode();
460         } catch (BindingException e) {
461             throw new ProfileException("Unable to encode response to relying party: "
462                     + requestContext.getRelyingPartyId(), e);
463         }
464     }
465
466     /** Represents the internal state of a SAML 2.0 SSO Request while it's being processed by the IdP. */
467     protected class SSORequestContext extends SAML2ProfileRequestContext<AuthnRequest, Response, SSOConfiguration> {
468
469         /** Current login context. */
470         private Saml2LoginContext loginContext;
471
472         /**
473          * Constructor.
474          * 
475          * @param request current profile request
476          * @param response current profile response
477          */
478         public SSORequestContext(ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response) {
479             super(request, response);
480         }
481
482         /**
483          * Gets the current login context.
484          * 
485          * @return current login context
486          */
487         public Saml2LoginContext getLoginContext() {
488             return loginContext;
489         }
490
491         /**
492          * Sets the current login context.
493          * 
494          * @param context current login context
495          */
496         public void setLoginContext(Saml2LoginContext context) {
497             loginContext = context;
498         }
499     }
500 }