Send back a valid authn statement upon successful authn even if attribute resolution...
[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 import edu.internet2.middleware.shibboleth.idp.util.HttpServletHelper;
65
66 /** Shibboleth SSO request profile handler. */
67 public class ShibbolethSSOProfileHandler extends AbstractSAML1ProfileHandler {
68
69     /** Class logger. */
70     private final Logger log = LoggerFactory.getLogger(ShibbolethSSOProfileHandler.class);
71
72     /** Builder of AuthenticationStatement objects. */
73     private SAMLObjectBuilder<AuthenticationStatement> authnStatementBuilder;
74
75     /** Builder of SubjectLocality objects. */
76     private SAMLObjectBuilder<SubjectLocality> subjectLocalityBuilder;
77
78     /** Builder of Endpoint objects. */
79     private SAMLObjectBuilder<Endpoint> endpointBuilder;
80
81     /** URL of the authentication manager servlet. */
82     private String authenticationManagerPath;
83
84     /**
85      * Constructor.
86      * 
87      * @param authnManagerPath path to the authentication manager servlet
88      */
89     public ShibbolethSSOProfileHandler(String authnManagerPath) {
90         if (DatatypeHelper.isEmpty(authnManagerPath)) {
91             throw new IllegalArgumentException("Authentication manager path may not be null");
92         }
93         authenticationManagerPath = authnManagerPath;
94
95         authnStatementBuilder = (SAMLObjectBuilder<AuthenticationStatement>) getBuilderFactory().getBuilder(
96                 AuthenticationStatement.DEFAULT_ELEMENT_NAME);
97
98         subjectLocalityBuilder = (SAMLObjectBuilder<SubjectLocality>) getBuilderFactory().getBuilder(
99                 SubjectLocality.DEFAULT_ELEMENT_NAME);
100
101         endpointBuilder = (SAMLObjectBuilder<Endpoint>) getBuilderFactory().getBuilder(
102                 AssertionConsumerService.DEFAULT_ELEMENT_NAME);
103     }
104
105     /** {@inheritDoc} */
106     public String getProfileId() {
107         return ShibbolethSSOConfiguration.PROFILE_ID;
108     }
109
110     /** {@inheritDoc} */
111     public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
112         log.debug("Processing incoming request");
113
114         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
115         LoginContext loginContext = HttpServletHelper.getLoginContext(httpRequest);
116
117         if (loginContext == null) {
118             log.debug("Incoming request does not contain a login context, processing as first leg of request");
119             performAuthentication(inTransport, outTransport);
120         } else {
121             log.debug("Incoming request contains a login context, processing as second leg of request");
122             completeAuthenticationRequest(inTransport, outTransport);
123         }
124     }
125
126     /**
127      * Creates a {@link LoginContext} an sends the request off to the AuthenticationManager to begin the process of
128      * authenticating the user.
129      * 
130      * @param inTransport inbound message transport
131      * @param outTransport outbound message transport
132      * 
133      * @throws ProfileException thrown if there is a problem creating the login context and transferring control to the
134      *             authentication manager
135      */
136     protected void performAuthentication(HTTPInTransport inTransport, HTTPOutTransport outTransport)
137             throws ProfileException {
138
139         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
140         HttpServletResponse httpResponse = ((HttpServletResponseAdapter) outTransport).getWrappedResponse();
141         ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext();
142
143         decodeRequest(requestContext, inTransport, outTransport);
144         ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
145
146         RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(loginContext.getRelyingPartyId());
147         loginContext.setDefaultAuthenticationMethod(rpConfig.getDefaultAuthenticationMethod());
148         ProfileConfiguration ssoConfig = rpConfig.getProfileConfiguration(ShibbolethSSOConfiguration.PROFILE_ID);
149         if (ssoConfig == null) {
150             String msg = MessageFormatter.format("Shibboleth SSO profile is not configured for relying party '{}'",
151                     loginContext.getRelyingPartyId());
152             log.warn(msg);
153             throw new ProfileException(msg);
154         }
155
156         HttpServletHelper.bindLoginContext(loginContext, httpRequest);
157
158         try {
159             RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(authenticationManagerPath);
160             dispatcher.forward(httpRequest, httpResponse);
161             return;
162         } catch (IOException e) {
163             String msg = "Error forwarding Shibboleth SSO request to AuthenticationManager";
164             log.error(msg, e);
165             throw new ProfileException(msg, e);
166         } catch (ServletException e) {
167             String msg = "Error forwarding Shibboleth SSO request to AuthenticationManager";
168             log.error(msg, e);
169             throw new ProfileException(msg, e);
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      * @param requestContext the request context to which decoded information should be added
179      * 
180      * @throws ProfileException throw if there is a problem decoding the request
181      */
182     protected void decodeRequest(ShibbolethSSORequestContext requestContext, HTTPInTransport inTransport,
183             HTTPOutTransport outTransport) throws ProfileException {
184         if (log.isDebugEnabled()) {
185             log.debug("Decoding message with decoder binding {}",
186                     getInboundMessageDecoder(requestContext).getBindingURI());
187         }
188
189         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
190
191         requestContext.setCommunicationProfileId(getProfileId());
192
193         requestContext.setMetadataProvider(getMetadataProvider());
194         requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
195
196         requestContext.setCommunicationProfileId(ShibbolethSSOConfiguration.PROFILE_ID);
197         requestContext.setInboundMessageTransport(inTransport);
198         requestContext.setInboundSAMLProtocol(ShibbolethConstants.SHIB_SSO_PROFILE_URI);
199         requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
200
201         requestContext.setOutboundMessageTransport(outTransport);
202         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML11P_NS);
203
204         SAMLMessageDecoder decoder = getInboundMessageDecoder(requestContext);
205         requestContext.setMessageDecoder(decoder);
206         try {
207             decoder.decode(requestContext);
208             log.debug("Decoded Shibboleth SSO request from relying party '{}'", requestContext
209                     .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) HttpServletHelper.getLoginContext(httpRequest);
242
243         ShibbolethSSORequestContext requestContext = buildRequestContext(loginContext, inTransport, outTransport);
244
245         Response samlResponse;
246         try {
247             if (loginContext.getAuthenticationFailure() != null) {
248                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "User failed authentication"));
249                 throw new ProfileException("Authentication failure", loginContext.getAuthenticationFailure());
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.setReleasedAttributes(requestContext.getAttributes().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         requestContext.setCommunicationProfileId(getProfileId());
292
293         requestContext.setMessageDecoder(getInboundMessageDecoder(requestContext));
294
295         requestContext.setLoginContext(loginContext);
296         requestContext.setRelayState(loginContext.getSpTarget());
297
298         requestContext.setInboundMessageTransport(in);
299         requestContext.setInboundSAMLProtocol(ShibbolethConstants.SHIB_SSO_PROFILE_URI);
300
301         requestContext.setOutboundMessageTransport(out);
302         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
303
304         requestContext.setMetadataProvider(getMetadataProvider());
305
306         String relyingPartyId = loginContext.getRelyingPartyId();
307         requestContext.setPeerEntityId(relyingPartyId);
308         requestContext.setInboundMessageIssuer(relyingPartyId);
309
310         populateRequestContext(requestContext);
311
312         return requestContext;
313     }
314
315     /** {@inheritDoc} */
316     protected void populateRelyingPartyInformation(BaseSAMLProfileRequestContext requestContext)
317             throws ProfileException {
318         super.populateRelyingPartyInformation(requestContext);
319
320         EntityDescriptor relyingPartyMetadata = requestContext.getPeerEntityMetadata();
321         if (relyingPartyMetadata != null) {
322             requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
323             requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata.getSPSSODescriptor(SAMLConstants.SAML11P_NS));
324         }
325     }
326
327     /** {@inheritDoc} */
328     protected void populateAssertingPartyInformation(BaseSAMLProfileRequestContext requestContext)
329             throws ProfileException {
330         super.populateAssertingPartyInformation(requestContext);
331
332         EntityDescriptor localEntityDescriptor = requestContext.getLocalEntityMetadata();
333         if (localEntityDescriptor != null) {
334             requestContext.setLocalEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
335             requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
336                     .getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
337         }
338     }
339
340     /** {@inheritDoc} */
341     protected void populateSAMLMessageInformation(BaseSAMLProfileRequestContext requestContext) throws ProfileException {
342         // nothing to do here
343     }
344
345     /**
346      * Selects the appropriate endpoint for the relying party and stores it in the request context.
347      * 
348      * @param requestContext current request context
349      * 
350      * @return Endpoint selected from the information provided in the request context
351      */
352     protected Endpoint selectEndpoint(BaseSAMLProfileRequestContext requestContext) {
353         ShibbolethSSOLoginContext loginContext = ((ShibbolethSSORequestContext) requestContext).getLoginContext();
354
355         Endpoint endpoint = null;
356         if (requestContext.getRelyingPartyConfiguration().getRelyingPartyId() == SAMLMDRelyingPartyConfigurationManager.ANONYMOUS_RP_NAME) {
357             if (loginContext.getSpAssertionConsumerService() != null) {
358                 endpoint = endpointBuilder.buildObject();
359                 endpoint.setLocation(loginContext.getSpAssertionConsumerService());
360                 endpoint.setBinding(getSupportedOutboundBindings().get(0));
361                 log.warn("Generating endpoint for anonymous relying party. ACS url {} and binding {}", new Object[] {
362                         requestContext.getInboundMessageIssuer(), endpoint.getLocation(), endpoint.getBinding(), });
363             } else {
364                 log.warn("Unable to generate endpoint for anonymous party.  No ACS url provided.");
365             }
366         } else {
367             ShibbolethSSOEndpointSelector endpointSelector = new ShibbolethSSOEndpointSelector();
368             endpointSelector.setSpAssertionConsumerService(loginContext.getSpAssertionConsumerService());
369             endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
370             endpointSelector.setMetadataProvider(getMetadataProvider());
371             endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
372             endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
373             endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
374             endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
375             endpoint = endpointSelector.selectEndpoint();
376         }
377
378         return endpoint;
379     }
380
381     /**
382      * Builds the authentication statement for the authenticated principal.
383      * 
384      * @param requestContext current request context
385      * 
386      * @return the created statement
387      * 
388      * @throws ProfileException thrown if the authentication statement can not be created
389      */
390     protected AuthenticationStatement buildAuthenticationStatement(ShibbolethSSORequestContext requestContext)
391             throws ProfileException {
392         ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
393
394         AuthenticationStatement statement = authnStatementBuilder.buildObject();
395         statement.setAuthenticationInstant(loginContext.getAuthenticationInstant());
396         statement.setAuthenticationMethod(loginContext.getAuthenticationMethod());
397
398         statement.setSubjectLocality(buildSubjectLocality(requestContext));
399
400         Subject statementSubject;
401         Endpoint endpoint = selectEndpoint(requestContext);
402         if (endpoint.getBinding().equals(SAMLConstants.SAML1_ARTIFACT_BINDING_URI)) {
403             statementSubject = buildSubject(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:artifact");
404         } else {
405             statementSubject = buildSubject(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:bearer");
406         }
407         statement.setSubject(statementSubject);
408
409         return statement;
410     }
411
412     /**
413      * Constructs the subject locality for the authentication statement.
414      * 
415      * @param requestContext current request context
416      * 
417      * @return subject locality for the authentication statement
418      */
419     protected SubjectLocality buildSubjectLocality(ShibbolethSSORequestContext requestContext) {
420         SubjectLocality subjectLocality = subjectLocalityBuilder.buildObject();
421
422         HTTPInTransport inTransport = (HTTPInTransport) requestContext.getInboundMessageTransport();
423         subjectLocality.setIPAddress(inTransport.getPeerAddress());
424
425         return subjectLocality;
426     }
427
428     /** Represents the internal state of a Shibboleth SSO Request while it's being processed by the IdP. */
429     public class ShibbolethSSORequestContext extends
430             BaseSAML1ProfileRequestContext<Request, Response, ShibbolethSSOConfiguration> {
431
432         /** SP-provide assertion consumer service URL. */
433         private String spAssertionConsumerService;
434
435         /** Current login context. */
436         private ShibbolethSSOLoginContext loginContext;
437
438         /**
439          * Gets the current login context.
440          * 
441          * @return current login context
442          */
443         public ShibbolethSSOLoginContext getLoginContext() {
444             return loginContext;
445         }
446
447         /**
448          * Sets the current login context.
449          * 
450          * @param context current login context
451          */
452         public void setLoginContext(ShibbolethSSOLoginContext context) {
453             loginContext = context;
454         }
455
456         /**
457          * Gets the SP-provided assertion consumer service URL.
458          * 
459          * @return SP-provided assertion consumer service URL
460          */
461         public String getSpAssertionConsumerService() {
462             return spAssertionConsumerService;
463         }
464
465         /**
466          * Sets the SP-provided assertion consumer service URL.
467          * 
468          * @param acs SP-provided assertion consumer service URL
469          */
470         public void setSpAssertionConsumerService(String acs) {
471             spAssertionConsumerService = acs;
472         }
473     }
474 }