532f9f21d54aefcdf81a6eb496e34d0f1d6e495f
[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.ServletRequest;
25 import javax.servlet.ServletResponse;
26 import javax.servlet.http.HttpServletRequest;
27 import javax.servlet.http.HttpSession;
28
29 import org.apache.log4j.Logger;
30 import org.opensaml.common.SAMLObjectBuilder;
31 import org.opensaml.common.binding.BindingException;
32 import org.opensaml.common.binding.decoding.MessageDecoder;
33 import org.opensaml.common.binding.encoding.MessageEncoder;
34 import org.opensaml.common.binding.security.SAMLSecurityPolicy;
35 import org.opensaml.saml2.core.AuthnContext;
36 import org.opensaml.saml2.core.AuthnContextClassRef;
37 import org.opensaml.saml2.core.AuthnContextDeclRef;
38 import org.opensaml.saml2.core.AuthnRequest;
39 import org.opensaml.saml2.core.AuthnStatement;
40 import org.opensaml.saml2.core.RequestedAuthnContext;
41 import org.opensaml.saml2.core.Response;
42 import org.opensaml.saml2.core.Statement;
43 import org.opensaml.saml2.core.StatusCode;
44 import org.opensaml.saml2.core.Subject;
45 import org.opensaml.saml2.metadata.IDPSSODescriptor;
46 import org.opensaml.saml2.metadata.SPSSODescriptor;
47 import org.opensaml.ws.security.SecurityPolicyException;
48 import org.opensaml.xml.io.MarshallingException;
49 import org.opensaml.xml.io.UnmarshallingException;
50
51 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
52 import edu.internet2.middleware.shibboleth.common.profile.ProfileRequest;
53 import edu.internet2.middleware.shibboleth.common.profile.ProfileResponse;
54 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
55 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.SSOConfiguration;
56 import edu.internet2.middleware.shibboleth.idp.authn.LoginContext;
57 import edu.internet2.middleware.shibboleth.idp.authn.Saml2LoginContext;
58
59 /** SAML 2.0 SSO request profile handler. */
60 public class SSOProfileHandler extends AbstractSAML2ProfileHandler {
61
62     /** Class logger. */
63     private final Logger log = Logger.getLogger(SSOProfileHandler.class);
64
65     /** Builder of AuthnStatement objects. */
66     private SAMLObjectBuilder<AuthnStatement> authnStatementBuilder;
67
68     /** Builder of AuthnContext objects. */
69     private SAMLObjectBuilder<AuthnContext> authnContextBuilder;
70
71     /** Builder of AuthnContextClassRef objects. */
72     private SAMLObjectBuilder<AuthnContextClassRef> authnContextClassRefBuilder;
73
74     /** Builder of AuthnContextDeclRef objects. */
75     private SAMLObjectBuilder<AuthnContextDeclRef> authnContextDeclRefBuilder;
76
77     /** URL of the authentication manager servlet. */
78     private String authenticationManagerPath;
79
80     /** URI of request decoder. */
81     private String decodingBinding;
82
83     /** URI of response encoder. */
84     private String encodingBinding;
85
86     /**
87      * Constructor.
88      * 
89      * @param authnManagerPath path to the authentication manager servlet
90      * @param decoder URI of the request decoder to use
91      * @param encoder URI of the response encoder to use
92      */
93     @SuppressWarnings("unchecked")
94     public SSOProfileHandler(String authnManagerPath, String decoder, String encoder) {
95         super();
96
97         if (authnManagerPath == null || decoder == null || encoder == null) {
98             throw new IllegalArgumentException("AuthN manager path, decoding, encoding bindings URI may not be null");
99         }
100         
101         authenticationManagerPath = authnManagerPath;
102         decodingBinding = decoder;
103         encodingBinding = encoder;
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     }
114     
115     /**
116      * Convenience method for getting the SAML 2 AuthnStatement builder.
117      * 
118      * @return SAML 2 AuthnStatement builder
119      */
120     public SAMLObjectBuilder<AuthnStatement> getAuthnStatementBuilder(){
121         return authnStatementBuilder;
122     }
123     
124     /**
125      * Convenience method for getting the SAML 2 AuthnContext builder.
126      * 
127      * @return SAML 2 AuthnContext builder
128      */
129     public SAMLObjectBuilder<AuthnContext> getAuthnContextBuilder(){
130         return authnContextBuilder;
131     }
132     
133     /**
134      * Convenience method for getting the SAML 2 AuthnContextClassRef builder.
135      * 
136      * @return SAML 2 AuthnContextClassRef builder
137      */
138     public SAMLObjectBuilder<AuthnContextClassRef> getAuthnContextClassRefBuilder(){
139         return authnContextClassRefBuilder;
140     }
141     
142     /**
143      * Convenience method for getting the SAML 2 AuthnContextDeclRef builder.
144      * 
145      * @return SAML 2 AuthnContextDeclRef builder
146      */
147     public SAMLObjectBuilder<AuthnContextDeclRef> getAuthnContextDeclRefBuilder(){
148         return authnContextDeclRefBuilder;
149     }
150
151     /** {@inheritDoc} */
152     public String getProfileId() {
153         return "urn:mace:shibboleth:2.0:idp:profiles:saml2:request:sso";
154     }
155
156     /** {@inheritDoc} */
157     public void processRequest(ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response)
158             throws ProfileException {
159
160         HttpSession httpSession = ((HttpServletRequest) request.getRawRequest()).getSession(true);
161         if (httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY) == null) {
162             performAuthentication(request, response);
163         } else {
164             completeAuthenticationRequest(request, response);
165         }
166     }
167
168     /**
169      * Creates a {@link Saml2LoginContext} an sends the request off to the AuthenticationManager to begin the
170      * process of authenticating the user.
171      * 
172      * @param request current request
173      * @param response current response
174      * 
175      * @throws ProfileException thrown if there is a problem creating the login context and transferring control to the
176      *             authentication manager
177      */
178     protected void performAuthentication(ProfileRequest<ServletRequest> request,
179             ProfileResponse<ServletResponse> response) throws ProfileException {
180         HttpServletRequest httpRequest = (HttpServletRequest) request.getRawRequest();
181
182         AuthnRequest authnRequest = null;
183         try {
184             MessageDecoder<ServletRequest> decoder = decodeRequest(request);
185             SAMLSecurityPolicy<ServletRequest> securityPolicy = decoder.getSecurityPolicy();
186
187             String relyingParty = securityPolicy.getIssuer();
188             authnRequest = (AuthnRequest) decoder.getSAMLMessage();
189
190             Saml2LoginContext loginContext = new Saml2LoginContext(relyingParty, authnRequest);
191             loginContext.setAuthenticationManagerURL(authenticationManagerPath);
192             loginContext.setProfileHandlerURL(httpRequest.getRequestURI());
193
194             HttpSession httpSession = httpRequest.getSession();
195             httpSession.setAttribute(Saml2LoginContext.LOGIN_CONTEXT_KEY, loginContext);
196             RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(authenticationManagerPath);
197             dispatcher.forward(httpRequest, response.getRawResponse());
198         } catch (MarshallingException e) {
199             log.error("Unable to marshall authentication request context");
200             throw new ProfileException("Unable to marshall authentication request context", e);
201         } catch (IOException ex) {
202             log.error("Error forwarding SAML 2 AuthnRequest " + authnRequest.getID() + " to AuthenticationManager", ex);
203             throw new ProfileException("Error forwarding SAML 2 AuthnRequest " + authnRequest.getID()
204                     + " to AuthenticationManager", ex);
205         } catch (ServletException ex) {
206             log.error("Error forwarding SAML 2 AuthnRequest " + authnRequest.getID() + " to AuthenticationManager", ex);
207             throw new ProfileException("Error forwarding SAML 2 AuthnRequest " + authnRequest.getID()
208                     + " to AuthenticationManager", ex);
209         }
210     }
211
212     /**
213      * Creates a response to the {@link AuthnRequest} and sends the user, with response in tow, back to the relying
214      * party after they've been authenticated.
215      * 
216      * @param request current request
217      * @param response current response
218      * 
219      * @throws ProfileException thrown if the response can not be created and sent back to the relying party
220      */
221     protected void completeAuthenticationRequest(ProfileRequest<ServletRequest> request,
222             ProfileResponse<ServletResponse> response) throws ProfileException {
223
224         HttpSession httpSession = ((HttpServletRequest) request.getRawRequest()).getSession(true);
225         
226         Saml2LoginContext loginContext = (Saml2LoginContext) httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
227         httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
228         
229         SSORequestContext requestContext = buildRequestContext(loginContext, request, response);
230
231         Response samlResponse;
232         try {
233             if (!loginContext.getAuthenticationOK()) {
234                 requestContext
235                         .setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.AUTHN_FAILED_URI, null));
236                 throw new ProfileException("User failed authentication");
237             }
238
239             ArrayList<Statement> statements = new ArrayList<Statement>();
240             statements.add(buildAuthnStatement(requestContext));
241             statements.add(buildAttributeStatement(requestContext));
242
243             Subject assertionSubject = buildSubject(requestContext, "urn:oasis:names:tc:SAML:2.0:cm:bearer");
244
245             samlResponse = buildResponse(requestContext, assertionSubject, statements);
246         } catch (ProfileException e) {
247             samlResponse = buildErrorResponse(requestContext);
248         }
249
250         requestContext.setSamlResponse(samlResponse);
251         encodeResponse(requestContext);
252         writeAuditLogEntry(requestContext);
253     }
254
255     /**
256      * Creates an appropriate message decoder, populates it, and decodes the incoming request.
257      * 
258      * @param request current request
259      * 
260      * @return message decoder containing the decoded message and other stateful information
261      * 
262      * @throws ProfileException thrown if the incomming message failed decoding
263      */
264     protected MessageDecoder<ServletRequest> decodeRequest(ProfileRequest<ServletRequest> request)
265             throws ProfileException {
266         MessageDecoder<ServletRequest> decoder = getMessageDecoderFactory().getMessageDecoder(decodingBinding);
267         if (decoder == null) {
268             log.error("No request decoder was registered for binding type: " + decodingBinding);
269             throw new ProfileException("No request decoder was registered for binding type: " + decodingBinding);
270         }
271
272         populateMessageDecoder(decoder);
273         decoder.setRequest(request.getRawRequest());
274         try {
275             decoder.decode();
276             return decoder;
277         } catch (BindingException e) {
278             log.error("Error decoding authentication request message", e);
279             throw new ProfileException("Error decoding authentication request message", e);
280         } catch (SecurityPolicyException e) {
281             log.error("Message did not meet security policy requirements", e);
282             throw new ProfileException("Message did not meet security policy requirements", e);
283         }
284     }
285
286     /**
287      * Creates an authentication request context from the current environmental information.
288      * 
289      * @param loginContext current login context
290      * @param request current request
291      * @param response current response
292      * 
293      * @return created authentication request context
294      * 
295      * @throws ProfileException thrown if there is a problem creating the context
296      */
297     protected SSORequestContext buildRequestContext(Saml2LoginContext loginContext,
298             ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response) throws ProfileException {
299         SSORequestContext requestContext = new SSORequestContext(request, response);
300
301         try {
302             String relyingPartyId = loginContext.getRelyingPartyId();
303             AuthnRequest authnRequest = loginContext.getAuthenticationRequest();
304
305             requestContext.setRelyingPartyId(relyingPartyId);
306
307             RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
308             requestContext.setRelyingPartyConfiguration(rpConfig);
309
310             requestContext.setRelyingPartyRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
311
312             requestContext.setAssertingPartyId(requestContext.getRelyingPartyConfiguration().getProviderId());
313
314             requestContext.setAssertingPartyRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
315
316             requestContext.setProfileConfiguration((SSOConfiguration) rpConfig
317                     .getProfileConfiguration(SSOConfiguration.PROFILE_ID));
318
319             requestContext.setSamlRequest(authnRequest);
320
321             return requestContext;
322         } catch (UnmarshallingException e) {
323             log.error("Unable to unmarshall authentication request context");
324             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
325                     "Error recovering request state"));
326             throw new ProfileException("Error recovering request state", e);
327         }
328     }
329
330     /**
331      * Creates an authentication statement for the current request.
332      * 
333      * @param requestContext current request context
334      * 
335      * @return constructed authentication statement
336      */
337     protected AuthnStatement buildAuthnStatement(SSORequestContext requestContext) {
338         Saml2LoginContext loginContext = requestContext.getLoginContext();
339
340         AuthnContext authnContext = buildAuthnContext(requestContext);
341
342         AuthnStatement statement = getAuthnStatementBuilder().buildObject();
343         statement.setAuthnContext(authnContext);
344         statement.setAuthnInstant(loginContext.getAuthenticationInstant());
345
346         // TODO
347         statement.setSessionIndex(null);
348
349         if (loginContext.getAuthenticationDuration() > 0) {
350             statement.setSessionNotOnOrAfter(loginContext.getAuthenticationInstant().plus(
351                     loginContext.getAuthenticationDuration()));
352         }
353
354         // TODO
355         statement.setSubjectLocality(null);
356
357         return statement;
358     }
359
360     /**
361      * Creates an {@link AuthnContext} for a succesful authentication request.
362      * 
363      * @param requestContext current request
364      * 
365      * @return the built authn context
366      */
367     protected AuthnContext buildAuthnContext(SSORequestContext requestContext) {
368         AuthnContext authnContext = getAuthnContextBuilder().buildObject();
369
370         Saml2LoginContext loginContext = requestContext.getLoginContext();
371         AuthnRequest authnRequest = requestContext.getSamlRequest();
372         RequestedAuthnContext requestedAuthnContext = authnRequest.getRequestedAuthnContext();
373         if (requestedAuthnContext != null) {
374             if (requestedAuthnContext.getAuthnContextClassRefs() != null) {
375                 for (AuthnContextClassRef classRef : requestedAuthnContext.getAuthnContextClassRefs()) {
376                     if (classRef.getAuthnContextClassRef().equals(loginContext.getAuthenticationMethod())) {
377                         AuthnContextClassRef ref = getAuthnContextClassRefBuilder().buildObject();
378                         ref.setAuthnContextClassRef(loginContext.getAuthenticationMethod());
379                         authnContext.setAuthnContextClassRef(ref);
380                     }
381                 }
382             } else if (requestedAuthnContext.getAuthnContextDeclRefs() != null) {
383                 for (AuthnContextDeclRef declRef : requestedAuthnContext.getAuthnContextDeclRefs()) {
384                     if (declRef.getAuthnContextDeclRef().equals(loginContext.getAuthenticationMethod())) {
385                         AuthnContextDeclRef ref = getAuthnContextDeclRefBuilder().buildObject();
386                         ref.setAuthnContextDeclRef(loginContext.getAuthenticationMethod());
387                         authnContext.setAuthnContextDeclRef(ref);
388                     }
389                 }
390             }
391         } else {
392             AuthnContextDeclRef ref = getAuthnContextDeclRefBuilder().buildObject();
393             ref.setAuthnContextDeclRef(loginContext.getAuthenticationMethod());
394             authnContext.setAuthnContextDeclRef(ref);
395         }
396
397         return authnContext;
398     }
399
400     /**
401      * Encodes the request's SAML response and writes it to the servlet response.
402      * 
403      * @param requestContext current request context
404      * 
405      * @throws ProfileException thrown if no message encoder is registered for this profiles binding
406      */
407     protected void encodeResponse(SSORequestContext requestContext) throws ProfileException {
408         if (log.isDebugEnabled()) {
409             log.debug("Encoding response to SAML request " + requestContext.getSamlRequest().getID()
410                     + " from relying party " + requestContext.getRelyingPartyId());
411         }
412         MessageEncoder<ServletResponse> encoder = getMessageEncoderFactory().getMessageEncoder(encodingBinding);
413         if (encoder == null) {
414             log.error("No response encoder was registered for binding type: " + encodingBinding);
415             throw new ProfileException("No response encoder was registered for binding type: " + encodingBinding);
416         }
417
418         super.populateMessageEncoder(encoder);
419         encoder.setResponse(requestContext.getProfileResponse().getRawResponse());
420         encoder.setSamlMessage(requestContext.getSamlResponse());
421         requestContext.setMessageEncoder(encoder);
422
423         try {
424             encoder.encode();
425         } catch (BindingException e) {
426             throw new ProfileException("Unable to encode response to relying party: "
427                     + requestContext.getRelyingPartyId(), e);
428         }
429     }
430
431     /** Represents the internal state of a SAML 2.0 SSO Request while it's being processed by the IdP. */
432     protected class SSORequestContext extends
433             SAML2ProfileRequestContext<AuthnRequest, Response, SSOConfiguration> {
434
435         /** Current login context. */
436         private Saml2LoginContext loginContext;
437
438         /**
439          * Constructor.
440          * 
441          * @param request current profile request
442          * @param response current profile response
443          */
444         public SSORequestContext(ProfileRequest<ServletRequest> request,
445                 ProfileResponse<ServletResponse> response) {
446             super(request, response);
447         }
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 }