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