Lots of code cleanup
[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
27 import org.opensaml.common.SAMLObjectBuilder;
28 import org.opensaml.common.binding.decoding.SAMLMessageDecoder;
29 import org.opensaml.common.xml.SAMLConstants;
30 import org.opensaml.saml1.core.AttributeStatement;
31 import org.opensaml.saml1.core.AuthenticationStatement;
32 import org.opensaml.saml1.core.Request;
33 import org.opensaml.saml1.core.Response;
34 import org.opensaml.saml1.core.Statement;
35 import org.opensaml.saml1.core.StatusCode;
36 import org.opensaml.saml1.core.Subject;
37 import org.opensaml.saml1.core.SubjectLocality;
38 import org.opensaml.saml2.metadata.AssertionConsumerService;
39 import org.opensaml.saml2.metadata.Endpoint;
40 import org.opensaml.saml2.metadata.EntityDescriptor;
41 import org.opensaml.saml2.metadata.IDPSSODescriptor;
42 import org.opensaml.saml2.metadata.SPSSODescriptor;
43 import org.opensaml.ws.message.decoder.MessageDecodingException;
44 import org.opensaml.ws.transport.http.HTTPInTransport;
45 import org.opensaml.ws.transport.http.HTTPOutTransport;
46 import org.opensaml.ws.transport.http.HttpServletRequestAdapter;
47 import org.opensaml.ws.transport.http.HttpServletResponseAdapter;
48 import org.opensaml.xml.security.SecurityException;
49 import org.opensaml.xml.util.DatatypeHelper;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52
53 import edu.internet2.middleware.shibboleth.common.ShibbolethConstants;
54 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
55 import edu.internet2.middleware.shibboleth.common.profile.provider.BaseSAMLProfileRequestContext;
56 import edu.internet2.middleware.shibboleth.common.relyingparty.ProfileConfiguration;
57 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
58 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.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 = LoggerFactory.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 ShibbolethSSOConfiguration.PROFILE_ID;
102     }
103
104     /** {@inheritDoc} */
105     public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
106         log.debug("Processing incoming request");
107
108         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
109         LoginContext loginContext = (LoginContext) httpRequest.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
110
111         if (loginContext == null) {
112             log.debug("Incoming request does not contain a login context, processing as first leg of request");
113             performAuthentication(inTransport, outTransport);
114         } else {
115             log.debug("Incoming request contains a login context, processing as second leg of request");
116             completeAuthenticationRequest(inTransport, outTransport);
117         }
118     }
119
120     /**
121      * Creates a {@link LoginContext} an sends the request off to the AuthenticationManager to begin the process of
122      * authenticating the user.
123      * 
124      * @param inTransport inbound message transport
125      * @param outTransport outbound message transport
126      * 
127      * @throws ProfileException thrown if there is a problem creating the login context and transferring control to the
128      *             authentication manager
129      */
130     protected void performAuthentication(HTTPInTransport inTransport, HTTPOutTransport outTransport)
131             throws ProfileException {
132
133         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
134         HttpServletResponse httpResponse = ((HttpServletResponseAdapter) outTransport).getWrappedResponse();
135
136         ShibbolethSSORequestContext requestContext = decodeRequest(inTransport, outTransport);
137         ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
138
139         RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(loginContext.getRelyingPartyId());
140         ProfileConfiguration ssoConfig = rpConfig.getProfileConfiguration(ShibbolethSSOConfiguration.PROFILE_ID);
141         if (ssoConfig == null) {
142             log.error("Shibboleth SSO profile is not configured for relying party " + loginContext.getRelyingPartyId());
143             throw new ProfileException("Shibboleth SSO profile is not configured for relying party "
144                     + loginContext.getRelyingPartyId());
145         }
146         loginContext.getRequestedAuthenticationMethods().add(rpConfig.getDefaultAuthenticationMethod());
147
148         httpRequest.setAttribute(LoginContext.LOGIN_CONTEXT_KEY, loginContext);
149
150         try {
151             RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(authenticationManagerPath);
152             dispatcher.forward(httpRequest, httpResponse);
153             return;
154         } catch (IOException ex) {
155             log.error("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
156             throw new ProfileException("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
157         } catch (ServletException ex) {
158             log.error("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
159             throw new ProfileException("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
160         }
161     }
162
163     /**
164      * Decodes an incoming request and populates a created request context with the resultant information.
165      * 
166      * @param inTransport inbound message transport
167      * @param outTransport outbound message transport
168      * 
169      * @return the created request context
170      * 
171      * @throws ProfileException throw if there is a problem decoding the request
172      */
173     protected ShibbolethSSORequestContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
174             throws ProfileException {
175         log.debug("Decoding message with decoder binding {}", getInboundBinding());
176
177         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
178
179         ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext();
180         requestContext.setMetadataProvider(getMetadataProvider());
181         requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
182
183         requestContext.setCommunicationProfileId(ShibbolethSSOConfiguration.PROFILE_ID);
184         requestContext.setInboundMessageTransport(inTransport);
185         requestContext.setInboundSAMLProtocol(ShibbolethConstants.SHIB_SSO_PROFILE_URI);
186         requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
187
188         requestContext.setOutboundMessageTransport(outTransport);
189         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML11P_NS);
190
191         SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
192         requestContext.setMessageDecoder(decoder);
193         try {
194             decoder.decode(requestContext);
195         } catch (MessageDecodingException e) {
196             log.error("Error decoding Shibboleth SSO request", e);
197             throw new ProfileException("Error decoding Shibboleth SSO request", e);
198         } catch (SecurityException e) {
199             log.error("Shibboleth SSO request does not meet security requirements", e);
200             throw new ProfileException("Shibboleth SSO request does not meet security requirements", e);
201         }
202
203         ShibbolethSSOLoginContext loginContext = new ShibbolethSSOLoginContext();
204         loginContext.setRelyingParty(requestContext.getInboundMessageIssuer());
205         loginContext.setSpAssertionConsumerService(requestContext.getSpAssertionConsumerService());
206         loginContext.setSpTarget(requestContext.getRelayState());
207         loginContext.setAuthenticationEngineURL(authenticationManagerPath);
208         loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(httpRequest));
209
210         requestContext.setLoginContext(loginContext);
211
212         return requestContext;
213     }
214
215     /**
216      * Creates a response to the Shibboleth SSO and sends the user, with response in tow, back to the relying party
217      * after they've been authenticated.
218      * 
219      * @param inTransport inbound message transport
220      * @param outTransport outbound message transport
221      * 
222      * @throws ProfileException thrown if the response can not be created and sent back to the relying party
223      */
224     protected void completeAuthenticationRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
225             throws ProfileException {
226         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
227         ShibbolethSSOLoginContext loginContext = (ShibbolethSSOLoginContext) httpRequest
228                 .getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
229
230         ShibbolethSSORequestContext requestContext = buildRequestContext(loginContext, inTransport, outTransport);
231
232         Response samlResponse;
233         try {
234             if (loginContext.getAuthenticationFailure() != null) {
235                 log.error("User authentication failed with the following error: {}", loginContext
236                         .getAuthenticationFailure().toString());
237                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "User failed authentication"));
238                 throw new ProfileException("Authentication failure", loginContext.getAuthenticationFailure());
239             }
240
241             resolveAttributes(requestContext);
242
243             ArrayList<Statement> statements = new ArrayList<Statement>();
244             statements.add(buildAuthenticationStatement(requestContext));
245             if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
246                 AttributeStatement attributeStatement = buildAttributeStatement(requestContext,
247                         "urn:oasis:names:tc:SAML:1.0:cm:bearer");
248                 if (attributeStatement != null) {
249                     requestContext.setRequestedAttributes(requestContext.getAttributes().keySet());
250                     statements.add(attributeStatement);
251                 }
252             }
253
254             samlResponse = buildResponse(requestContext, statements);
255         } catch (ProfileException e) {
256             samlResponse = buildErrorResponse(requestContext);
257         }
258
259         requestContext.setOutboundSAMLMessage(samlResponse);
260         requestContext.setOutboundSAMLMessageId(samlResponse.getID());
261         requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
262         encodeResponse(requestContext);
263         writeAuditLogEntry(requestContext);
264     }
265
266     /**
267      * Creates an authentication request context from the current environmental information.
268      * 
269      * @param loginContext current login context
270      * @param in inbound transport
271      * @param out outbount transport
272      * 
273      * @return created authentication request context
274      * 
275      * @throws ProfileException thrown if there is a problem creating the context
276      */
277     protected ShibbolethSSORequestContext buildRequestContext(ShibbolethSSOLoginContext loginContext,
278             HTTPInTransport in, HTTPOutTransport out) throws ProfileException {
279         ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext();
280
281         requestContext.setMessageDecoder(getMessageDecoders().get(getInboundBinding()));
282
283         requestContext.setLoginContext(loginContext);
284         requestContext.setRelayState(loginContext.getSpTarget());
285
286         requestContext.setInboundMessageTransport(in);
287         requestContext.setInboundSAMLProtocol(ShibbolethConstants.SHIB_SSO_PROFILE_URI);
288
289         requestContext.setOutboundMessageTransport(out);
290         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
291
292         requestContext.setMetadataProvider(getMetadataProvider());
293
294         String relyingPartyId = loginContext.getRelyingPartyId();
295         requestContext.setInboundMessageIssuer(relyingPartyId);
296
297         populateRequestContext(requestContext);
298
299         return requestContext;
300     }
301
302     /** {@inheritDoc} */
303     protected void populateRelyingPartyInformation(BaseSAMLProfileRequestContext requestContext)
304             throws ProfileException {
305         super.populateRelyingPartyInformation(requestContext);
306
307         EntityDescriptor relyingPartyMetadata = requestContext.getPeerEntityMetadata();
308         if (relyingPartyMetadata != null) {
309             requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
310             requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata.getSPSSODescriptor(SAMLConstants.SAML11P_NS));
311         }
312     }
313
314     /** {@inheritDoc} */
315     protected void populateAssertingPartyInformation(BaseSAMLProfileRequestContext requestContext)
316             throws ProfileException {
317         super.populateAssertingPartyInformation(requestContext);
318
319         EntityDescriptor localEntityDescriptor = requestContext.getLocalEntityMetadata();
320         if (localEntityDescriptor != null) {
321             requestContext.setLocalEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
322             requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
323                     .getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
324         }
325     }
326
327     /** {@inheritDoc} */
328     protected void populateSAMLMessageInformation(BaseSAMLProfileRequestContext requestContext) 
329         throws ProfileException {
330         // nothing to do here
331     }
332
333     /**
334      * Selects the appropriate endpoint for the relying party and stores it in the request context.
335      * 
336      * @param requestContext current request context
337      * 
338      * @return Endpoint selected from the information provided in the request context
339      */
340     protected Endpoint selectEndpoint(BaseSAMLProfileRequestContext requestContext) {
341         ShibbolethSSOLoginContext loginContext = ((ShibbolethSSORequestContext) requestContext).getLoginContext();
342
343         ShibbolethSSOEndpointSelector endpointSelector = new ShibbolethSSOEndpointSelector();
344         endpointSelector.setSpAssertionConsumerService(loginContext.getSpAssertionConsumerService());
345         endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
346         endpointSelector.setMetadataProvider(getMetadataProvider());
347         endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
348         endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
349         endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
350         endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
351
352         return endpointSelector.selectEndpoint();
353     }
354
355     /**
356      * Builds the authentication statement for the authenticated principal.
357      * 
358      * @param requestContext current request context
359      * 
360      * @return the created statement
361      * 
362      * @throws ProfileException thrown if the authentication statement can not be created
363      */
364     protected AuthenticationStatement buildAuthenticationStatement(ShibbolethSSORequestContext requestContext)
365             throws ProfileException {
366         ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
367
368         AuthenticationStatement statement = authnStatementBuilder.buildObject();
369         statement.setAuthenticationInstant(loginContext.getAuthenticationInstant());
370         statement.setAuthenticationMethod(loginContext.getAuthenticationMethod());
371
372         statement.setSubjectLocality(buildSubjectLocality(requestContext));
373
374         Subject statementSubject = buildSubject(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:bearer");
375         statement.setSubject(statementSubject);
376
377         return statement;
378     }
379
380     /**
381      * Constructs the subject locality for the authentication statement.
382      * 
383      * @param requestContext curent request context
384      * 
385      * @return subject locality for the authentication statement
386      */
387     protected SubjectLocality buildSubjectLocality(ShibbolethSSORequestContext requestContext) {
388         SubjectLocality subjectLocality = subjectLocalityBuilder.buildObject();
389
390         HTTPInTransport inTransport = (HTTPInTransport) requestContext.getInboundMessageTransport();
391         subjectLocality.setIPAddress(inTransport.getPeerAddress());
392
393         return subjectLocality;
394     }
395
396     /** Represents the internal state of a Shibboleth SSO Request while it's being processed by the IdP. */
397     public class ShibbolethSSORequestContext extends
398             BaseSAML1ProfileRequestContext<Request, Response, ShibbolethSSOConfiguration> {
399
400         /** SP-provide assertion consumer service URL. */
401         private String spAssertionConsumerService;
402
403         /** Current login context. */
404         private ShibbolethSSOLoginContext loginContext;
405
406         /**
407          * Gets the current login context.
408          * 
409          * @return current login context
410          */
411         public ShibbolethSSOLoginContext getLoginContext() {
412             return loginContext;
413         }
414
415         /**
416          * Sets the current login context.
417          * 
418          * @param context current login context
419          */
420         public void setLoginContext(ShibbolethSSOLoginContext context) {
421             loginContext = context;
422         }
423
424         /**
425          * Gets the SP-provided assertion consumer service URL.
426          * 
427          * @return SP-provided assertion consumer service URL
428          */
429         public String getSpAssertionConsumerService() {
430             return spAssertionConsumerService;
431         }
432
433         /**
434          * Sets the SP-provided assertion consumer service URL.
435          * 
436          * @param acs SP-provided assertion consumer service URL
437          */
438         public void setSpAssertionConsumerService(String acs) {
439             spAssertionConsumerService = acs;
440         }
441     }
442 }