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