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