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