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