ccc5479f1a4a86cb1c65157ed0b94ed742f64745
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / idp / profile / saml2 / SSOProfileHandler.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.saml2;
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.HttpSession;
26
27 import org.apache.log4j.Logger;
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.saml2.binding.AuthnResponseEndpointSelector;
32 import org.opensaml.saml2.core.AuthnContext;
33 import org.opensaml.saml2.core.AuthnContextClassRef;
34 import org.opensaml.saml2.core.AuthnContextDeclRef;
35 import org.opensaml.saml2.core.AuthnRequest;
36 import org.opensaml.saml2.core.AuthnStatement;
37 import org.opensaml.saml2.core.RequestedAuthnContext;
38 import org.opensaml.saml2.core.Response;
39 import org.opensaml.saml2.core.Statement;
40 import org.opensaml.saml2.core.StatusCode;
41 import org.opensaml.saml2.core.SubjectLocality;
42 import org.opensaml.saml2.metadata.AssertionConsumerService;
43 import org.opensaml.saml2.metadata.Endpoint;
44 import org.opensaml.saml2.metadata.EntityDescriptor;
45 import org.opensaml.saml2.metadata.IDPSSODescriptor;
46 import org.opensaml.saml2.metadata.SPSSODescriptor;
47 import org.opensaml.saml2.metadata.provider.MetadataProvider;
48 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
49 import org.opensaml.ws.message.decoder.MessageDecodingException;
50 import org.opensaml.ws.security.SecurityPolicyException;
51 import org.opensaml.ws.transport.http.HTTPInTransport;
52 import org.opensaml.ws.transport.http.HTTPOutTransport;
53 import org.opensaml.ws.transport.http.HttpServletRequestAdapter;
54 import org.opensaml.ws.transport.http.HttpServletResponseAdapter;
55 import org.opensaml.xml.io.MarshallingException;
56 import org.opensaml.xml.io.UnmarshallingException;
57
58 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
59 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
60 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.SSOConfiguration;
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.Saml2LoginContext;
64
65 /** SAML 2.0 SSO request profile handler. */
66 public class SSOProfileHandler extends AbstractSAML2ProfileHandler {
67
68     /** Class logger. */
69     private final Logger log = Logger.getLogger(SSOProfileHandler.class);
70
71     /** Builder of AuthnStatement objects. */
72     private SAMLObjectBuilder<AuthnStatement> authnStatementBuilder;
73
74     /** Builder of AuthnContext objects. */
75     private SAMLObjectBuilder<AuthnContext> authnContextBuilder;
76
77     /** Builder of AuthnContextClassRef objects. */
78     private SAMLObjectBuilder<AuthnContextClassRef> authnContextClassRefBuilder;
79
80     /** Builder of AuthnContextDeclRef objects. */
81     private SAMLObjectBuilder<AuthnContextDeclRef> authnContextDeclRefBuilder;
82
83     /** Builder of SubjectLocality objects. */
84     private SAMLObjectBuilder<SubjectLocality> subjectLocalityBuilder;
85
86     /** URL of the authentication manager servlet. */
87     private String authenticationManagerPath;
88
89     /** URI of request decoder. */
90     private String decodingBinding;
91
92     /**
93      * Constructor.
94      * 
95      * @param authnManagerPath path to the authentication manager servlet
96      */
97     @SuppressWarnings("unchecked")
98     public SSOProfileHandler(String authnManagerPath) {
99         super();
100
101         authenticationManagerPath = authnManagerPath;
102
103         authnStatementBuilder = (SAMLObjectBuilder<AuthnStatement>) getBuilderFactory().getBuilder(
104                 AuthnStatement.DEFAULT_ELEMENT_NAME);
105         authnContextBuilder = (SAMLObjectBuilder<AuthnContext>) getBuilderFactory().getBuilder(
106                 AuthnContext.DEFAULT_ELEMENT_NAME);
107         authnContextClassRefBuilder = (SAMLObjectBuilder<AuthnContextClassRef>) getBuilderFactory().getBuilder(
108                 AuthnContextClassRef.DEFAULT_ELEMENT_NAME);
109         authnContextDeclRefBuilder = (SAMLObjectBuilder<AuthnContextDeclRef>) getBuilderFactory().getBuilder(
110                 AuthnContextDeclRef.DEFAULT_ELEMENT_NAME);
111         subjectLocalityBuilder = (SAMLObjectBuilder<SubjectLocality>) getBuilderFactory().getBuilder(
112                 SubjectLocality.DEFAULT_ELEMENT_NAME);
113     }
114
115     /** {@inheritDoc} */
116     public String getProfileId() {
117         return "urn:mace:shibboleth:2.0:idp:profiles:saml2:request:sso";
118     }
119
120     /** {@inheritDoc} */
121     public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
122         HttpServletRequest servletRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
123         HttpSession httpSession = servletRequest.getSession();
124
125         if (httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY) == null) {
126             performAuthentication(inTransport, outTransport);
127         } else {
128             completeAuthenticationRequest(inTransport, outTransport);
129         }
130     }
131
132     /**
133      * Creates a {@link Saml2LoginContext} an sends the request off to the AuthenticationManager to begin the process of
134      * authenticating the user.
135      * 
136      * @param inTransport inbound request transport
137      * @param outTransport outbound response transport
138      * 
139      * @throws ProfileException thrown if there is a problem creating the login context and transferring control to the
140      *             authentication manager
141      */
142     protected void performAuthentication(HTTPInTransport inTransport, HTTPOutTransport outTransport)
143             throws ProfileException {
144         HttpServletRequest servletRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
145
146         try {
147             SSORequestContext requestContext = decodeRequest(inTransport, outTransport);
148
149             String relyingPartyId = requestContext.getPeerEntityId();
150             RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
151             if (rpConfig == null) {
152                 log.error("No relying party configuration for " + relyingPartyId);
153                 throw new ProfileException("No relying party configuration for " + relyingPartyId);
154             }
155
156             Saml2LoginContext loginContext = new Saml2LoginContext(relyingPartyId, requestContext.getRelayState(),
157                     requestContext.getInboundSAMLMessage());
158             loginContext.setAuthenticationEngineURL(authenticationManagerPath);
159             loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(servletRequest));
160             if (loginContext.getRequestedAuthenticationMethods().size() == 0) {
161                 loginContext.getRequestedAuthenticationMethods().add(rpConfig.getDefaultAuthenticationMethod());
162             }
163
164             HttpSession httpSession = servletRequest.getSession();
165             httpSession.setAttribute(Saml2LoginContext.LOGIN_CONTEXT_KEY, loginContext);
166             RequestDispatcher dispatcher = servletRequest.getRequestDispatcher(authenticationManagerPath);
167             dispatcher.forward(servletRequest, ((HttpServletResponseAdapter) outTransport).getWrappedResponse());
168         } catch (MarshallingException e) {
169             log.error("Unable to marshall authentication request context");
170             throw new ProfileException("Unable to marshall authentication request context", e);
171         } catch (IOException ex) {
172             log.error("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
173             throw new ProfileException("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
174         } catch (ServletException ex) {
175             log.error("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
176             throw new ProfileException("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
177         }
178     }
179
180     /**
181      * Creates a response to the {@link AuthnRequest} and sends the user, with response in tow, back to the relying
182      * party after they've been authenticated.
183      * 
184      * @param inTransport inbound message transport
185      * @param outTransport outbound message transport
186      * 
187      * @throws ProfileException thrown if the response can not be created and sent back to the relying party
188      */
189     protected void completeAuthenticationRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
190             throws ProfileException {
191         HttpServletRequest servletRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
192         HttpSession httpSession = servletRequest.getSession();
193
194         Saml2LoginContext loginContext = (Saml2LoginContext) httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
195         httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
196
197         SSORequestContext requestContext = buildRequestContext(loginContext, inTransport, outTransport);
198
199         checkSamlVersion(requestContext);
200
201         Response samlResponse;
202         try {
203             if (loginContext.getPrincipalName() == null) {
204                 log.error("User's login context did not contain a principal, user considered unauthenticiated.");
205                 requestContext
206                         .setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.AUTHN_FAILED_URI, null));
207                 throw new ProfileException("User failed authentication");
208             }
209
210             resolveAttributes(requestContext);
211
212             ArrayList<Statement> statements = new ArrayList<Statement>();
213             statements.add(buildAuthnStatement(requestContext));
214             if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
215                 requestContext.setRequestedAttributes(requestContext.getPrincipalAttributes().keySet());
216                 statements.add(buildAttributeStatement(requestContext));
217             }
218
219             samlResponse = buildResponse(requestContext, "urn:oasis:names:tc:SAML:2.0:cm:bearer", statements);
220         } catch (ProfileException e) {
221             samlResponse = buildErrorResponse(requestContext);
222         }
223
224         requestContext.setOutboundSAMLMessage(samlResponse);
225         requestContext.setOutboundSAMLMessageId(samlResponse.getID());
226         requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
227         encodeResponse(requestContext);
228         writeAuditLogEntry(requestContext);
229     }
230
231     /**
232      * Decodes an incoming request and stores the information in a created request context.
233      * 
234      * @param inTransport inbound transport
235      * @param outTransport outbound transport
236      * 
237      * @return request context with decoded information
238      * 
239      * @throws ProfileException thrown if the incomming message failed decoding
240      */
241     protected SSORequestContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
242             throws ProfileException {
243         if (log.isDebugEnabled()) {
244             log.debug("Decoding message with decoder binding " + decodingBinding);
245         }
246
247         SSORequestContext requestContext = new SSORequestContext();
248         requestContext.setInboundMessageTransport(inTransport);
249         requestContext.setOutboundMessageTransport(outTransport);
250         requestContext.setMetadataProvider(getMetadataProvider());
251
252         try {
253             SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
254             requestContext.setMessageDecoder(decoder);
255             decoder.decode(requestContext);
256             return requestContext;
257         } catch (MessageDecodingException e) {
258             log.error("Error decoding authentication request message", e);
259             throw new ProfileException("Error decoding authentication request message", e);
260         } catch (SecurityPolicyException e) {
261             log.error("Message did not meet security policy requirements", e);
262             throw new ProfileException("Message did not meet security policy requirements", e);
263         }
264     }
265
266     /**
267      * Creates an authentication request context from the current environmental information.
268      * 
269      * @param loginContext current login context
270      * @param in inbound transport
271      * @param out outbount transport
272      * 
273      * @return created authentication request context
274      * 
275      * @throws ProfileException thrown if there is a problem creating the context
276      */
277     protected SSORequestContext buildRequestContext(Saml2LoginContext loginContext, HTTPInTransport in,
278             HTTPOutTransport out) throws ProfileException {
279         SSORequestContext requestContext = new SSORequestContext();
280
281         try {
282             requestContext.setLoginContext(loginContext);
283             requestContext.setPrincipalName(loginContext.getPrincipalName());
284             requestContext.setPrincipalAuthenticationMethod(loginContext.getAuthenticationMethod());
285             requestContext.setUserSession(getUserSession(in));
286             requestContext.setRelayState(loginContext.getRelayState());
287
288             requestContext.setInboundMessageTransport(in);
289             requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
290             requestContext.setInboundMessage(loginContext.getAuthenticationRequest());
291             requestContext.setInboundSAMLMessage(loginContext.getAuthenticationRequest());
292             requestContext.setInboundSAMLMessageId(loginContext.getAuthenticationRequest().getID());
293
294             MetadataProvider metadataProvider = getMetadataProvider();
295             requestContext.setMetadataProvider(metadataProvider);
296
297             String relyingPartyId = loginContext.getRelyingPartyId();
298             requestContext.setPeerEntityId(relyingPartyId);
299             EntityDescriptor relyingPartyMetadata = metadataProvider.getEntityDescriptor(relyingPartyId);
300             requestContext.setPeerEntityMetadata(relyingPartyMetadata);
301             requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
302             requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata.getSPSSODescriptor(SAMLConstants.SAML20P_NS));
303             RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
304             requestContext.setRelyingPartyConfiguration(rpConfig);
305             requestContext.setPeerEntityEndpoint(selectEndpoint(requestContext));
306
307             String assertingPartyId = rpConfig.getProviderId();
308             requestContext.setLocalEntityId(assertingPartyId);
309             EntityDescriptor assertingPartyMetadata = metadataProvider.getEntityDescriptor(assertingPartyId);
310             requestContext.setLocalEntityMetadata(assertingPartyMetadata);
311             requestContext.setLocalEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
312             requestContext.setLocalEntityRoleMetadata(assertingPartyMetadata
313                     .getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
314
315             requestContext.setOutboundMessageTransport(out);
316             requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
317             SSOConfiguration profileConfig = (SSOConfiguration) rpConfig
318                     .getProfileConfiguration(SSOConfiguration.PROFILE_ID);
319             requestContext.setProfileConfiguration(profileConfig);
320             requestContext.setOutboundMessageArtifactType(profileConfig.getOutboundArtifactType());
321             if (profileConfig.getSigningCredential() != null) {
322                 requestContext.setOutboundSAMLMessageSigningCredential(profileConfig.getSigningCredential());
323             } else if (rpConfig.getDefaultSigningCredential() != null) {
324                 requestContext.setOutboundSAMLMessageSigningCredential(rpConfig.getDefaultSigningCredential());
325             }
326
327             return requestContext;
328         } catch (UnmarshallingException e) {
329             log.error("Unable to unmarshall authentication request context");
330             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
331                     "Error recovering request state"));
332             throw new ProfileException("Error recovering request state", e);
333         } catch (MetadataProviderException e) {
334             log.error("Unable to locate metadata for asserting or relying party");
335             requestContext
336                     .setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error locating party metadata"));
337             throw new ProfileException("Error locating party metadata");
338         }
339     }
340
341     /**
342      * Creates an authentication statement for the current request.
343      * 
344      * @param requestContext current request context
345      * 
346      * @return constructed authentication statement
347      */
348     protected AuthnStatement buildAuthnStatement(SSORequestContext requestContext) {
349         Saml2LoginContext loginContext = requestContext.getLoginContext();
350
351         AuthnContext authnContext = buildAuthnContext(requestContext);
352
353         AuthnStatement statement = authnStatementBuilder.buildObject();
354         statement.setAuthnContext(authnContext);
355         statement.setAuthnInstant(loginContext.getAuthenticationInstant());
356
357         // TODO
358         statement.setSessionIndex(null);
359
360         if (loginContext.getAuthenticationDuration() > 0) {
361             statement.setSessionNotOnOrAfter(loginContext.getAuthenticationInstant().plus(
362                     loginContext.getAuthenticationDuration()));
363         }
364
365         statement.setSubjectLocality(buildSubjectLocality(requestContext));
366
367         return statement;
368     }
369
370     /**
371      * Creates an {@link AuthnContext} for a succesful authentication request.
372      * 
373      * @param requestContext current request
374      * 
375      * @return the built authn context
376      */
377     protected AuthnContext buildAuthnContext(SSORequestContext requestContext) {
378         AuthnContext authnContext = authnContextBuilder.buildObject();
379
380         Saml2LoginContext loginContext = requestContext.getLoginContext();
381         AuthnRequest authnRequest = requestContext.getInboundSAMLMessage();
382         RequestedAuthnContext requestedAuthnContext = authnRequest.getRequestedAuthnContext();
383         if (requestedAuthnContext != null) {
384             if (requestedAuthnContext.getAuthnContextClassRefs() != null) {
385                 for (AuthnContextClassRef classRef : requestedAuthnContext.getAuthnContextClassRefs()) {
386                     if (classRef.getAuthnContextClassRef().equals(loginContext.getAuthenticationMethod())) {
387                         AuthnContextClassRef ref = authnContextClassRefBuilder.buildObject();
388                         ref.setAuthnContextClassRef(loginContext.getAuthenticationMethod());
389                         authnContext.setAuthnContextClassRef(ref);
390                     }
391                 }
392             } else if (requestedAuthnContext.getAuthnContextDeclRefs() != null) {
393                 for (AuthnContextDeclRef declRef : requestedAuthnContext.getAuthnContextDeclRefs()) {
394                     if (declRef.getAuthnContextDeclRef().equals(loginContext.getAuthenticationMethod())) {
395                         AuthnContextDeclRef ref = authnContextDeclRefBuilder.buildObject();
396                         ref.setAuthnContextDeclRef(loginContext.getAuthenticationMethod());
397                         authnContext.setAuthnContextDeclRef(ref);
398                     }
399                 }
400             }
401         } else {
402             AuthnContextDeclRef ref = authnContextDeclRefBuilder.buildObject();
403             ref.setAuthnContextDeclRef(loginContext.getAuthenticationMethod());
404             authnContext.setAuthnContextDeclRef(ref);
405         }
406
407         return authnContext;
408     }
409
410     /**
411      * Constructs the subject locality for the authentication statement.
412      * 
413      * @param requestContext curent request context
414      * 
415      * @return subject locality for the authentication statement
416      */
417     protected SubjectLocality buildSubjectLocality(SSORequestContext requestContext) {
418         HTTPInTransport transport = (HTTPInTransport) requestContext.getInboundMessageTransport();
419         SubjectLocality subjectLocality = subjectLocalityBuilder.buildObject();
420         subjectLocality.setAddress(transport.getPeerAddress());
421         subjectLocality.setDNSName(transport.getPeerDomainName());
422
423         return subjectLocality;
424     }
425
426     /**
427      * Selects the appropriate endpoint for the relying party and stores it in the request context.
428      * 
429      * @param requestContext current request context
430      * 
431      * @return Endpoint selected from the information provided in the request context
432      */
433     protected Endpoint selectEndpoint(SSORequestContext requestContext) {
434         AuthnResponseEndpointSelector endpointSelector = new AuthnResponseEndpointSelector();
435         endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
436         endpointSelector.setMetadataProvider(getMetadataProvider());
437         endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
438         endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
439         endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
440         endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
441         return endpointSelector.selectEndpoint();
442     }
443
444     /** Represents the internal state of a SAML 2.0 SSO Request while it's being processed by the IdP. */
445     protected class SSORequestContext extends BaseSAML2ProfileRequestContext<AuthnRequest, Response, SSOConfiguration> {
446
447         /** Current login context. */
448         private Saml2LoginContext loginContext;
449
450         /**
451          * Gets the current login context.
452          * 
453          * @return current login context
454          */
455         public Saml2LoginContext getLoginContext() {
456             return loginContext;
457         }
458
459         /**
460          * Sets the current login context.
461          * 
462          * @param context current login context
463          */
464         public void setLoginContext(Saml2LoginContext context) {
465             loginContext = context;
466         }
467     }
468 }