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