2 * The Shibboleth License, Version 1. Copyright (c) 2002 University Corporation for Advanced Internet Development, Inc.
3 * All rights reserved Redistribution and use in source and binary forms, with or without modification, are permitted
4 * provided that the following conditions are met: Redistributions of source code must retain the above copyright
5 * notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the
6 * above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other
7 * materials provided with the distribution, if any, must include the following acknowledgment: "This product includes
8 * software developed by the University Corporation for Advanced Internet Development <http://www.ucaid.edu> Internet2
9 * Project. Alternately, this acknowledegement may appear in the software itself, if and wherever such third-party
10 * acknowledgments normally appear. Neither the name of Shibboleth nor the names of its contributors, nor Internet2,
11 * nor the University Corporation for Advanced Internet Development, Inc., nor UCAID may be used to endorse or promote
12 * products derived from this software without specific prior written permission. For written permission, please
13 * contact shibboleth@shibboleth.org Products derived from this software may not be called Shibboleth, Internet2,
14 * UCAID, or the University Corporation for Advanced Internet Development, nor may Shibboleth appear in their name,
15 * without prior written permission of the University Corporation for Advanced Internet Development. THIS SOFTWARE IS
16 * PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND WITH ALL FAULTS. ANY EXPRESS OR IMPLIED WARRANTIES,
17 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND
18 * NON-INFRINGEMENT ARE DISCLAIMED AND THE ENTIRE RISK OF SATISFACTORY QUALITY, PERFORMANCE, ACCURACY, AND EFFORT IS
19 * WITH LICENSEE. IN NO EVENT SHALL THE COPYRIGHT OWNER, CONTRIBUTORS OR THE UNIVERSITY CORPORATION FOR ADVANCED
20 * INTERNET DEVELOPMENT, INC. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
23 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
24 * POSSIBILITY OF SUCH DAMAGE.
27 package edu.internet2.middleware.shibboleth.hs;
29 import java.io.IOException;
30 import java.util.Collections;
31 import java.util.Date;
33 import javax.servlet.RequestDispatcher;
34 import javax.servlet.ServletException;
35 import javax.servlet.UnavailableException;
36 import javax.servlet.http.HttpServletRequest;
37 import javax.servlet.http.HttpServletResponse;
39 import org.apache.log4j.Level;
40 import org.apache.log4j.Logger;
41 import org.apache.log4j.MDC;
42 import org.doomdark.uuid.UUIDGenerator;
43 import org.opensaml.QName;
44 import org.opensaml.SAMLAuthorityBinding;
45 import org.opensaml.SAMLBinding;
46 import org.opensaml.SAMLException;
47 import org.opensaml.SAMLNameIdentifier;
48 import org.opensaml.SAMLResponse;
49 import org.w3c.dom.Document;
50 import org.w3c.dom.Element;
51 import org.w3c.dom.NodeList;
53 import sun.misc.BASE64Decoder;
55 import edu.internet2.middleware.shibboleth.common.AuthNPrincipal;
56 import edu.internet2.middleware.shibboleth.common.Credentials;
57 import edu.internet2.middleware.shibboleth.common.NameIdentifierMapping;
58 import edu.internet2.middleware.shibboleth.common.NameIdentifierMappingException;
59 import edu.internet2.middleware.shibboleth.common.OriginConfig;
60 import edu.internet2.middleware.shibboleth.common.RelyingParty;
61 import edu.internet2.middleware.shibboleth.common.ServiceProviderMapperException;
62 import edu.internet2.middleware.shibboleth.common.ShibPOSTProfile;
63 import edu.internet2.middleware.shibboleth.common.ShibbolethConfigurationException;
64 import edu.internet2.middleware.shibboleth.common.ShibbolethOriginConfig;
65 import edu.internet2.middleware.shibboleth.common.TargetFederationComponent;
66 import edu.internet2.middleware.shibboleth.metadata.Endpoint;
67 import edu.internet2.middleware.shibboleth.metadata.Provider;
68 import edu.internet2.middleware.shibboleth.metadata.ProviderRole;
69 import edu.internet2.middleware.shibboleth.metadata.SPProviderRole;
71 public class HandleServlet extends TargetFederationComponent {
73 private static Logger log = Logger.getLogger(HandleServlet.class.getName());
74 private static Logger transactionLog = Logger.getLogger("Shibboleth-TRANSACTION");
76 private Semaphore throttle;
77 private HSConfig configuration;
78 private Credentials credentials;
79 private HSNameMapper nameMapper;
80 private ShibPOSTProfile postProfile = new ShibPOSTProfile();
81 private HSServiceProviderMapper targetMapper;
83 protected void loadConfiguration() throws ShibbolethConfigurationException {
85 Document originConfig = OriginConfig.getOriginConfig(this.getServletContext());
87 //Load global configuration properties
88 configuration = new HSConfig(originConfig.getDocumentElement());
90 //Load signing credentials
91 NodeList itemElements = originConfig.getDocumentElement().getElementsByTagNameNS(
92 Credentials.credentialsNamespace, "Credentials");
93 if (itemElements.getLength() < 1) {
94 log.error("Credentials not specified.");
95 throw new ShibbolethConfigurationException(
96 "The Handle Service requires that signing credentials be supplied in the <Credentials> configuration element.");
99 if (itemElements.getLength() > 1) {
100 log.error("Multiple Credentials specifications found, using first.");
103 credentials = new Credentials((Element) itemElements.item(0));
106 itemElements = originConfig.getDocumentElement().getElementsByTagNameNS(NameIdentifierMapping.mappingNamespace,
109 for (int i = 0; i < itemElements.getLength(); i++) {
111 nameMapper.addNameMapping((Element) itemElements.item(i));
112 } catch (NameIdentifierMappingException e) {
113 log.error("Name Identifier mapping could not be loaded: " + e);
118 itemElements = originConfig.getDocumentElement().getElementsByTagNameNS(
119 ShibbolethOriginConfig.originConfigNamespace, "FederationProvider");
120 for (int i = 0; i < itemElements.getLength(); i++) {
121 addFederationProvider((Element) itemElements.item(i));
123 if (providerCount() < 1) {
124 log.error("No Federation Provider metadata loaded.");
125 throw new ShibbolethConfigurationException("Could not load federation metadata.");
128 //Load relying party config
130 targetMapper = new HSServiceProviderMapper(originConfig.getDocumentElement(), configuration, credentials,
132 } catch (ServiceProviderMapperException e) {
133 log.error("Could not load origin configuration: " + e);
134 throw new ShibbolethConfigurationException("Could not load origin configuration.");
140 public void init() throws ServletException {
142 MDC.put("serviceId", "[HS] Core");
143 transactionLog.setLevel((Level) Level.INFO);
145 log.info("Initializing Handle Service.");
147 nameMapper = new HSNameMapper();
150 throttle = new Semaphore(configuration.getMaxThreads());
152 log.info("Handle Service initialization complete.");
154 } catch (ShibbolethConfigurationException ex) {
155 log.fatal("Handle Service runtime configuration error. Please fix and re-initialize. Cause: " + ex);
156 throw new UnavailableException("Handle Service failed to initialize.");
160 public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
162 MDC.put("serviceId", "[HS] " + UUIDGenerator.getInstance().generateRandomBasedUUID());
163 MDC.put("remoteAddr", req.getRemoteAddr());
164 log.info("Handling request.");
168 checkRequestParams(req);
170 req.setAttribute("shire", req.getParameter("shire"));
171 req.setAttribute("target", req.getParameter("target"));
173 HSRelyingParty relyingParty = targetMapper.getRelyingParty(req.getParameter("providerId"));
176 String username = configuration.getAuthHeaderName().equalsIgnoreCase("REMOTE_USER")
177 ? req.getRemoteUser()
178 : req.getHeader(configuration.getAuthHeaderName());
180 //Make sure that the selected relying party configuration is appropriate for this
182 if (!relyingParty.isLegacyProvider()) {
183 if (isValidAssertionConsumerURL(relyingParty, req.getParameter("shire"))) {
184 log.info("Supplied consumer URL validated for this provider.");
186 log.error("Supplied assertion consumer service URL (" + req.getParameter("shire")
187 + ") is NOT valid for provider (" + relyingParty.getProviderId() + ").");
188 throw new InvalidClientDataException("Invalid assertion consumer service URL.");
192 SAMLNameIdentifier nameId = nameMapper.getNameIdentifierName(relyingParty.getHSNameFormatId(),
193 new AuthNPrincipal(username), relyingParty, relyingParty.getIdentityProvider());
195 String authenticationMethod = req.getHeader("SAMLAuthenticationMethod");
196 if (authenticationMethod == null || authenticationMethod.equals("")) {
197 authenticationMethod = relyingParty.getDefaultAuthMethod().toString();
198 log.debug("User was authenticated via the default method for this relying party ("
199 + authenticationMethod + ").");
201 log.debug("User was authenticated via the method (" + authenticationMethod + ").");
204 byte[] buf = generateAssertion(relyingParty, nameId, req.getParameter("shire"), req.getRemoteAddr(),
205 authenticationMethod);
207 createForm(req, res, buf);
209 if (relyingParty.isLegacyProvider()) {
210 transactionLog.info("Authentication assertion issued to legacy provider (SHIRE: "
211 + req.getParameter("shire") + ") on behalf of principal (" + username + ") for resource ("
212 + req.getParameter("target") + "). Name Identifier: (" + nameId.getName()
213 + "). Name Identifier Format: (" + nameId.getFormat() + ").");
215 transactionLog.info("Authentication assertion issued to provider (" + req.getParameter("providerId")
216 + ") on behalf of principal (" + username + "). Name Identifier: (" + nameId.getName()
217 + "). Name Identifier Format: (" + nameId.getFormat() + ").");
220 } catch (NameIdentifierMappingException ex) {
222 handleError(req, res, ex);
224 } catch (InvalidClientDataException ex) {
226 handleError(req, res, ex);
228 } catch (SAMLException ex) {
230 handleError(req, res, ex);
232 } catch (InterruptedException ex) {
234 handleError(req, res, ex);
241 public void destroy() {
242 log.info("Cleaning up resources.");
243 nameMapper.destroy();
246 protected byte[] generateAssertion(HSRelyingParty relyingParty, SAMLNameIdentifier nameId, String shireURL,
247 String clientAddress, String authType) throws SAMLException, IOException {
249 SAMLAuthorityBinding binding = new SAMLAuthorityBinding(SAMLBinding.SAML_SOAP_HTTPS, relyingParty.getAAUrl()
250 .toString(), new QName(org.opensaml.XML.SAMLP_NS, "AttributeQuery"));
252 SAMLResponse r = postProfile.prepare(shireURL, relyingParty, nameId, clientAddress, authType, new Date(System
253 .currentTimeMillis()), Collections.singleton(binding));
258 protected void createForm(HttpServletRequest req, HttpServletResponse res, byte[] buf) throws IOException,
261 //Hardcoded to ASCII to ensure Base64 encoding compatibility
262 req.setAttribute("assertion", new String(buf, "ASCII"));
264 if (log.isDebugEnabled()) {
266 log.debug("Dumping generated SAML Response:" + System.getProperty("line.separator")
267 + new String(new BASE64Decoder().decodeBuffer(new String(buf, "ASCII")), "UTF8"));
268 } catch (IOException e) {
269 log.error("Encountered an error while decoding SAMLReponse for logging purposes.");
273 RequestDispatcher rd = req.getRequestDispatcher("/hs.jsp");
274 rd.forward(req, res);
277 protected void handleError(HttpServletRequest req, HttpServletResponse res, Exception e) throws ServletException,
280 req.setAttribute("errorText", e.toString());
281 req.setAttribute("requestURL", req.getRequestURI().toString());
282 RequestDispatcher rd = req.getRequestDispatcher("/hserror.jsp");
284 rd.forward(req, res);
287 protected void checkRequestParams(HttpServletRequest req) throws InvalidClientDataException {
289 if (req.getParameter("target") == null || req.getParameter("target").equals("")) {
290 throw new InvalidClientDataException("Invalid data from SHIRE: no target URL received.");
292 if ((req.getParameter("shire") == null) || (req.getParameter("shire").equals(""))) {
293 throw new InvalidClientDataException("Invalid data from SHIRE: No acceptance URL received.");
295 if ((req.getRemoteUser() == null) || (req.getRemoteUser().equals(""))) {
296 throw new InvalidClientDataException("Unable to authenticate remote user");
298 if ((req.getRemoteAddr() == null) || (req.getRemoteAddr().equals(""))) {
299 throw new InvalidClientDataException("Unable to obtain client address.");
303 protected boolean isValidAssertionConsumerURL(RelyingParty relyingParty, String shireURL)
304 throws InvalidClientDataException {
306 Provider provider = lookup(relyingParty.getProviderId());
307 if (provider == null) {
308 log.info("No metadata found for provider: (" + relyingParty.getProviderId() + ").");
309 throw new InvalidClientDataException("Request is from an unkown Service Provider.");
312 ProviderRole[] roles = provider.getRoles();
313 if (roles.length == 0) {
314 log.info("Inappropriate metadata for provider.");
318 for (int i = 0; roles.length > i; i++) {
319 if (roles[i] instanceof SPProviderRole) {
320 Endpoint[] endpoints = ((SPProviderRole) roles[i]).getAssertionConsumerServiceURLs();
321 for (int j = 0; endpoints.length > j; j++) {
322 if (shireURL.equals(endpoints[j].getLocation())) {
328 log.info("Supplied consumer URL not found in metadata.");
332 class InvalidClientDataException extends Exception {
334 public InvalidClientDataException(String message) {
339 private class Semaphore {
343 public Semaphore(int value) {
347 public synchronized void enter() throws InterruptedException {
354 public synchronized void exit() {