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