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