2023b8b14c658396307afea9845cf68d85e2c280
[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.RelyingPartyConfiguration;
57 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml1.ShibbolethSSOConfiguration;
58 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.SSOConfiguration;
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         if (getRelyingPartyConfiguration(loginContext.getRelyingPartyId()) == null) {
147             log.error("Shibboleth SSO profile is not configured for relying party " + loginContext.getRelyingPartyId());
148             throw new ProfileException("Shibboleth SSO profile is not configured for relying party "
149                     + loginContext.getRelyingPartyId());
150         }
151
152         httpSession.setAttribute(LoginContext.LOGIN_CONTEXT_KEY, loginContext);
153
154         try {
155             RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(authenticationManagerPath);
156             dispatcher.forward(httpRequest, httpResponse);
157             return;
158         } catch (IOException ex) {
159             log.error("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
160             throw new ProfileException("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
161         } catch (ServletException ex) {
162             log.error("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
163             throw new ProfileException("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
164         }
165     }
166
167     /**
168      * Decodes an incoming request and populates a created request context with the resultant information.
169      * 
170      * @param inTransport inbound message transport
171      * @param outTransport outbound message transport
172      * 
173      * @return the created request context
174      * 
175      * @throws ProfileException throw if there is a problem decoding the request
176      */
177     protected ShibbolethSSORequestContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
178             throws ProfileException {
179         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
180
181         ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext();
182         requestContext.setInboundMessageTransport(inTransport);
183         requestContext.setOutboundMessageTransport(outTransport);
184
185         SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
186         requestContext.setMessageDecoder(decoder);
187         try {
188             decoder.decode(requestContext);
189         } catch (MessageDecodingException e) {
190             log.error("Error decoding Shibboleth SSO request", e);
191             throw new ProfileException("Error decoding Shibboleth SSO request", e);
192         } catch (SecurityPolicyException e) {
193             log.error("Shibboleth SSO request does not meet security policy requirements", e);
194             throw new ProfileException("Shibboleth SSO request does not meet security policy requirements", e);
195         }
196
197         ShibbolethSSOLoginContext loginContext = new ShibbolethSSOLoginContext();
198         loginContext.setRelyingParty(requestContext.getPeerEntityId());
199         loginContext.setSpAssertionConsumerService(requestContext.getSpAssertionConsumerService());
200         loginContext.setRelyingParty(requestContext.getRelayState());
201         loginContext.setAuthenticationEngineURL(authenticationManagerPath);
202         loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(httpRequest));
203         requestContext.setLoginContext(loginContext);
204
205         return requestContext;
206     }
207
208     /**
209      * Creates a response to the Shibboleth SSO and sends the user, with response in tow, back to the relying party
210      * after they've been authenticated.
211      * 
212      * @param inTransport inbound message transport
213      * @param outTransport outbound message transport
214      * 
215      * @throws ProfileException thrown if the response can not be created and sent back to the relying party
216      */
217     protected void completeAuthenticationRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
218             throws ProfileException {
219         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
220         HttpSession httpSession = httpRequest.getSession(true);
221
222         ShibbolethSSOLoginContext loginContext = (ShibbolethSSOLoginContext) httpSession
223                 .getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
224         httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
225
226         ShibbolethSSORequestContext requestContext = buildRequestContext(loginContext, inTransport, outTransport);
227
228         Response samlResponse;
229         try {
230             if (loginContext.getPrincipalName() == null) {
231                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "User failed authentication"));
232                 throw new ProfileException("User failed authentication");
233             }
234
235             resolveAttributes(requestContext);
236
237             ArrayList<Statement> statements = new ArrayList<Statement>();
238             statements.add(buildAuthenticationStatement(requestContext));
239             if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
240                 requestContext.setRequestedAttributes(requestContext.getPrincipalAttributes().keySet());
241                 statements.add(buildAttributeStatement(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:bearer"));
242             }
243
244             samlResponse = buildResponse(requestContext, statements);
245         } catch (ProfileException e) {
246             samlResponse = buildErrorResponse(requestContext);
247         }
248
249         requestContext.setOutboundSAMLMessage(samlResponse);
250         requestContext.setOutboundSAMLMessageId(samlResponse.getID());
251         requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
252         encodeResponse(requestContext);
253         writeAuditLogEntry(requestContext);
254     }
255
256     /**
257      * Creates an authentication request context from the current environmental information.
258      * 
259      * @param loginContext current login context
260      * @param in inbound transport
261      * @param out outbount transport
262      * 
263      * @return created authentication request context
264      * 
265      * @throws ProfileException thrown if there is a problem creating the context
266      */
267     protected ShibbolethSSORequestContext buildRequestContext(ShibbolethSSOLoginContext loginContext,
268             HTTPInTransport in, HTTPOutTransport out) throws ProfileException {
269         ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext();
270
271         try {
272             requestContext.setLoginContext(loginContext);
273             requestContext.setPrincipalName(loginContext.getPrincipalName());
274             requestContext.setPrincipalAuthenticationMethod(loginContext.getAuthenticationMethod());
275             requestContext.setUserSession(getUserSession(in));
276             requestContext.setRelayState(loginContext.getSpTarget());
277
278             requestContext.setInboundMessageTransport(in);
279             requestContext.setInboundSAMLProtocol(ShibbolethConstants.SHIB_SSO_PROFILE_URI);
280
281             MetadataProvider metadataProvider = getMetadataProvider();
282             requestContext.setMetadataProvider(metadataProvider);
283
284             String relyingPartyId = loginContext.getRelyingPartyId();
285             requestContext.setPeerEntityId(relyingPartyId);
286             EntityDescriptor relyingPartyMetadata = metadataProvider.getEntityDescriptor(relyingPartyId);
287             requestContext.setPeerEntityMetadata(relyingPartyMetadata);
288             requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
289             requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata.getSPSSODescriptor(SAMLConstants.SAML11P_NS));
290             RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
291             requestContext.setRelyingPartyConfiguration(rpConfig);
292             requestContext.setPeerEntityEndpoint(selectEndpoint(requestContext));
293
294             String assertingPartyId = rpConfig.getProviderId();
295             requestContext.setLocalEntityId(assertingPartyId);
296             EntityDescriptor assertingPartyMetadata = metadataProvider.getEntityDescriptor(assertingPartyId);
297             requestContext.setLocalEntityMetadata(assertingPartyMetadata);
298             requestContext.setLocalEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
299             requestContext.setLocalEntityRoleMetadata(assertingPartyMetadata
300                     .getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
301
302             requestContext.setOutboundMessageTransport(out);
303             requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
304             ShibbolethSSOConfiguration profileConfig = (ShibbolethSSOConfiguration) rpConfig
305                     .getProfileConfiguration(SSOConfiguration.PROFILE_ID);
306             requestContext.setProfileConfiguration(profileConfig);
307             requestContext.setOutboundMessageArtifactType(profileConfig.getOutboundArtifactType());
308             if (profileConfig.getSigningCredential() != null) {
309                 requestContext.setOutboundSAMLMessageSigningCredential(profileConfig.getSigningCredential());
310             } else if (rpConfig.getDefaultSigningCredential() != null) {
311                 requestContext.setOutboundSAMLMessageSigningCredential(rpConfig.getDefaultSigningCredential());
312             }
313
314             return requestContext;
315         } catch (MetadataProviderException e) {
316             log.error("Unable to locate metadata for asserting or relying party");
317             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Error locating party metadata"));
318             throw new ProfileException("Error locating party metadata");
319         }
320     }
321
322     /**
323      * Selects the appropriate endpoint for the relying party and stores it in the request context.
324      * 
325      * @param requestContext current request context
326      * 
327      * @return Endpoint selected from the information provided in the request context
328      */
329     protected Endpoint selectEndpoint(ShibbolethSSORequestContext requestContext) {
330         ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
331
332         ShibbolethSSOEndpointSelector endpointSelector = new ShibbolethSSOEndpointSelector();
333         endpointSelector.setSpAssertionConsumerService(loginContext.getSpAssertionConsumerService());
334         endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
335         endpointSelector.setMetadataProvider(getMetadataProvider());
336         endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
337         endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
338         endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
339         endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
340
341         return endpointSelector.selectEndpoint();
342     }
343
344     /**
345      * Builds the authentication statement for the authenticated principal.
346      * 
347      * @param requestContext current request context
348      * 
349      * @return the created statement
350      * 
351      * @throws ProfileException thrown if the authentication statement can not be created
352      */
353     protected AuthenticationStatement buildAuthenticationStatement(ShibbolethSSORequestContext requestContext)
354             throws ProfileException {
355         ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
356
357         AuthenticationStatement statement = authnStatementBuilder.buildObject();
358         statement.setAuthenticationInstant(loginContext.getAuthenticationInstant());
359         statement.setAuthenticationMethod(loginContext.getAuthenticationMethod());
360
361         statement.setSubjectLocality(buildSubjectLocality(requestContext));
362
363         Subject statementSubject = buildSubject(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:bearer");
364         statement.setSubject(statementSubject);
365
366         return statement;
367     }
368
369     /**
370      * Constructs the subject locality for the authentication statement.
371      * 
372      * @param requestContext curent request context
373      * 
374      * @return subject locality for the authentication statement
375      */
376     protected SubjectLocality buildSubjectLocality(ShibbolethSSORequestContext requestContext) {
377         SubjectLocality subjectLocality = subjectLocalityBuilder.buildObject();
378
379         HTTPInTransport inTransport = (HTTPInTransport) requestContext.getInboundMessageTransport();
380         subjectLocality.setIPAddress(inTransport.getPeerAddress());
381         subjectLocality.setDNSAddress(inTransport.getPeerDomainName());
382
383         return subjectLocality;
384     }
385
386     /** Represents the internal state of a Shibboleth SSO Request while it's being processed by the IdP. */
387     public class ShibbolethSSORequestContext extends
388             BaseSAML1ProfileRequestContext<Request, Response, ShibbolethSSOConfiguration> {
389
390         /** Time since the epoch. */
391         private long time;
392
393         /** SP-provide assertion consumer service URL. */
394         private String spAssertionConsumerService;
395
396         /** Current login context. */
397         private ShibbolethSSOLoginContext loginContext;
398
399         /**
400          * Gets the current login context.
401          * 
402          * @return current login context
403          */
404         public ShibbolethSSOLoginContext getLoginContext() {
405             return loginContext;
406         }
407
408         /**
409          * Sets the current login context.
410          * 
411          * @param context current login context
412          */
413         public void setLoginContext(ShibbolethSSOLoginContext context) {
414             loginContext = context;
415         }
416
417         /**
418          * Gets the SP-provided assertion consumer service URL.
419          * 
420          * @return SP-provided assertion consumer service URL
421          */
422         public String getSpAssertionConsumerService() {
423             return spAssertionConsumerService;
424         }
425
426         /**
427          * Sets the SP-provided assertion consumer service URL.
428          * 
429          * @param acs SP-provided assertion consumer service URL
430          */
431         public void setSpAssertionConsumerService(String acs) {
432             spAssertionConsumerService = acs;
433         }
434
435         /**
436          * Sets the time since the epoch.
437          * 
438          * @return time since the epoch
439          */
440         public long getTime() {
441             return time;
442         }
443
444         /**
445          * Sets the time since the epoch.
446          * 
447          * @param time time since the epoch
448          */
449         public void setTime(long time) {
450             this.time = time;
451         }
452     }
453 }