90262c78311fe202a0b2d3b618d73c9af63cebe7
[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.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 incoming request");
108
109         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
110         LoginContext loginContext = (LoginContext) httpRequest.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
111
112         if (loginContext == null) {
113             log.debug("Incoming request does not contain a login context, processing as first leg of request");
114             performAuthentication(inTransport, outTransport);
115         } else {
116             log.debug("Incoming request contains a login context, processing as second leg of request");
117             completeAuthenticationRequest(inTransport, outTransport);
118         }
119     }
120
121     /**
122      * Creates a {@link LoginContext} an sends the request off to the AuthenticationManager to begin the process of
123      * authenticating the user.
124      * 
125      * @param inTransport inbound message transport
126      * @param outTransport outbound message transport
127      * 
128      * @throws ProfileException thrown if there is a problem creating the login context and transferring control to the
129      *             authentication manager
130      */
131     protected void performAuthentication(HTTPInTransport inTransport, HTTPOutTransport outTransport)
132             throws ProfileException {
133
134         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
135         HttpServletResponse httpResponse = ((HttpServletResponseAdapter) outTransport).getWrappedResponse();
136
137         ShibbolethSSORequestContext requestContext = decodeRequest(inTransport, outTransport);
138         ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
139
140         RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(loginContext.getRelyingPartyId());
141         ProfileConfiguration ssoConfig = rpConfig.getProfileConfiguration(ShibbolethSSOConfiguration.PROFILE_ID);
142         if (ssoConfig == null) {
143             log.error("Shibboleth SSO profile is not configured for relying party " + loginContext.getRelyingPartyId());
144             throw new ProfileException("Shibboleth SSO profile is not configured for relying party "
145                     + loginContext.getRelyingPartyId());
146         }
147         loginContext.getRequestedAuthenticationMethods().add(rpConfig.getDefaultAuthenticationMethod());
148
149         httpRequest.setAttribute(LoginContext.LOGIN_CONTEXT_KEY, loginContext);
150
151         try {
152             RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(authenticationManagerPath);
153             dispatcher.forward(httpRequest, httpResponse);
154             return;
155         } catch (IOException ex) {
156             log.error("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
157             throw new ProfileException("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
158         } catch (ServletException ex) {
159             log.error("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
160             throw new ProfileException("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
161         }
162     }
163
164     /**
165      * Decodes an incoming request and populates a created request context with the resultant information.
166      * 
167      * @param inTransport inbound message transport
168      * @param outTransport outbound message transport
169      * 
170      * @return the created request context
171      * 
172      * @throws ProfileException throw if there is a problem decoding the request
173      */
174     protected ShibbolethSSORequestContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
175             throws ProfileException {
176         log.debug("Decoding message with decoder binding {}", getInboundBinding());
177
178         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
179
180         ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext();
181         requestContext.setMetadataProvider(getMetadataProvider());
182         requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
183
184         requestContext.setCommunicationProfileId(ShibbolethSSOConfiguration.PROFILE_ID);
185         requestContext.setInboundMessageTransport(inTransport);
186         requestContext.setInboundSAMLProtocol(ShibbolethConstants.SHIB_SSO_PROFILE_URI);
187         requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
188
189         requestContext.setOutboundMessageTransport(outTransport);
190         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML11P_NS);
191
192         SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
193         requestContext.setMessageDecoder(decoder);
194         try {
195             decoder.decode(requestContext);
196         } catch (MessageDecodingException e) {
197             log.error("Error decoding Shibboleth SSO request", e);
198             throw new ProfileException("Error decoding Shibboleth SSO request", e);
199         } catch (SecurityException e) {
200             log.error("Shibboleth SSO request does not meet security requirements", e);
201             throw new ProfileException("Shibboleth SSO request does not meet security requirements", e);
202         }
203
204         ShibbolethSSOLoginContext loginContext = new ShibbolethSSOLoginContext();
205         loginContext.setRelyingParty(requestContext.getInboundMessageIssuer());
206         loginContext.setSpAssertionConsumerService(requestContext.getSpAssertionConsumerService());
207         loginContext.setSpTarget(requestContext.getRelayState());
208         loginContext.setAuthenticationEngineURL(authenticationManagerPath);
209         loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(httpRequest));
210
211         requestContext.setLoginContext(loginContext);
212
213         return requestContext;
214     }
215
216     /**
217      * Creates a response to the Shibboleth SSO and sends the user, with response in tow, back to the relying party
218      * after they've been authenticated.
219      * 
220      * @param inTransport inbound message transport
221      * @param outTransport outbound message transport
222      * 
223      * @throws ProfileException thrown if the response can not be created and sent back to the relying party
224      */
225     protected void completeAuthenticationRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
226             throws ProfileException {
227         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
228         ShibbolethSSOLoginContext loginContext = (ShibbolethSSOLoginContext) httpRequest
229                 .getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
230
231         ShibbolethSSORequestContext requestContext = buildRequestContext(loginContext, inTransport, outTransport);
232
233         Response samlResponse;
234         try {
235             if (loginContext.getAuthenticationFailure() != null) {
236                 log.error("User authentication failed with the following error: {}", loginContext
237                         .getAuthenticationFailure().toString());
238                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "User failed authentication"));
239                 throw new ProfileException("Authentication failure", loginContext.getAuthenticationFailure());
240             }
241
242             resolveAttributes(requestContext);
243
244             ArrayList<Statement> statements = new ArrayList<Statement>();
245             statements.add(buildAuthenticationStatement(requestContext));
246             if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
247                 AttributeStatement attributeStatement = buildAttributeStatement(requestContext,
248                         "urn:oasis:names:tc:SAML:1.0:cm:bearer");
249                 if (attributeStatement != null) {
250                     requestContext.setRequestedAttributes(requestContext.getAttributes().keySet());
251                     statements.add(attributeStatement);
252                 }
253             }
254
255             samlResponse = buildResponse(requestContext, statements);
256         } catch (ProfileException e) {
257             samlResponse = buildErrorResponse(requestContext);
258         }
259
260         requestContext.setOutboundSAMLMessage(samlResponse);
261         requestContext.setOutboundSAMLMessageId(samlResponse.getID());
262         requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
263         encodeResponse(requestContext);
264         writeAuditLogEntry(requestContext);
265     }
266
267     /**
268      * Creates an authentication request context from the current environmental information.
269      * 
270      * @param loginContext current login context
271      * @param in inbound transport
272      * @param out outbount transport
273      * 
274      * @return created authentication request context
275      * 
276      * @throws ProfileException thrown if there is a problem creating the context
277      */
278     protected ShibbolethSSORequestContext buildRequestContext(ShibbolethSSOLoginContext loginContext,
279             HTTPInTransport in, HTTPOutTransport out) throws ProfileException {
280         ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext();
281
282         requestContext.setMessageDecoder(getMessageDecoders().get(getInboundBinding()));
283
284         requestContext.setLoginContext(loginContext);
285         requestContext.setPrincipalName(loginContext.getPrincipalName());
286         requestContext.setPrincipalAuthenticationMethod(loginContext.getAuthenticationMethod());
287         requestContext.setUserSession(getUserSession(in));
288         requestContext.setRelayState(loginContext.getSpTarget());
289
290         requestContext.setInboundMessageTransport(in);
291         requestContext.setInboundSAMLProtocol(ShibbolethConstants.SHIB_SSO_PROFILE_URI);
292
293         requestContext.setOutboundMessageTransport(out);
294         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
295
296         MetadataProvider metadataProvider = getMetadataProvider();
297         requestContext.setMetadataProvider(metadataProvider);
298
299         String relyingPartyId = loginContext.getRelyingPartyId();
300         requestContext.setInboundMessageIssuer(relyingPartyId);
301
302         try {
303             EntityDescriptor relyingPartyMetadata = metadataProvider.getEntityDescriptor(relyingPartyId);
304             if (relyingPartyMetadata != null) {
305                 requestContext.setPeerEntityMetadata(relyingPartyMetadata);
306                 requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
307                 requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata
308                         .getSPSSODescriptor(SAMLConstants.SAML11P_NS));
309             }
310         } catch (MetadataProviderException e) {
311             log.error("Unable to locate metadata for relying party");
312             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
313                     "Error locating relying party metadata"));
314             throw new ProfileException("Error locating relying party metadata");
315         }
316
317         RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
318         if (rpConfig == null) {
319             log.error("Unable to retrieve relying party configuration data for entity with ID {}", relyingPartyId);
320             throw new ProfileException("Unable to retrieve relying party configuration data for entity with ID "
321                     + relyingPartyId);
322         }
323         requestContext.setRelyingPartyConfiguration(rpConfig);
324
325         ShibbolethSSOConfiguration profileConfig = (ShibbolethSSOConfiguration) rpConfig
326                 .getProfileConfiguration(ShibbolethSSOConfiguration.PROFILE_ID);
327         requestContext.setProfileConfiguration(profileConfig);
328         requestContext.setOutboundMessageArtifactType(profileConfig.getOutboundArtifactType());
329         requestContext.setPeerEntityEndpoint(selectEndpoint(requestContext));
330
331         String assertingPartyId = rpConfig.getProviderId();
332         requestContext.setLocalEntityId(assertingPartyId);
333         requestContext.setOutboundMessageIssuer(assertingPartyId);
334         try {
335             EntityDescriptor localEntityDescriptor = metadataProvider.getEntityDescriptor(assertingPartyId);
336             if (localEntityDescriptor != null) {
337                 requestContext.setLocalEntityMetadata(localEntityDescriptor);
338                 requestContext.setLocalEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
339                 requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
340                         .getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
341             }
342         } catch (MetadataProviderException e) {
343             log.error("Unable to locate metadata for asserting party");
344             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
345                     "Error locating asserting party metadata"));
346             throw new ProfileException("Error locating asserting party metadata");
347         }
348
349         return requestContext;
350     }
351
352     /**
353      * Selects the appropriate endpoint for the relying party and stores it in the request context.
354      * 
355      * @param requestContext current request context
356      * 
357      * @return Endpoint selected from the information provided in the request context
358      */
359     protected Endpoint selectEndpoint(ShibbolethSSORequestContext requestContext) {
360         ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
361
362         ShibbolethSSOEndpointSelector endpointSelector = new ShibbolethSSOEndpointSelector();
363         endpointSelector.setSpAssertionConsumerService(loginContext.getSpAssertionConsumerService());
364         endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
365         endpointSelector.setMetadataProvider(getMetadataProvider());
366         endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
367         endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
368         endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
369         endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
370
371         return endpointSelector.selectEndpoint();
372     }
373
374     /**
375      * Builds the authentication statement for the authenticated principal.
376      * 
377      * @param requestContext current request context
378      * 
379      * @return the created statement
380      * 
381      * @throws ProfileException thrown if the authentication statement can not be created
382      */
383     protected AuthenticationStatement buildAuthenticationStatement(ShibbolethSSORequestContext requestContext)
384             throws ProfileException {
385         ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
386
387         AuthenticationStatement statement = authnStatementBuilder.buildObject();
388         statement.setAuthenticationInstant(loginContext.getAuthenticationInstant());
389         statement.setAuthenticationMethod(loginContext.getAuthenticationMethod());
390
391         statement.setSubjectLocality(buildSubjectLocality(requestContext));
392
393         Subject statementSubject = buildSubject(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:bearer");
394         statement.setSubject(statementSubject);
395
396         return statement;
397     }
398
399     /**
400      * Constructs the subject locality for the authentication statement.
401      * 
402      * @param requestContext curent request context
403      * 
404      * @return subject locality for the authentication statement
405      */
406     protected SubjectLocality buildSubjectLocality(ShibbolethSSORequestContext requestContext) {
407         SubjectLocality subjectLocality = subjectLocalityBuilder.buildObject();
408
409         HTTPInTransport inTransport = (HTTPInTransport) requestContext.getInboundMessageTransport();
410         subjectLocality.setIPAddress(inTransport.getPeerAddress());
411
412         return subjectLocality;
413     }
414
415     /** Represents the internal state of a Shibboleth SSO Request while it's being processed by the IdP. */
416     public class ShibbolethSSORequestContext extends
417             BaseSAML1ProfileRequestContext<Request, Response, ShibbolethSSOConfiguration> {
418
419         /** SP-provide assertion consumer service URL. */
420         private String spAssertionConsumerService;
421
422         /** Current login context. */
423         private ShibbolethSSOLoginContext loginContext;
424
425         /**
426          * Gets the current login context.
427          * 
428          * @return current login context
429          */
430         public ShibbolethSSOLoginContext getLoginContext() {
431             return loginContext;
432         }
433
434         /**
435          * Sets the current login context.
436          * 
437          * @param context current login context
438          */
439         public void setLoginContext(ShibbolethSSOLoginContext context) {
440             loginContext = context;
441         }
442
443         /**
444          * Gets the SP-provided assertion consumer service URL.
445          * 
446          * @return SP-provided assertion consumer service URL
447          */
448         public String getSpAssertionConsumerService() {
449             return spAssertionConsumerService;
450         }
451
452         /**
453          * Sets the SP-provided assertion consumer service URL.
454          * 
455          * @param acs SP-provided assertion consumer service URL
456          */
457         public void setSpAssertionConsumerService(String acs) {
458             spAssertionConsumerService = acs;
459         }
460     }
461 }