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