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