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