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