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