Move the signing throttling into IdPProtocolSupport so that it effects all signing...
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / idp / IdPResponder.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 above
6  * copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials
7  * provided with the distribution, if any, must include the following acknowledgment: "This product includes software
8  * developed by the University Corporation for Advanced Internet Development <http://www.ucaid.edu> Internet2 Project.
9  * 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, nor
11  * 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 contact
13  * shibboleth@shibboleth.org Products derived from this software may not be called Shibboleth, Internet2, UCAID, or the
14  * University Corporation for Advanced Internet Development, nor may Shibboleth appear in their name, without prior
15  * written permission of the University Corporation for Advanced Internet Development. THIS SOFTWARE IS PROVIDED BY THE
16  * COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND WITH ALL FAULTS. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE
18  * DISCLAIMED AND THE ENTIRE RISK OF SATISFACTORY QUALITY, PERFORMANCE, ACCURACY, AND EFFORT IS WITH LICENSEE. IN NO
19  * EVENT SHALL THE COPYRIGHT OWNER, CONTRIBUTORS OR THE UNIVERSITY CORPORATION FOR ADVANCED INTERNET DEVELOPMENT, INC.
20  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
21  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
23  * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 package edu.internet2.middleware.shibboleth.idp;
27
28 import java.io.IOException;
29 import java.net.URI;
30 import java.util.HashMap;
31 import java.util.Random;
32
33 import javax.servlet.RequestDispatcher;
34 import javax.servlet.ServletException;
35 import javax.servlet.UnavailableException;
36 import javax.servlet.http.HttpServlet;
37 import javax.servlet.http.HttpServletRequest;
38 import javax.servlet.http.HttpServletResponse;
39
40 import org.apache.log4j.Logger;
41 import org.apache.log4j.MDC;
42 import org.opensaml.SAMLBinding;
43 import org.opensaml.SAMLBindingFactory;
44 import org.opensaml.SAMLException;
45 import org.opensaml.SAMLRequest;
46 import org.opensaml.SAMLResponse;
47 import org.w3c.dom.Document;
48 import org.w3c.dom.Element;
49 import org.w3c.dom.NodeList;
50
51 import sun.misc.BASE64Decoder;
52 import edu.internet2.middleware.shibboleth.aa.arp.ArpEngine;
53 import edu.internet2.middleware.shibboleth.aa.arp.ArpException;
54 import edu.internet2.middleware.shibboleth.aa.attrresolv.AttributeResolver;
55 import edu.internet2.middleware.shibboleth.aa.attrresolv.AttributeResolverException;
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.NameMapper;
60 import edu.internet2.middleware.shibboleth.common.OriginConfig;
61 import edu.internet2.middleware.shibboleth.common.ServiceProviderMapper;
62 import edu.internet2.middleware.shibboleth.common.ServiceProviderMapperException;
63 import edu.internet2.middleware.shibboleth.common.ShibbolethConfigurationException;
64 import edu.internet2.middleware.shibboleth.metadata.Metadata;
65 import edu.internet2.middleware.shibboleth.metadata.MetadataException;
66
67 /**
68  * Primary entry point for requests to the SAML IdP. Listens on multiple endpoints, routes requests to the appropriate
69  * IdP processing components, and delivers proper protocol responses.
70  * 
71  * @author Walter Hoehn
72  */
73
74 public class IdPResponder extends HttpServlet {
75
76         private static Logger transactionLog = Logger.getLogger("Shibboleth-TRANSACTION");
77         private static Logger log = Logger.getLogger(IdPResponder.class.getName());
78         private static Random idgen = new Random();
79         private SAMLBinding binding;
80
81         private IdPConfig configuration;
82         private HashMap protocolHandlers = new HashMap();
83         private IdPProtocolSupport protocolSupport;
84
85         /*
86          * @see javax.servlet.GenericServlet#init()
87          */
88         public void init() throws ServletException {
89
90                 super.init();
91                 MDC.put("serviceId", "[IdP] Core");
92                 log.info("Initializing Identity Provider.");
93
94                 try {
95                         binding = SAMLBindingFactory.getInstance(SAMLBinding.SOAP);
96
97                         Document originConfig = OriginConfig.getOriginConfig(this.getServletContext());
98
99                         // Load global configuration properties
100                         configuration = new IdPConfig(originConfig.getDocumentElement());
101
102                         // Load name mappings
103                         NameMapper nameMapper = new NameMapper();
104                         NodeList itemElements = originConfig.getDocumentElement().getElementsByTagNameNS(
105                                         NameIdentifierMapping.mappingNamespace, "NameMapping");
106
107                         for (int i = 0; i < itemElements.getLength(); i++) {
108                                 try {
109                                         nameMapper.addNameMapping((Element) itemElements.item(i));
110                                 } catch (NameIdentifierMappingException e) {
111                                         log.error("Name Identifier mapping could not be loaded: " + e);
112                                 }
113                         }
114
115                         // Load signing credentials
116                         itemElements = originConfig.getDocumentElement().getElementsByTagNameNS(Credentials.credentialsNamespace,
117                                         "Credentials");
118                         if (itemElements.getLength() < 1) {
119                                 log.error("No credentials specified.");
120                         }
121                         if (itemElements.getLength() > 1) {
122                                 log.error("Multiple Credentials specifications found, using first.");
123                         }
124                         Credentials credentials = new Credentials((Element) itemElements.item(0));
125
126                         // Load relying party config
127                         ServiceProviderMapper spMapper;
128                         try {
129                                 spMapper = new ServiceProviderMapper(originConfig.getDocumentElement(), configuration, credentials,
130                                                 nameMapper);
131                         } catch (ServiceProviderMapperException e) {
132                                 log.error("Could not load Identity Provider configuration: " + e);
133                                 throw new ShibbolethConfigurationException("Could not load Identity Provider configuration.");
134                         }
135
136                         // Startup Attribute Resolver & ARP engine
137                         AttributeResolver resolver = null;
138                         ArpEngine arpEngine = null;
139                         try {
140                                 resolver = new AttributeResolver(configuration);
141
142                                 itemElements = originConfig.getDocumentElement().getElementsByTagNameNS(IdPConfig.configNameSpace,
143                                                 "ReleasePolicyEngine");
144
145                                 if (itemElements.getLength() > 1) {
146                                         log.warn("Encountered multiple <ReleasePolicyEngine> configuration elements.  Using first...");
147                                 }
148                                 if (itemElements.getLength() < 1) {
149                                         arpEngine = new ArpEngine();
150                                 } else {
151                                         arpEngine = new ArpEngine((Element) itemElements.item(0));
152                                 }
153
154                         } catch (ArpException ae) {
155                                 log.fatal("The Identity Provider could not be initialized "
156                                                 + "due to a problem with the ARP Engine configuration: " + ae);
157                                 throw new ShibbolethConfigurationException("Could not load ARP Engine.");
158                         } catch (AttributeResolverException ne) {
159                                 log.fatal("The Identity Provider could not be initialized due "
160                                                 + "to a problem with the Attribute Resolver configuration: " + ne);
161                                 throw new ShibbolethConfigurationException("Could not load Attribute Resolver.");
162                         }
163
164                         // Load protocol handlers and support library
165                         protocolSupport = new IdPProtocolSupport(configuration, transactionLog, nameMapper, spMapper, arpEngine,
166                                         resolver);
167                         itemElements = originConfig.getDocumentElement().getElementsByTagNameNS(IdPConfig.configNameSpace,
168                                         "ProtocolHandler");
169
170                         // Default if no handlers are specified
171                         if (itemElements.getLength() < 1) {
172                                 // TODO work out defaulting
173
174                                 // If handlers were specified, load them and register them against their locations
175                         } else {
176                                 EACHHANDLER : for (int i = 0; i < itemElements.getLength(); i++) {
177                                         IdPProtocolHandler handler = ProtocolHandlerFactory.getInstance((Element) itemElements.item(i));
178                                         URI[] locations = handler.getLocations();
179                                         EACHLOCATION : for (int j = 0; j < locations.length; j++) {
180                                                 if (protocolHandlers.containsKey(locations[j].toString())) {
181                                                         log.error("Multiple protocol handlers are registered to listen at ("
182                                                                         + locations[j]
183                                                                         + ").  Ignoring all except ("
184                                                                         + ((IdPProtocolHandler) protocolHandlers.get(locations[j].toString()))
185                                                                                         .getHandlerName() + ").");
186                                                         continue EACHLOCATION;
187                                                 }
188                                                 log.info("Registering handler (" + handler.getHandlerName() + ") to listen at (" + locations[j]
189                                                                 + ").");
190                                                 protocolHandlers.put(locations[j].toString(), handler);
191                                         }
192                                 }
193                         }
194
195                         // Load metadata
196                         itemElements = originConfig.getDocumentElement().getElementsByTagNameNS(IdPConfig.configNameSpace,
197                                         "FederationProvider");
198                         for (int i = 0; i < itemElements.getLength(); i++) {
199                                 protocolSupport.addFederationProvider((Element) itemElements.item(i));
200                         }
201                         if (protocolSupport.providerCount() < 1) {
202                                 log.error("No Federation Provider metadata loaded.");
203                                 throw new ShibbolethConfigurationException("Could not load federation metadata.");
204                         }
205
206                         log.info("Identity Provider initialization complete.");
207
208                 } catch (ShibbolethConfigurationException ae) {
209                         log.fatal("The Identity Provider could not be initialized: " + ae);
210                         throw new UnavailableException("Identity Provider failed to initialize.");
211                 } catch (SAMLException se) {
212                         log.fatal("SAML SOAP binding could not be loaded: " + se);
213                         throw new UnavailableException("Identity Provider failed to initialize.");
214                 }
215         }
216
217         /*
218          * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
219          *      javax.servlet.http.HttpServletResponse)
220          */
221         public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
222
223                 MDC.put("serviceId", "[IdP] " + idgen.nextInt());
224                 MDC.put("remoteAddr", request.getRemoteAddr());
225                 log.debug("Recieved a request via GET for location (" + request.getRequestURL() + ").");
226
227                 try {
228                         // Determine which protocol we are responding to (at this point normally Shibv1 vs. EAuth)
229                         IdPProtocolHandler activeHandler = (IdPProtocolHandler) protocolHandlers.get(request.getRequestURL()
230                                         .toString());
231                         if (activeHandler == null) {
232                                 log.error("No protocol handler registered for location (" + request.getRequestURL() + ").");
233                                 throw new SAMLException("Request submitted to an invalid location.");
234                         }
235
236                         // Pass request to the appropriate handler
237                         log.info("Processing " + activeHandler.getHandlerName() + " request.");
238                         if (activeHandler.processRequest(request, response, null, protocolSupport) != null) {
239                                 // This shouldn't happen unless somebody configures a protocol handler incorrectly
240                                 log.error("Protocol Handler returned a SAML Response, but there is no binding to handle it.");
241                                 throw new SAMLException(SAMLException.RESPONDER, "General error processing request.");
242                         }
243
244                 } catch (SAMLException ex) {
245                         log.error(ex);
246                         displayBrowserError(request, response, ex);
247                         return;
248                 }
249         }
250
251         /*
252          * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest,
253          *      javax.servlet.http.HttpServletResponse)
254          */
255         public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
256
257                 MDC.put("serviceId", "[IdP] " + idgen.nextInt());
258                 MDC.put("remoteAddr", request.getRemoteAddr());
259                 log.debug("Recieved a request via POST for location (" + request.getRequestURL() + ").");
260
261                 // Parse SOAP request and marshall SAML request object
262                 SAMLRequest samlRequest = null;
263                 try {
264                         try {
265                                 samlRequest = binding.receive(request);
266                         } catch (SAMLException e) {
267                                 log.fatal("Unable to parse request: " + e);
268                                 throw new SAMLException("Invalid request data.");
269                         }
270
271                         // If we have DEBUG logging turned on, dump out the request to the log
272                         // This takes some processing, so only do it if we need to
273                         if (log.isDebugEnabled()) {
274                                 try {
275                                         log.debug("Dumping generated SAML Request:"
276                                                         + System.getProperty("line.separator")
277                                                         + new String(new BASE64Decoder().decodeBuffer(new String(samlRequest.toBase64(), "ASCII")),
278                                                                         "UTF8"));
279                                 } catch (SAMLException e) {
280                                         log.error("Encountered an error while decoding SAMLRequest for logging purposes.");
281                                 } catch (IOException e) {
282                                         log.error("Encountered an error while decoding SAMLRequest for logging purposes.");
283                                 }
284                         }
285
286                         // Determine which protocol handler is active for this endpoint
287                         IdPProtocolHandler activeHandler = (IdPProtocolHandler) protocolHandlers.get(request.getRequestURL()
288                                         .toString());
289                         if (activeHandler == null) {
290                                 log.error("No protocol handler registered for location (" + request.getRequestURL() + ").");
291                                 throw new SAMLException("Request submitted to an invalid location.");
292                         }
293
294                         // Pass request to the appropriate handler and respond
295                         log.info("Processing " + activeHandler.getHandlerName() + " request.");
296
297                         SAMLResponse samlResponse = activeHandler.processRequest(request, response, samlRequest, protocolSupport);
298                         binding.respond(response, samlResponse, null);
299
300                 } catch (SAMLException e) {
301                         sendFailureToSAMLBinding(response, samlRequest, e);
302                 }
303         }
304
305         private void sendFailureToSAMLBinding(HttpServletResponse httpResponse, SAMLRequest samlRequest,
306                         SAMLException exception) throws ServletException {
307
308                 log.error("Error while processing request: " + exception);
309                 try {
310                         SAMLResponse samlResponse = new SAMLResponse((samlRequest != null) ? samlRequest.getId() : null, null,
311                                         null, exception);
312                         if (log.isDebugEnabled()) {
313                                 try {
314                                         log.debug("Dumping generated SAML Error Response:"
315                                                         + System.getProperty("line.separator")
316                                                         + new String(
317                                                                         new BASE64Decoder().decodeBuffer(new String(samlResponse.toBase64(), "ASCII")),
318                                                                         "UTF8"));
319                                 } catch (IOException e) {
320                                         log.error("Encountered an error while decoding SAMLReponse for logging purposes.");
321                                 }
322                         }
323                         binding.respond(httpResponse, samlResponse, null);
324                         log.debug("Returning SAML Error Response.");
325                 } catch (SAMLException se) {
326                         try {
327                                 binding.respond(httpResponse, null, exception);
328                         } catch (SAMLException e) {
329                                 log.error("Caught exception while responding to requester: " + e.getMessage());
330                                 try {
331                                         httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error while responding.");
332                                 } catch (IOException ee) {
333                                         log.fatal("Could not construct a SAML error response: " + ee);
334                                         throw new ServletException("Identity Provider response failure.");
335                                 }
336                         }
337                         log.error("Identity Provider failed to make an error message: " + se);
338                 }
339         }
340
341         private static void displayBrowserError(HttpServletRequest req, HttpServletResponse res, Exception e)
342                         throws ServletException, IOException {
343
344                 req.setAttribute("errorText", e.toString());
345                 req.setAttribute("requestURL", req.getRequestURI().toString());
346                 RequestDispatcher rd = req.getRequestDispatcher("/IdPError.jsp");
347                 rd.forward(req, res);
348         }
349
350 }
351
352 class FederationProviderFactory {
353
354         private static Logger log = Logger.getLogger(FederationProviderFactory.class.getName());
355
356         public static Metadata loadProvider(Element e) throws MetadataException {
357
358                 String className = e.getAttribute("type");
359                 if (className == null || className.equals("")) {
360                         log.error("Federation Provider requires specification of the attribute \"type\".");
361                         throw new MetadataException("Failed to initialize Federation Provider.");
362                 } else {
363                         try {
364                                 Class[] params = {Class.forName("org.w3c.dom.Element"),};
365                                 return (Metadata) Class.forName(className).getConstructor(params).newInstance(new Object[]{e});
366                         } catch (Exception loaderException) {
367                                 log.error("Failed to load Federation Provider implementation class: " + loaderException);
368                                 Throwable cause = loaderException.getCause();
369                                 while (cause != null) {
370                                         log.error("caused by: " + cause);
371                                         cause = cause.getCause();
372                                 }
373                                 throw new MetadataException("Failed to initialize Federation Provider.");
374                         }
375                 }
376         }
377 }