Per Howard's request, allow protocol handlers to be registered based on just the...
[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.MalformedURLException;
30 import java.net.URI;
31 import java.net.URL;
32 import java.util.HashMap;
33 import java.util.Random;
34
35 import javax.servlet.RequestDispatcher;
36 import javax.servlet.ServletException;
37 import javax.servlet.UnavailableException;
38 import javax.servlet.http.HttpServlet;
39 import javax.servlet.http.HttpServletRequest;
40 import javax.servlet.http.HttpServletResponse;
41
42 import org.apache.log4j.Logger;
43 import org.apache.log4j.MDC;
44 import org.opensaml.SAMLBinding;
45 import org.opensaml.SAMLBindingFactory;
46 import org.opensaml.SAMLException;
47 import org.opensaml.SAMLRequest;
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 import edu.internet2.middleware.shibboleth.aa.arp.ArpEngine;
55 import edu.internet2.middleware.shibboleth.aa.arp.ArpException;
56 import edu.internet2.middleware.shibboleth.aa.attrresolv.AttributeResolver;
57 import edu.internet2.middleware.shibboleth.aa.attrresolv.AttributeResolverException;
58 import edu.internet2.middleware.shibboleth.artifact.ArtifactMapper;
59 import edu.internet2.middleware.shibboleth.artifact.ArtifactMapperFactory;
60 import edu.internet2.middleware.shibboleth.artifact.provider.MemoryArtifactMapper;
61 import edu.internet2.middleware.shibboleth.common.Credentials;
62 import edu.internet2.middleware.shibboleth.common.NameIdentifierMapping;
63 import edu.internet2.middleware.shibboleth.common.NameIdentifierMappingException;
64 import edu.internet2.middleware.shibboleth.common.NameMapper;
65 import edu.internet2.middleware.shibboleth.common.OriginConfig;
66 import edu.internet2.middleware.shibboleth.common.ServiceProviderMapper;
67 import edu.internet2.middleware.shibboleth.common.ServiceProviderMapperException;
68 import edu.internet2.middleware.shibboleth.common.ShibbolethConfigurationException;
69 import edu.internet2.middleware.shibboleth.metadata.Metadata;
70 import edu.internet2.middleware.shibboleth.metadata.MetadataException;
71
72 /**
73  * Primary entry point for requests to the SAML IdP. Listens on multiple endpoints, routes requests to the appropriate
74  * IdP processing components, and delivers proper protocol responses.
75  * 
76  * @author Walter Hoehn
77  */
78
79 public class IdPResponder extends HttpServlet {
80
81         private static Logger transactionLog = Logger.getLogger("Shibboleth-TRANSACTION");
82         private static Logger log = Logger.getLogger(IdPResponder.class.getName());
83         private static Random idgen = new Random();
84         private SAMLBinding binding;
85
86         private IdPConfig configuration;
87         private HashMap protocolHandlers = new HashMap();
88         private IdPProtocolSupport protocolSupport;
89
90         /*
91          * @see javax.servlet.GenericServlet#init()
92          */
93         public void init() throws ServletException {
94
95                 super.init();
96                 MDC.put("serviceId", "[IdP] Core");
97                 log.info("Initializing Identity Provider.");
98
99                 try {
100                         binding = SAMLBindingFactory.getInstance(SAMLBinding.SOAP);
101
102                         Document originConfig = OriginConfig.getOriginConfig(this.getServletContext());
103
104                         // Load global configuration properties
105                         configuration = new IdPConfig(originConfig.getDocumentElement());
106
107                         // Load name mappings
108                         NameMapper nameMapper = new NameMapper();
109                         NodeList itemElements = originConfig.getDocumentElement().getElementsByTagNameNS(
110                                         NameIdentifierMapping.mappingNamespace, "NameMapping");
111
112                         for (int i = 0; i < itemElements.getLength(); i++) {
113                                 try {
114                                         nameMapper.addNameMapping((Element) itemElements.item(i));
115                                 } catch (NameIdentifierMappingException e) {
116                                         log.error("Name Identifier mapping could not be loaded: " + e);
117                                 }
118                         }
119
120                         // Load signing credentials
121                         itemElements = originConfig.getDocumentElement().getElementsByTagNameNS(Credentials.credentialsNamespace,
122                                         "Credentials");
123                         if (itemElements.getLength() < 1) {
124                                 log.error("No credentials specified.");
125                         }
126                         if (itemElements.getLength() > 1) {
127                                 log.error("Multiple Credentials specifications found, using first.");
128                         }
129                         Credentials credentials = new Credentials((Element) itemElements.item(0));
130
131                         // Load relying party config
132                         ServiceProviderMapper spMapper;
133                         try {
134                                 spMapper = new ServiceProviderMapper(originConfig.getDocumentElement(), configuration, credentials,
135                                                 nameMapper);
136                         } catch (ServiceProviderMapperException e) {
137                                 log.error("Could not load Identity Provider configuration: " + e);
138                                 throw new ShibbolethConfigurationException("Could not load Identity Provider configuration.");
139                         }
140
141                         // Startup Attribute Resolver & ARP engine
142                         AttributeResolver resolver = null;
143                         ArpEngine arpEngine = null;
144                         try {
145                                 resolver = new AttributeResolver(configuration);
146
147                                 itemElements = originConfig.getDocumentElement().getElementsByTagNameNS(IdPConfig.configNameSpace,
148                                                 "ReleasePolicyEngine");
149
150                                 if (itemElements.getLength() > 1) {
151                                         log.warn("Encountered multiple <ReleasePolicyEngine/> configuration elements.  Using first...");
152                                 }
153                                 if (itemElements.getLength() < 1) {
154                                         arpEngine = new ArpEngine();
155                                 } else {
156                                         arpEngine = new ArpEngine((Element) itemElements.item(0));
157                                 }
158
159                         } catch (ArpException ae) {
160                                 log.fatal("The Identity Provider could not be initialized "
161                                                 + "due to a problem with the ARP Engine configuration: " + ae);
162                                 throw new ShibbolethConfigurationException("Could not load ARP Engine.");
163                         } catch (AttributeResolverException ne) {
164                                 log.fatal("The Identity Provider could not be initialized due "
165                                                 + "to a problem with the Attribute Resolver configuration: " + ne);
166                                 throw new ShibbolethConfigurationException("Could not load Attribute Resolver.");
167                         }
168
169                         // Load artifact mapping implementation
170                         ArtifactMapper artifactMapper = null;
171                         itemElements = originConfig.getDocumentElement().getElementsByTagNameNS(IdPConfig.configNameSpace,
172                                         "ArtifactMapper");
173                         if (itemElements.getLength() > 1) {
174                                 log.warn("Encountered multiple <ArtifactMapper/> configuration elements.  Using first...");
175                         }
176                         if (itemElements.getLength() > 0) {
177                                 artifactMapper = ArtifactMapperFactory.getInstance((Element) itemElements.item(0));
178                         } else {
179                                 log.debug("No Artifact Mapper configuration found.  Defaulting to Memory-based implementation.");
180                                 artifactMapper = new MemoryArtifactMapper();
181                         }
182
183                         // Load protocol handlers and support library
184                         protocolSupport = new IdPProtocolSupport(configuration, transactionLog, nameMapper, spMapper, arpEngine,
185                                         resolver, artifactMapper);
186                         itemElements = originConfig.getDocumentElement().getElementsByTagNameNS(IdPConfig.configNameSpace,
187                                         "ProtocolHandler");
188
189                         // Default if no handlers are specified
190                         if (itemElements.getLength() < 1) {
191                                 // TODO work out defaulting
192
193                                 // If handlers were specified, load them and register them against their locations
194                         } else {
195                                 EACHHANDLER : for (int i = 0; i < itemElements.getLength(); i++) {
196                                         IdPProtocolHandler handler = ProtocolHandlerFactory.getInstance((Element) itemElements.item(i));
197                                         URI[] locations = handler.getLocations();
198                                         EACHLOCATION : for (int j = 0; j < locations.length; j++) {
199                                                 if (protocolHandlers.containsKey(locations[j].toString())) {
200                                                         log.error("Multiple protocol handlers are registered to listen at ("
201                                                                         + locations[j]
202                                                                         + ").  Ignoring all except ("
203                                                                         + ((IdPProtocolHandler) protocolHandlers.get(locations[j].toString()))
204                                                                                         .getHandlerName() + ").");
205                                                         continue EACHLOCATION;
206                                                 }
207                                                 log.info("Registering handler (" + handler.getHandlerName() + ") to listen at (" + locations[j]
208                                                                 + ").");
209                                                 protocolHandlers.put(locations[j].toString(), handler);
210                                         }
211                                 }
212                         }
213
214                         // Load metadata
215                         itemElements = originConfig.getDocumentElement().getElementsByTagNameNS(IdPConfig.configNameSpace,
216                                         "FederationProvider");
217                         for (int i = 0; i < itemElements.getLength(); i++) {
218                                 protocolSupport.addFederationProvider((Element) itemElements.item(i));
219                         }
220                         if (protocolSupport.providerCount() < 1) {
221                                 log.error("No Federation Provider metadata loaded.");
222                                 throw new ShibbolethConfigurationException("Could not load federation metadata.");
223                         }
224
225                         log.info("Identity Provider initialization complete.");
226
227                 } catch (ShibbolethConfigurationException ae) {
228                         log.fatal("The Identity Provider could not be initialized: " + ae);
229                         throw new UnavailableException("Identity Provider failed to initialize.");
230                 } catch (SAMLException se) {
231                         log.fatal("SAML SOAP binding could not be loaded: " + se);
232                         throw new UnavailableException("Identity Provider failed to initialize.");
233                 }
234         }
235
236         /*
237          * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
238          *      javax.servlet.http.HttpServletResponse)
239          */
240         public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
241
242                 MDC.put("serviceId", "[IdP] " + idgen.nextInt());
243                 MDC.put("remoteAddr", request.getRemoteAddr());
244                 log.debug("Recieved a request via GET for location (" + request.getRequestURL() + ").");
245
246                 try {
247                         // Determine which protocol we are responding to (at this point normally Shibv1 vs. EAuth)
248                         String requestURL = request.getRequestURL().toString();
249                         IdPProtocolHandler activeHandler = (IdPProtocolHandler) protocolHandlers.get(requestURL);
250                         if (activeHandler == null) {
251                                 log.debug("No protocol handler registered for location (" + request.getRequestURL()
252                                                 + ").  Attempting to match against relative path.");
253                                 try {
254                                         activeHandler = (IdPProtocolHandler) protocolHandlers.get(new URL(requestURL).getPath());
255                                 } catch (MalformedURLException e) {
256                                         // squelch, we will just fail to find a handler
257                                 }
258                         }
259
260                         if (activeHandler == null) {
261                                 log.error("No protocol handler registered for location (" + request.getRequestURL() + ").");
262                                 throw new SAMLException("Request submitted to an invalid location.");
263                         }
264
265                         // Pass request to the appropriate handler
266                         log.info("Processing " + activeHandler.getHandlerName() + " request.");
267                         if (activeHandler.processRequest(request, response, null, protocolSupport) != null) {
268                                 // This shouldn't happen unless somebody configures a protocol handler incorrectly
269                                 log.error("Protocol Handler returned a SAML Response, but there is no binding to handle it.");
270                                 throw new SAMLException(SAMLException.RESPONDER, "General error processing request.");
271                         }
272
273                 } catch (SAMLException ex) {
274                         log.error(ex);
275                         displayBrowserError(request, response, ex);
276                         return;
277                 }
278         }
279
280         /*
281          * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest,
282          *      javax.servlet.http.HttpServletResponse)
283          */
284         public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
285
286                 MDC.put("serviceId", "[IdP] " + idgen.nextInt());
287                 MDC.put("remoteAddr", request.getRemoteAddr());
288                 log.debug("Recieved a request via POST for location (" + request.getRequestURL() + ").");
289
290                 // Parse SOAP request and marshall SAML request object
291                 SAMLRequest samlRequest = null;
292                 try {
293                         try {
294                                 samlRequest = binding.receive(request);
295                         } catch (SAMLException e) {
296                                 log.fatal("Unable to parse request: " + e);
297                                 throw new SAMLException("Invalid request data.");
298                         }
299
300                         // If we have DEBUG logging turned on, dump out the request to the log
301                         // This takes some processing, so only do it if we need to
302                         if (log.isDebugEnabled()) {
303                                 try {
304                                         log.debug("Dumping generated SAML Request:"
305                                                         + System.getProperty("line.separator")
306                                                         + new String(new BASE64Decoder().decodeBuffer(new String(samlRequest.toBase64(), "ASCII")),
307                                                                         "UTF8"));
308                                 } catch (SAMLException e) {
309                                         log.error("Encountered an error while decoding SAMLRequest for logging purposes.");
310                                 } catch (IOException e) {
311                                         log.error("Encountered an error while decoding SAMLRequest for logging purposes.");
312                                 }
313                         }
314
315                         // Determine which protocol handler is active for this endpoint
316                         String requestURL = request.getRequestURL().toString();
317                         IdPProtocolHandler activeHandler = (IdPProtocolHandler) protocolHandlers.get(requestURL);
318                         if (activeHandler == null) {
319                                 log.debug("No protocol handler registered for location (" + request.getRequestURL()
320                                                 + ").  Attempting to match against relative path.");
321                                 try {
322                                         activeHandler = (IdPProtocolHandler) protocolHandlers.get(new URL(requestURL).getPath());
323                                 } catch (MalformedURLException e) {
324                                         // squelch, we will just fail to find a handler
325                                 }
326                         }
327
328                         // Pass request to the appropriate handler and respond
329                         log.info("Processing " + activeHandler.getHandlerName() + " request.");
330
331                         SAMLResponse samlResponse = activeHandler.processRequest(request, response, samlRequest, protocolSupport);
332                         binding.respond(response, samlResponse, null);
333
334                 } catch (SAMLException e) {
335                         sendFailureToSAMLBinding(response, samlRequest, e);
336                 }
337         }
338
339         private void sendFailureToSAMLBinding(HttpServletResponse httpResponse, SAMLRequest samlRequest,
340                         SAMLException exception) throws ServletException {
341
342                 log.error("Error while processing request: " + exception);
343                 try {
344                         SAMLResponse samlResponse = new SAMLResponse((samlRequest != null) ? samlRequest.getId() : null, null,
345                                         null, exception);
346                         if (log.isDebugEnabled()) {
347                                 try {
348                                         log.debug("Dumping generated SAML Error Response:"
349                                                         + System.getProperty("line.separator")
350                                                         + new String(
351                                                                         new BASE64Decoder().decodeBuffer(new String(samlResponse.toBase64(), "ASCII")),
352                                                                         "UTF8"));
353                                 } catch (IOException e) {
354                                         log.error("Encountered an error while decoding SAMLReponse for logging purposes.");
355                                 }
356                         }
357                         binding.respond(httpResponse, samlResponse, null);
358                         log.debug("Returning SAML Error Response.");
359                 } catch (SAMLException se) {
360                         try {
361                                 binding.respond(httpResponse, null, exception);
362                         } catch (SAMLException e) {
363                                 log.error("Caught exception while responding to requester: " + e.getMessage());
364                                 try {
365                                         httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error while responding.");
366                                 } catch (IOException ee) {
367                                         log.fatal("Could not construct a SAML error response: " + ee);
368                                         throw new ServletException("Identity Provider response failure.");
369                                 }
370                         }
371                         log.error("Identity Provider failed to make an error message: " + se);
372                 }
373         }
374
375         private static void displayBrowserError(HttpServletRequest req, HttpServletResponse res, Exception e)
376                         throws ServletException, IOException {
377
378                 req.setAttribute("errorText", e.toString());
379                 req.setAttribute("requestURL", req.getRequestURI().toString());
380                 RequestDispatcher rd = req.getRequestDispatcher("/IdPError.jsp");
381                 rd.forward(req, res);
382         }
383
384 }
385
386 class FederationProviderFactory {
387
388         private static Logger log = Logger.getLogger(FederationProviderFactory.class.getName());
389
390         public static Metadata loadProvider(Element e) throws MetadataException {
391
392                 String className = e.getAttribute("type");
393                 if (className == null || className.equals("")) {
394                         log.error("Federation Provider requires specification of the attribute \"type\".");
395                         throw new MetadataException("Failed to initialize Federation Provider.");
396                 } else {
397                         try {
398                                 Class[] params = {Class.forName("org.w3c.dom.Element"),};
399                                 return (Metadata) Class.forName(className).getConstructor(params).newInstance(new Object[]{e});
400                         } catch (Exception loaderException) {
401                                 log.error("Failed to load Federation Provider implementation class: " + loaderException);
402                                 Throwable cause = loaderException.getCause();
403                                 while (cause != null) {
404                                         log.error("caused by: " + cause);
405                                         cause = cause.getCause();
406                                 }
407                                 throw new MetadataException("Failed to initialize Federation Provider.");
408                         }
409                 }
410         }
411 }