Fix logging message, addresses SIDP-90
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / idp / profile / saml1 / ShibbolethSSOProfileHandler.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.saml1;
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.http.HttpServletRequest;
25 import javax.servlet.http.HttpServletResponse;
26 import javax.servlet.http.HttpSession;
27
28 import org.opensaml.common.SAMLObjectBuilder;
29 import org.opensaml.common.binding.decoding.SAMLMessageDecoder;
30 import org.opensaml.common.xml.SAMLConstants;
31 import org.opensaml.saml1.core.AttributeStatement;
32 import org.opensaml.saml1.core.AuthenticationStatement;
33 import org.opensaml.saml1.core.Request;
34 import org.opensaml.saml1.core.Response;
35 import org.opensaml.saml1.core.Statement;
36 import org.opensaml.saml1.core.StatusCode;
37 import org.opensaml.saml1.core.Subject;
38 import org.opensaml.saml1.core.SubjectLocality;
39 import org.opensaml.saml2.metadata.AssertionConsumerService;
40 import org.opensaml.saml2.metadata.Endpoint;
41 import org.opensaml.saml2.metadata.EntityDescriptor;
42 import org.opensaml.saml2.metadata.IDPSSODescriptor;
43 import org.opensaml.saml2.metadata.SPSSODescriptor;
44 import org.opensaml.saml2.metadata.provider.MetadataProvider;
45 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
46 import org.opensaml.ws.message.decoder.MessageDecodingException;
47 import org.opensaml.ws.transport.http.HTTPInTransport;
48 import org.opensaml.ws.transport.http.HTTPOutTransport;
49 import org.opensaml.ws.transport.http.HttpServletRequestAdapter;
50 import org.opensaml.ws.transport.http.HttpServletResponseAdapter;
51 import org.opensaml.xml.security.SecurityException;
52 import org.opensaml.xml.util.DatatypeHelper;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55
56 import edu.internet2.middleware.shibboleth.common.ShibbolethConstants;
57 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
58 import edu.internet2.middleware.shibboleth.common.relyingparty.ProfileConfiguration;
59 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
60 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml1.ShibbolethSSOConfiguration;
61 import edu.internet2.middleware.shibboleth.common.util.HttpHelper;
62 import edu.internet2.middleware.shibboleth.idp.authn.LoginContext;
63 import edu.internet2.middleware.shibboleth.idp.authn.ShibbolethSSOLoginContext;
64
65 /** Shibboleth SSO request profile handler. */
66 public class ShibbolethSSOProfileHandler extends AbstractSAML1ProfileHandler {
67
68     /** Class logger. */
69     private final Logger log = LoggerFactory.getLogger(ShibbolethSSOProfileHandler.class);
70
71     /** Builder of AuthenticationStatement objects. */
72     private SAMLObjectBuilder<AuthenticationStatement> authnStatementBuilder;
73
74     /** Builder of SubjectLocality objects. */
75     private SAMLObjectBuilder<SubjectLocality> subjectLocalityBuilder;
76
77     /** URL of the authentication manager servlet. */
78     private String authenticationManagerPath;
79
80     /**
81      * Constructor.
82      * 
83      * @param authnManagerPath path to the authentication manager servlet
84      * 
85      * @throws IllegalArgumentException thrown if either the authentication manager path or encoding binding URI are
86      *             null or empty
87      */
88     public ShibbolethSSOProfileHandler(String authnManagerPath) {
89         if (DatatypeHelper.isEmpty(authnManagerPath)) {
90             throw new IllegalArgumentException("Authentication manager path may not be null");
91         }
92         authenticationManagerPath = authnManagerPath;
93
94         authnStatementBuilder = (SAMLObjectBuilder<AuthenticationStatement>) getBuilderFactory().getBuilder(
95                 AuthenticationStatement.DEFAULT_ELEMENT_NAME);
96
97         subjectLocalityBuilder = (SAMLObjectBuilder<SubjectLocality>) getBuilderFactory().getBuilder(
98                 SubjectLocality.DEFAULT_ELEMENT_NAME);
99     }
100
101     /** {@inheritDoc} */
102     public String getProfileId() {
103         return "urn:mace:shibboleth:2.0:idp:profiles:shibboleth:request:sso";
104     }
105
106     /** {@inheritDoc} */
107     public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
108         log.debug("Processing incomming request");
109
110         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
111         HttpSession httpSession = httpRequest.getSession();
112         LoginContext loginContext = (LoginContext) httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
113
114         if (loginContext == null) {
115             log.debug("User session does not contain a login context, processing as first leg of request");
116             performAuthentication(inTransport, outTransport);
117         } else if (!loginContext.isPrincipalAuthenticated()) {
118             log
119                     .debug("User session contained a login context but user was not authenticated, processing as first leg of request");
120             performAuthentication(inTransport, outTransport);
121         } else {
122             log.debug("User session contains a login context, processing as second leg of request");
123             completeAuthenticationRequest(inTransport, outTransport);
124         }
125     }
126
127     /**
128      * Creates a {@link LoginContext} an sends the request off to the AuthenticationManager to begin the process of
129      * authenticating the user.
130      * 
131      * @param inTransport inbound message transport
132      * @param outTransport outbound message transport
133      * 
134      * @throws ProfileException thrown if there is a problem creating the login context and transferring control to the
135      *             authentication manager
136      */
137     protected void performAuthentication(HTTPInTransport inTransport, HTTPOutTransport outTransport)
138             throws ProfileException {
139
140         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
141         HttpServletResponse httpResponse = ((HttpServletResponseAdapter) outTransport).getWrappedResponse();
142         HttpSession httpSession = httpRequest.getSession(true);
143
144         ShibbolethSSORequestContext requestContext = decodeRequest(inTransport, outTransport);
145         ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
146
147         RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(loginContext.getRelyingPartyId());
148         ProfileConfiguration ssoConfig = rpConfig.getProfileConfiguration(ShibbolethSSOConfiguration.PROFILE_ID);
149         if (ssoConfig == null) {
150             log.error("Shibboleth SSO profile is not configured for relying party " + loginContext.getRelyingPartyId());
151             throw new ProfileException("Shibboleth SSO profile is not configured for relying party "
152                     + loginContext.getRelyingPartyId());
153         }
154         loginContext.getRequestedAuthenticationMethods().add(rpConfig.getDefaultAuthenticationMethod());
155
156         httpSession.setAttribute(LoginContext.LOGIN_CONTEXT_KEY, loginContext);
157
158         try {
159             RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(authenticationManagerPath);
160             dispatcher.forward(httpRequest, httpResponse);
161             return;
162         } catch (IOException ex) {
163             httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
164             log.error("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
165             throw new ProfileException("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
166         } catch (ServletException ex) {
167             httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
168             log.error("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
169             throw new ProfileException("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
170         }
171     }
172
173     /**
174      * Decodes an incoming request and populates a created request context with the resultant information.
175      * 
176      * @param inTransport inbound message transport
177      * @param outTransport outbound message transport
178      * 
179      * @return the created request context
180      * 
181      * @throws ProfileException throw if there is a problem decoding the request
182      */
183     protected ShibbolethSSORequestContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
184             throws ProfileException {
185         log.debug("Decoding message with decoder binding {}", getInboundBinding());
186         
187         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
188
189         ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext();
190         requestContext.setMetadataProvider(getMetadataProvider());
191         requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
192
193         requestContext.setCommunicationProfileId(ShibbolethSSOConfiguration.PROFILE_ID);
194         requestContext.setInboundMessageTransport(inTransport);
195         requestContext.setInboundSAMLProtocol(ShibbolethConstants.SHIB_SSO_PROFILE_URI);
196         requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
197
198         requestContext.setOutboundMessageTransport(outTransport);
199         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML11P_NS);
200
201         SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
202         requestContext.setMessageDecoder(decoder);
203         try {
204             decoder.decode(requestContext);
205         } catch (MessageDecodingException e) {
206             log.error("Error decoding Shibboleth SSO request", e);
207             throw new ProfileException("Error decoding Shibboleth SSO request", e);
208         } catch (SecurityException e) {
209             log.error("Shibboleth SSO request does not meet security requirements", e);
210             throw new ProfileException("Shibboleth SSO request does not meet security requirements", e);
211         }
212
213         ShibbolethSSOLoginContext loginContext = new ShibbolethSSOLoginContext();
214         loginContext.setRelyingParty(requestContext.getInboundMessageIssuer());
215         loginContext.setSpAssertionConsumerService(requestContext.getSpAssertionConsumerService());
216         loginContext.setSpTarget(requestContext.getRelayState());
217         loginContext.setAuthenticationEngineURL(authenticationManagerPath);
218         loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(httpRequest));
219
220         requestContext.setLoginContext(loginContext);
221
222         return requestContext;
223     }
224
225     /**
226      * Creates a response to the Shibboleth SSO and sends the user, with response in tow, back to the relying party
227      * after they've been authenticated.
228      * 
229      * @param inTransport inbound message transport
230      * @param outTransport outbound message transport
231      * 
232      * @throws ProfileException thrown if the response can not be created and sent back to the relying party
233      */
234     protected void completeAuthenticationRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
235             throws ProfileException {
236         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
237         HttpSession httpSession = httpRequest.getSession(true);
238
239         ShibbolethSSOLoginContext loginContext = (ShibbolethSSOLoginContext) httpSession
240                 .getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
241         httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
242
243         ShibbolethSSORequestContext requestContext = buildRequestContext(loginContext, inTransport, outTransport);
244
245         Response samlResponse;
246         try {
247             if (loginContext.getPrincipalName() == null) {
248                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "User failed authentication"));
249                 throw new ProfileException("User failed authentication");
250             }
251
252             resolveAttributes(requestContext);
253
254             ArrayList<Statement> statements = new ArrayList<Statement>();
255             statements.add(buildAuthenticationStatement(requestContext));
256             if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
257                 AttributeStatement attributeStatement = buildAttributeStatement(requestContext,
258                         "urn:oasis:names:tc:SAML:1.0:cm:bearer");
259                 if (attributeStatement != null) {
260                     requestContext.setRequestedAttributes(requestContext.getPrincipalAttributes().keySet());
261                     statements.add(attributeStatement);
262                 }
263             }
264
265             samlResponse = buildResponse(requestContext, statements);
266         } catch (ProfileException e) {
267             samlResponse = buildErrorResponse(requestContext);
268         }
269
270         requestContext.setOutboundSAMLMessage(samlResponse);
271         requestContext.setOutboundSAMLMessageId(samlResponse.getID());
272         requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
273         encodeResponse(requestContext);
274         writeAuditLogEntry(requestContext);
275     }
276
277     /**
278      * Creates an authentication request context from the current environmental information.
279      * 
280      * @param loginContext current login context
281      * @param in inbound transport
282      * @param out outbount transport
283      * 
284      * @return created authentication request context
285      * 
286      * @throws ProfileException thrown if there is a problem creating the context
287      */
288     protected ShibbolethSSORequestContext buildRequestContext(ShibbolethSSOLoginContext loginContext,
289             HTTPInTransport in, HTTPOutTransport out) throws ProfileException {
290         ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext();
291
292         requestContext.setMessageDecoder(getMessageDecoders().get(getInboundBinding()));
293
294         requestContext.setLoginContext(loginContext);
295         requestContext.setPrincipalName(loginContext.getPrincipalName());
296         requestContext.setPrincipalAuthenticationMethod(loginContext.getAuthenticationMethod());
297         requestContext.setUserSession(getUserSession(in));
298         requestContext.setRelayState(loginContext.getSpTarget());
299
300         requestContext.setInboundMessageTransport(in);
301         requestContext.setInboundSAMLProtocol(ShibbolethConstants.SHIB_SSO_PROFILE_URI);
302
303         requestContext.setOutboundMessageTransport(out);
304         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
305
306         MetadataProvider metadataProvider = getMetadataProvider();
307         requestContext.setMetadataProvider(metadataProvider);
308
309         String relyingPartyId = loginContext.getRelyingPartyId();
310         requestContext.setInboundMessageIssuer(relyingPartyId);
311
312         try {
313             EntityDescriptor relyingPartyMetadata = metadataProvider.getEntityDescriptor(relyingPartyId);
314             if (relyingPartyMetadata != null) {
315                 requestContext.setPeerEntityMetadata(relyingPartyMetadata);
316                 requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
317                 requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata
318                         .getSPSSODescriptor(SAMLConstants.SAML11P_NS));
319             }
320         } catch (MetadataProviderException e) {
321             log.error("Unable to locate metadata for relying party");
322             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
323                     "Error locating relying party metadata"));
324             throw new ProfileException("Error locating relying party metadata");
325         }
326
327         RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
328         if (rpConfig == null) {
329             log.error("Unable to retrieve relying party configuration data for entity with ID {}", relyingPartyId);
330             throw new ProfileException("Unable to retrieve relying party configuration data for entity with ID "
331                     + relyingPartyId);
332         }
333         requestContext.setRelyingPartyConfiguration(rpConfig);
334
335         ShibbolethSSOConfiguration profileConfig = (ShibbolethSSOConfiguration) rpConfig
336                 .getProfileConfiguration(ShibbolethSSOConfiguration.PROFILE_ID);
337         requestContext.setProfileConfiguration(profileConfig);
338         requestContext.setOutboundMessageArtifactType(profileConfig.getOutboundArtifactType());
339         if (profileConfig.getSigningCredential() != null) {
340             requestContext.setOutboundSAMLMessageSigningCredential(profileConfig.getSigningCredential());
341         } else if (rpConfig.getDefaultSigningCredential() != null) {
342             requestContext.setOutboundSAMLMessageSigningCredential(rpConfig.getDefaultSigningCredential());
343         }
344
345         requestContext.setPeerEntityEndpoint(selectEndpoint(requestContext));
346
347         String assertingPartyId = rpConfig.getProviderId();
348         requestContext.setLocalEntityId(assertingPartyId);
349         try {
350             EntityDescriptor localEntityDescriptor = metadataProvider.getEntityDescriptor(assertingPartyId);
351             if (localEntityDescriptor != null) {
352                 requestContext.setLocalEntityMetadata(localEntityDescriptor);
353                 requestContext.setLocalEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
354                 requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
355                         .getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
356             }
357         } catch (MetadataProviderException e) {
358             log.error("Unable to locate metadata for asserting party");
359             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
360                     "Error locating asserting party metadata"));
361             throw new ProfileException("Error locating asserting party metadata");
362         }
363
364         return requestContext;
365     }
366
367     /**
368      * Selects the appropriate endpoint for the relying party and stores it in the request context.
369      * 
370      * @param requestContext current request context
371      * 
372      * @return Endpoint selected from the information provided in the request context
373      */
374     protected Endpoint selectEndpoint(ShibbolethSSORequestContext requestContext) {
375         ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
376
377         ShibbolethSSOEndpointSelector endpointSelector = new ShibbolethSSOEndpointSelector();
378         endpointSelector.setSpAssertionConsumerService(loginContext.getSpAssertionConsumerService());
379         endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
380         endpointSelector.setMetadataProvider(getMetadataProvider());
381         endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
382         endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
383         endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
384         endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
385
386         return endpointSelector.selectEndpoint();
387     }
388
389     /**
390      * Builds the authentication statement for the authenticated principal.
391      * 
392      * @param requestContext current request context
393      * 
394      * @return the created statement
395      * 
396      * @throws ProfileException thrown if the authentication statement can not be created
397      */
398     protected AuthenticationStatement buildAuthenticationStatement(ShibbolethSSORequestContext requestContext)
399             throws ProfileException {
400         ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
401
402         AuthenticationStatement statement = authnStatementBuilder.buildObject();
403         statement.setAuthenticationInstant(loginContext.getAuthenticationInstant());
404         statement.setAuthenticationMethod(loginContext.getAuthenticationMethod());
405
406         statement.setSubjectLocality(buildSubjectLocality(requestContext));
407
408         Subject statementSubject = buildSubject(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:bearer");
409         statement.setSubject(statementSubject);
410
411         return statement;
412     }
413
414     /**
415      * Constructs the subject locality for the authentication statement.
416      * 
417      * @param requestContext curent request context
418      * 
419      * @return subject locality for the authentication statement
420      */
421     protected SubjectLocality buildSubjectLocality(ShibbolethSSORequestContext requestContext) {
422         SubjectLocality subjectLocality = subjectLocalityBuilder.buildObject();
423
424         HTTPInTransport inTransport = (HTTPInTransport) requestContext.getInboundMessageTransport();
425         subjectLocality.setIPAddress(inTransport.getPeerAddress());
426         subjectLocality.setDNSAddress(inTransport.getPeerDomainName());
427
428         return subjectLocality;
429     }
430
431     /** Represents the internal state of a Shibboleth SSO Request while it's being processed by the IdP. */
432     public class ShibbolethSSORequestContext extends
433             BaseSAML1ProfileRequestContext<Request, Response, ShibbolethSSOConfiguration> {
434
435         /** SP-provide assertion consumer service URL. */
436         private String spAssertionConsumerService;
437
438         /** Current login context. */
439         private ShibbolethSSOLoginContext loginContext;
440
441         /**
442          * Gets the current login context.
443          * 
444          * @return current login context
445          */
446         public ShibbolethSSOLoginContext getLoginContext() {
447             return loginContext;
448         }
449
450         /**
451          * Sets the current login context.
452          * 
453          * @param context current login context
454          */
455         public void setLoginContext(ShibbolethSSOLoginContext context) {
456             loginContext = context;
457         }
458
459         /**
460          * Gets the SP-provided assertion consumer service URL.
461          * 
462          * @return SP-provided assertion consumer service URL
463          */
464         public String getSpAssertionConsumerService() {
465             return spAssertionConsumerService;
466         }
467
468         /**
469          * Sets the SP-provided assertion consumer service URL.
470          * 
471          * @param acs SP-provided assertion consumer service URL
472          */
473         public void setSpAssertionConsumerService(String acs) {
474             spAssertionConsumerService = acs;
475         }
476     }
477 }