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