Shibboleth SSO profile handler sets incorrect protocol string in outbound message...
[java-idp.git] / src / main / java / 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.ServletContext;
23 import javax.servlet.http.HttpServletRequest;
24 import javax.servlet.http.HttpServletResponse;
25
26 import org.opensaml.common.SAMLObjectBuilder;
27 import org.opensaml.common.binding.decoding.SAMLMessageDecoder;
28 import org.opensaml.common.xml.SAMLConstants;
29 import org.opensaml.saml1.core.AttributeStatement;
30 import org.opensaml.saml1.core.AuthenticationStatement;
31 import org.opensaml.saml1.core.Request;
32 import org.opensaml.saml1.core.Response;
33 import org.opensaml.saml1.core.Statement;
34 import org.opensaml.saml1.core.StatusCode;
35 import org.opensaml.saml1.core.Subject;
36 import org.opensaml.saml1.core.SubjectLocality;
37 import org.opensaml.saml2.metadata.AssertionConsumerService;
38 import org.opensaml.saml2.metadata.Endpoint;
39 import org.opensaml.saml2.metadata.EntityDescriptor;
40 import org.opensaml.saml2.metadata.IDPSSODescriptor;
41 import org.opensaml.saml2.metadata.SPSSODescriptor;
42 import org.opensaml.util.URLBuilder;
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.SAMLMDRelyingPartyConfigurationManager;
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.ShibbolethSSOLoginContext;
62 import edu.internet2.middleware.shibboleth.idp.util.HttpServletHelper;
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     /** Builder of Endpoint objects. */
77     private SAMLObjectBuilder<Endpoint> endpointBuilder;
78
79     /** URL of the authentication manager servlet. */
80     private String authenticationManagerPath;
81
82     /**
83      * Constructor.
84      * 
85      * @param authnManagerPath path to the authentication manager servlet
86      */
87     public ShibbolethSSOProfileHandler(String authnManagerPath) {
88         if (DatatypeHelper.isEmpty(authnManagerPath)) {
89             throw new IllegalArgumentException("Authentication manager path may not be null");
90         }
91         if (authnManagerPath.startsWith("/")) {
92             authenticationManagerPath = authnManagerPath;
93         } else {
94             authenticationManagerPath = "/" + authnManagerPath;
95         }
96
97         authnStatementBuilder = (SAMLObjectBuilder<AuthenticationStatement>) getBuilderFactory().getBuilder(
98                 AuthenticationStatement.DEFAULT_ELEMENT_NAME);
99
100         subjectLocalityBuilder = (SAMLObjectBuilder<SubjectLocality>) getBuilderFactory().getBuilder(
101                 SubjectLocality.DEFAULT_ELEMENT_NAME);
102
103         endpointBuilder = (SAMLObjectBuilder<Endpoint>) getBuilderFactory().getBuilder(
104                 AssertionConsumerService.DEFAULT_ELEMENT_NAME);
105     }
106
107     /** {@inheritDoc} */
108     public String getProfileId() {
109         return ShibbolethSSOConfiguration.PROFILE_ID;
110     }
111
112     /** {@inheritDoc} */
113     public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
114         log.debug("Processing incoming request");
115
116         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
117         HttpServletResponse httpResponse = ((HttpServletResponseAdapter) outTransport).getWrappedResponse();
118         ServletContext servletContext = httpRequest.getSession().getServletContext();
119
120         ShibbolethSSOLoginContext loginContext = (ShibbolethSSOLoginContext) HttpServletHelper.getLoginContext(
121                 getStorageService(), servletContext, httpRequest);
122
123         if (loginContext == null) {
124             log.debug("Incoming request does not contain a login context, processing as first leg of request");
125             performAuthentication(inTransport, outTransport);
126         } else {
127             log.debug("Incoming request contains a login context, processing as second leg of request");
128             HttpServletHelper.unbindLoginContext(getStorageService(), servletContext, httpRequest, httpResponse);
129             completeAuthenticationRequest(loginContext, inTransport, outTransport);
130         }
131     }
132
133     /**
134      * Creates a {@link ShibbolethSSOLoginContext} an sends the request off to the AuthenticationManager to begin the
135      * process of authenticating the user.
136      * 
137      * @param inTransport inbound message transport
138      * @param outTransport outbound message 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
146         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
147         HttpServletResponse httpResponse = ((HttpServletResponseAdapter) outTransport).getWrappedResponse();
148         ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext();
149
150         decodeRequest(requestContext, inTransport, outTransport);
151         ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
152
153         RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(loginContext.getRelyingPartyId());
154         loginContext.setDefaultAuthenticationMethod(rpConfig.getDefaultAuthenticationMethod());
155         ProfileConfiguration ssoConfig = rpConfig.getProfileConfiguration(ShibbolethSSOConfiguration.PROFILE_ID);
156         if (ssoConfig == null) {
157             String msg = "Shibboleth SSO profile is not configured for relying party "
158                     + loginContext.getRelyingPartyId();
159             log.warn(msg);
160             throw new ProfileException(msg);
161         }
162
163         HttpServletHelper.bindLoginContext(loginContext, getStorageService(), httpRequest.getSession()
164                 .getServletContext(), httpRequest, httpResponse);
165
166         try {
167             URLBuilder urlBuilder = HttpServletHelper.getServletContextUrl(httpRequest);
168             urlBuilder.setPath(urlBuilder.getPath() + authenticationManagerPath);
169             String authnEngineUrl = urlBuilder.buildURL();
170             log.debug("Redirecting user to authentication engine at {}", authnEngineUrl);
171             httpResponse.sendRedirect(authnEngineUrl);
172         } catch (IOException e) {
173             String msg = "Error forwarding Shibboleth SSO request to AuthenticationManager";
174             log.error(msg, e);
175             throw new ProfileException(msg, e);
176         }
177     }
178
179     /**
180      * Decodes an incoming request and populates a created request context with the resultant information.
181      * 
182      * @param inTransport inbound message transport
183      * @param outTransport outbound message transport
184      * @param requestContext the request context to which decoded information should be added
185      * 
186      * @throws ProfileException throw if there is a problem decoding the request
187      */
188     protected void decodeRequest(ShibbolethSSORequestContext requestContext, HTTPInTransport inTransport,
189             HTTPOutTransport outTransport) throws ProfileException {
190         if (log.isDebugEnabled()) {
191             log.debug("Decoding message with decoder binding {}", getInboundMessageDecoder(requestContext)
192                     .getBindingURI());
193         }
194
195         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
196
197         requestContext.setCommunicationProfileId(getProfileId());
198
199         requestContext.setMetadataProvider(getMetadataProvider());
200         requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
201
202         requestContext.setCommunicationProfileId(ShibbolethSSOConfiguration.PROFILE_ID);
203         requestContext.setInboundMessageTransport(inTransport);
204         requestContext.setInboundSAMLProtocol(ShibbolethConstants.SHIB_SSO_PROFILE_URI);
205         requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
206
207         requestContext.setOutboundMessageTransport(outTransport);
208         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML11P_NS);
209
210         SAMLMessageDecoder decoder = getInboundMessageDecoder(requestContext);
211         requestContext.setMessageDecoder(decoder);
212         try {
213             decoder.decode(requestContext);
214             log.debug("Decoded Shibboleth SSO request from relying party '{}'", requestContext
215                     .getInboundMessageIssuer());
216         } catch (MessageDecodingException e) {
217             String msg = "Error decoding Shibboleth SSO request";
218             log.warn(msg, e);
219             throw new ProfileException(msg, e);
220         } catch (SecurityException e) {
221             String msg = "Shibboleth SSO request does not meet security requirements: " + e.getMessage();
222             log.warn(msg);
223             throw new ProfileException(msg, e);
224         }
225
226         ShibbolethSSOLoginContext loginContext = new ShibbolethSSOLoginContext();
227         loginContext.setRelyingParty(requestContext.getInboundMessageIssuer());
228         loginContext.setSpAssertionConsumerService(requestContext.getSpAssertionConsumerService());
229         loginContext.setSpTarget(requestContext.getRelayState());
230         loginContext.setAuthenticationEngineURL(authenticationManagerPath);
231         loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(httpRequest));
232         requestContext.setLoginContext(loginContext);
233     }
234
235     /**
236      * Creates a response to the Shibboleth SSO and sends the user, with response in tow, back to the relying party
237      * after they've been authenticated.
238      * 
239      * @param loginContext login context for this request
240      * @param inTransport inbound message transport
241      * @param outTransport outbound message transport
242      * 
243      * @throws ProfileException thrown if the response can not be created and sent back to the relying party
244      */
245     protected void completeAuthenticationRequest(ShibbolethSSOLoginContext loginContext, HTTPInTransport inTransport,
246             HTTPOutTransport outTransport) throws ProfileException {
247         ShibbolethSSORequestContext requestContext = buildRequestContext(loginContext, inTransport, outTransport);
248
249         Response samlResponse;
250         try {
251             if (loginContext.getAuthenticationFailure() != null) {
252                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "User failed authentication"));
253                 throw new ProfileException("Authentication failure", loginContext.getAuthenticationFailure());
254             }
255
256             resolveAttributes(requestContext);
257
258             ArrayList<Statement> statements = new ArrayList<Statement>();
259             statements.add(buildAuthenticationStatement(requestContext));
260             if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
261                 AttributeStatement attributeStatement = buildAttributeStatement(requestContext,
262                         "urn:oasis:names:tc:SAML:1.0:cm:bearer");
263                 if (attributeStatement != null) {
264                     requestContext.setReleasedAttributes(requestContext.getAttributes().keySet());
265                     statements.add(attributeStatement);
266                 }
267             }
268
269             samlResponse = buildResponse(requestContext, statements);
270         } catch (ProfileException e) {
271             samlResponse = buildErrorResponse(requestContext);
272         }
273
274         requestContext.setOutboundSAMLMessage(samlResponse);
275         requestContext.setOutboundSAMLMessageId(samlResponse.getID());
276         requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
277         encodeResponse(requestContext);
278         writeAuditLogEntry(requestContext);
279     }
280
281     /**
282      * Creates an authentication request context from the current environmental information.
283      * 
284      * @param loginContext current login context
285      * @param in inbound transport
286      * @param out outbount transport
287      * 
288      * @return created authentication request context
289      * 
290      * @throws ProfileException thrown if there is a problem creating the context
291      */
292     protected ShibbolethSSORequestContext buildRequestContext(ShibbolethSSOLoginContext loginContext,
293             HTTPInTransport in, HTTPOutTransport out) throws ProfileException {
294         ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext();
295         requestContext.setCommunicationProfileId(getProfileId());
296
297         requestContext.setMessageDecoder(getInboundMessageDecoder(requestContext));
298
299         requestContext.setLoginContext(loginContext);
300         requestContext.setRelayState(loginContext.getSpTarget());
301
302         requestContext.setInboundMessageTransport(in);
303         requestContext.setInboundSAMLProtocol(ShibbolethConstants.SHIB_SSO_PROFILE_URI);
304
305         requestContext.setOutboundMessageTransport(out);
306         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML11P_NS);
307
308         requestContext.setMetadataProvider(getMetadataProvider());
309
310         String relyingPartyId = loginContext.getRelyingPartyId();
311         requestContext.setPeerEntityId(relyingPartyId);
312         requestContext.setInboundMessageIssuer(relyingPartyId);
313
314         populateRequestContext(requestContext);
315
316         return requestContext;
317     }
318
319     /** {@inheritDoc} */
320     protected void populateRelyingPartyInformation(BaseSAMLProfileRequestContext requestContext)
321             throws ProfileException {
322         super.populateRelyingPartyInformation(requestContext);
323
324         EntityDescriptor relyingPartyMetadata = requestContext.getPeerEntityMetadata();
325         if (relyingPartyMetadata != null) {
326             requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
327             requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata.getSPSSODescriptor(SAMLConstants.SAML11P_NS));
328         }
329     }
330
331     /** {@inheritDoc} */
332     protected void populateAssertingPartyInformation(BaseSAMLProfileRequestContext requestContext)
333             throws ProfileException {
334         super.populateAssertingPartyInformation(requestContext);
335
336         EntityDescriptor localEntityDescriptor = requestContext.getLocalEntityMetadata();
337         if (localEntityDescriptor != null) {
338             requestContext.setLocalEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
339             requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
340                     .getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
341         }
342     }
343
344     /** {@inheritDoc} */
345     protected void populateSAMLMessageInformation(BaseSAMLProfileRequestContext requestContext) throws ProfileException {
346         // nothing to do here
347     }
348
349     /**
350      * Selects the appropriate endpoint for the relying party and stores it in the request context.
351      * 
352      * @param requestContext current request context
353      * 
354      * @return Endpoint selected from the information provided in the request context
355      */
356     protected Endpoint selectEndpoint(BaseSAMLProfileRequestContext requestContext) {
357         ShibbolethSSOLoginContext loginContext = ((ShibbolethSSORequestContext) requestContext).getLoginContext();
358
359         Endpoint endpoint = null;
360         if (requestContext.getRelyingPartyConfiguration().getRelyingPartyId() == SAMLMDRelyingPartyConfigurationManager.ANONYMOUS_RP_NAME) {
361             if (loginContext.getSpAssertionConsumerService() != null) {
362                 endpoint = endpointBuilder.buildObject();
363                 endpoint.setLocation(loginContext.getSpAssertionConsumerService());
364                 endpoint.setBinding(getSupportedOutboundBindings().get(0));
365                 log.warn("Generating endpoint for anonymous relying party. ACS url {} and binding {}", new Object[] {
366                         requestContext.getInboundMessageIssuer(), endpoint.getLocation(), endpoint.getBinding(), });
367             } else {
368                 log.warn("Unable to generate endpoint for anonymous party.  No ACS url provided.");
369             }
370         } else {
371             ShibbolethSSOEndpointSelector endpointSelector = new ShibbolethSSOEndpointSelector();
372             endpointSelector.setSpAssertionConsumerService(loginContext.getSpAssertionConsumerService());
373             endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
374             endpointSelector.setMetadataProvider(getMetadataProvider());
375             endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
376             endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
377             endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
378             endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
379             endpoint = endpointSelector.selectEndpoint();
380         }
381
382         return endpoint;
383     }
384
385     /**
386      * Builds the authentication statement for the authenticated principal.
387      * 
388      * @param requestContext current request context
389      * 
390      * @return the created statement
391      * 
392      * @throws ProfileException thrown if the authentication statement can not be created
393      */
394     protected AuthenticationStatement buildAuthenticationStatement(ShibbolethSSORequestContext requestContext)
395             throws ProfileException {
396         ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
397
398         AuthenticationStatement statement = authnStatementBuilder.buildObject();
399         statement.setAuthenticationInstant(loginContext.getAuthenticationInstant());
400         statement.setAuthenticationMethod(loginContext.getAuthenticationMethod());
401
402         statement.setSubjectLocality(buildSubjectLocality(requestContext));
403
404         Subject statementSubject;
405         Endpoint endpoint = selectEndpoint(requestContext);
406         if (endpoint.getBinding().equals(SAMLConstants.SAML1_ARTIFACT_BINDING_URI)) {
407             statementSubject = buildSubject(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:artifact");
408         } else {
409             statementSubject = buildSubject(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:bearer");
410         }
411         statement.setSubject(statementSubject);
412
413         return statement;
414     }
415
416     /**
417      * Constructs the subject locality for the authentication statement.
418      * 
419      * @param requestContext current request context
420      * 
421      * @return subject locality for the authentication statement
422      */
423     protected SubjectLocality buildSubjectLocality(ShibbolethSSORequestContext requestContext) {
424         SubjectLocality subjectLocality = subjectLocalityBuilder.buildObject();
425
426         HTTPInTransport inTransport = (HTTPInTransport) requestContext.getInboundMessageTransport();
427         subjectLocality.setIPAddress(inTransport.getPeerAddress());
428
429         return subjectLocality;
430     }
431
432     /** Represents the internal state of a Shibboleth SSO Request while it's being processed by the IdP. */
433     public class ShibbolethSSORequestContext extends
434             BaseSAML1ProfileRequestContext<Request, Response, ShibbolethSSOConfiguration> {
435
436         /** SP-provide assertion consumer service URL. */
437         private String spAssertionConsumerService;
438
439         /** Current login context. */
440         private ShibbolethSSOLoginContext loginContext;
441
442         /**
443          * Gets the current login context.
444          * 
445          * @return current login context
446          */
447         public ShibbolethSSOLoginContext getLoginContext() {
448             return loginContext;
449         }
450
451         /**
452          * Sets the current login context.
453          * 
454          * @param context current login context
455          */
456         public void setLoginContext(ShibbolethSSOLoginContext context) {
457             loginContext = context;
458         }
459
460         /**
461          * Gets the SP-provided assertion consumer service URL.
462          * 
463          * @return SP-provided assertion consumer service URL
464          */
465         public String getSpAssertionConsumerService() {
466             return spAssertionConsumerService;
467         }
468
469         /**
470          * Sets the SP-provided assertion consumer service URL.
471          * 
472          * @param acs SP-provided assertion consumer service URL
473          */
474         public void setSpAssertionConsumerService(String acs) {
475             spAssertionConsumerService = acs;
476         }
477     }
478 }