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