da49c80559f6bbed2d33f6dbfe75c03460b00ce8
[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.Properties;
66
67 import javax.servlet.RequestDispatcher;
68 import javax.servlet.ServletException;
69 import javax.servlet.UnavailableException;
70 import javax.servlet.http.HttpServlet;
71 import javax.servlet.http.HttpServletRequest;
72 import javax.servlet.http.HttpServletResponse;
73
74 import org.apache.log4j.Logger;
75 import org.apache.log4j.MDC;
76 import org.doomdark.uuid.UUIDGenerator;
77 import org.opensaml.Init;
78 import org.opensaml.QName;
79 import org.opensaml.SAMLAuthorityBinding;
80 import org.opensaml.SAMLBinding;
81 import org.opensaml.SAMLException;
82 import org.opensaml.SAMLResponse;
83
84 import sun.misc.BASE64Decoder;
85 import edu.internet2.middleware.shibboleth.common.AuthNPrincipal;
86 import edu.internet2.middleware.shibboleth.common.ShibPOSTProfile;
87 import edu.internet2.middleware.shibboleth.common.ShibPOSTProfileFactory;
88 import edu.internet2.middleware.shibboleth.common.ShibResource;
89
90 public class HandleServlet extends HttpServlet {
91
92         protected Properties configuration;
93         protected HandleRepository handleRepository;
94         protected ShibPOSTProfile postProfile;
95         private static Logger log = Logger.getLogger(HandleServlet.class.getName());
96         private Certificate[] certificates;
97         private PrivateKey privateKey;
98         protected Properties loadConfiguration() throws HSConfigurationException {
99
100                 //Set defaults
101                 Properties defaultProps = new Properties();
102         defaultProps.setProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.username","REMOTE_USER");
103                 defaultProps.setProperty(
104                         "edu.internet2.middleware.shibboleth.hs.HandleRepository.implementation",
105                         "edu.internet2.middleware.shibboleth.hs.provider.MemoryHandleRepository");
106                 defaultProps.setProperty("edu.internet2.middleware.shibboleth.hs.BaseHandleRepository.handleTTL", "1800000");
107                 defaultProps.setProperty(
108                         "edu.internet2.middleware.shibboleth.hs.provider.CryptoHandleRepository.keyStorePath",
109                         "/conf/handle.jks");
110                 defaultProps.setProperty("edu.internet2.middleware.shibboleth.audiences", "urn:mace:InCommon:pilot:2003");
111
112                 //Load from file
113                 Properties properties = new Properties(defaultProps);
114                 String propertiesFileLocation = getInitParameter("OriginPropertiesFile");
115                 if (propertiesFileLocation == null) {
116                         propertiesFileLocation = "/conf/origin.properties";
117                 }
118                 try {
119                         log.debug("Loading Configuration from (" + propertiesFileLocation + ").");
120                         properties.load(new ShibResource(propertiesFileLocation, this.getClass()).getInputStream());
121
122                         //Make sure we have all required parameters
123                         StringBuffer missingProperties = new StringBuffer();
124                         String[] requiredProperties =
125                                 {
126                                         "edu.internet2.middleware.shibboleth.hs.HandleServlet.issuer",
127                                         "edu.internet2.middleware.shibboleth.hs.HandleServlet.authenticationDomain",
128                                         "edu.internet2.middleware.shibboleth.hs.HandleServlet.AAUrl",
129                                         "edu.internet2.middleware.shibboleth.hs.HandleServlet.keyStorePath",
130                                         "edu.internet2.middleware.shibboleth.hs.HandleServlet.keyStorePassword",
131                                         "edu.internet2.middleware.shibboleth.hs.HandleServlet.keyStoreKeyAlias",
132                                         "edu.internet2.middleware.shibboleth.hs.HandleServlet.keyStoreKeyPassword",
133                                         "edu.internet2.middleware.shibboleth.audiences" };
134
135                         for (int i = 0; i < requiredProperties.length; i++) {
136                                 if (properties.getProperty(requiredProperties[i]) == null) {
137                                         missingProperties.append("\"");
138                                         missingProperties.append(requiredProperties[i]);
139                                         missingProperties.append("\" ");
140                                 }
141                         }
142                         if (missingProperties.length() > 0) {
143                                 log.error(
144                                         "Missing configuration data.  The following configuration properites have not been set: "
145                                                 + missingProperties.toString());
146                                 throw new HSConfigurationException("Missing configuration data.");
147                         }
148
149                 } catch (IOException e) {
150                         log.error("Could not load HS servlet configuration: " + e);
151                         throw new HSConfigurationException("Could not load HS servlet configuration.");
152                 }
153
154                 if (log.isDebugEnabled()) {
155                         ByteArrayOutputStream debugStream = new ByteArrayOutputStream();
156                         PrintStream debugPrinter = new PrintStream(debugStream);
157                         properties.list(debugPrinter);
158                         log.debug(
159                                 "Runtime configuration parameters: " + System.getProperty("line.separator") + debugStream.toString());
160                         try {
161                                 debugStream.close();
162                         } catch (IOException e) {
163                                 log.error("Encountered a problem cleaning up resources: could not close debug stream.");
164                         }
165                 }
166
167                 return properties;
168         }
169
170         public void init() throws ServletException {
171                 super.init();
172                 MDC.put("serviceId", "[HS] Core");
173                 try {
174                         log.info("Initializing Handle Service.");
175                         configuration = loadConfiguration();
176
177                         Init.init();
178
179                         initPKI();
180
181                         postProfile =
182                                 ShibPOSTProfileFactory.getInstance(
183                                         Arrays.asList(
184                                                 configuration.getProperty("edu.internet2.middleware.shibboleth.audiences").replaceAll(
185                                                         "\\s",
186                                                         "").split(
187                                                         ",")),
188                                         configuration.getProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.issuer"));
189
190                         handleRepository = HandleRepositoryFactory.getInstance(configuration);
191                         log.info("Handle Service initialization complete.");
192
193                 } catch (SAMLException ex) {
194                         log.fatal("Error initializing SAML libraries: " + ex);
195                         throw new UnavailableException("Handle Service failed to initialize.");
196                 } catch (HSConfigurationException ex) {
197                         log.fatal("Handle Service runtime configuration error.  Please fix and re-initialize. Cause: " + ex);
198                         throw new UnavailableException("Handle Service failed to initialize.");
199                 } catch (HandleRepositoryException ex) {
200                         log.fatal("Unable to load Handle Repository: " + ex);
201                         throw new UnavailableException("Handle Service failed to initialize.");
202                 }
203         }
204
205         protected void initPKI() throws HSConfigurationException {
206                 try {
207                         KeyStore keyStore = KeyStore.getInstance("JKS");
208
209                         keyStore.load(
210                                 new ShibResource(
211                                         configuration.getProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.keyStorePath"),
212                                         this.getClass())
213                                         .getInputStream(),
214                                 configuration
215                                         .getProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.keyStorePassword")
216                                         .toCharArray());
217
218                         privateKey =
219                                 (PrivateKey) keyStore.getKey(
220                                         configuration.getProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.keyStoreKeyAlias"),
221                                         configuration
222                                                 .getProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.keyStoreKeyPassword")
223                                                 .toCharArray());
224
225                         if (configuration.getProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.certAlias") != null) {
226                                 certificates =
227                                         keyStore.getCertificateChain(
228                                                 configuration.getProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.certAlias"));
229                         } else {
230                                 certificates =
231                                         keyStore.getCertificateChain(
232                                                 configuration.getProperty(
233                                                         "edu.internet2.middleware.shibboleth.hs.HandleServlet.keyStoreKeyAlias"));
234                         }
235                 } catch (KeyStoreException e) {
236                         throw new HSConfigurationException("An error occurred while accessing the java keystore: " + e);
237                 } catch (NoSuchAlgorithmException e) {
238                         throw new HSConfigurationException("Appropriate JCE provider not found in the java environment: " + e);
239                 } catch (CertificateException e) {
240                         throw new HSConfigurationException(
241                                 "The java keystore contained a certificate that could not be loaded: " + e);
242                 } catch (IOException e) {
243                         throw new HSConfigurationException("An error occurred while reading the java keystore: " + e);
244                 } catch (UnrecoverableKeyException e) {
245                         throw new HSConfigurationException(
246                                 "An error occurred while attempting to load the key from the java keystore: " + e);
247                 }
248         }
249         public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
250
251                 MDC.put("serviceId", "[HS] " + UUIDGenerator.getInstance().generateRandomBasedUUID());
252                 MDC.put("remoteAddr", req.getRemoteAddr());
253                 log.info("Handling request.");
254
255                 try {
256                         checkRequestParams(req);
257
258                         req.setAttribute("shire", req.getParameter("shire"));
259                         req.setAttribute("target", req.getParameter("target"));
260             
261             String header=configuration.getProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.username");
262             String username=header.equalsIgnoreCase("REMOTE_USER") ? req.getRemoteUser() : req.getHeader(header);
263
264                         String handle = handleRepository.getHandle(new AuthNPrincipal(username));
265                         log.info("Issued Handle (" + handle + ") to (" + username + ")");
266
267                         byte[] buf = generateAssertion(handle, req.getParameter("shire"), req.getRemoteAddr(), req.getAuthType());
268
269                         createForm(req, res, buf);
270
271                 } catch (HandleRepositoryException ex) {
272                         log.error(ex);
273                         handleError(req, res, ex);
274                         return;
275                 } catch (InvalidClientDataException ex) {
276                         log.error(ex);
277                         handleError(req, res, ex);
278                         return;
279                 } catch (SAMLException ex) {
280                         log.error(ex);
281                         handleError(req, res, ex);
282                         return;
283                 }
284
285         }
286
287         protected byte[] generateAssertion(String handle, String shireURL, String clientAddress, String authType)
288                 throws SAMLException, IOException {
289
290                 SAMLAuthorityBinding binding =
291                         new SAMLAuthorityBinding(
292                                 SAMLBinding.SAML_SOAP_HTTPS,
293                                 configuration.getProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.AAUrl"),
294                                 new QName(org.opensaml.XML.SAMLP_NS, "AttributeQuery"));
295
296                 SAMLResponse r =
297                         postProfile.prepare(
298                                 shireURL,
299                                 handle,
300                                 configuration.getProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.authenticationDomain"),
301                                 clientAddress,
302                                 authType,
303                                 new Date(System.currentTimeMillis()),
304                                 Collections.singleton(binding),
305                                 privateKey,
306                                 Arrays.asList(certificates),
307                                 null,
308                                 null);
309
310                 return r.toBase64();
311         }
312
313         protected void createForm(HttpServletRequest req, HttpServletResponse res, byte[] buf)
314                 throws IOException, ServletException {
315
316                 //Hardcoded to ASCII to ensure Base64 encoding compatibility
317                 req.setAttribute("assertion", new String(buf, "ASCII"));
318
319                 if (log.isDebugEnabled()) {
320                         try {
321                                 log.debug(
322                                         "Dumping generated SAML Response:"
323                                                 + System.getProperty("line.separator")
324                                                 + new String(new BASE64Decoder().decodeBuffer(new String(buf, "ASCII")), "UTF8"));
325                         } catch (IOException e) {
326                                 log.error("Encountered an error while decoding SAMLReponse for logging purposes.");
327                         }
328                 }
329
330                 RequestDispatcher rd = req.getRequestDispatcher("/hs.jsp");
331                 rd.forward(req, res);
332         }
333
334         protected void handleError(HttpServletRequest req, HttpServletResponse res, Exception e)
335                 throws ServletException, IOException {
336
337                 req.setAttribute("errorText", e.toString());
338                 req.setAttribute("requestURL", req.getRequestURI().toString());
339                 RequestDispatcher rd = req.getRequestDispatcher("/hserror.jsp");
340
341                 rd.forward(req, res);
342
343         }
344
345         protected void checkRequestParams(HttpServletRequest req) throws InvalidClientDataException {
346
347                 if (req.getParameter("target") == null || req.getParameter("target").equals("")) {
348                         throw new InvalidClientDataException("Invalid data from SHIRE: no target URL received.");
349                 }
350                 if ((req.getParameter("shire") == null) || (req.getParameter("shire").equals(""))) {
351                         throw new InvalidClientDataException("Invalid data from SHIRE: No acceptance URL received.");
352                 }
353                 if ((req.getRemoteUser() == null) || (req.getRemoteUser().equals(""))) {
354                         throw new InvalidClientDataException("Unable to authenticate remote user");
355                 }
356                 if ((req.getRemoteAddr() == null) || (req.getRemoteAddr().equals(""))) {
357                         throw new InvalidClientDataException("Unable to obtain client address.");
358                 }
359         }
360
361         class InvalidClientDataException extends Exception {
362                 public InvalidClientDataException(String message) {
363                         super(message);
364                 }
365         }
366 }
367
368
369     
370