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