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