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