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