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