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