a117776a4eac3fc567060336e9267cb59aa55ebc
[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.HttpServletRequest;
48 import javax.servlet.http.HttpServletResponse;
49
50 import org.apache.log4j.Level;
51 import org.apache.log4j.Logger;
52 import org.apache.log4j.MDC;
53 import org.doomdark.uuid.UUIDGenerator;
54 import org.opensaml.QName;
55 import org.opensaml.SAMLAuthorityBinding;
56 import org.opensaml.SAMLBinding;
57 import org.opensaml.SAMLException;
58 import org.opensaml.SAMLNameIdentifier;
59 import org.opensaml.SAMLResponse;
60 import org.w3c.dom.Document;
61 import org.w3c.dom.Element;
62 import org.w3c.dom.NodeList;
63
64 import sun.misc.BASE64Decoder;
65 import edu.internet2.middleware.shibboleth.common.AuthNPrincipal;
66 import edu.internet2.middleware.shibboleth.common.Credentials;
67 import edu.internet2.middleware.shibboleth.common.NameIdentifierMapping;
68 import edu.internet2.middleware.shibboleth.common.NameIdentifierMappingException;
69 import edu.internet2.middleware.shibboleth.common.OriginComponent;
70 import edu.internet2.middleware.shibboleth.common.ServiceProviderMapperException;
71 import edu.internet2.middleware.shibboleth.common.ShibPOSTProfile;
72 import edu.internet2.middleware.shibboleth.common.ShibbolethConfigurationException;
73
74 public class HandleServlet extends OriginComponent {
75
76         private static Logger log = Logger.getLogger(HandleServlet.class.getName());
77         private static Logger transactionLog = Logger.getLogger("edu.internet2.middleware.shibboleth.TRANSACTION");
78
79         private Semaphore throttle;
80         private HSConfig configuration;
81         private Credentials credentials;
82         private HSNameMapper nameMapper;
83         private ShibPOSTProfile postProfile = new ShibPOSTProfile();
84         private HSServiceProviderMapper targetMapper;
85
86         protected void loadConfiguration() throws ShibbolethConfigurationException {
87
88                 Document originConfig = getOriginConfig();
89
90                 //Load global configuration properties
91                 configuration = new HSConfig(originConfig.getDocumentElement());
92
93                 //Load signing credentials
94                 NodeList itemElements =
95                         originConfig.getDocumentElement().getElementsByTagNameNS(
96                                 Credentials.credentialsNamespace,
97                                 "Credentials");
98                 if (itemElements.getLength() < 1) {
99                         log.error("Credentials not specified.");
100                         throw new ShibbolethConfigurationException("The Handle Service requires that signing credentials be supplied in the <Credentials> configuration element.");
101                 }
102
103                 if (itemElements.getLength() > 1) {
104                         log.error("Multiple Credentials specifications found, using first.");
105                 }
106
107                 credentials = new Credentials((Element) itemElements.item(0));
108
109                 //Load name mappings
110                 itemElements =
111                         originConfig.getDocumentElement().getElementsByTagNameNS(
112                                 NameIdentifierMapping.mappingNamespace,
113                                 "NameMapping");
114
115                 for (int i = 0; i < itemElements.getLength(); i++) {
116                         try {
117                                 nameMapper.addNameMapping((Element) itemElements.item(i));
118                         } catch (NameIdentifierMappingException e) {
119                                 log.error("Name Identifier mapping could not be loaded: " + e);
120                         }
121                 }
122
123                 //Load relying party config
124                 try {
125                         targetMapper =
126                                 new HSServiceProviderMapper(
127                                         originConfig.getDocumentElement(),
128                                         configuration,
129                                         credentials,
130                                         nameMapper);
131                 } catch (ServiceProviderMapperException e) {
132                         log.error("Could not load origin configuration: " + e);
133                         throw new ShibbolethConfigurationException("Could not load origin configuration.");
134                 }
135
136         }
137
138         public void init() throws ServletException {
139                 super.init();
140                 MDC.put("serviceId", "[HS] Core");
141                 transactionLog.setLevel((Level) Level.INFO);
142                 try {
143                         log.info("Initializing Handle Service.");
144
145                         nameMapper = new HSNameMapper();
146                         loadConfiguration();
147
148                         throttle = new Semaphore(configuration.getMaxThreads());
149
150                         log.info("Handle Service initialization complete.");
151
152                 } catch (ShibbolethConfigurationException ex) {
153                         log.fatal("Handle Service runtime configuration error.  Please fix and re-initialize. Cause: " + ex);
154                         throw new UnavailableException("Handle Service failed to initialize.");
155                 }
156         }
157
158         public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
159
160                 MDC.put("serviceId", "[HS] " + UUIDGenerator.getInstance().generateRandomBasedUUID());
161                 MDC.put("remoteAddr", req.getRemoteAddr());
162                 log.info("Handling request.");
163
164                 try {
165                         throttle.enter();
166                         checkRequestParams(req);
167
168                         req.setAttribute("shire", req.getParameter("shire"));
169                         req.setAttribute("target", req.getParameter("target"));
170
171                         HSRelyingParty relyingParty = targetMapper.getRelyingParty(req.getParameter("providerId"));
172
173                         String username =
174                                 configuration.getAuthHeaderName().equalsIgnoreCase("REMOTE_USER")
175                                         ? req.getRemoteUser()
176                                         : req.getHeader(configuration.getAuthHeaderName());
177
178                         SAMLNameIdentifier nameId =
179                                 nameMapper.getNameIdentifierName(
180                                         relyingParty.getHSNameFormatId(),
181                                         new AuthNPrincipal(username),
182                                         relyingParty,
183                                         relyingParty.getIdentityProvider());
184
185                         String authenticationMethod = req.getHeader("SAMLAuthenticationMethod");
186                         if (authenticationMethod == null || authenticationMethod.equals("")) {
187                                 authenticationMethod = relyingParty.getDefaultAuthMethod().toString();
188                                 log.debug(
189                                         "User was authenticated via the default method for this relying party ("
190                                                 + authenticationMethod
191                                                 + ").");
192                         } else {
193                                 log.debug("User was authenticated via the method (" + authenticationMethod + ").");
194                         }
195
196                         byte[] buf =
197                                 generateAssertion(
198                                         relyingParty,
199                                         nameId,
200                                         req.getParameter("shire"),
201                                         req.getRemoteAddr(),
202                                         authenticationMethod);
203
204                         createForm(req, res, buf);
205
206                         transactionLog.info(
207                                 "Authentication assertion issued to SHIRE ("
208                                         + req.getParameter("shire")
209                                         + ") providerId ("
210                                         + req.getParameter("providerId")
211                                         + ") on behalf of principal ("
212                                         + username
213                                         + ") for resource ("
214                                         + req.getParameter("target")
215                                         + "). Name Identifier: ("
216                                         + nameId.getName()
217                                         + "). Name Identifier Format: ("
218                                         + nameId.getFormat()
219                                         + ").");
220
221                 } catch (NameIdentifierMappingException ex) {
222                         log.error(ex);
223                         handleError(req, res, ex);
224                         return;
225                 } catch (InvalidClientDataException ex) {
226                         log.error(ex);
227                         handleError(req, res, ex);
228                         return;
229                 } catch (SAMLException ex) {
230                         log.error(ex);
231                         handleError(req, res, ex);
232                         return;
233                 } catch (InterruptedException ex) {
234                         log.error(ex);
235                         handleError(req, res, ex);
236                         return;
237                 } finally {
238                         throttle.exit();
239                 }
240         }
241         
242         public void destroy() {
243                 log.info("Cleaning up resources.");
244                 nameMapper.destroy();
245         }
246
247         protected byte[] generateAssertion(
248                 HSRelyingParty relyingParty,
249                 SAMLNameIdentifier nameId,
250                 String shireURL,
251                 String clientAddress,
252                 String authType)
253                 throws SAMLException, IOException {
254
255                 SAMLAuthorityBinding binding =
256                         new SAMLAuthorityBinding(
257                                 SAMLBinding.SAML_SOAP_HTTPS,
258                                 relyingParty.getAAUrl().toString(),
259                                 new QName(org.opensaml.XML.SAMLP_NS, "AttributeQuery"));
260
261                 SAMLResponse r =
262                         postProfile.prepare(
263                                 shireURL,
264                                 relyingParty,
265                                 nameId,
266                                 clientAddress,
267                                 authType,
268                                 new Date(System.currentTimeMillis()),
269                                 Collections.singleton(binding));
270
271                 return r.toBase64();
272         }
273
274         protected void createForm(HttpServletRequest req, HttpServletResponse res, byte[] buf)
275                 throws IOException, ServletException {
276
277                 //Hardcoded to ASCII to ensure Base64 encoding compatibility
278                 req.setAttribute("assertion", new String(buf, "ASCII"));
279
280                 if (log.isDebugEnabled()) {
281                         try {
282                                 log.debug(
283                                         "Dumping generated SAML Response:"
284                                                 + System.getProperty("line.separator")
285                                                 + new String(new BASE64Decoder().decodeBuffer(new String(buf, "ASCII")), "UTF8"));
286                         } catch (IOException e) {
287                                 log.error("Encountered an error while decoding SAMLReponse for logging purposes.");
288                         }
289                 }
290
291                 RequestDispatcher rd = req.getRequestDispatcher("/hs.jsp");
292                 rd.forward(req, res);
293         }
294
295         protected void handleError(HttpServletRequest req, HttpServletResponse res, Exception e)
296                 throws ServletException, IOException {
297
298                 req.setAttribute("errorText", e.toString());
299                 req.setAttribute("requestURL", req.getRequestURI().toString());
300                 RequestDispatcher rd = req.getRequestDispatcher("/hserror.jsp");
301
302                 rd.forward(req, res);
303         }
304
305         protected void checkRequestParams(HttpServletRequest req) throws InvalidClientDataException {
306
307                 if (req.getParameter("target") == null || req.getParameter("target").equals("")) {
308                         throw new InvalidClientDataException("Invalid data from SHIRE: no target URL received.");
309                 }
310                 if ((req.getParameter("shire") == null) || (req.getParameter("shire").equals(""))) {
311                         throw new InvalidClientDataException("Invalid data from SHIRE: No acceptance URL received.");
312                 }
313                 if ((req.getRemoteUser() == null) || (req.getRemoteUser().equals(""))) {
314                         throw new InvalidClientDataException("Unable to authenticate remote user");
315                 }
316                 if ((req.getRemoteAddr() == null) || (req.getRemoteAddr().equals(""))) {
317                         throw new InvalidClientDataException("Unable to obtain client address.");
318                 }
319         }
320
321         class InvalidClientDataException extends Exception {
322                 public InvalidClientDataException(String message) {
323                         super(message);
324                 }
325         }
326
327         private class Semaphore {
328                 private int value;
329
330                 public Semaphore(int value) {
331                         this.value = value;
332                 }
333
334                 public synchronized void enter() throws InterruptedException {
335                         --value;
336                         if (value < 0) {
337                                 wait();
338                         }
339                 }
340
341                 public synchronized void exit() {
342                         ++value;
343                         notify();
344                 }
345         }
346
347 }