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