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