Configure logging with <Logging> element in origin.xml.
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / hs / HandleServlet.java
1 /*
2  * The Shibboleth License, Version 1. Copyright (c) 2002 University Corporation for Advanced Internet Development, Inc.
3  * All rights reserved
4  * 
5  * 
6  * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
7  * following conditions are met:
8  * 
9  * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
10  * disclaimer.
11  * 
12  * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
13  * disclaimer in the documentation and/or other materials provided with the distribution, if any, must include the
14  * following acknowledgment: "This product includes software developed by the University Corporation for Advanced
15  * Internet Development <http://www.ucaid.edu> Internet2 Project. Alternately, this acknowledegement may appear in the
16  * software itself, if and wherever such third-party acknowledgments normally appear.
17  * 
18  * Neither the name of Shibboleth nor the names of its contributors, nor Internet2, nor the University Corporation for
19  * Advanced Internet Development, Inc., nor UCAID may be used to endorse or promote products derived from this software
20  * without specific prior written permission. For written permission, please contact shibboleth@shibboleth.org
21  * 
22  * Products derived from this software may not be called Shibboleth, Internet2, UCAID, or the University Corporation
23  * for Advanced Internet Development, nor may Shibboleth appear in their name, without prior written permission of the
24  * University Corporation for Advanced Internet Development.
25  * 
26  * 
27  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND WITH ALL FAULTS. ANY EXPRESS OR
28  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
29  * PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE DISCLAIMED AND THE ENTIRE RISK OF SATISFACTORY QUALITY, PERFORMANCE,
30  * ACCURACY, AND EFFORT IS WITH LICENSEE. IN NO EVENT SHALL THE COPYRIGHT OWNER, CONTRIBUTORS OR THE UNIVERSITY
31  * CORPORATION FOR ADVANCED INTERNET DEVELOPMENT, INC. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
32  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
33  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
35  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36  */
37
38 package edu.internet2.middleware.shibboleth.hs;
39
40 import java.io.IOException;
41 import java.util.Collections;
42 import java.util.Date;
43
44 import javax.servlet.RequestDispatcher;
45 import javax.servlet.ServletException;
46 import javax.servlet.UnavailableException;
47 import javax.servlet.http.HttpServlet;
48 import javax.servlet.http.HttpServletRequest;
49 import javax.servlet.http.HttpServletResponse;
50
51 import org.apache.log4j.Level;
52 import org.apache.log4j.Logger;
53 import org.apache.log4j.MDC;
54 import org.doomdark.uuid.UUIDGenerator;
55 import org.opensaml.QName;
56 import org.opensaml.SAMLAuthorityBinding;
57 import org.opensaml.SAMLBinding;
58 import org.opensaml.SAMLException;
59 import org.opensaml.SAMLNameIdentifier;
60 import org.opensaml.SAMLResponse;
61 import org.w3c.dom.Document;
62 import org.w3c.dom.Element;
63 import org.w3c.dom.NodeList;
64
65 import sun.misc.BASE64Decoder;
66 import edu.internet2.middleware.shibboleth.common.AuthNPrincipal;
67 import edu.internet2.middleware.shibboleth.common.Credentials;
68 import edu.internet2.middleware.shibboleth.common.NameIdentifierMapping;
69 import edu.internet2.middleware.shibboleth.common.NameIdentifierMappingException;
70 import edu.internet2.middleware.shibboleth.common.OriginConfig;
71 import edu.internet2.middleware.shibboleth.common.ServiceProviderMapperException;
72 import edu.internet2.middleware.shibboleth.common.ShibPOSTProfile;
73 import edu.internet2.middleware.shibboleth.common.ShibbolethConfigurationException;
74
75 public class HandleServlet extends HttpServlet {
76
77         private static Logger log = Logger.getLogger(HandleServlet.class.getName());
78         private static Logger transactionLog = Logger.getLogger("Shibboleth-TRANSACTION");
79
80         private Semaphore throttle;
81         private HSConfig configuration;
82         private Credentials credentials;
83         private HSNameMapper nameMapper;
84         private ShibPOSTProfile postProfile = new ShibPOSTProfile();
85         private HSServiceProviderMapper targetMapper;
86
87         protected void loadConfiguration() throws ShibbolethConfigurationException {
88
89                 Document originConfig = OriginConfig.getOriginConfig(this.getServletContext());
90
91                 //Load global configuration properties
92                 configuration = new HSConfig(originConfig.getDocumentElement());
93
94                 //Load signing credentials
95                 NodeList itemElements =
96                         originConfig.getDocumentElement().getElementsByTagNameNS(
97                                 Credentials.credentialsNamespace,
98                                 "Credentials");
99                 if (itemElements.getLength() < 1) {
100                         log.error("Credentials not specified.");
101                         throw new ShibbolethConfigurationException("The Handle Service requires that signing credentials be supplied in the <Credentials> configuration element.");
102                 }
103
104                 if (itemElements.getLength() > 1) {
105                         log.error("Multiple Credentials specifications found, using first.");
106                 }
107
108                 credentials = new Credentials((Element) itemElements.item(0));
109
110                 //Load name mappings
111                 itemElements =
112                         originConfig.getDocumentElement().getElementsByTagNameNS(
113                                 NameIdentifierMapping.mappingNamespace,
114                                 "NameMapping");
115
116                 for (int i = 0; i < itemElements.getLength(); i++) {
117                         try {
118                                 nameMapper.addNameMapping((Element) itemElements.item(i));
119                         } catch (NameIdentifierMappingException e) {
120                                 log.error("Name Identifier mapping could not be loaded: " + e);
121                         }
122                 }
123
124                 //Load relying party config
125                 try {
126                         targetMapper =
127                                 new HSServiceProviderMapper(
128                                         originConfig.getDocumentElement(),
129                                         configuration,
130                                         credentials,
131                                         nameMapper);
132                 } catch (ServiceProviderMapperException e) {
133                         log.error("Could not load origin configuration: " + e);
134                         throw new ShibbolethConfigurationException("Could not load origin configuration.");
135                 }
136
137         }
138
139         public void init() throws ServletException {
140                 super.init();
141                 MDC.put("serviceId", "[HS] Core");
142                 transactionLog.setLevel((Level) Level.INFO);
143                 try {
144                         log.info("Initializing Handle Service.");
145
146                         nameMapper = new HSNameMapper();
147                         loadConfiguration();
148
149                         throttle = new Semaphore(configuration.getMaxThreads());
150
151                         log.info("Handle Service initialization complete.");
152
153                 } catch (ShibbolethConfigurationException ex) {
154                         log.fatal("Handle Service runtime configuration error.  Please fix and re-initialize. Cause: " + ex);
155                         throw new UnavailableException("Handle Service failed to initialize.");
156                 }
157         }
158
159         public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
160
161                 MDC.put("serviceId", "[HS] " + UUIDGenerator.getInstance().generateRandomBasedUUID());
162                 MDC.put("remoteAddr", req.getRemoteAddr());
163                 log.info("Handling request.");
164
165                 try {
166                         throttle.enter();
167                         checkRequestParams(req);
168
169                         req.setAttribute("shire", req.getParameter("shire"));
170                         req.setAttribute("target", req.getParameter("target"));
171
172                         HSRelyingParty relyingParty = targetMapper.getRelyingParty(req.getParameter("providerId"));
173
174                         String username =
175                                 configuration.getAuthHeaderName().equalsIgnoreCase("REMOTE_USER")
176                                         ? req.getRemoteUser()
177                                         : req.getHeader(configuration.getAuthHeaderName());
178
179                         SAMLNameIdentifier nameId =
180                                 nameMapper.getNameIdentifierName(
181                                         relyingParty.getHSNameFormatId(),
182                                         new AuthNPrincipal(username),
183                                         relyingParty,
184                                         relyingParty.getIdentityProvider());
185
186                         String authenticationMethod = req.getHeader("SAMLAuthenticationMethod");
187                         if (authenticationMethod == null || authenticationMethod.equals("")) {
188                                 authenticationMethod = relyingParty.getDefaultAuthMethod().toString();
189                                 log.debug(
190                                         "User was authenticated via the default method for this relying party ("
191                                                 + authenticationMethod
192                                                 + ").");
193                         } else {
194                                 log.debug("User was authenticated via the method (" + authenticationMethod + ").");
195                         }
196
197                         byte[] buf =
198                                 generateAssertion(
199                                         relyingParty,
200                                         nameId,
201                                         req.getParameter("shire"),
202                                         req.getRemoteAddr(),
203                                         authenticationMethod);
204
205                         createForm(req, res, buf);
206
207                         transactionLog.info(
208                                 "Authentication assertion issued to SHIRE ("
209                                         + req.getParameter("shire")
210                                         + ") providerId ("
211                                         + req.getParameter("providerId")
212                                         + ") on behalf of principal ("
213                                         + username
214                                         + ") for resource ("
215                                         + req.getParameter("target")
216                                         + "). Name Identifier: ("
217                                         + nameId.getName()
218                                         + "). Name Identifier Format: ("
219                                         + nameId.getFormat()
220                                         + ").");
221
222                 } catch (NameIdentifierMappingException ex) {
223                         log.error(ex);
224                         handleError(req, res, ex);
225                         return;
226                 } catch (InvalidClientDataException ex) {
227                         log.error(ex);
228                         handleError(req, res, ex);
229                         return;
230                 } catch (SAMLException ex) {
231                         log.error(ex);
232                         handleError(req, res, ex);
233                         return;
234                 } catch (InterruptedException ex) {
235                         log.error(ex);
236                         handleError(req, res, ex);
237                         return;
238                 } finally {
239                         throttle.exit();
240                 }
241         }
242         
243         public void destroy() {
244                 log.info("Cleaning up resources.");
245                 nameMapper.destroy();
246         }
247
248         protected byte[] generateAssertion(
249                 HSRelyingParty relyingParty,
250                 SAMLNameIdentifier nameId,
251                 String shireURL,
252                 String clientAddress,
253                 String authType)
254                 throws SAMLException, IOException {
255
256                 SAMLAuthorityBinding binding =
257                         new SAMLAuthorityBinding(
258                                 SAMLBinding.SAML_SOAP_HTTPS,
259                                 relyingParty.getAAUrl().toString(),
260                                 new QName(org.opensaml.XML.SAMLP_NS, "AttributeQuery"));
261
262                 SAMLResponse r =
263                         postProfile.prepare(
264                                 shireURL,
265                                 relyingParty,
266                                 nameId,
267                                 clientAddress,
268                                 authType,
269                                 new Date(System.currentTimeMillis()),
270                                 Collections.singleton(binding));
271
272                 return r.toBase64();
273         }
274
275         protected void createForm(HttpServletRequest req, HttpServletResponse res, byte[] buf)
276                 throws IOException, ServletException {
277
278                 //Hardcoded to ASCII to ensure Base64 encoding compatibility
279                 req.setAttribute("assertion", new String(buf, "ASCII"));
280
281                 if (log.isDebugEnabled()) {
282                         try {
283                                 log.debug(
284                                         "Dumping generated SAML Response:"
285                                                 + System.getProperty("line.separator")
286                                                 + new String(new BASE64Decoder().decodeBuffer(new String(buf, "ASCII")), "UTF8"));
287                         } catch (IOException e) {
288                                 log.error("Encountered an error while decoding SAMLReponse for logging purposes.");
289                         }
290                 }
291
292                 RequestDispatcher rd = req.getRequestDispatcher("/hs.jsp");
293                 rd.forward(req, res);
294         }
295
296         protected void handleError(HttpServletRequest req, HttpServletResponse res, Exception e)
297                 throws ServletException, IOException {
298
299                 req.setAttribute("errorText", e.toString());
300                 req.setAttribute("requestURL", req.getRequestURI().toString());
301                 RequestDispatcher rd = req.getRequestDispatcher("/hserror.jsp");
302
303                 rd.forward(req, res);
304         }
305
306         protected void checkRequestParams(HttpServletRequest req) throws InvalidClientDataException {
307
308                 if (req.getParameter("target") == null || req.getParameter("target").equals("")) {
309                         throw new InvalidClientDataException("Invalid data from SHIRE: no target URL received.");
310                 }
311                 if ((req.getParameter("shire") == null) || (req.getParameter("shire").equals(""))) {
312                         throw new InvalidClientDataException("Invalid data from SHIRE: No acceptance URL received.");
313                 }
314                 if ((req.getRemoteUser() == null) || (req.getRemoteUser().equals(""))) {
315                         throw new InvalidClientDataException("Unable to authenticate remote user");
316                 }
317                 if ((req.getRemoteAddr() == null) || (req.getRemoteAddr().equals(""))) {
318                         throw new InvalidClientDataException("Unable to obtain client address.");
319                 }
320         }
321
322         class InvalidClientDataException extends Exception {
323                 public InvalidClientDataException(String message) {
324                         super(message);
325                 }
326         }
327
328         private class Semaphore {
329                 private int value;
330
331                 public Semaphore(int value) {
332                         this.value = value;
333                 }
334
335                 public synchronized void enter() throws InterruptedException {
336                         --value;
337                         if (value < 0) {
338                                 wait();
339                         }
340                 }
341
342                 public synchronized void exit() {
343                         ++value;
344                         notify();
345                 }
346         }
347
348 }