https://bugs.internet2.edu/jira/browse/SIDP-265
[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         loginContext.setDefaultAuthenticationMethod(rpConfig.getDefaultAuthenticationMethod());
150         ProfileConfiguration ssoConfig = rpConfig.getProfileConfiguration(ShibbolethSSOConfiguration.PROFILE_ID);
151         if (ssoConfig == null) {
152             String msg = MessageFormatter.format("Shibboleth SSO profile is not configured for relying party '{}'", loginContext.getRelyingPartyId());
153             log.warn(msg);
154             throw new ProfileException(msg);
155         }
156
157         httpRequest.setAttribute(LoginContext.LOGIN_CONTEXT_KEY, loginContext);
158
159         try {
160             RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(authenticationManagerPath);
161             dispatcher.forward(httpRequest, httpResponse);
162             return;
163         } catch (IOException e) {
164             String msg = "Error forwarding Shibboleth SSO request to AuthenticationManager"; 
165             log.error(msg, e);
166             throw new ProfileException(msg, e);
167         } catch (ServletException e) {
168             String msg = "Error forwarding Shibboleth SSO request to AuthenticationManager";
169             log.error(msg, e);
170             throw new ProfileException(msg, e);
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             log.debug("Decoded Shibboleth SSO request from relying party '{}'", requestContext.getInboundMessageIssuer());
207         } catch (MessageDecodingException e) {
208             String msg = "Error decoding Shibboleth SSO request"; 
209             log.warn(msg, e);
210             throw new ProfileException(msg, e);
211         } catch (SecurityException e) {
212             String msg = "Shibboleth SSO request does not meet security requirements";
213             log.warn(msg, e);
214             throw new ProfileException("msg", e);
215         }
216
217         ShibbolethSSOLoginContext loginContext = new ShibbolethSSOLoginContext();
218         loginContext.setRelyingParty(requestContext.getInboundMessageIssuer());
219         loginContext.setSpAssertionConsumerService(requestContext.getSpAssertionConsumerService());
220         loginContext.setSpTarget(requestContext.getRelayState());
221         loginContext.setAuthenticationEngineURL(authenticationManagerPath);
222         loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(httpRequest));
223         requestContext.setLoginContext(loginContext);
224     }
225
226     /**
227      * Creates a response to the Shibboleth SSO and sends the user, with response in tow, back to the relying party
228      * after they've been authenticated.
229      * 
230      * @param inTransport inbound message transport
231      * @param outTransport outbound message transport
232      * 
233      * @throws ProfileException thrown if the response can not be created and sent back to the relying party
234      */
235     protected void completeAuthenticationRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
236             throws ProfileException {
237         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
238         ShibbolethSSOLoginContext loginContext = (ShibbolethSSOLoginContext) httpRequest
239                 .getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
240
241         ShibbolethSSORequestContext requestContext = buildRequestContext(loginContext, inTransport, outTransport);
242
243         Response samlResponse;
244         try {
245             if (loginContext.getAuthenticationFailure() != null) {
246                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "User failed authentication"));
247                 throw new ProfileException("Authentication failure", loginContext.getAuthenticationFailure());
248             }
249
250             resolveAttributes(requestContext);
251
252             ArrayList<Statement> statements = new ArrayList<Statement>();
253             statements.add(buildAuthenticationStatement(requestContext));
254             if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
255                 AttributeStatement attributeStatement = buildAttributeStatement(requestContext,
256                         "urn:oasis:names:tc:SAML:1.0:cm:bearer");
257                 if (attributeStatement != null) {
258                     requestContext.setReleasedAttributes(requestContext.getAttributes().keySet());
259                     statements.add(attributeStatement);
260                 }
261             }
262
263             samlResponse = buildResponse(requestContext, statements);
264         } catch (ProfileException e) {
265             samlResponse = buildErrorResponse(requestContext);
266         }
267
268         requestContext.setOutboundSAMLMessage(samlResponse);
269         requestContext.setOutboundSAMLMessageId(samlResponse.getID());
270         requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
271         encodeResponse(requestContext);
272         writeAuditLogEntry(requestContext);
273     }
274
275     /**
276      * Creates an authentication request context from the current environmental information.
277      * 
278      * @param loginContext current login context
279      * @param in inbound transport
280      * @param out outbount transport
281      * 
282      * @return created authentication request context
283      * 
284      * @throws ProfileException thrown if there is a problem creating the context
285      */
286     protected ShibbolethSSORequestContext buildRequestContext(ShibbolethSSOLoginContext loginContext,
287             HTTPInTransport in, HTTPOutTransport out) throws ProfileException {
288         ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext();
289         requestContext.setCommunicationProfileId(getProfileId());
290
291         requestContext.setMessageDecoder(getMessageDecoders().get(getInboundBinding()));
292
293         requestContext.setLoginContext(loginContext);
294         requestContext.setRelayState(loginContext.getSpTarget());
295
296         requestContext.setInboundMessageTransport(in);
297         requestContext.setInboundSAMLProtocol(ShibbolethConstants.SHIB_SSO_PROFILE_URI);
298
299         requestContext.setOutboundMessageTransport(out);
300         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
301
302         requestContext.setMetadataProvider(getMetadataProvider());
303
304         String relyingPartyId = loginContext.getRelyingPartyId();
305         requestContext.setPeerEntityId(relyingPartyId);
306         requestContext.setInboundMessageIssuer(relyingPartyId);
307
308         populateRequestContext(requestContext);
309
310         return requestContext;
311     }
312
313     /** {@inheritDoc} */
314     protected void populateRelyingPartyInformation(BaseSAMLProfileRequestContext requestContext)
315             throws ProfileException {
316         super.populateRelyingPartyInformation(requestContext);
317
318         EntityDescriptor relyingPartyMetadata = requestContext.getPeerEntityMetadata();
319         if (relyingPartyMetadata != null) {
320             requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
321             requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata.getSPSSODescriptor(SAMLConstants.SAML11P_NS));
322         }
323     }
324
325     /** {@inheritDoc} */
326     protected void populateAssertingPartyInformation(BaseSAMLProfileRequestContext requestContext)
327             throws ProfileException {
328         super.populateAssertingPartyInformation(requestContext);
329
330         EntityDescriptor localEntityDescriptor = requestContext.getLocalEntityMetadata();
331         if (localEntityDescriptor != null) {
332             requestContext.setLocalEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
333             requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
334                     .getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
335         }
336     }
337
338     /** {@inheritDoc} */
339     protected void populateSAMLMessageInformation(BaseSAMLProfileRequestContext requestContext) throws ProfileException {
340         // nothing to do here
341     }
342
343     /**
344      * Selects the appropriate endpoint for the relying party and stores it in the request context.
345      * 
346      * @param requestContext current request context
347      * 
348      * @return Endpoint selected from the information provided in the request context
349      */
350     protected Endpoint selectEndpoint(BaseSAMLProfileRequestContext requestContext) {
351         ShibbolethSSOLoginContext loginContext = ((ShibbolethSSORequestContext) requestContext).getLoginContext();
352
353         Endpoint endpoint = null;
354         if (requestContext.getRelyingPartyConfiguration().getRelyingPartyId() == SAMLMDRelyingPartyConfigurationManager.ANONYMOUS_RP_NAME) {
355             if (loginContext.getSpAssertionConsumerService() != null) {
356                 endpoint = endpointBuilder.buildObject();
357                 endpoint.setLocation(loginContext.getSpAssertionConsumerService());
358                 endpoint.setBinding(getSupportedOutboundBindings().get(0));
359                 log.warn("Generating endpoint for anonymous relying party. ACS url {} and binding {}", new Object[] {
360                         requestContext.getInboundMessageIssuer(), endpoint.getLocation(), endpoint.getBinding(), });
361             } else {
362                 log.warn("Unable to generate endpoint for anonymous party.  No ACS url provided.");
363             }
364         } else {
365             ShibbolethSSOEndpointSelector endpointSelector = new ShibbolethSSOEndpointSelector();
366             endpointSelector.setSpAssertionConsumerService(loginContext.getSpAssertionConsumerService());
367             endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
368             endpointSelector.setMetadataProvider(getMetadataProvider());
369             endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
370             endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
371             endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
372             endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
373             endpoint = endpointSelector.selectEndpoint();
374         }
375
376         return endpoint;
377     }
378
379     /**
380      * Builds the authentication statement for the authenticated principal.
381      * 
382      * @param requestContext current request context
383      * 
384      * @return the created statement
385      * 
386      * @throws ProfileException thrown if the authentication statement can not be created
387      */
388     protected AuthenticationStatement buildAuthenticationStatement(ShibbolethSSORequestContext requestContext)
389             throws ProfileException {
390         ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
391
392         AuthenticationStatement statement = authnStatementBuilder.buildObject();
393         statement.setAuthenticationInstant(loginContext.getAuthenticationInstant());
394         statement.setAuthenticationMethod(loginContext.getAuthenticationMethod());
395
396         statement.setSubjectLocality(buildSubjectLocality(requestContext));
397
398         Subject statementSubject;
399         Endpoint endpoint = selectEndpoint(requestContext);
400         if (endpoint.getBinding().equals(SAMLConstants.SAML1_ARTIFACT_BINDING_URI)) {
401             statementSubject = buildSubject(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:artifact");
402         } else {
403             statementSubject = buildSubject(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:bearer");
404         }
405         statement.setSubject(statementSubject);
406
407         return statement;
408     }
409
410     /**
411      * Constructs the subject locality for the authentication statement.
412      * 
413      * @param requestContext current request context
414      * 
415      * @return subject locality for the authentication statement
416      */
417     protected SubjectLocality buildSubjectLocality(ShibbolethSSORequestContext requestContext) {
418         SubjectLocality subjectLocality = subjectLocalityBuilder.buildObject();
419
420         HTTPInTransport inTransport = (HTTPInTransport) requestContext.getInboundMessageTransport();
421         subjectLocality.setIPAddress(inTransport.getPeerAddress());
422
423         return subjectLocality;
424     }
425
426     /** Represents the internal state of a Shibboleth SSO Request while it's being processed by the IdP. */
427     public class ShibbolethSSORequestContext extends
428             BaseSAML1ProfileRequestContext<Request, Response, ShibbolethSSOConfiguration> {
429
430         /** SP-provide assertion consumer service URL. */
431         private String spAssertionConsumerService;
432
433         /** Current login context. */
434         private ShibbolethSSOLoginContext loginContext;
435
436         /**
437          * Gets the current login context.
438          * 
439          * @return current login context
440          */
441         public ShibbolethSSOLoginContext getLoginContext() {
442             return loginContext;
443         }
444
445         /**
446          * Sets the current login context.
447          * 
448          * @param context current login context
449          */
450         public void setLoginContext(ShibbolethSSOLoginContext context) {
451             loginContext = context;
452         }
453
454         /**
455          * Gets the SP-provided assertion consumer service URL.
456          * 
457          * @return SP-provided assertion consumer service URL
458          */
459         public String getSpAssertionConsumerService() {
460             return spAssertionConsumerService;
461         }
462
463         /**
464          * Sets the SP-provided assertion consumer service URL.
465          * 
466          * @param acs SP-provided assertion consumer service URL
467          */
468         public void setSpAssertionConsumerService(String acs) {
469             spAssertionConsumerService = acs;
470         }
471     }
472 }