Added some scratch code to file credential loader.
[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.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;
91
92 public class HandleServlet extends HttpServlet {
93
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 {
101
102                 //Set defaults
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",
111                         "/conf/handle.jks");
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);
116
117                 //Load from file
118                 Properties properties = new Properties(defaultProps);
119                 String propertiesFileLocation = getInitParameter("OriginPropertiesFile");
120                 if (propertiesFileLocation == null) {
121                         propertiesFileLocation = "/conf/origin.properties";
122                 }
123                 try {
124                         log.debug("Loading Configuration from (" + propertiesFileLocation + ").");
125                         properties.load(new ShibResource(propertiesFileLocation, this.getClass()).getInputStream());
126
127                         //Make sure we have all required parameters
128                         StringBuffer missingProperties = new StringBuffer();
129                         String[] requiredProperties =
130                                 {
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" };
140
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("\" ");
146                                 }
147                         }
148                         if (missingProperties.length() > 0) {
149                                 log.error(
150                                         "Missing configuration data.  The following configuration properites have not been set: "
151                                                 + missingProperties.toString());
152                                 throw new HSConfigurationException("Missing configuration data.");
153                         }
154
155                 } catch (IOException e) {
156                         log.error("Could not load HS servlet configuration: " + e);
157                         throw new HSConfigurationException("Could not load HS servlet configuration.");
158                 }
159
160                 if (log.isDebugEnabled()) {
161                         ByteArrayOutputStream debugStream = new ByteArrayOutputStream();
162                         PrintStream debugPrinter = new PrintStream(debugStream);
163                         properties.list(debugPrinter);
164                         log.debug(
165                                 "Runtime configuration parameters: " + System.getProperty("line.separator") + debugStream.toString());
166                         try {
167                                 debugStream.close();
168                         } catch (IOException e) {
169                                 log.error("Encountered a problem cleaning up resources: could not close debug stream.");
170                         }
171                 }
172                 
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$")) {
178                                 log.debug(
179                                         "The configuration property ("
180                                                 + propName
181                                                 + ") contains trailing whitespace.  Trimming... ");
182                                 properties.setProperty(propName, properties.getProperty(propName).trim());
183                         }
184                 }
185
186                 return properties;
187         }
188
189         public void init() throws ServletException {
190                 super.init();
191                 MDC.put("serviceId", "[HS] Core");
192                 try {
193                         log.info("Initializing Handle Service.");
194                         configuration = loadConfiguration();
195
196                         initPKI();
197
198                         postProfile =
199                                 ShibPOSTProfileFactory.getInstance(
200                                         Arrays.asList(
201                                                 configuration.getProperty("edu.internet2.middleware.shibboleth.audiences").replaceAll(
202                                                         "\\s",
203                                                         "").split(
204                                                         ",")),
205                                         configuration.getProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.issuer"));
206
207                         handleRepository = HandleRepositoryFactory.getInstance(configuration);
208                         log.info("Handle Service initialization complete.");
209
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.");
219                 }
220         }
221
222         protected void initPKI() throws HSConfigurationException {
223                 try {
224                         KeyStore keyStore = KeyStore.getInstance("JKS");
225
226                         keyStore.load(
227                                 new ShibResource(
228                                         configuration.getProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.keyStorePath"),
229                                         this.getClass())
230                                         .getInputStream(),
231                                 configuration
232                                         .getProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.keyStorePassword")
233                                         .toCharArray());
234
235                         privateKey =
236                                 (PrivateKey) keyStore.getKey(
237                                         configuration.getProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.keyStoreKeyAlias"),
238                                         configuration
239                                                 .getProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.keyStoreKeyPassword")
240                                                 .toCharArray());
241                         
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")
247                                                 + ").");
248                         }
249                         
250
251                         if (configuration.getProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.certAlias") != null) {
252                                 certificates =
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")
259                                                         + ").");
260                                 }
261                         } else {
262                                 certificates =
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")
271                                                         + ").");
272                                 }
273                         }
274
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);
287                 }
288         }
289         public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
290
291                 MDC.put("serviceId", "[HS] " + UUIDGenerator.getInstance().generateRandomBasedUUID());
292                 MDC.put("remoteAddr", req.getRemoteAddr());
293                 log.info("Handling request.");
294
295                 try {
296                         checkRequestParams(req);
297
298                         req.setAttribute("shire", req.getParameter("shire"));
299                         req.setAttribute("target", req.getParameter("target"));
300
301                         String header = configuration.getProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.username");
302                         String username = header.equalsIgnoreCase("REMOTE_USER") ? req.getRemoteUser() : req.getHeader(header);
303
304                         StringBuffer format = new StringBuffer();
305                         String handle = handleRepository.getHandle(new AuthNPrincipal(username), format);
306                         log.info("Issued Handle (" + handle + ") to (" + username + ")");
307
308                         byte[] buf =
309                                 generateAssertion(
310                                         handle,
311                                         format.toString(),
312                                         req.getParameter("shire"),
313                                         req.getRemoteAddr(),
314                                         configuration.getProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.authMethod"));
315
316                         log.log(
317                                 AuditLevel.AUDIT,
318                                 "Authentication assertion issued to SHIRE ("
319                                         + req.getParameter("shire")
320                                         + ") on behalf of principal ("
321                                         + username
322                                         + ") for resource ("
323                                         + req.getParameter("target")
324                                         + "). Attribue Query Handle: ("
325                                         + handle
326                                         + ").");
327
328                         createForm(req, res, buf);
329
330                 } catch (HandleRepositoryException ex) {
331                         log.error(ex);
332                         handleError(req, res, ex);
333                         return;
334                 } catch (InvalidClientDataException ex) {
335                         log.error(ex);
336                         handleError(req, res, ex);
337                         return;
338                 } catch (SAMLException ex) {
339                         log.error(ex);
340                         handleError(req, res, ex);
341                         return;
342                 }
343
344         }
345
346         protected byte[] generateAssertion(String handle, String format, String shireURL, String clientAddress, String authType)
347                 throws SAMLException, IOException {
348
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"));
354
355                 SAMLResponse r =
356                         postProfile.prepare(
357                                 shireURL,
358                                 handle,
359                                 configuration.getProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.siteName"),
360                 format,
361                                 clientAddress,
362                                 authType,
363                                 new Date(System.currentTimeMillis()),
364                                 Collections.singleton(binding),
365                                 privateKey,
366                                 Arrays.asList(certificates),
367                                 null,
368                                 null);
369
370                 return r.toBase64();
371         }
372
373         protected void createForm(HttpServletRequest req, HttpServletResponse res, byte[] buf)
374                 throws IOException, ServletException {
375
376                 //Hardcoded to ASCII to ensure Base64 encoding compatibility
377                 req.setAttribute("assertion", new String(buf, "ASCII"));
378
379                 if (log.isDebugEnabled()) {
380                         try {
381                                 log.debug(
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.");
387                         }
388                 }
389
390                 RequestDispatcher rd = req.getRequestDispatcher("/hs.jsp");
391                 rd.forward(req, res);
392         }
393
394         protected void handleError(HttpServletRequest req, HttpServletResponse res, Exception e)
395                 throws ServletException, IOException {
396
397                 req.setAttribute("errorText", e.toString());
398                 req.setAttribute("requestURL", req.getRequestURI().toString());
399                 RequestDispatcher rd = req.getRequestDispatcher("/hserror.jsp");
400
401                 rd.forward(req, res);
402
403         }
404
405         protected void checkRequestParams(HttpServletRequest req) throws InvalidClientDataException {
406
407                 if (req.getParameter("target") == null || req.getParameter("target").equals("")) {
408                         throw new InvalidClientDataException("Invalid data from SHIRE: no target URL received.");
409                 }
410                 if ((req.getParameter("shire") == null) || (req.getParameter("shire").equals(""))) {
411                         throw new InvalidClientDataException("Invalid data from SHIRE: No acceptance URL received.");
412                 }
413                 if ((req.getRemoteUser() == null) || (req.getRemoteUser().equals(""))) {
414                         throw new InvalidClientDataException("Unable to authenticate remote user");
415                 }
416                 if ((req.getRemoteAddr() == null) || (req.getRemoteAddr().equals(""))) {
417                         throw new InvalidClientDataException("Unable to obtain client address.");
418                 }
419         }
420
421         class InvalidClientDataException extends Exception {
422                 public InvalidClientDataException(String message) {
423                         super(message);
424                 }
425         }
426 }
427
428
429     
430