Attempt to fix some NPEs when information is not available from the decoder or metada...
[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.transport.http.HTTPInTransport;
47 import org.opensaml.ws.transport.http.HTTPOutTransport;
48 import org.opensaml.ws.transport.http.HttpServletRequestAdapter;
49 import org.opensaml.ws.transport.http.HttpServletResponseAdapter;
50 import org.opensaml.xml.security.SecurityException;
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         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         HttpSession httpSession = httpRequest.getSession(true);
228
229         ShibbolethSSOLoginContext loginContext = (ShibbolethSSOLoginContext) httpSession
230                 .getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
231         httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
232
233         ShibbolethSSORequestContext requestContext = buildRequestContext(loginContext, inTransport, outTransport);
234
235         Response samlResponse;
236         try {
237             if (loginContext.getPrincipalName() == null) {
238                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "User failed authentication"));
239                 throw new ProfileException("User failed authentication");
240             }
241
242             resolveAttributes(requestContext);
243
244             ArrayList<Statement> statements = new ArrayList<Statement>();
245             statements.add(buildAuthenticationStatement(requestContext));
246             if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
247                 requestContext.setRequestedAttributes(requestContext.getPrincipalAttributes().keySet());
248                 statements.add(buildAttributeStatement(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:bearer"));
249             }
250
251             samlResponse = buildResponse(requestContext, statements);
252         } catch (ProfileException e) {
253             samlResponse = buildErrorResponse(requestContext);
254         }
255
256         requestContext.setOutboundSAMLMessage(samlResponse);
257         requestContext.setOutboundSAMLMessageId(samlResponse.getID());
258         requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
259         encodeResponse(requestContext);
260         writeAuditLogEntry(requestContext);
261     }
262
263     /**
264      * Creates an authentication request context from the current environmental information.
265      * 
266      * @param loginContext current login context
267      * @param in inbound transport
268      * @param out outbount transport
269      * 
270      * @return created authentication request context
271      * 
272      * @throws ProfileException thrown if there is a problem creating the context
273      */
274     protected ShibbolethSSORequestContext buildRequestContext(ShibbolethSSOLoginContext loginContext,
275             HTTPInTransport in, HTTPOutTransport out) throws ProfileException {
276         ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext();
277
278         requestContext.setMessageDecoder(getMessageDecoders().get(getInboundBinding()));
279
280         requestContext.setLoginContext(loginContext);
281         requestContext.setPrincipalName(loginContext.getPrincipalName());
282         requestContext.setPrincipalAuthenticationMethod(loginContext.getAuthenticationMethod());
283         requestContext.setUserSession(getUserSession(in));
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         MetadataProvider metadataProvider = getMetadataProvider();
293         requestContext.setMetadataProvider(metadataProvider);
294
295         String relyingPartyId = loginContext.getRelyingPartyId();
296         requestContext.setInboundMessageIssuer(relyingPartyId);
297
298         try {
299             EntityDescriptor relyingPartyMetadata = metadataProvider.getEntityDescriptor(relyingPartyId);
300             if (relyingPartyMetadata != null) {
301                 requestContext.setPeerEntityMetadata(relyingPartyMetadata);
302                 requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
303                 requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata
304                         .getSPSSODescriptor(SAMLConstants.SAML11P_NS));
305             }
306         } catch (MetadataProviderException e) {
307             log.error("Unable to locate metadata for relying party");
308             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
309                     "Error locating relying party metadata"));
310             throw new ProfileException("Error locating relying party metadata");
311         }
312
313         RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
314         if (rpConfig == null) {
315             log.error("Unable to retrieve relying party configuration data for entity with ID {}", relyingPartyId);
316             throw new ProfileException("Unable to retrieve relying party configuration data for entity with ID "
317                     + relyingPartyId);
318         }
319         requestContext.setRelyingPartyConfiguration(rpConfig);
320
321         ShibbolethSSOConfiguration profileConfig = (ShibbolethSSOConfiguration) rpConfig
322                 .getProfileConfiguration(ShibbolethSSOConfiguration.PROFILE_ID);
323         requestContext.setProfileConfiguration(profileConfig);
324         requestContext.setOutboundMessageArtifactType(profileConfig.getOutboundArtifactType());
325         if (profileConfig.getSigningCredential() != null) {
326             requestContext.setOutboundSAMLMessageSigningCredential(profileConfig.getSigningCredential());
327         } else if (rpConfig.getDefaultSigningCredential() != null) {
328             requestContext.setOutboundSAMLMessageSigningCredential(rpConfig.getDefaultSigningCredential());
329         }
330
331         requestContext.setPeerEntityEndpoint(selectEndpoint(requestContext));
332
333         String assertingPartyId = rpConfig.getProviderId();
334         requestContext.setLocalEntityId(assertingPartyId);
335         try {
336             EntityDescriptor localEntityDescriptor = metadataProvider.getEntityDescriptor(assertingPartyId);
337             if (localEntityDescriptor != null) {
338                 requestContext.setLocalEntityMetadata(localEntityDescriptor);
339                 requestContext.setLocalEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
340                 requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
341                         .getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
342             }
343         } catch (MetadataProviderException e) {
344             log.error("Unable to locate metadata for asserting party");
345             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
346                     "Error locating asserting party metadata"));
347             throw new ProfileException("Error locating asserting party metadata");
348         }
349
350         return requestContext;
351     }
352
353     /**
354      * Selects the appropriate endpoint for the relying party and stores it in the request context.
355      * 
356      * @param requestContext current request context
357      * 
358      * @return Endpoint selected from the information provided in the request context
359      */
360     protected Endpoint selectEndpoint(ShibbolethSSORequestContext requestContext) {
361         ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
362
363         ShibbolethSSOEndpointSelector endpointSelector = new ShibbolethSSOEndpointSelector();
364         endpointSelector.setSpAssertionConsumerService(loginContext.getSpAssertionConsumerService());
365         endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
366         endpointSelector.setMetadataProvider(getMetadataProvider());
367         endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
368         endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
369         endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
370         endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
371
372         return endpointSelector.selectEndpoint();
373     }
374
375     /**
376      * Builds the authentication statement for the authenticated principal.
377      * 
378      * @param requestContext current request context
379      * 
380      * @return the created statement
381      * 
382      * @throws ProfileException thrown if the authentication statement can not be created
383      */
384     protected AuthenticationStatement buildAuthenticationStatement(ShibbolethSSORequestContext requestContext)
385             throws ProfileException {
386         ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
387
388         AuthenticationStatement statement = authnStatementBuilder.buildObject();
389         statement.setAuthenticationInstant(loginContext.getAuthenticationInstant());
390         statement.setAuthenticationMethod(loginContext.getAuthenticationMethod());
391
392         statement.setSubjectLocality(buildSubjectLocality(requestContext));
393
394         Subject statementSubject = buildSubject(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:bearer");
395         statement.setSubject(statementSubject);
396
397         return statement;
398     }
399
400     /**
401      * Constructs the subject locality for the authentication statement.
402      * 
403      * @param requestContext curent request context
404      * 
405      * @return subject locality for the authentication statement
406      */
407     protected SubjectLocality buildSubjectLocality(ShibbolethSSORequestContext requestContext) {
408         SubjectLocality subjectLocality = subjectLocalityBuilder.buildObject();
409
410         HTTPInTransport inTransport = (HTTPInTransport) requestContext.getInboundMessageTransport();
411         subjectLocality.setIPAddress(inTransport.getPeerAddress());
412         subjectLocality.setDNSAddress(inTransport.getPeerDomainName());
413
414         return subjectLocality;
415     }
416
417     /** Represents the internal state of a Shibboleth SSO Request while it's being processed by the IdP. */
418     public class ShibbolethSSORequestContext extends
419             BaseSAML1ProfileRequestContext<Request, Response, ShibbolethSSOConfiguration> {
420
421         /** SP-provide assertion consumer service URL. */
422         private String spAssertionConsumerService;
423
424         /** Current login context. */
425         private ShibbolethSSOLoginContext loginContext;
426
427         /**
428          * Gets the current login context.
429          * 
430          * @return current login context
431          */
432         public ShibbolethSSOLoginContext getLoginContext() {
433             return loginContext;
434         }
435
436         /**
437          * Sets the current login context.
438          * 
439          * @param context current login context
440          */
441         public void setLoginContext(ShibbolethSSOLoginContext context) {
442             loginContext = context;
443         }
444
445         /**
446          * Gets the SP-provided assertion consumer service URL.
447          * 
448          * @return SP-provided assertion consumer service URL
449          */
450         public String getSpAssertionConsumerService() {
451             return spAssertionConsumerService;
452         }
453
454         /**
455          * Sets the SP-provided assertion consumer service URL.
456          * 
457          * @param acs SP-provided assertion consumer service URL
458          */
459         public void setSpAssertionConsumerService(String acs) {
460             spAssertionConsumerService = acs;
461         }
462     }
463 }