Start to convert HS to new config.
[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.Enumeration;
66 import java.util.Properties;
67
68 import javax.servlet.RequestDispatcher;
69 import javax.servlet.ServletException;
70 import javax.servlet.UnavailableException;
71 import javax.servlet.http.HttpServlet;
72 import javax.servlet.http.HttpServletRequest;
73 import javax.servlet.http.HttpServletResponse;
74
75 import org.apache.log4j.Logger;
76 import org.apache.log4j.MDC;
77 import org.apache.xerces.parsers.DOMParser;
78 import org.doomdark.uuid.UUIDGenerator;
79 import org.opensaml.QName;
80 import org.opensaml.SAMLAuthenticationStatement;
81 import org.opensaml.SAMLAuthorityBinding;
82 import org.opensaml.SAMLBinding;
83 import org.opensaml.SAMLException;
84 import org.opensaml.SAMLNameIdentifier;
85 import org.opensaml.SAMLResponse;
86 import org.w3c.dom.Element;
87 import org.w3c.dom.NodeList;
88 import org.xml.sax.InputSource;
89 import org.xml.sax.SAXException;
90
91 import sun.misc.BASE64Decoder;
92 import edu.internet2.middleware.shibboleth.common.AuditLevel;
93 import edu.internet2.middleware.shibboleth.common.AuthNPrincipal;
94 import edu.internet2.middleware.shibboleth.common.Credentials;
95 import edu.internet2.middleware.shibboleth.common.NameIdentifierMapping;
96 import edu.internet2.middleware.shibboleth.common.NameIdentifierMappingException;
97 import edu.internet2.middleware.shibboleth.common.NameMapper;
98 import edu.internet2.middleware.shibboleth.common.RelyingParty;
99 import edu.internet2.middleware.shibboleth.common.ShibPOSTProfile;
100 import edu.internet2.middleware.shibboleth.common.ShibPOSTProfileFactory;
101 import edu.internet2.middleware.shibboleth.common.ShibResource;
102 import edu.internet2.middleware.shibboleth.common.ShibbolethOriginConfig;
103 import edu.internet2.middleware.shibboleth.common.ShibResource.ResourceNotAvailableException;
104
105 public class HandleServlet extends HttpServlet {
106
107
108         private static Logger log = Logger.getLogger(HandleServlet.class.getName());
109         private Semaphore throttle;
110         private ShibbolethOriginConfig configuration;
111         private Credentials credentials;
112         private HSNameMapper nameMapper = new HSNameMapper();
113         
114         //TODO this is temporary, until we have the mapper
115         private RelyingParty relyingParty;
116         
117         protected void loadConfiguration() throws HSConfigurationException {
118
119                 //TODO This should be setup to do schema checking
120                 DOMParser parser = new DOMParser();
121                 String originConfigFile = getInitParameter("OriginConfigFile");
122                 log.debug("Loading Configuration from (" + originConfigFile + ").");
123                 try {
124                         parser.parse(new InputSource(new ShibResource(originConfigFile, this.getClass()).getInputStream()));
125
126                 } catch (ResourceNotAvailableException e) {
127                         // TODO Auto-generated catch block
128                         e.printStackTrace();
129                 } catch (SAXException e) {
130                         // TODO Auto-generated catch block
131                         e.printStackTrace();
132                 } catch (IOException e) {
133                         // TODO Auto-generated catch block
134                         e.printStackTrace();
135                 }
136
137                 //Load global configuration properties
138                 configuration = new ShibbolethOriginConfig(parser.getDocument().getDocumentElement());
139
140                 //Load signing credentials
141                 NodeList itemElements =
142                         parser.getDocument().getDocumentElement().getElementsByTagNameNS(
143                                 Credentials.credentialsNamespace,
144                                 "Credentials");
145                 if (itemElements.getLength() < 1) {
146                         log.error("Credentials not specified.");
147                         throw new HSConfigurationException("The Handle Service requires that signing credentials be supplied in the <Credentials> configuration element.");
148                 }
149
150                 if (itemElements.getLength() > 1) {
151                         log.error("Multiple Credentials specifications, using first.");
152                 }
153
154                 credentials = new Credentials((Element) itemElements.item(0));
155
156                 //Load name mappings
157                 itemElements =
158                         parser.getDocument().getDocumentElement().getElementsByTagNameNS(
159                                 NameIdentifierMapping.mappingNamespace,
160                                 "NameMapping");
161
162                 for (int i = 0; i < itemElements.getLength(); i++) {
163                         try {
164                                 nameMapper.addNameMapping((Element) itemElements.item(i));
165                         } catch (NameIdentifierMappingException e1) {
166                                 // TODO Auto-generated catch block
167                                 e1.printStackTrace();
168                         }
169                 }
170
171                 //TODO this is temporary, until we have the mapper
172                 relyingParty = new RelyingParty(null, configuration);
173                 
174         }
175
176         public void init() throws ServletException {
177                 super.init();
178                 MDC.put("serviceId", "[HS] Core");
179                 try {
180                         log.info("Initializing Handle Service.");
181                         
182                         loadConfiguration();
183
184                         throttle =
185                                 new Semaphore(
186                                         Integer.parseInt(
187                                                 configuration.getConfigProperty(
188                                                         "edu.internet2.middleware.shibboleth.hs.HandleServlet.maxThreads")));
189
190                         log.info("Handle Service initialization complete.");
191
192                 } catch (HSConfigurationException ex) {
193                         log.fatal("Handle Service runtime configuration error.  Please fix and re-initialize. Cause: " + ex);
194                         throw new UnavailableException("Handle Service failed to initialize.");
195                 }
196         }
197
198         public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
199
200                 MDC.put("serviceId", "[HS] " + UUIDGenerator.getInstance().generateRandomBasedUUID());
201                 MDC.put("remoteAddr", req.getRemoteAddr());
202                 log.info("Handling request.");
203
204                 try {
205                         throttle.enter();
206                         checkRequestParams(req);
207
208                         req.setAttribute("shire", req.getParameter("shire"));
209                         req.setAttribute("target", req.getParameter("target"));
210
211                         //TODO this is temporary, the first thing to do here is to lookup the relyingParty
212
213                         String header =
214                                 relyingParty.getConfigProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.username");
215                         String username = header.equalsIgnoreCase("REMOTE_USER") ? req.getRemoteUser() : req.getHeader(header);
216
217                         //TODO get right data in here
218                         SAMLNameIdentifier nameId =
219                                 nameMapper.getNameIdentifierName(null, new AuthNPrincipal(username), relyingParty, null);
220
221                         //Print out something better here
222                         //log.info("Issued Handle (" + handle + ") to (" + username + ")");
223
224                         byte[] buf =
225                                 generateAssertion(
226                                         nameId,
227                                         req.getParameter("shire"),
228                                         req.getRemoteAddr(),
229                                         relyingParty.getConfigProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.authMethod"));
230
231                         createForm(req, res, buf);
232
233                 } catch (NameIdentifierMappingException ex) {
234                         log.error(ex);
235                         handleError(req, res, ex);
236                         return;
237                 } catch (InvalidClientDataException ex) {
238                         log.error(ex);
239                         handleError(req, res, ex);
240                         return;
241                 } catch (SAMLException ex) {
242                         log.error(ex);
243                         handleError(req, res, ex);
244                         return;
245                 } catch (InterruptedException ex) {
246                         log.error(ex);
247                         handleError(req, res, ex);
248                         return;
249                 } finally {
250                         throttle.exit();
251                 }
252         }
253
254         protected byte[] generateAssertion(
255                 SAMLNameIdentifier nameId,
256                 String shireURL,
257                 String clientAddress,
258                 String authType)
259                 throws SAMLException, IOException {
260
261 //TODO hmmm... maybe audiences should change here based on relying party
262                 ShibPOSTProfile postProfile =
263                         ShibPOSTProfileFactory.getInstance(
264                                 Arrays.asList(
265                                         relyingParty.getConfigProperty("edu.internet2.middleware.shibboleth.audiences").replaceAll(
266                                                 "\\s",
267                                                 "").split(
268                                                 ",")),
269                                 relyingParty.getConfigProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.issuer"));
270
271                 SAMLAuthorityBinding binding =
272                         new SAMLAuthorityBinding(
273                                 SAMLBinding.SAML_SOAP_HTTPS,
274                                 relyingParty.getConfigProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.AAUrl"),
275                                 new QName(org.opensaml.XML.SAMLP_NS, "AttributeQuery"));
276
277                 //Find out right property name  for provider id and credential
278
279                 SAMLResponse r =
280                         postProfile.prepare(
281                                 shireURL,
282                                 nameId,
283                                 //TODO Scott mentioned this should be optional at some point
284                                 clientAddress,
285                                 authType,
286                                 new Date(System.currentTimeMillis()),
287                                 Collections.singleton(binding),
288                                 credentials.getCredential(
289                                         relyingParty.getConfigProperty(
290                                                 "edu.internet2.middleware.shibboleth.hs.HandleServlet.credentialName")),
291                                 null,
292                                 null);
293
294                 return r.toBase64();
295         }
296
297         protected void createForm(HttpServletRequest req, HttpServletResponse res, byte[] buf)
298                 throws IOException, ServletException {
299
300                 //Hardcoded to ASCII to ensure Base64 encoding compatibility
301                 req.setAttribute("assertion", new String(buf, "ASCII"));
302
303                 if (log.isDebugEnabled()) {
304                         try {
305                                 log.debug(
306                                         "Dumping generated SAML Response:"
307                                                 + System.getProperty("line.separator")
308                                                 + new String(new BASE64Decoder().decodeBuffer(new String(buf, "ASCII")), "UTF8"));
309                         } catch (IOException e) {
310                                 log.error("Encountered an error while decoding SAMLReponse for logging purposes.");
311                         }
312                 }
313
314                 RequestDispatcher rd = req.getRequestDispatcher("/hs.jsp");
315                 rd.forward(req, res);
316         }
317
318         protected void handleError(HttpServletRequest req, HttpServletResponse res, Exception e)
319                 throws ServletException, IOException {
320
321                 req.setAttribute("errorText", e.toString());
322                 req.setAttribute("requestURL", req.getRequestURI().toString());
323                 RequestDispatcher rd = req.getRequestDispatcher("/hserror.jsp");
324
325                 rd.forward(req, res);
326         }
327
328         protected void checkRequestParams(HttpServletRequest req) throws InvalidClientDataException {
329
330                 if (req.getParameter("target") == null || req.getParameter("target").equals("")) {
331                         throw new InvalidClientDataException("Invalid data from SHIRE: no target URL received.");
332                 }
333                 if ((req.getParameter("shire") == null) || (req.getParameter("shire").equals(""))) {
334                         throw new InvalidClientDataException("Invalid data from SHIRE: No acceptance URL received.");
335                 }
336                 if ((req.getRemoteUser() == null) || (req.getRemoteUser().equals(""))) {
337                         throw new InvalidClientDataException("Unable to authenticate remote user");
338                 }
339                 if ((req.getRemoteAddr() == null) || (req.getRemoteAddr().equals(""))) {
340                         throw new InvalidClientDataException("Unable to obtain client address.");
341                 }
342         }
343
344         class InvalidClientDataException extends Exception {
345                 public InvalidClientDataException(String message) {
346                         super(message);
347                 }
348         }
349
350         private class Semaphore {
351                 private int value;
352
353                 public Semaphore(int value) {
354                         this.value = value;
355                 }
356
357                 public synchronized void enter() throws InterruptedException {
358                         --value;
359                         if (value < 0) {
360                                 wait();
361                         }
362                 }
363
364                 public synchronized void exit() {
365                         ++value;
366                         notify();
367                 }
368         }
369 }
370
371
372     
373