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