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