Clean up AuthN state better in the event of a failure
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / idp / profile / saml1 / ShibbolethSSOProfileHandler.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.saml1;
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.HttpServletResponse;
26 import javax.servlet.http.HttpSession;
27
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.saml1.core.AuthenticationStatement;
32 import org.opensaml.saml1.core.Request;
33 import org.opensaml.saml1.core.Response;
34 import org.opensaml.saml1.core.Statement;
35 import org.opensaml.saml1.core.StatusCode;
36 import org.opensaml.saml1.core.Subject;
37 import org.opensaml.saml1.core.SubjectLocality;
38 import org.opensaml.saml2.metadata.AssertionConsumerService;
39 import org.opensaml.saml2.metadata.Endpoint;
40 import org.opensaml.saml2.metadata.EntityDescriptor;
41 import org.opensaml.saml2.metadata.IDPSSODescriptor;
42 import org.opensaml.saml2.metadata.SPSSODescriptor;
43 import org.opensaml.saml2.metadata.provider.MetadataProvider;
44 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
45 import org.opensaml.ws.message.decoder.MessageDecodingException;
46 import org.opensaml.ws.transport.http.HTTPInTransport;
47 import org.opensaml.ws.transport.http.HTTPOutTransport;
48 import org.opensaml.ws.transport.http.HttpServletRequestAdapter;
49 import org.opensaml.ws.transport.http.HttpServletResponseAdapter;
50 import org.opensaml.xml.security.SecurityException;
51 import org.opensaml.xml.util.DatatypeHelper;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54
55 import edu.internet2.middleware.shibboleth.common.ShibbolethConstants;
56 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
57 import edu.internet2.middleware.shibboleth.common.relyingparty.ProfileConfiguration;
58 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
59 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml1.ShibbolethSSOConfiguration;
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.ShibbolethSSOLoginContext;
63
64 /** Shibboleth SSO request profile handler. */
65 public class ShibbolethSSOProfileHandler extends AbstractSAML1ProfileHandler {
66
67     /** Class logger. */
68     private final Logger log = LoggerFactory.getLogger(ShibbolethSSOProfileHandler.class);
69
70     /** Builder of AuthenticationStatement objects. */
71     private SAMLObjectBuilder<AuthenticationStatement> authnStatementBuilder;
72
73     /** Builder of SubjectLocality objects. */
74     private SAMLObjectBuilder<SubjectLocality> subjectLocalityBuilder;
75
76     /** URL of the authentication manager servlet. */
77     private String authenticationManagerPath;
78
79     /**
80      * Constructor.
81      * 
82      * @param authnManagerPath path to the authentication manager servlet
83      * 
84      * @throws IllegalArgumentException thrown if either the authentication manager path or encoding binding URI are
85      *             null or empty
86      */
87     public ShibbolethSSOProfileHandler(String authnManagerPath) {
88         if (DatatypeHelper.isEmpty(authnManagerPath)) {
89             throw new IllegalArgumentException("Authentication manager path may not be null");
90         }
91         authenticationManagerPath = authnManagerPath;
92
93         authnStatementBuilder = (SAMLObjectBuilder<AuthenticationStatement>) getBuilderFactory().getBuilder(
94                 AuthenticationStatement.DEFAULT_ELEMENT_NAME);
95
96         subjectLocalityBuilder = (SAMLObjectBuilder<SubjectLocality>) getBuilderFactory().getBuilder(
97                 SubjectLocality.DEFAULT_ELEMENT_NAME);
98     }
99
100     /** {@inheritDoc} */
101     public String getProfileId() {
102         return "urn:mace:shibboleth:2.0:idp:profiles:shibboleth:request:sso";
103     }
104
105     /** {@inheritDoc} */
106     public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
107         log.debug("Processing incomming request");
108
109         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
110         HttpSession httpSession = httpRequest.getSession();
111         LoginContext loginContext = (LoginContext) httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
112
113         if (loginContext == null) {
114             log.debug("User session does not contain a login context, processing as first leg of request");
115             performAuthentication(inTransport, outTransport);
116         }else if (!loginContext.isPrincipalAuthenticated()){
117             log.debug("User session contained a login context but user was not authenticated, processing as first leg of request");
118             performAuthentication(inTransport, outTransport);
119         } else {
120             log.debug("User session contains a login context, processing as second leg of request");
121             completeAuthenticationRequest(inTransport, outTransport);
122         }
123     }
124
125     /**
126      * Creates a {@link LoginContext} an sends the request off to the AuthenticationManager to begin the process of
127      * authenticating the user.
128      * 
129      * @param inTransport inbound message transport
130      * @param outTransport outbound message transport
131      * 
132      * @throws ProfileException thrown if there is a problem creating the login context and transferring control to the
133      *             authentication manager
134      */
135     protected void performAuthentication(HTTPInTransport inTransport, HTTPOutTransport outTransport)
136             throws ProfileException {
137
138         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
139         HttpServletResponse httpResponse = ((HttpServletResponseAdapter) outTransport).getWrappedResponse();
140         HttpSession httpSession = httpRequest.getSession(true);
141
142         ShibbolethSSORequestContext requestContext = decodeRequest(inTransport, outTransport);
143         ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
144
145         RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(loginContext.getRelyingPartyId());
146         ProfileConfiguration ssoConfig = rpConfig.getProfileConfiguration(ShibbolethSSOConfiguration.PROFILE_ID);
147         if (ssoConfig == null) {
148             log.error("Shibboleth SSO profile is not configured for relying party " + loginContext.getRelyingPartyId());
149             throw new ProfileException("Shibboleth SSO profile is not configured for relying party "
150                     + loginContext.getRelyingPartyId());
151         }
152         loginContext.getRequestedAuthenticationMethods().add(rpConfig.getDefaultAuthenticationMethod());
153
154         httpSession.setAttribute(LoginContext.LOGIN_CONTEXT_KEY, loginContext);
155
156         try {
157             RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(authenticationManagerPath);
158             dispatcher.forward(httpRequest, httpResponse);
159             return;
160         } catch (IOException ex) {
161             httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
162             log.error("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
163             throw new ProfileException("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
164         } catch (ServletException ex) {
165             httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
166             log.error("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
167             throw new ProfileException("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
168         }
169     }
170
171     /**
172      * Decodes an incoming request and populates a created request context with the resultant information.
173      * 
174      * @param inTransport inbound message transport
175      * @param outTransport outbound message transport
176      * 
177      * @return the created request context
178      * 
179      * @throws ProfileException throw if there is a problem decoding the request
180      */
181     protected ShibbolethSSORequestContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
182             throws ProfileException {
183         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
184
185         ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext();
186         requestContext.setMetadataProvider(getMetadataProvider());
187         requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
188
189         requestContext.setCommunicationProfileId(ShibbolethSSOConfiguration.PROFILE_ID);
190         requestContext.setInboundMessageTransport(inTransport);
191         requestContext.setInboundSAMLProtocol(ShibbolethConstants.SHIB_SSO_PROFILE_URI);
192         requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
193
194         requestContext.setOutboundMessageTransport(outTransport);
195         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML11P_NS);
196
197         SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
198         requestContext.setMessageDecoder(decoder);
199         try {
200             decoder.decode(requestContext);
201         } catch (MessageDecodingException e) {
202             log.error("Error decoding Shibboleth SSO request", e);
203             throw new ProfileException("Error decoding Shibboleth SSO request", e);
204         } catch (SecurityException e) {
205             log.error("Shibboleth SSO request does not meet security requirements", e);
206             throw new ProfileException("Shibboleth SSO request does not meet security requirements", e);
207         }
208
209         ShibbolethSSOLoginContext loginContext = new ShibbolethSSOLoginContext();
210         loginContext.setRelyingParty(requestContext.getInboundMessageIssuer());
211         loginContext.setSpAssertionConsumerService(requestContext.getSpAssertionConsumerService());
212         loginContext.setSpTarget(requestContext.getRelayState());
213         loginContext.setAuthenticationEngineURL(authenticationManagerPath);
214         loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(httpRequest));
215
216         requestContext.setLoginContext(loginContext);
217
218         return requestContext;
219     }
220
221     /**
222      * Creates a response to the Shibboleth SSO and sends the user, with response in tow, back to the relying party
223      * after they've been authenticated.
224      * 
225      * @param inTransport inbound message transport
226      * @param outTransport outbound message transport
227      * 
228      * @throws ProfileException thrown if the response can not be created and sent back to the relying party
229      */
230     protected void completeAuthenticationRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
231             throws ProfileException {
232         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
233         HttpSession httpSession = httpRequest.getSession(true);
234
235         ShibbolethSSOLoginContext loginContext = (ShibbolethSSOLoginContext) httpSession
236                 .getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
237         httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
238
239         ShibbolethSSORequestContext requestContext = buildRequestContext(loginContext, inTransport, outTransport);
240
241         Response samlResponse;
242         try {
243             if (loginContext.getPrincipalName() == null) {
244                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "User failed authentication"));
245                 throw new ProfileException("User failed authentication");
246             }
247
248             resolveAttributes(requestContext);
249
250             ArrayList<Statement> statements = new ArrayList<Statement>();
251             statements.add(buildAuthenticationStatement(requestContext));
252             if (requestContext.getProfileConfiguration().includeAttributeStatement()
253                     && !requestContext.getPrincipalAttributes().isEmpty()) {
254                 requestContext.setRequestedAttributes(requestContext.getPrincipalAttributes().keySet());
255                 statements.add(buildAttributeStatement(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:bearer"));
256             }
257
258             samlResponse = buildResponse(requestContext, statements);
259         } catch (ProfileException e) {
260             samlResponse = buildErrorResponse(requestContext);
261         }
262
263         requestContext.setOutboundSAMLMessage(samlResponse);
264         requestContext.setOutboundSAMLMessageId(samlResponse.getID());
265         requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
266         encodeResponse(requestContext);
267         writeAuditLogEntry(requestContext);
268     }
269
270     /**
271      * Creates an authentication request context from the current environmental information.
272      * 
273      * @param loginContext current login context
274      * @param in inbound transport
275      * @param out outbount transport
276      * 
277      * @return created authentication request context
278      * 
279      * @throws ProfileException thrown if there is a problem creating the context
280      */
281     protected ShibbolethSSORequestContext buildRequestContext(ShibbolethSSOLoginContext loginContext,
282             HTTPInTransport in, HTTPOutTransport out) throws ProfileException {
283         ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext();
284
285         requestContext.setMessageDecoder(getMessageDecoders().get(getInboundBinding()));
286
287         requestContext.setLoginContext(loginContext);
288         requestContext.setPrincipalName(loginContext.getPrincipalName());
289         requestContext.setPrincipalAuthenticationMethod(loginContext.getAuthenticationMethod());
290         requestContext.setUserSession(getUserSession(in));
291         requestContext.setRelayState(loginContext.getSpTarget());
292
293         requestContext.setInboundMessageTransport(in);
294         requestContext.setInboundSAMLProtocol(ShibbolethConstants.SHIB_SSO_PROFILE_URI);
295
296         requestContext.setOutboundMessageTransport(out);
297         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
298
299         MetadataProvider metadataProvider = getMetadataProvider();
300         requestContext.setMetadataProvider(metadataProvider);
301
302         String relyingPartyId = loginContext.getRelyingPartyId();
303         requestContext.setInboundMessageIssuer(relyingPartyId);
304
305         try {
306             EntityDescriptor relyingPartyMetadata = metadataProvider.getEntityDescriptor(relyingPartyId);
307             if (relyingPartyMetadata != null) {
308                 requestContext.setPeerEntityMetadata(relyingPartyMetadata);
309                 requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
310                 requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata
311                         .getSPSSODescriptor(SAMLConstants.SAML11P_NS));
312             }
313         } catch (MetadataProviderException e) {
314             log.error("Unable to locate metadata for relying party");
315             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
316                     "Error locating relying party metadata"));
317             throw new ProfileException("Error locating relying party metadata");
318         }
319
320         RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
321         if (rpConfig == null) {
322             log.error("Unable to retrieve relying party configuration data for entity with ID {}", relyingPartyId);
323             throw new ProfileException("Unable to retrieve relying party configuration data for entity with ID "
324                     + relyingPartyId);
325         }
326         requestContext.setRelyingPartyConfiguration(rpConfig);
327
328         ShibbolethSSOConfiguration profileConfig = (ShibbolethSSOConfiguration) rpConfig
329                 .getProfileConfiguration(ShibbolethSSOConfiguration.PROFILE_ID);
330         requestContext.setProfileConfiguration(profileConfig);
331         requestContext.setOutboundMessageArtifactType(profileConfig.getOutboundArtifactType());
332         if (profileConfig.getSigningCredential() != null) {
333             requestContext.setOutboundSAMLMessageSigningCredential(profileConfig.getSigningCredential());
334         } else if (rpConfig.getDefaultSigningCredential() != null) {
335             requestContext.setOutboundSAMLMessageSigningCredential(rpConfig.getDefaultSigningCredential());
336         }
337
338         requestContext.setPeerEntityEndpoint(selectEndpoint(requestContext));
339
340         String assertingPartyId = rpConfig.getProviderId();
341         requestContext.setLocalEntityId(assertingPartyId);
342         try {
343             EntityDescriptor localEntityDescriptor = metadataProvider.getEntityDescriptor(assertingPartyId);
344             if (localEntityDescriptor != null) {
345                 requestContext.setLocalEntityMetadata(localEntityDescriptor);
346                 requestContext.setLocalEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
347                 requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
348                         .getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
349             }
350         } catch (MetadataProviderException e) {
351             log.error("Unable to locate metadata for asserting party");
352             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
353                     "Error locating asserting party metadata"));
354             throw new ProfileException("Error locating asserting party metadata");
355         }
356
357         return requestContext;
358     }
359
360     /**
361      * Selects the appropriate endpoint for the relying party and stores it in the request context.
362      * 
363      * @param requestContext current request context
364      * 
365      * @return Endpoint selected from the information provided in the request context
366      */
367     protected Endpoint selectEndpoint(ShibbolethSSORequestContext requestContext) {
368         ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
369
370         ShibbolethSSOEndpointSelector endpointSelector = new ShibbolethSSOEndpointSelector();
371         endpointSelector.setSpAssertionConsumerService(loginContext.getSpAssertionConsumerService());
372         endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
373         endpointSelector.setMetadataProvider(getMetadataProvider());
374         endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
375         endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
376         endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
377         endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
378
379         return endpointSelector.selectEndpoint();
380     }
381
382     /**
383      * Builds the authentication statement for the authenticated principal.
384      * 
385      * @param requestContext current request context
386      * 
387      * @return the created statement
388      * 
389      * @throws ProfileException thrown if the authentication statement can not be created
390      */
391     protected AuthenticationStatement buildAuthenticationStatement(ShibbolethSSORequestContext requestContext)
392             throws ProfileException {
393         ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
394
395         AuthenticationStatement statement = authnStatementBuilder.buildObject();
396         statement.setAuthenticationInstant(loginContext.getAuthenticationInstant());
397         statement.setAuthenticationMethod(loginContext.getAuthenticationMethod());
398
399         statement.setSubjectLocality(buildSubjectLocality(requestContext));
400
401         Subject statementSubject = buildSubject(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:bearer");
402         statement.setSubject(statementSubject);
403
404         return statement;
405     }
406
407     /**
408      * Constructs the subject locality for the authentication statement.
409      * 
410      * @param requestContext curent request context
411      * 
412      * @return subject locality for the authentication statement
413      */
414     protected SubjectLocality buildSubjectLocality(ShibbolethSSORequestContext requestContext) {
415         SubjectLocality subjectLocality = subjectLocalityBuilder.buildObject();
416
417         HTTPInTransport inTransport = (HTTPInTransport) requestContext.getInboundMessageTransport();
418         subjectLocality.setIPAddress(inTransport.getPeerAddress());
419         subjectLocality.setDNSAddress(inTransport.getPeerDomainName());
420
421         return subjectLocality;
422     }
423
424     /** Represents the internal state of a Shibboleth SSO Request while it's being processed by the IdP. */
425     public class ShibbolethSSORequestContext extends
426             BaseSAML1ProfileRequestContext<Request, Response, ShibbolethSSOConfiguration> {
427
428         /** SP-provide assertion consumer service URL. */
429         private String spAssertionConsumerService;
430
431         /** Current login context. */
432         private ShibbolethSSOLoginContext loginContext;
433
434         /**
435          * Gets the current login context.
436          * 
437          * @return current login context
438          */
439         public ShibbolethSSOLoginContext getLoginContext() {
440             return loginContext;
441         }
442
443         /**
444          * Sets the current login context.
445          * 
446          * @param context current login context
447          */
448         public void setLoginContext(ShibbolethSSOLoginContext context) {
449             loginContext = context;
450         }
451
452         /**
453          * Gets the SP-provided assertion consumer service URL.
454          * 
455          * @return SP-provided assertion consumer service URL
456          */
457         public String getSpAssertionConsumerService() {
458             return spAssertionConsumerService;
459         }
460
461         /**
462          * Sets the SP-provided assertion consumer service URL.
463          * 
464          * @param acs SP-provided assertion consumer service URL
465          */
466         public void setSpAssertionConsumerService(String acs) {
467             spAssertionConsumerService = acs;
468         }
469     }
470 }