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