2 * The Shibboleth License, Version 1.
4 * University Corporation for Advanced Internet Development, Inc.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions are met:
11 * Redistributions of source code must retain the above copyright notice, this
12 * list of conditions and the following disclaimer.
14 * Redistributions in binary form must reproduce the above copyright notice,
15 * this list of conditions and the following disclaimer in the documentation
16 * and/or other materials provided with the distribution, if any, must include
17 * the following acknowledgment: "This product includes software developed by
18 * the University Corporation for Advanced Internet Development
19 * <http://www.ucaid.edu>Internet2 Project. Alternately, this acknowledegement
20 * may appear in the software itself, if and wherever such third-party
21 * acknowledgments normally appear.
23 * Neither the name of Shibboleth nor the names of its contributors, nor
24 * Internet2, nor the University Corporation for Advanced Internet Development,
25 * Inc., nor UCAID may be used to endorse or promote products derived from this
26 * software without specific prior written permission. For written permission,
27 * please contact shibboleth@shibboleth.org
29 * Products derived from this software may not be called Shibboleth, Internet2,
30 * UCAID, or the University Corporation for Advanced Internet Development, nor
31 * may Shibboleth appear in their name, without prior written permission of the
32 * University Corporation for Advanced Internet Development.
35 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
36 * AND WITH ALL FAULTS. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
37 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
38 * PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE DISCLAIMED AND THE ENTIRE RISK
39 * OF SATISFACTORY QUALITY, PERFORMANCE, ACCURACY, AND EFFORT IS WITH LICENSEE.
40 * IN NO EVENT SHALL THE COPYRIGHT OWNER, CONTRIBUTORS OR THE UNIVERSITY
41 * CORPORATION FOR ADVANCED INTERNET DEVELOPMENT, INC. BE LIABLE FOR ANY DIRECT,
42 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
43 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
44 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
45 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
46 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
47 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
50 package edu.internet2.middleware.shibboleth.hs;
52 import java.io.ByteArrayOutputStream;
53 import java.io.IOException;
54 import java.io.PrintStream;
55 import java.security.KeyStore;
56 import java.security.KeyStoreException;
57 import java.security.NoSuchAlgorithmException;
58 import java.security.PrivateKey;
59 import java.security.UnrecoverableKeyException;
60 import java.security.cert.Certificate;
61 import java.security.cert.CertificateException;
62 import java.util.Arrays;
63 import java.util.Collections;
64 import java.util.Date;
65 import java.util.Enumeration;
66 import java.util.Properties;
68 import javax.servlet.RequestDispatcher;
69 import javax.servlet.ServletException;
70 import javax.servlet.UnavailableException;
71 import javax.servlet.http.HttpServlet;
72 import javax.servlet.http.HttpServletRequest;
73 import javax.servlet.http.HttpServletResponse;
75 import org.apache.log4j.Logger;
76 import org.apache.log4j.MDC;
77 import org.doomdark.uuid.UUIDGenerator;
78 import org.opensaml.QName;
79 import org.opensaml.SAMLAuthenticationStatement;
80 import org.opensaml.SAMLAuthorityBinding;
81 import org.opensaml.SAMLBinding;
82 import org.opensaml.SAMLException;
83 import org.opensaml.SAMLResponse;
85 import sun.misc.BASE64Decoder;
86 import edu.internet2.middleware.shibboleth.common.AuditLevel;
87 import edu.internet2.middleware.shibboleth.common.AuthNPrincipal;
88 import edu.internet2.middleware.shibboleth.common.ShibPOSTProfile;
89 import edu.internet2.middleware.shibboleth.common.ShibPOSTProfileFactory;
90 import edu.internet2.middleware.shibboleth.common.ShibResource;
92 public class HandleServlet extends HttpServlet {
94 protected Properties configuration;
95 protected HandleRepository handleRepository;
96 protected ShibPOSTProfile postProfile;
97 private static Logger log = Logger.getLogger(HandleServlet.class.getName());
98 private Certificate[] certificates;
99 private PrivateKey privateKey;
100 protected Properties loadConfiguration() throws HSConfigurationException {
103 Properties defaultProps = new Properties();
104 defaultProps.setProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.username", "REMOTE_USER");
105 defaultProps.setProperty(
106 "edu.internet2.middleware.shibboleth.hs.HandleRepository.implementation",
107 "edu.internet2.middleware.shibboleth.hs.provider.MemoryHandleRepository");
108 defaultProps.setProperty("edu.internet2.middleware.shibboleth.hs.BaseHandleRepository.handleTTL", "1800000");
109 defaultProps.setProperty(
110 "edu.internet2.middleware.shibboleth.hs.provider.CryptoHandleRepository.keyStorePath",
112 defaultProps.setProperty("edu.internet2.middleware.shibboleth.audiences", "urn:mace:inqueue");
113 defaultProps.setProperty(
114 "edu.internet2.middleware.shibboleth.hs.HandleServlet.authMethod",
115 SAMLAuthenticationStatement.AuthenticationMethod_Unspecified);
118 Properties properties = new Properties(defaultProps);
119 String propertiesFileLocation = getInitParameter("OriginPropertiesFile");
120 if (propertiesFileLocation == null) {
121 propertiesFileLocation = "/conf/origin.properties";
124 log.debug("Loading Configuration from (" + propertiesFileLocation + ").");
125 properties.load(new ShibResource(propertiesFileLocation, this.getClass()).getInputStream());
127 //Make sure we have all required parameters
128 StringBuffer missingProperties = new StringBuffer();
129 String[] requiredProperties =
131 "edu.internet2.middleware.shibboleth.hs.HandleServlet.issuer",
132 "edu.internet2.middleware.shibboleth.hs.HandleServlet.siteName",
133 "edu.internet2.middleware.shibboleth.hs.HandleServlet.AAUrl",
134 "edu.internet2.middleware.shibboleth.hs.HandleServlet.keyStorePath",
135 "edu.internet2.middleware.shibboleth.hs.HandleServlet.keyStorePassword",
136 "edu.internet2.middleware.shibboleth.hs.HandleServlet.keyStoreKeyAlias",
137 "edu.internet2.middleware.shibboleth.hs.HandleServlet.keyStoreKeyPassword",
138 "edu.internet2.middleware.shibboleth.hs.HandleServlet.authMethod",
139 "edu.internet2.middleware.shibboleth.audiences" };
141 for (int i = 0; i < requiredProperties.length; i++) {
142 if (properties.getProperty(requiredProperties[i]) == null) {
143 missingProperties.append("\"");
144 missingProperties.append(requiredProperties[i]);
145 missingProperties.append("\" ");
148 if (missingProperties.length() > 0) {
150 "Missing configuration data. The following configuration properites have not been set: "
151 + missingProperties.toString());
152 throw new HSConfigurationException("Missing configuration data.");
155 } catch (IOException e) {
156 log.error("Could not load HS servlet configuration: " + e);
157 throw new HSConfigurationException("Could not load HS servlet configuration.");
160 if (log.isDebugEnabled()) {
161 ByteArrayOutputStream debugStream = new ByteArrayOutputStream();
162 PrintStream debugPrinter = new PrintStream(debugStream);
163 properties.list(debugPrinter);
165 "Runtime configuration parameters: " + System.getProperty("line.separator") + debugStream.toString());
168 } catch (IOException e) {
169 log.error("Encountered a problem cleaning up resources: could not close debug stream.");
173 //Be nice and trim "extra" whitespace from config properties
174 Enumeration propNames = properties.propertyNames();
175 while (propNames.hasMoreElements()) {
176 String propName = (String) propNames.nextElement();
177 if (properties.getProperty(propName, "").matches(".+\\s$")) {
179 "The configuration property ("
181 + ") contains trailing whitespace. Trimming... ");
182 properties.setProperty(propName, properties.getProperty(propName).trim());
189 public void init() throws ServletException {
191 MDC.put("serviceId", "[HS] Core");
193 log.info("Initializing Handle Service.");
194 configuration = loadConfiguration();
199 ShibPOSTProfileFactory.getInstance(
201 configuration.getProperty("edu.internet2.middleware.shibboleth.audiences").replaceAll(
205 configuration.getProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.issuer"));
207 handleRepository = HandleRepositoryFactory.getInstance(configuration);
208 log.info("Handle Service initialization complete.");
210 } catch (SAMLException ex) {
211 log.fatal("Error initializing SAML libraries: " + ex);
212 throw new UnavailableException("Handle Service failed to initialize.");
213 } catch (HSConfigurationException ex) {
214 log.fatal("Handle Service runtime configuration error. Please fix and re-initialize. Cause: " + ex);
215 throw new UnavailableException("Handle Service failed to initialize.");
216 } catch (HandleRepositoryException ex) {
217 log.fatal("Unable to load Handle Repository: " + ex);
218 throw new UnavailableException("Handle Service failed to initialize.");
222 protected void initPKI() throws HSConfigurationException {
224 KeyStore keyStore = KeyStore.getInstance("JKS");
228 configuration.getProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.keyStorePath"),
232 .getProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.keyStorePassword")
236 (PrivateKey) keyStore.getKey(
237 configuration.getProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.keyStoreKeyAlias"),
239 .getProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.keyStoreKeyPassword")
242 if (privateKey == null) {
243 throw new HSConfigurationException(
244 "No key entry was found with an alias of ("
245 + configuration.getProperty(
246 "edu.internet2.middleware.shibboleth.hs.HandleServlet.keyStoreKeyAlias")
251 if (configuration.getProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.certAlias") != null) {
253 keyStore.getCertificateChain(
254 configuration.getProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.certAlias"));
255 if (certificates == null) {
256 throw new HSConfigurationException(
257 "An error occurred while reading the java keystore: No certificate found with the specified alias ("
258 + configuration.getProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.certAlias")
263 keyStore.getCertificateChain(
264 configuration.getProperty(
265 "edu.internet2.middleware.shibboleth.hs.HandleServlet.keyStoreKeyAlias"));
266 if (certificates == null) {
267 throw new HSConfigurationException(
268 "An error occurred while reading the java keystore: No certificate found with the specified alias ("
269 + configuration.getProperty(
270 "edu.internet2.middleware.shibboleth.hs.HandleServlet.keyStoreKeyAlias")
275 } catch (KeyStoreException e) {
276 throw new HSConfigurationException("An error occurred while accessing the java keystore: " + e);
277 } catch (NoSuchAlgorithmException e) {
278 throw new HSConfigurationException("Appropriate JCE provider not found in the java environment: " + e);
279 } catch (CertificateException e) {
280 throw new HSConfigurationException(
281 "The java keystore contained a certificate that could not be loaded: " + e);
282 } catch (IOException e) {
283 throw new HSConfigurationException("An error occurred while reading the java keystore: " + e);
284 } catch (UnrecoverableKeyException e) {
285 throw new HSConfigurationException(
286 "An error occurred while attempting to load the key from the java keystore: " + e);
289 public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
291 MDC.put("serviceId", "[HS] " + UUIDGenerator.getInstance().generateRandomBasedUUID());
292 MDC.put("remoteAddr", req.getRemoteAddr());
293 log.info("Handling request.");
296 checkRequestParams(req);
298 req.setAttribute("shire", req.getParameter("shire"));
299 req.setAttribute("target", req.getParameter("target"));
301 String header = configuration.getProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.username");
302 String username = header.equalsIgnoreCase("REMOTE_USER") ? req.getRemoteUser() : req.getHeader(header);
304 StringBuffer format = new StringBuffer();
305 String handle = handleRepository.getHandle(new AuthNPrincipal(username), format);
306 log.info("Issued Handle (" + handle + ") to (" + username + ")");
312 req.getParameter("shire"),
314 configuration.getProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.authMethod"));
318 "Authentication assertion issued to SHIRE ("
319 + req.getParameter("shire")
320 + ") on behalf of principal ("
323 + req.getParameter("target")
324 + "). Attribue Query Handle: ("
328 createForm(req, res, buf);
330 } catch (HandleRepositoryException ex) {
332 handleError(req, res, ex);
334 } catch (InvalidClientDataException ex) {
336 handleError(req, res, ex);
338 } catch (SAMLException ex) {
340 handleError(req, res, ex);
346 protected byte[] generateAssertion(String handle, String format, String shireURL, String clientAddress, String authType)
347 throws SAMLException, IOException {
349 SAMLAuthorityBinding binding =
350 new SAMLAuthorityBinding(
351 SAMLBinding.SAML_SOAP_HTTPS,
352 configuration.getProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.AAUrl"),
353 new QName(org.opensaml.XML.SAMLP_NS, "AttributeQuery"));
359 configuration.getProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.siteName"),
363 new Date(System.currentTimeMillis()),
364 Collections.singleton(binding),
366 Arrays.asList(certificates),
373 protected void createForm(HttpServletRequest req, HttpServletResponse res, byte[] buf)
374 throws IOException, ServletException {
376 //Hardcoded to ASCII to ensure Base64 encoding compatibility
377 req.setAttribute("assertion", new String(buf, "ASCII"));
379 if (log.isDebugEnabled()) {
382 "Dumping generated SAML Response:"
383 + System.getProperty("line.separator")
384 + new String(new BASE64Decoder().decodeBuffer(new String(buf, "ASCII")), "UTF8"));
385 } catch (IOException e) {
386 log.error("Encountered an error while decoding SAMLReponse for logging purposes.");
390 RequestDispatcher rd = req.getRequestDispatcher("/hs.jsp");
391 rd.forward(req, res);
394 protected void handleError(HttpServletRequest req, HttpServletResponse res, Exception e)
395 throws ServletException, IOException {
397 req.setAttribute("errorText", e.toString());
398 req.setAttribute("requestURL", req.getRequestURI().toString());
399 RequestDispatcher rd = req.getRequestDispatcher("/hserror.jsp");
401 rd.forward(req, res);
405 protected void checkRequestParams(HttpServletRequest req) throws InvalidClientDataException {
407 if (req.getParameter("target") == null || req.getParameter("target").equals("")) {
408 throw new InvalidClientDataException("Invalid data from SHIRE: no target URL received.");
410 if ((req.getParameter("shire") == null) || (req.getParameter("shire").equals(""))) {
411 throw new InvalidClientDataException("Invalid data from SHIRE: No acceptance URL received.");
413 if ((req.getRemoteUser() == null) || (req.getRemoteUser().equals(""))) {
414 throw new InvalidClientDataException("Unable to authenticate remote user");
416 if ((req.getRemoteAddr() == null) || (req.getRemoteAddr().equals(""))) {
417 throw new InvalidClientDataException("Unable to obtain client address.");
421 class InvalidClientDataException extends Exception {
422 public InvalidClientDataException(String message) {