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