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