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