Actually provide the SecurityPolicyResolver to the decoder
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / idp / profile / saml2 / SSOProfileHandler.java
1 /*
2  * Copyright [2007] [University Corporation for Advanced Internet Development, Inc.]
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package edu.internet2.middleware.shibboleth.idp.profile.saml2;
18
19 import java.io.IOException;
20 import java.util.ArrayList;
21
22 import javax.servlet.RequestDispatcher;
23 import javax.servlet.ServletException;
24 import javax.servlet.http.HttpServletRequest;
25 import javax.servlet.http.HttpSession;
26
27 import org.opensaml.common.SAMLObjectBuilder;
28 import org.opensaml.common.binding.decoding.SAMLMessageDecoder;
29 import org.opensaml.common.xml.SAMLConstants;
30 import org.opensaml.saml2.binding.AuthnResponseEndpointSelector;
31 import org.opensaml.saml2.core.AuthnContext;
32 import org.opensaml.saml2.core.AuthnContextClassRef;
33 import org.opensaml.saml2.core.AuthnContextDeclRef;
34 import org.opensaml.saml2.core.AuthnRequest;
35 import org.opensaml.saml2.core.AuthnStatement;
36 import org.opensaml.saml2.core.RequestedAuthnContext;
37 import org.opensaml.saml2.core.Response;
38 import org.opensaml.saml2.core.Statement;
39 import org.opensaml.saml2.core.StatusCode;
40 import org.opensaml.saml2.core.SubjectLocality;
41 import org.opensaml.saml2.metadata.AssertionConsumerService;
42 import org.opensaml.saml2.metadata.Endpoint;
43 import org.opensaml.saml2.metadata.EntityDescriptor;
44 import org.opensaml.saml2.metadata.IDPSSODescriptor;
45 import org.opensaml.saml2.metadata.SPSSODescriptor;
46 import org.opensaml.saml2.metadata.provider.MetadataProvider;
47 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
48 import org.opensaml.ws.message.decoder.MessageDecodingException;
49 import org.opensaml.ws.transport.http.HTTPInTransport;
50 import org.opensaml.ws.transport.http.HTTPOutTransport;
51 import org.opensaml.ws.transport.http.HttpServletRequestAdapter;
52 import org.opensaml.ws.transport.http.HttpServletResponseAdapter;
53 import org.opensaml.xml.io.MarshallingException;
54 import org.opensaml.xml.io.UnmarshallingException;
55 import org.opensaml.xml.security.SecurityException;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
60 import edu.internet2.middleware.shibboleth.common.relyingparty.ProfileConfiguration;
61 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
62 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.SSOConfiguration;
63 import edu.internet2.middleware.shibboleth.common.util.HttpHelper;
64 import edu.internet2.middleware.shibboleth.idp.authn.LoginContext;
65 import edu.internet2.middleware.shibboleth.idp.authn.Saml2LoginContext;
66
67 /** SAML 2.0 SSO request profile handler. */
68 public class SSOProfileHandler extends AbstractSAML2ProfileHandler {
69
70     /** Class logger. */
71     private final Logger log = LoggerFactory.getLogger(SSOProfileHandler.class);
72
73     /** Builder of AuthnStatement objects. */
74     private SAMLObjectBuilder<AuthnStatement> authnStatementBuilder;
75
76     /** Builder of AuthnContext objects. */
77     private SAMLObjectBuilder<AuthnContext> authnContextBuilder;
78
79     /** Builder of AuthnContextClassRef objects. */
80     private SAMLObjectBuilder<AuthnContextClassRef> authnContextClassRefBuilder;
81
82     /** Builder of AuthnContextDeclRef objects. */
83     private SAMLObjectBuilder<AuthnContextDeclRef> authnContextDeclRefBuilder;
84
85     /** Builder of SubjectLocality objects. */
86     private SAMLObjectBuilder<SubjectLocality> subjectLocalityBuilder;
87
88     /** URL of the authentication manager servlet. */
89     private String authenticationManagerPath;
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      */
99     @SuppressWarnings("unchecked")
100     public SSOProfileHandler(String authnManagerPath) {
101         super();
102
103         authenticationManagerPath = authnManagerPath;
104
105         authnStatementBuilder = (SAMLObjectBuilder<AuthnStatement>) getBuilderFactory().getBuilder(
106                 AuthnStatement.DEFAULT_ELEMENT_NAME);
107         authnContextBuilder = (SAMLObjectBuilder<AuthnContext>) getBuilderFactory().getBuilder(
108                 AuthnContext.DEFAULT_ELEMENT_NAME);
109         authnContextClassRefBuilder = (SAMLObjectBuilder<AuthnContextClassRef>) getBuilderFactory().getBuilder(
110                 AuthnContextClassRef.DEFAULT_ELEMENT_NAME);
111         authnContextDeclRefBuilder = (SAMLObjectBuilder<AuthnContextDeclRef>) getBuilderFactory().getBuilder(
112                 AuthnContextDeclRef.DEFAULT_ELEMENT_NAME);
113         subjectLocalityBuilder = (SAMLObjectBuilder<SubjectLocality>) getBuilderFactory().getBuilder(
114                 SubjectLocality.DEFAULT_ELEMENT_NAME);
115     }
116
117     /** {@inheritDoc} */
118     public String getProfileId() {
119         return "urn:mace:shibboleth:2.0:idp:profiles:saml2:request:sso";
120     }
121
122     /** {@inheritDoc} */
123     public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
124         HttpServletRequest servletRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
125         HttpSession httpSession = servletRequest.getSession(true);
126
127         if (httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY) == null) {
128             performAuthentication(inTransport, outTransport);
129         } else {
130             completeAuthenticationRequest(inTransport, outTransport);
131         }
132     }
133
134     /**
135      * Creates a {@link Saml2LoginContext} an sends the request off to the AuthenticationManager to begin the process of
136      * authenticating the user.
137      * 
138      * @param inTransport inbound request transport
139      * @param outTransport outbound response transport
140      * 
141      * @throws ProfileException thrown if there is a problem creating the login context and transferring control to the
142      *             authentication manager
143      */
144     protected void performAuthentication(HTTPInTransport inTransport, HTTPOutTransport outTransport)
145             throws ProfileException {
146         HttpServletRequest servletRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
147
148         try {
149             SSORequestContext requestContext = decodeRequest(inTransport, outTransport);
150
151             String relyingPartyId = requestContext.getInboundMessageIssuer();
152             RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
153             ProfileConfiguration ssoConfig = rpConfig.getProfileConfiguration(SSOConfiguration.PROFILE_ID);
154             if (ssoConfig == null) {
155                 log.error("SAML 2 SSO profile is not configured for relying party "
156                         + requestContext.getInboundMessageIssuer());
157                 throw new ProfileException("SAML 2 SSO profile is not configured for relying party "
158                         + requestContext.getInboundMessageIssuer());
159             }
160
161             log.debug("Creating login context and transferring control to authentication engine");
162             Saml2LoginContext loginContext = new Saml2LoginContext(relyingPartyId, requestContext.getRelayState(),
163                     requestContext.getInboundSAMLMessage());
164             loginContext.setAuthenticationEngineURL(authenticationManagerPath);
165             loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(servletRequest));
166             if (loginContext.getRequestedAuthenticationMethods().size() == 0) {
167                 loginContext.getRequestedAuthenticationMethods().add(rpConfig.getDefaultAuthenticationMethod());
168             }
169
170             HttpSession httpSession = servletRequest.getSession();
171             httpSession.setAttribute(Saml2LoginContext.LOGIN_CONTEXT_KEY, loginContext);
172             RequestDispatcher dispatcher = servletRequest.getRequestDispatcher(authenticationManagerPath);
173             dispatcher.forward(servletRequest, ((HttpServletResponseAdapter) outTransport).getWrappedResponse());
174         } catch (MarshallingException e) {
175             log.error("Unable to marshall authentication request context");
176             throw new ProfileException("Unable to marshall authentication request context", e);
177         } catch (IOException ex) {
178             log.error("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
179             throw new ProfileException("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
180         } catch (ServletException ex) {
181             log.error("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
182             throw new ProfileException("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
183         }
184     }
185
186     /**
187      * Creates a response to the {@link AuthnRequest} and sends the user, with response in tow, back to the relying
188      * party after they've been authenticated.
189      * 
190      * @param inTransport inbound message transport
191      * @param outTransport outbound message transport
192      * 
193      * @throws ProfileException thrown if the response can not be created and sent back to the relying party
194      */
195     protected void completeAuthenticationRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
196             throws ProfileException {
197         HttpServletRequest servletRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
198         HttpSession httpSession = servletRequest.getSession();
199
200         Saml2LoginContext loginContext = (Saml2LoginContext) httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
201         httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
202
203         SSORequestContext requestContext = buildRequestContext(loginContext, inTransport, outTransport);
204
205         checkSamlVersion(requestContext);
206
207         Response samlResponse;
208         try {
209             if (loginContext.getPrincipalName() == null) {
210                 log.error("User's login context did not contain a principal, user considered unauthenticiated.");
211                 requestContext
212                         .setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.AUTHN_FAILED_URI, null));
213                 throw new ProfileException("User failed authentication");
214             }
215
216             resolveAttributes(requestContext);
217
218             ArrayList<Statement> statements = new ArrayList<Statement>();
219             statements.add(buildAuthnStatement(requestContext));
220             if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
221                 requestContext.setRequestedAttributes(requestContext.getPrincipalAttributes().keySet());
222                 statements.add(buildAttributeStatement(requestContext));
223             }
224
225             samlResponse = buildResponse(requestContext, "urn:oasis:names:tc:SAML:2.0:cm:bearer", statements);
226         } catch (ProfileException e) {
227             samlResponse = buildErrorResponse(requestContext);
228         }
229
230         requestContext.setOutboundSAMLMessage(samlResponse);
231         requestContext.setOutboundSAMLMessageId(samlResponse.getID());
232         requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
233         encodeResponse(requestContext);
234         writeAuditLogEntry(requestContext);
235     }
236
237     /**
238      * Decodes an incoming request and stores the information in a created request context.
239      * 
240      * @param inTransport inbound transport
241      * @param outTransport outbound transport
242      * 
243      * @return request context with decoded information
244      * 
245      * @throws ProfileException thrown if the incomming message failed decoding
246      */
247     protected SSORequestContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
248             throws ProfileException {
249         log.debug("Decoding message with decoder binding {}", decodingBinding);
250
251         SSORequestContext requestContext = new SSORequestContext();
252         requestContext.setMetadataProvider(getMetadataProvider());
253         requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
254
255         requestContext.setCommunicationProfileId(SSOConfiguration.PROFILE_ID);
256         requestContext.setInboundMessageTransport(inTransport);
257         requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
258         requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
259
260         requestContext.setOutboundMessageTransport(outTransport);
261         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
262
263         try {
264             SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
265             requestContext.setMessageDecoder(decoder);
266             decoder.decode(requestContext);
267             return requestContext;
268         } catch (MessageDecodingException e) {
269             log.error("Error decoding authentication request message", e);
270             throw new ProfileException("Error decoding authentication request message", e);
271         } catch (SecurityException e) {
272             log.error("Message did not meet security requirements", e);
273             throw new ProfileException("Message did not meet security requirements", e);
274         }
275     }
276
277     /**
278      * Creates an authentication request context from the current environmental information.
279      * 
280      * @param loginContext current login context
281      * @param in inbound transport
282      * @param out outbount transport
283      * 
284      * @return created authentication request context
285      * 
286      * @throws ProfileException thrown if there is a problem creating the context
287      */
288     protected SSORequestContext buildRequestContext(Saml2LoginContext loginContext, HTTPInTransport in,
289             HTTPOutTransport out) throws ProfileException {
290         SSORequestContext requestContext = new SSORequestContext();
291
292         try {
293             requestContext.setMessageDecoder(getMessageDecoders().get(getInboundBinding()));
294
295             requestContext.setLoginContext(loginContext);
296             requestContext.setPrincipalName(loginContext.getPrincipalName());
297             requestContext.setPrincipalAuthenticationMethod(loginContext.getAuthenticationMethod());
298             requestContext.setUserSession(getUserSession(in));
299             requestContext.setRelayState(loginContext.getRelayState());
300
301             requestContext.setInboundMessageTransport(in);
302             requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
303             requestContext.setInboundMessage(loginContext.getAuthenticationRequest());
304             requestContext.setInboundSAMLMessage(loginContext.getAuthenticationRequest());
305             requestContext.setInboundSAMLMessageId(loginContext.getAuthenticationRequest().getID());
306
307             MetadataProvider metadataProvider = getMetadataProvider();
308             requestContext.setMetadataProvider(metadataProvider);
309
310             String relyingPartyId = loginContext.getRelyingPartyId();
311             requestContext.setInboundMessageIssuer(relyingPartyId);
312             EntityDescriptor relyingPartyMetadata = metadataProvider.getEntityDescriptor(relyingPartyId);
313             requestContext.setPeerEntityMetadata(relyingPartyMetadata);
314             requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
315             requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata.getSPSSODescriptor(SAMLConstants.SAML20P_NS));
316             RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
317             requestContext.setRelyingPartyConfiguration(rpConfig);
318             requestContext.setPeerEntityEndpoint(selectEndpoint(requestContext));
319
320             String assertingPartyId = rpConfig.getProviderId();
321             requestContext.setLocalEntityId(assertingPartyId);
322             EntityDescriptor assertingPartyMetadata = metadataProvider.getEntityDescriptor(assertingPartyId);
323             requestContext.setLocalEntityMetadata(assertingPartyMetadata);
324             requestContext.setLocalEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
325             requestContext.setLocalEntityRoleMetadata(assertingPartyMetadata
326                     .getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
327
328             requestContext.setOutboundMessageTransport(out);
329             requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
330             SSOConfiguration profileConfig = (SSOConfiguration) rpConfig
331                     .getProfileConfiguration(SSOConfiguration.PROFILE_ID);
332             requestContext.setProfileConfiguration(profileConfig);
333             requestContext.setOutboundMessageArtifactType(profileConfig.getOutboundArtifactType());
334             if (profileConfig.getSigningCredential() != null) {
335                 requestContext.setOutboundSAMLMessageSigningCredential(profileConfig.getSigningCredential());
336             } else if (rpConfig.getDefaultSigningCredential() != null) {
337                 requestContext.setOutboundSAMLMessageSigningCredential(rpConfig.getDefaultSigningCredential());
338             }
339
340             return requestContext;
341         } catch (UnmarshallingException e) {
342             log.error("Unable to unmarshall authentication request context");
343             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
344                     "Error recovering request state"));
345             throw new ProfileException("Error recovering request state", e);
346         } catch (MetadataProviderException e) {
347             log.error("Unable to locate metadata for asserting or relying party");
348             requestContext
349                     .setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error locating party metadata"));
350             throw new ProfileException("Error locating party metadata");
351         }
352     }
353
354     /**
355      * Creates an authentication statement for the current request.
356      * 
357      * @param requestContext current request context
358      * 
359      * @return constructed authentication statement
360      */
361     protected AuthnStatement buildAuthnStatement(SSORequestContext requestContext) {
362         Saml2LoginContext loginContext = requestContext.getLoginContext();
363
364         AuthnContext authnContext = buildAuthnContext(requestContext);
365
366         AuthnStatement statement = authnStatementBuilder.buildObject();
367         statement.setAuthnContext(authnContext);
368         statement.setAuthnInstant(loginContext.getAuthenticationInstant());
369
370         // TODO
371         statement.setSessionIndex(null);
372
373         if (loginContext.getAuthenticationDuration() > 0) {
374             statement.setSessionNotOnOrAfter(loginContext.getAuthenticationInstant().plus(
375                     loginContext.getAuthenticationDuration()));
376         }
377
378         statement.setSubjectLocality(buildSubjectLocality(requestContext));
379
380         return statement;
381     }
382
383     /**
384      * Creates an {@link AuthnContext} for a succesful authentication request.
385      * 
386      * @param requestContext current request
387      * 
388      * @return the built authn context
389      */
390     protected AuthnContext buildAuthnContext(SSORequestContext requestContext) {
391         AuthnContext authnContext = authnContextBuilder.buildObject();
392
393         Saml2LoginContext loginContext = requestContext.getLoginContext();
394         AuthnRequest authnRequest = requestContext.getInboundSAMLMessage();
395         RequestedAuthnContext requestedAuthnContext = authnRequest.getRequestedAuthnContext();
396         if (requestedAuthnContext != null) {
397             if (requestedAuthnContext.getAuthnContextClassRefs() != null) {
398                 for (AuthnContextClassRef classRef : requestedAuthnContext.getAuthnContextClassRefs()) {
399                     if (classRef.getAuthnContextClassRef().equals(loginContext.getAuthenticationMethod())) {
400                         AuthnContextClassRef ref = authnContextClassRefBuilder.buildObject();
401                         ref.setAuthnContextClassRef(loginContext.getAuthenticationMethod());
402                         authnContext.setAuthnContextClassRef(ref);
403                     }
404                 }
405             } else if (requestedAuthnContext.getAuthnContextDeclRefs() != null) {
406                 for (AuthnContextDeclRef declRef : requestedAuthnContext.getAuthnContextDeclRefs()) {
407                     if (declRef.getAuthnContextDeclRef().equals(loginContext.getAuthenticationMethod())) {
408                         AuthnContextDeclRef ref = authnContextDeclRefBuilder.buildObject();
409                         ref.setAuthnContextDeclRef(loginContext.getAuthenticationMethod());
410                         authnContext.setAuthnContextDeclRef(ref);
411                     }
412                 }
413             }
414         } else {
415             AuthnContextDeclRef ref = authnContextDeclRefBuilder.buildObject();
416             ref.setAuthnContextDeclRef(loginContext.getAuthenticationMethod());
417             authnContext.setAuthnContextDeclRef(ref);
418         }
419
420         return authnContext;
421     }
422
423     /**
424      * Constructs the subject locality for the authentication statement.
425      * 
426      * @param requestContext curent request context
427      * 
428      * @return subject locality for the authentication statement
429      */
430     protected SubjectLocality buildSubjectLocality(SSORequestContext requestContext) {
431         HTTPInTransport transport = (HTTPInTransport) requestContext.getInboundMessageTransport();
432         SubjectLocality subjectLocality = subjectLocalityBuilder.buildObject();
433         subjectLocality.setAddress(transport.getPeerAddress());
434         subjectLocality.setDNSName(transport.getPeerDomainName());
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      * @return Endpoint selected from the information provided in the request context
445      */
446     protected Endpoint selectEndpoint(SSORequestContext requestContext) {
447         AuthnResponseEndpointSelector endpointSelector = new AuthnResponseEndpointSelector();
448         endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
449         endpointSelector.setMetadataProvider(getMetadataProvider());
450         endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
451         endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
452         endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
453         endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
454         return endpointSelector.selectEndpoint();
455     }
456
457     /** Represents the internal state of a SAML 2.0 SSO Request while it's being processed by the IdP. */
458     protected class SSORequestContext extends BaseSAML2ProfileRequestContext<AuthnRequest, Response, SSOConfiguration> {
459
460         /** Current login context. */
461         private Saml2LoginContext loginContext;
462
463         /**
464          * Gets the current login context.
465          * 
466          * @return current login context
467          */
468         public Saml2LoginContext getLoginContext() {
469             return loginContext;
470         }
471
472         /**
473          * Sets the current login context.
474          * 
475          * @param context current login context
476          */
477         public void setLoginContext(Saml2LoginContext context) {
478             loginContext = context;
479         }
480     }
481 }