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