View Javadoc

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