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