Mostly synched with OpenSAML changes
[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.io.UnsupportedEncodingException;
21 import java.net.URLDecoder;
22 import java.util.ArrayList;
23 import java.util.List;
24
25 import javax.servlet.RequestDispatcher;
26 import javax.servlet.ServletException;
27 import javax.servlet.http.HttpServletRequest;
28 import javax.servlet.http.HttpServletResponse;
29 import javax.servlet.http.HttpSession;
30
31 import org.apache.log4j.Logger;
32 import org.opensaml.common.SAMLObjectBuilder;
33 import org.opensaml.common.binding.BasicEndpointSelector;
34 import org.opensaml.common.xml.SAMLConstants;
35 import org.opensaml.saml1.core.AuthenticationStatement;
36 import org.opensaml.saml1.core.Request;
37 import org.opensaml.saml1.core.Response;
38 import org.opensaml.saml1.core.Statement;
39 import org.opensaml.saml1.core.StatusCode;
40 import org.opensaml.saml1.core.Subject;
41 import org.opensaml.saml1.core.SubjectLocality;
42 import org.opensaml.saml2.metadata.AssertionConsumerService;
43 import org.opensaml.saml2.metadata.Endpoint;
44 import org.opensaml.saml2.metadata.EntityDescriptor;
45 import org.opensaml.saml2.metadata.IDPSSODescriptor;
46 import org.opensaml.saml2.metadata.SPSSODescriptor;
47 import org.opensaml.saml2.metadata.provider.MetadataProvider;
48 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
49 import org.opensaml.ws.message.encoder.MessageEncodingException;
50 import org.opensaml.ws.transport.http.HTTPInTransport;
51 import org.opensaml.ws.transport.http.HTTPOutTransport;
52 import org.opensaml.ws.transport.http.HttpServletRequestAdapter;
53 import org.opensaml.ws.transport.http.HttpServletResponseAdapter;
54 import org.opensaml.xml.util.DatatypeHelper;
55
56 import edu.internet2.middleware.shibboleth.common.ShibbolethConstants;
57 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
58 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
59 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml1.ShibbolethSSOConfiguration;
60 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.SSOConfiguration;
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 = Logger.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     /** URL of the authentication manager servlet. */
78     private String authenticationManagerPath;
79
80     /** URI of SAML 1 bindings supported for outgoing message encoding. */
81     private ArrayList<String> supportedOutgoingBindings;
82
83     /**
84      * Constructor.
85      * 
86      * @param authnManagerPath path to the authentication manager servlet
87      * @param outgoingBindings URIs of SAML 1 bindings supported for outgoing message encoding
88      * 
89      * @throws IllegalArgumentException thrown if either the authentication manager path or encoding binding URI are
90      *             null or empty
91      */
92     public ShibbolethSSOProfileHandler(String authnManagerPath, List<String> outgoingBindings) {
93         if (DatatypeHelper.isEmpty(authnManagerPath)) {
94             throw new IllegalArgumentException("Authentication manager path may not be null");
95         }
96         authenticationManagerPath = authnManagerPath;
97
98         if (outgoingBindings == null || outgoingBindings.isEmpty()) {
99             throw new IllegalArgumentException("List of supported outgoing bindings may not be empty");
100         }
101         supportedOutgoingBindings = new ArrayList<String>(outgoingBindings);
102
103         authnStatementBuilder = (SAMLObjectBuilder<AuthenticationStatement>) getBuilderFactory().getBuilder(
104                 AuthenticationStatement.DEFAULT_ELEMENT_NAME);
105
106         subjectLocalityBuilder = (SAMLObjectBuilder<SubjectLocality>) getBuilderFactory().getBuilder(
107                 SubjectLocality.DEFAULT_ELEMENT_NAME);
108     }
109
110     /** {@inheritDoc} */
111     public String getProfileId() {
112         return "urn:mace:shibboleth:2.0:idp:profiles:shibboleth:request:sso";
113     }
114
115     /** {@inheritDoc} */
116     public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
117         if (log.isDebugEnabled()) {
118             log.debug("Processing incomming request");
119         }
120
121         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
122         HttpSession httpSession = httpRequest.getSession();
123
124         if (httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY) == null) {
125             if (log.isDebugEnabled()) {
126                 log.debug("User session does not contain a login context, processing as first leg of request");
127             }
128             performAuthentication(inTransport, outTransport);
129         } else {
130             if (log.isDebugEnabled()) {
131                 log.debug("User session contains a login context, processing as second leg of request");
132             }
133             completeAuthenticationRequest(inTransport, outTransport);
134         }
135     }
136
137     /**
138      * Creates a {@link LoginContext} an sends the request off to the AuthenticationManager to begin the process of
139      * authenticating the user.
140      * 
141      * @param inTransport inbound message transport
142      * @param outTransport outbound message transport
143      * 
144      * @throws ProfileException thrown if there is a problem creating the login context and transferring control to the
145      *             authentication manager
146      */
147     protected void performAuthentication(HTTPInTransport inTransport, HTTPOutTransport outTransport)
148             throws ProfileException {
149
150         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
151         HttpServletResponse httpResponse = ((HttpServletResponseAdapter) outTransport).getWrappedResponse();
152         HttpSession httpSession = httpRequest.getSession(true);
153
154         LoginContext loginContext = buildLoginContext(httpRequest);
155         if (getRelyingPartyConfiguration(loginContext.getRelyingPartyId()) == null) {
156             log.error("Shibboleth SSO profile is not configured for relying party " + loginContext.getRelyingPartyId());
157             throw new ProfileException("Shibboleth SSO profile is not configured for relying party "
158                     + loginContext.getRelyingPartyId());
159         }
160
161         httpSession.setAttribute(LoginContext.LOGIN_CONTEXT_KEY, loginContext);
162
163         try {
164             RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(authenticationManagerPath);
165             dispatcher.forward(httpRequest, httpResponse);
166             return;
167         } catch (IOException ex) {
168             log.error("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
169             throw new ProfileException("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
170         } catch (ServletException ex) {
171             log.error("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
172             throw new ProfileException("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
173         }
174     }
175
176     /**
177      * Creates a response to the Shibboleth SSO and sends the user, with response in tow, back to the relying party
178      * after they've been authenticated.
179      * 
180      * @param inTransport inbound message transport
181      * @param outTransport outbound message transport
182      * 
183      * @throws ProfileException thrown if the response can not be created and sent back to the relying party
184      */
185     protected void completeAuthenticationRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
186             throws ProfileException {
187         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
188         HttpSession httpSession = httpRequest.getSession(true);
189
190         ShibbolethSSOLoginContext loginContext = (ShibbolethSSOLoginContext) httpSession
191                 .getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
192         httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
193
194         ShibbolethSSORequestContext requestContext = buildRequestContext(loginContext, inTransport, outTransport);
195
196         Response samlResponse;
197         try {
198             if (loginContext.getPrincipalName() == null) {
199                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "User failed authentication"));
200                 throw new ProfileException("User failed authentication");
201             }
202
203             resolveAttributes(requestContext);
204
205             ArrayList<Statement> statements = new ArrayList<Statement>();
206             statements.add(buildAuthenticationStatement(requestContext));
207             if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
208                 statements.add(buildAttributeStatement(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:bearer"));
209             }
210
211             samlResponse = buildResponse(requestContext, statements);
212         } catch (ProfileException e) {
213             samlResponse = buildErrorResponse(requestContext);
214         }
215
216         requestContext.setOutboundSAMLMessage(samlResponse);
217         requestContext.setOutboundSAMLMessageId(samlResponse.getID());
218         requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
219         encodeResponse(requestContext);
220         writeAuditLogEntry(requestContext);
221     }
222
223     /**
224      * Creates a login context from the incoming HTTP request.
225      * 
226      * @param request current HTTP request
227      * 
228      * @return the constructed login context
229      * 
230      * @throws ProfileException thrown if the incomming request did not contain a providerId, shire, and target
231      *             parameter
232      */
233     protected ShibbolethSSOLoginContext buildLoginContext(HttpServletRequest request) throws ProfileException {
234         ShibbolethSSOLoginContext loginContext = new ShibbolethSSOLoginContext();
235
236         try {
237             String providerId = DatatypeHelper.safeTrimOrNullString(request.getParameter("providerId"));
238             if (providerId == null) {
239                 log.error("No providerId parameter in Shibboleth SSO request");
240                 throw new ProfileException("No providerId parameter in Shibboleth SSO request");
241             }
242             loginContext.setRelyingParty(URLDecoder.decode(providerId, "UTF-8"));
243
244             RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(providerId);
245             if (rpConfig == null) {
246                 log.error("No relying party configuration available for " + providerId);
247                 throw new ProfileException("No relying party configuration available for " + providerId);
248             }
249             loginContext.getRequestedAuthenticationMethods().add(rpConfig.getDefaultAuthenticationMethod());
250
251             String acs = DatatypeHelper.safeTrimOrNullString(request.getParameter("shire"));
252             if (acs == null) {
253                 log.error("No shire parameter in Shibboleth SSO request");
254                 throw new ProfileException("No shire parameter in Shibboleth SSO request");
255             }
256             loginContext.setSpAssertionConsumerService(URLDecoder.decode(acs, "UTF-8"));
257
258             String target = DatatypeHelper.safeTrimOrNullString(request.getParameter("target"));
259             if (target == null) {
260                 log.error("No target parameter in Shibboleth SSO request");
261                 throw new ProfileException("No target parameter in Shibboleth SSO request");
262             }
263             loginContext.setSpTarget(URLDecoder.decode(target, "UTF-8"));
264         } catch (UnsupportedEncodingException e) {
265             // UTF-8 encoding required to be supported by all JVMs.
266         }
267
268         loginContext.setAuthenticationEngineURL(authenticationManagerPath);
269         loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(request));
270         return loginContext;
271     }
272
273     /**
274      * Creates an authentication request context from the current environmental information.
275      * 
276      * @param loginContext current login context
277      * @param in inbound transport
278      * @param out outbount transport
279      * 
280      * @return created authentication request context
281      * 
282      * @throws ProfileException thrown if there is a problem creating the context
283      */
284     protected ShibbolethSSORequestContext buildRequestContext(ShibbolethSSOLoginContext loginContext,
285             HTTPInTransport in, HTTPOutTransport out) throws ProfileException {
286         ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext();
287
288         try {
289             requestContext.setLoginContext(loginContext);
290             requestContext.setPrincipalName(loginContext.getPrincipalName());
291             requestContext.setPrincipalAuthenticationMethod(loginContext.getAuthenticationMethod());
292             requestContext.setUserSession(getUserSession(in));
293             requestContext.setRelayState(loginContext.getSpTarget());
294
295             requestContext.setMessageInTransport(in);
296             requestContext.setInboundSAMLProtocol(ShibbolethConstants.SHIB_SSO_PROFILE_URI);
297
298             MetadataProvider metadataProvider = getMetadataProvider();
299             requestContext.setMetadataProvider(metadataProvider);
300
301             String relyingPartyId = loginContext.getRelyingPartyId();
302             requestContext.setRelyingPartyEntityId(relyingPartyId);
303             EntityDescriptor relyingPartyMetadata = metadataProvider.getEntityDescriptor(relyingPartyId);
304             requestContext.setRelyingPartyMetadata(relyingPartyMetadata);
305             requestContext.setRelyingPartyRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
306             requestContext.setRelyingPartyRoleMetadata(relyingPartyMetadata
307                     .getSPSSODescriptor(SAMLConstants.SAML11P_NS));
308             RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
309             requestContext.setRelyingPartyConfiguration(rpConfig);
310             requestContext.setRelyingPartyEndpoint(selectEndpoint(requestContext));
311
312             String assertingPartyId = rpConfig.getProviderId();
313             requestContext.setAssertingPartyEntityId(assertingPartyId);
314             EntityDescriptor assertingPartyMetadata = metadataProvider.getEntityDescriptor(assertingPartyId);
315             requestContext.setAssertingPartyMetadata(assertingPartyMetadata);
316             requestContext.setAssertingPartyRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
317             requestContext.setAssertingPartyRoleMetadata(assertingPartyMetadata
318                     .getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
319
320             requestContext.setMessageOutTransport(out);
321             requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
322             ShibbolethSSOConfiguration profileConfig = (ShibbolethSSOConfiguration) rpConfig
323                     .getProfileConfiguration(SSOConfiguration.PROFILE_ID);
324             requestContext.setProfileConfiguration(profileConfig);
325             if (profileConfig.getSigningCredential() != null) {
326                 requestContext.setOutboundSAMLMessageSigningCredential(profileConfig.getSigningCredential());
327             } else if (rpConfig.getDefaultSigningCredential() != null) {
328                 requestContext.setOutboundSAMLMessageSigningCredential(rpConfig.getDefaultSigningCredential());
329             }
330
331             return requestContext;
332         } catch (MetadataProviderException e) {
333             log.error("Unable to locate metadata for asserting or relying party");
334             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Error locating party metadata"));
335             throw new ProfileException("Error locating party metadata");
336         }
337     }
338
339     /**
340      * Selects the appropriate endpoint for the relying party and stores it in the request context.
341      * 
342      * @param requestContext current request context
343      * 
344      * @return Endpoint selected from the information provided in the request context
345      */
346     protected Endpoint selectEndpoint(ShibbolethSSORequestContext requestContext) {
347         ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
348
349         if (loginContext.getSpAssertionConsumerService() != null) {
350             SAMLObjectBuilder<AssertionConsumerService> acsBuilder = (SAMLObjectBuilder<AssertionConsumerService>) getBuilderFactory()
351                     .getBuilder(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
352             AssertionConsumerService acsEndpoint = acsBuilder.buildObject();
353             acsEndpoint.setBinding(getMessageEncoder().getBindingURI());
354             acsEndpoint.setLocation(loginContext.getSpAssertionConsumerService());
355             return acsEndpoint;
356         }
357
358         BasicEndpointSelector endpointSelector = new BasicEndpointSelector();
359         endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
360         endpointSelector.setMetadataProvider(getMetadataProvider());
361         endpointSelector.setRelyingParty(requestContext.getRelyingPartyMetadata());
362         endpointSelector.setRelyingPartyRole(requestContext.getRelyingPartyRoleMetadata());
363         endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
364         endpointSelector.getSupportedIssuerBindings().addAll(supportedOutgoingBindings);
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.getMessageInTransport();
404         subjectLocality.setIPAddress(inTransport.getPeerAddress());
405         subjectLocality.setDNSAddress(inTransport.getPeerDomainName());
406
407         return subjectLocality;
408     }
409
410     /**
411      * Encodes the request's SAML response and writes it to the servlet response.
412      * 
413      * @param requestContext current request context
414      * 
415      * @throws ProfileException thrown if no message encoder is registered for this profiles binding
416      */
417     protected void encodeResponse(ShibbolethSSORequestContext requestContext) throws ProfileException {
418         if (log.isDebugEnabled()) {
419             log.debug("Encoding response to SAML request " + requestContext.getInboundSAMLMessageId()
420                     + " from relying party " + requestContext.getRelyingPartyEntityId());
421         }
422
423         try {
424             getMessageEncoder().encode(requestContext);
425         } catch (MessageEncodingException e) {
426             throw new ProfileException("Unable to encode response to relying party: "
427                     + requestContext.getRelyingPartyEntityId(), e);
428         }
429     }
430
431     /** Represents the internal state of a Shibboleth SSO Request while it's being processed by the IdP. */
432     protected class ShibbolethSSORequestContext extends
433             BaseSAML1ProfileRequestContext<Request, Response, ShibbolethSSOConfiguration> {
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 }