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