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