Trim trailing whitespace from config properties, since this seems to cause hard to...
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / hs / HandleServlet.java
1 /* 
2  * The Shibboleth License, Version 1. 
3  * Copyright (c) 2002 
4  * University Corporation for Advanced Internet Development, Inc. 
5  * All rights reserved
6  * 
7  * 
8  * Redistribution and use in source and binary forms, with or without 
9  * modification, are permitted provided that the following conditions are met:
10  * 
11  * Redistributions of source code must retain the above copyright notice, this 
12  * list of conditions and the following disclaimer.
13  * 
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.
22  * 
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
28  * 
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.
33  * 
34  * 
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.
48  */
49
50 package edu.internet2.middleware.shibboleth.hs;
51
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;
67
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;
74
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;
84
85 import sun.misc.BASE64Decoder;
86 import edu.internet2.middleware.shibboleth.common.AuthNPrincipal;
87 import edu.internet2.middleware.shibboleth.common.ShibPOSTProfile;
88 import edu.internet2.middleware.shibboleth.common.ShibPOSTProfileFactory;
89 import edu.internet2.middleware.shibboleth.common.ShibResource;
90
91 public class HandleServlet extends HttpServlet {
92
93         protected Properties configuration;
94         protected HandleRepository handleRepository;
95         protected ShibPOSTProfile postProfile;
96         private static Logger log = Logger.getLogger(HandleServlet.class.getName());
97         private Certificate[] certificates;
98         private PrivateKey privateKey;
99         protected Properties loadConfiguration() throws HSConfigurationException {
100
101                 //Set defaults
102                 Properties defaultProps = new Properties();
103                 defaultProps.setProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.username", "REMOTE_USER");
104                 defaultProps.setProperty(
105                         "edu.internet2.middleware.shibboleth.hs.HandleRepository.implementation",
106                         "edu.internet2.middleware.shibboleth.hs.provider.MemoryHandleRepository");
107                 defaultProps.setProperty("edu.internet2.middleware.shibboleth.hs.BaseHandleRepository.handleTTL", "1800000");
108                 defaultProps.setProperty(
109                         "edu.internet2.middleware.shibboleth.hs.provider.CryptoHandleRepository.keyStorePath",
110                         "/conf/handle.jks");
111                 defaultProps.setProperty("edu.internet2.middleware.shibboleth.audiences", "urn:mace:incommon:pilot");
112                 defaultProps.setProperty(
113                         "edu.internet2.middleware.shibboleth.hs.HandleServlet.authMethod",
114                         SAMLAuthenticationStatement.AuthenticationMethod_Unspecified);
115
116                 //Load from file
117                 Properties properties = new Properties(defaultProps);
118                 String propertiesFileLocation = getInitParameter("OriginPropertiesFile");
119                 if (propertiesFileLocation == null) {
120                         propertiesFileLocation = "/conf/origin.properties";
121                 }
122                 try {
123                         log.debug("Loading Configuration from (" + propertiesFileLocation + ").");
124                         properties.load(new ShibResource(propertiesFileLocation, this.getClass()).getInputStream());
125
126                         //Make sure we have all required parameters
127                         StringBuffer missingProperties = new StringBuffer();
128                         String[] requiredProperties =
129                                 {
130                                         "edu.internet2.middleware.shibboleth.hs.HandleServlet.issuer",
131                                         "edu.internet2.middleware.shibboleth.hs.HandleServlet.siteName",
132                                         "edu.internet2.middleware.shibboleth.hs.HandleServlet.AAUrl",
133                                         "edu.internet2.middleware.shibboleth.hs.HandleServlet.keyStorePath",
134                                         "edu.internet2.middleware.shibboleth.hs.HandleServlet.keyStorePassword",
135                                         "edu.internet2.middleware.shibboleth.hs.HandleServlet.keyStoreKeyAlias",
136                                         "edu.internet2.middleware.shibboleth.hs.HandleServlet.keyStoreKeyPassword",
137                                         "edu.internet2.middleware.shibboleth.hs.HandleServlet.authMethod",
138                                         "edu.internet2.middleware.shibboleth.audiences" };
139
140                         for (int i = 0; i < requiredProperties.length; i++) {
141                                 if (properties.getProperty(requiredProperties[i]) == null) {
142                                         missingProperties.append("\"");
143                                         missingProperties.append(requiredProperties[i]);
144                                         missingProperties.append("\" ");
145                                 }
146                         }
147                         if (missingProperties.length() > 0) {
148                                 log.error(
149                                         "Missing configuration data.  The following configuration properites have not been set: "
150                                                 + missingProperties.toString());
151                                 throw new HSConfigurationException("Missing configuration data.");
152                         }
153
154                 } catch (IOException e) {
155                         log.error("Could not load HS servlet configuration: " + e);
156                         throw new HSConfigurationException("Could not load HS servlet configuration.");
157                 }
158
159                 if (log.isDebugEnabled()) {
160                         ByteArrayOutputStream debugStream = new ByteArrayOutputStream();
161                         PrintStream debugPrinter = new PrintStream(debugStream);
162                         properties.list(debugPrinter);
163                         log.debug(
164                                 "Runtime configuration parameters: " + System.getProperty("line.separator") + debugStream.toString());
165                         try {
166                                 debugStream.close();
167                         } catch (IOException e) {
168                                 log.error("Encountered a problem cleaning up resources: could not close debug stream.");
169                         }
170                 }
171                 
172                 //Be nice and trim "extra" whitespace from config properties
173                 Enumeration propNames = properties.propertyNames();
174                 while (propNames.hasMoreElements()) {
175                         String propName = (String) propNames.nextElement();
176                         if (properties.getProperty(propName, "").matches(".+\\s$")) {
177                                 log.debug(
178                                         "The configuration property ("
179                                                 + propName
180                                                 + ") contains trailing whitespace.  Trimming... ");
181                                 properties.setProperty(propName, properties.getProperty(propName).trim());
182                         }
183                 }
184
185                 return properties;
186         }
187
188         public void init() throws ServletException {
189                 super.init();
190                 MDC.put("serviceId", "[HS] Core");
191                 try {
192                         log.info("Initializing Handle Service.");
193                         configuration = loadConfiguration();
194
195                         initPKI();
196
197                         postProfile =
198                                 ShibPOSTProfileFactory.getInstance(
199                                         Arrays.asList(
200                                                 configuration.getProperty("edu.internet2.middleware.shibboleth.audiences").replaceAll(
201                                                         "\\s",
202                                                         "").split(
203                                                         ",")),
204                                         configuration.getProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.issuer"));
205
206                         handleRepository = HandleRepositoryFactory.getInstance(configuration);
207                         log.info("Handle Service initialization complete.");
208
209                 } catch (SAMLException ex) {
210                         log.fatal("Error initializing SAML libraries: " + ex);
211                         throw new UnavailableException("Handle Service failed to initialize.");
212                 } catch (HSConfigurationException ex) {
213                         log.fatal("Handle Service runtime configuration error.  Please fix and re-initialize. Cause: " + ex);
214                         throw new UnavailableException("Handle Service failed to initialize.");
215                 } catch (HandleRepositoryException ex) {
216                         log.fatal("Unable to load Handle Repository: " + ex);
217                         throw new UnavailableException("Handle Service failed to initialize.");
218                 }
219         }
220
221         protected void initPKI() throws HSConfigurationException {
222                 try {
223                         KeyStore keyStore = KeyStore.getInstance("JKS");
224
225                         keyStore.load(
226                                 new ShibResource(
227                                         configuration.getProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.keyStorePath"),
228                                         this.getClass())
229                                         .getInputStream(),
230                                 configuration
231                                         .getProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.keyStorePassword")
232                                         .toCharArray());
233
234                         privateKey =
235                                 (PrivateKey) keyStore.getKey(
236                                         configuration.getProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.keyStoreKeyAlias"),
237                                         configuration
238                                                 .getProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.keyStoreKeyPassword")
239                                                 .toCharArray());
240
241                         if (configuration.getProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.certAlias") != null) {
242                                 certificates =
243                                         keyStore.getCertificateChain(
244                                                 configuration.getProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.certAlias"));
245                                 if (certificates == null) {
246                                         throw new HSConfigurationException(
247                                                 "An error occurred while reading the java keystore: No certificate found with the specified alias ("
248                                                         + configuration.getProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.certAlias")
249                                                         + ").");
250                                 }
251                         } else {
252                                 certificates =
253                                         keyStore.getCertificateChain(
254                                                 configuration.getProperty(
255                                                         "edu.internet2.middleware.shibboleth.hs.HandleServlet.keyStoreKeyAlias"));
256                                 if (certificates == null) {
257                                         throw new HSConfigurationException(
258                                                 "An error occurred while reading the java keystore: No certificate found with the specified alias ("
259                                                         + configuration.getProperty(
260                                                                 "edu.internet2.middleware.shibboleth.hs.HandleServlet.keyStoreKeyAlias")
261                                                         + ").");
262                                 }
263                         }
264
265                 } catch (KeyStoreException e) {
266                         throw new HSConfigurationException("An error occurred while accessing the java keystore: " + e);
267                 } catch (NoSuchAlgorithmException e) {
268                         throw new HSConfigurationException("Appropriate JCE provider not found in the java environment: " + e);
269                 } catch (CertificateException e) {
270                         throw new HSConfigurationException(
271                                 "The java keystore contained a certificate that could not be loaded: " + e);
272                 } catch (IOException e) {
273                         throw new HSConfigurationException("An error occurred while reading the java keystore: " + e);
274                 } catch (UnrecoverableKeyException e) {
275                         throw new HSConfigurationException(
276                                 "An error occurred while attempting to load the key from the java keystore: " + e);
277                 }
278         }
279         public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
280
281                 MDC.put("serviceId", "[HS] " + UUIDGenerator.getInstance().generateRandomBasedUUID());
282                 MDC.put("remoteAddr", req.getRemoteAddr());
283                 log.info("Handling request.");
284
285                 try {
286                         checkRequestParams(req);
287
288                         req.setAttribute("shire", req.getParameter("shire"));
289                         req.setAttribute("target", req.getParameter("target"));
290
291                         String header = configuration.getProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.username");
292                         String username = header.equalsIgnoreCase("REMOTE_USER") ? req.getRemoteUser() : req.getHeader(header);
293
294                         String handle = handleRepository.getHandle(new AuthNPrincipal(username));
295                         log.info("Issued Handle (" + handle + ") to (" + username + ")");
296
297                         byte[] buf =
298                                 generateAssertion(
299                                         handle,
300                                         req.getParameter("shire"),
301                                         req.getRemoteAddr(),
302                                         configuration.getProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.authMethod"));
303
304                         createForm(req, res, buf);
305
306                 } catch (HandleRepositoryException ex) {
307                         log.error(ex);
308                         handleError(req, res, ex);
309                         return;
310                 } catch (InvalidClientDataException ex) {
311                         log.error(ex);
312                         handleError(req, res, ex);
313                         return;
314                 } catch (SAMLException ex) {
315                         log.error(ex);
316                         handleError(req, res, ex);
317                         return;
318                 }
319
320         }
321
322         protected byte[] generateAssertion(String handle, String shireURL, String clientAddress, String authType)
323                 throws SAMLException, IOException {
324
325                 SAMLAuthorityBinding binding =
326                         new SAMLAuthorityBinding(
327                                 SAMLBinding.SAML_SOAP_HTTPS,
328                                 configuration.getProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.AAUrl"),
329                                 new QName(org.opensaml.XML.SAMLP_NS, "AttributeQuery"));
330
331                 SAMLResponse r =
332                         postProfile.prepare(
333                                 shireURL,
334                                 handle,
335                                 configuration.getProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.siteName"),
336                                 clientAddress,
337                                 authType,
338                                 new Date(System.currentTimeMillis()),
339                                 Collections.singleton(binding),
340                                 privateKey,
341                                 Arrays.asList(certificates),
342                                 null,
343                                 null);
344
345                 return r.toBase64();
346         }
347
348         protected void createForm(HttpServletRequest req, HttpServletResponse res, byte[] buf)
349                 throws IOException, ServletException {
350
351                 //Hardcoded to ASCII to ensure Base64 encoding compatibility
352                 req.setAttribute("assertion", new String(buf, "ASCII"));
353
354                 if (log.isDebugEnabled()) {
355                         try {
356                                 log.debug(
357                                         "Dumping generated SAML Response:"
358                                                 + System.getProperty("line.separator")
359                                                 + new String(new BASE64Decoder().decodeBuffer(new String(buf, "ASCII")), "UTF8"));
360                         } catch (IOException e) {
361                                 log.error("Encountered an error while decoding SAMLReponse for logging purposes.");
362                         }
363                 }
364
365                 RequestDispatcher rd = req.getRequestDispatcher("/hs.jsp");
366                 rd.forward(req, res);
367         }
368
369         protected void handleError(HttpServletRequest req, HttpServletResponse res, Exception e)
370                 throws ServletException, IOException {
371
372                 req.setAttribute("errorText", e.toString());
373                 req.setAttribute("requestURL", req.getRequestURI().toString());
374                 RequestDispatcher rd = req.getRequestDispatcher("/hserror.jsp");
375
376                 rd.forward(req, res);
377
378         }
379
380         protected void checkRequestParams(HttpServletRequest req) throws InvalidClientDataException {
381
382                 if (req.getParameter("target") == null || req.getParameter("target").equals("")) {
383                         throw new InvalidClientDataException("Invalid data from SHIRE: no target URL received.");
384                 }
385                 if ((req.getParameter("shire") == null) || (req.getParameter("shire").equals(""))) {
386                         throw new InvalidClientDataException("Invalid data from SHIRE: No acceptance URL received.");
387                 }
388                 if ((req.getRemoteUser() == null) || (req.getRemoteUser().equals(""))) {
389                         throw new InvalidClientDataException("Unable to authenticate remote user");
390                 }
391                 if ((req.getRemoteAddr() == null) || (req.getRemoteAddr().equals(""))) {
392                         throw new InvalidClientDataException("Unable to obtain client address.");
393                 }
394         }
395
396         class InvalidClientDataException extends Exception {
397                 public InvalidClientDataException(String message) {
398                         super(message);
399                 }
400         }
401 }
402
403
404     
405