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