49f6178101bc3f0f0ac7e83759337928358720cf
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / aa / AAServlet.java
1 /* 
2  * The Shibboleth License, Version 1. 
3  * Copyright (c) 2002 
4  * University Corporation for Advanced Internet Development, Inc. 
5  * All rights reserved
6  * 
7  * 
8  * Redistribution and use in source and binary forms, with or without 
9  * modification, are permitted provided that the following conditions are met:
10  * 
11  * Redistributions of source code must retain the above copyright notice, this 
12  * list of conditions and the following disclaimer.
13  * 
14  * Redistributions in binary form must reproduce the above copyright notice, 
15  * this list of conditions and the following disclaimer in the documentation 
16  * and/or other materials provided with the distribution, if any, must include 
17  * the following acknowledgment: "This product includes software developed by 
18  * the University Corporation for Advanced Internet Development 
19  * <http://www.ucaid.edu>Internet2 Project. Alternately, this acknowledegement 
20  * may appear in the software itself, if and wherever such third-party 
21  * acknowledgments normally appear.
22  * 
23  * Neither the name of Shibboleth nor the names of its contributors, nor 
24  * Internet2, nor the University Corporation for Advanced Internet Development, 
25  * Inc., nor UCAID may be used to endorse or promote products derived from this 
26  * software without specific prior written permission. For written permission, 
27  * please contact shibboleth@shibboleth.org
28  * 
29  * Products derived from this software may not be called Shibboleth, Internet2, 
30  * UCAID, or the University Corporation for Advanced Internet Development, nor 
31  * may Shibboleth appear in their name, without prior written permission of the 
32  * University Corporation for Advanced Internet Development.
33  * 
34  * 
35  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
36  * AND WITH ALL FAULTS. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
37  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 
38  * PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE DISCLAIMED AND THE ENTIRE RISK 
39  * OF SATISFACTORY QUALITY, PERFORMANCE, ACCURACY, AND EFFORT IS WITH LICENSEE. 
40  * IN NO EVENT SHALL THE COPYRIGHT OWNER, CONTRIBUTORS OR THE UNIVERSITY 
41  * CORPORATION FOR ADVANCED INTERNET DEVELOPMENT, INC. BE LIABLE FOR ANY DIRECT, 
42  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
43  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
44  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 
45  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
46  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
47  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
48  */
49
50 package edu.internet2.middleware.shibboleth.aa;
51
52 import java.io.ByteArrayOutputStream;
53 import java.io.IOException;
54 import java.io.PrintStream;
55 import java.net.MalformedURLException;
56 import java.net.URL;
57 import java.security.Principal;
58 import java.util.Arrays;
59 import java.util.List;
60 import java.util.Properties;
61
62 import javax.naming.NamingException;
63 import javax.naming.directory.DirContext;
64 import javax.naming.directory.InitialDirContext;
65 import javax.servlet.ServletException;
66 import javax.servlet.UnavailableException;
67 import javax.servlet.http.HttpServlet;
68 import javax.servlet.http.HttpServletRequest;
69 import javax.servlet.http.HttpServletResponse;
70
71 import org.apache.log4j.Logger;
72 import org.apache.log4j.MDC;
73 import org.opensaml.QName;
74 import org.opensaml.SAMLException;
75 import org.opensaml.SAMLIdentifier;
76
77 import edu.internet2.middleware.eduPerson.Init;
78 import edu.internet2.middleware.shibboleth.aa.arp.ArpEngine;
79 import edu.internet2.middleware.shibboleth.aa.arp.ArpException;
80 import edu.internet2.middleware.shibboleth.common.AuthNPrincipal;
81 import edu.internet2.middleware.shibboleth.common.ShibResource;
82 import edu.internet2.middleware.shibboleth.hs.HandleRepository;
83 import edu.internet2.middleware.shibboleth.hs.HandleRepositoryException;
84 import edu.internet2.middleware.shibboleth.hs.HandleRepositoryFactory;
85 import edu.internet2.middleware.shibboleth.hs.InvalidHandleException;
86
87 /**
88  *  Attribute Authority & Release Policy
89  *  Handles Initialization and incoming requests to AA
90  *
91  * @author Parviz Dousti (dousti@cmu.edu)
92  * @author      Walter Hoehn (wassa@columbia.edu)
93  */
94
95 public class AAServlet extends HttpServlet {
96
97     protected AAResponder responder;
98     protected HandleRepository handleRepository;
99     protected Properties configuration;
100     private static Logger log = Logger.getLogger(AAServlet.class.getName());    
101     
102         public void init() throws ServletException {
103                 super.init();
104
105                 MDC.put("serviceId", "[AA] Core");
106                 log.info("Initializing Attribute Authority.");
107
108                 try {
109
110                         configuration = loadConfiguration();
111
112                         ArpEngine arpEngine = new ArpEngine(configuration);
113                         
114                         handleRepository = HandleRepositoryFactory.getInstance(configuration);
115
116                         log.info(
117                                 "Using JNDI context ("
118                                         + configuration.getProperty("java.naming.factory.initial")
119                                         + ") for attribute retrieval.");
120
121                         DirContext ctx = new InitialDirContext(configuration);
122                         Init.init();
123                         responder =
124                                 new AAResponder(
125                                         arpEngine,
126                                         ctx,
127                                         configuration.getProperty(
128                                                 "edu.internet2.middleware.shibboleth.aa.AAServlet.authorityName"));
129
130                         log.info("Attribute Authority initialization complete.");
131
132                 } catch (NamingException ne) {
133                         log.fatal(
134                                 "The AA could not be initialized due to a problem with the JNDI context configuration: "
135                                         + ne);
136                         throw new UnavailableException("Attribute Authority failed to initialize.");
137                 } catch (ArpException ae) {
138                         log.fatal(
139                                 "The AA could not be initialized due to a problem with the ARP Engine configuration: " + ae);
140                         throw new UnavailableException("Attribute Authority failed to initialize.");
141                 } catch (AAException ae) {
142                         log.fatal("The AA could not be initialized: " + ae);
143                         throw new UnavailableException("Attribute Authority failed to initialize.");
144                 } catch (HandleRepositoryException he) {
145                         log.fatal(
146                                 "The AA could not be initialized due to a problem with the Handle Repository configuration: "
147                                         + he);
148                         throw new UnavailableException("Attribute Authority failed to initialize.");
149                 }
150         }
151         protected Properties loadConfiguration() throws AAException {
152
153                 //Set defaults
154                 Properties defaultProps = new Properties();
155                 defaultProps.setProperty(
156                         "edu.internet2.middleware.shibboleth.aa.arp.provider.FileSystemArpRepository.Path",
157                         "/conf/arps/");
158                 defaultProps.setProperty(
159                         "edu.internet2.middleware.shibboleth.aa.arp.ArpRepository.implementation",
160                         "edu.internet2.middleware.shibboleth.aa.arp.provider.FileSystemArpRepository");
161                 defaultProps.setProperty("edu.internet2.middleware.shibboleth.aa.AAServlet.ldapUserDnPhrase", "uid=");
162                 defaultProps.setProperty(
163                         "java.naming.factory.initial",
164                         "edu.internet2.middleware.shibboleth.aaLocal.EchoCtxFactory");
165                 defaultProps.setProperty(
166                         "edu.internet2.middleware.shibboleth.hs.provider.CryptoHandleRepository.keyStorePath",
167                         "/conf/handle.jks");
168                 defaultProps.setProperty("edu.internet2.middleware.shibboleth.audiences", "urn:mace:InCommon:pilot:2003");
169                 defaultProps.setProperty("edu.internet2.middleware.shibboleth.aa.AAServlet.passThruErrors", "false");
170
171                 //Load from file
172                 Properties properties = new Properties(defaultProps);
173                 String propertiesFileLocation = getInitParameter("OriginPropertiesFile");
174                 if (propertiesFileLocation == null) {
175                         propertiesFileLocation = "/conf/origin.properties";
176                 }
177                 try {
178                         log.debug("Loading Configuration from (" + propertiesFileLocation + ").");
179                         properties.load(new ShibResource(propertiesFileLocation, this.getClass()).getInputStream());
180
181                         //Make sure we have all required parameters
182                         StringBuffer missingProperties = new StringBuffer();
183                         String[] requiredProperties =
184                                 {
185                                         "edu.internet2.middleware.shibboleth.aa.AAServlet.authorityName",
186                                         "java.naming.factory.initial",
187                                         "edu.internet2.middleware.shibboleth.aa.arp.ArpRepository.implementation",
188                                         "edu.internet2.middleware.shibboleth.audiences" };
189
190                         for (int i = 0; i < requiredProperties.length; i++) {
191                                 if (properties.getProperty(requiredProperties[i]) == null) {
192                                         missingProperties.append("\"");
193                                         missingProperties.append(requiredProperties[i]);
194                                         missingProperties.append("\" ");
195                                 }
196                         }
197                         if (missingProperties.length() > 0) {
198                                 log.error(
199                                         "Missing configuration data.  The following configuration properites have not been set: "
200                                                 + missingProperties.toString());
201                                 throw new AAException("Missing configuration data.");
202                         }
203
204                 } catch (IOException e) {
205                         log.error("Could not load AA servlet configuration: " + e);
206                         throw new AAException("Could not load AA servlet configuration.");
207                 }
208
209                 if (log.isDebugEnabled()) {
210                         ByteArrayOutputStream debugStream = new ByteArrayOutputStream();
211                         PrintStream debugPrinter = new PrintStream(debugStream);
212                         properties.list(debugPrinter);
213                         log.debug(
214                                 "Runtime configuration parameters: " + System.getProperty("line.separator") + debugStream.toString());
215                         try {
216                                 debugStream.close();
217                         } catch (IOException e) {
218                                 log.error("Encountered a problem cleaning up resources: could not close debug stream.");
219                         }
220                 }
221
222                 return properties;
223         }
224
225         public void doPost(HttpServletRequest req, HttpServletResponse resp)
226                 throws ServletException, IOException {
227
228                 log.debug("Recieved a request.");
229                 MDC.put("serviceId", "[AA] " + new SAMLIdentifier().toString());
230                 MDC.put("remoteAddr", req.getRemoteAddr());
231                 log.info("Handling request.");
232
233                 AASaml saml = null;
234
235                 try {
236                         saml =
237                                 new AASaml(
238                                         configuration.getProperty(
239                                                 "edu.internet2.middleware.shibboleth.aa.AAServlet.authorityName"),
240                                         configuration.getProperty("edu.internet2.middleware.shibboleth.audiences").replaceAll(
241                                                 "\\s",
242                                                 "").split(
243                                                 ","));
244                         saml.receive(req);
245
246                         log.info("Attribute Query Handle for this request: (" + saml.getHandle() + ").");
247                         Principal principal = null;
248                         if (saml.getHandle().equalsIgnoreCase("foo")) {
249                                 // for testing
250                                 principal = new AuthNPrincipal("test-handle");
251                         } else {
252                                 principal = handleRepository.getPrincipal(saml.getHandle());
253                         }
254
255                         URL resource = null;
256                         try {
257                                 resource = new URL(saml.getResource());
258                         } catch (MalformedURLException mue) {
259                                 log.error(
260                                         "Request contained an improperly formatted resource identifier.  Attempting to "
261                                                 + "handle request without one.");
262                         }
263
264                         if (saml.getShar() == null) {
265                                 log.info("Request is from an unauthenticated SHAR.");
266                         } else {
267                                 log.info("Request is from SHAR: (" + saml.getShar() + ").");
268                         }
269
270                         List attrs =
271                                 Arrays.asList(
272                                         responder.getReleaseAttributes(
273                                                 principal,
274                                                 configuration.getProperty(
275                                                         "edu.internet2.middleware.shibboleth.aa.AAServlet.ldapUserDnPhrase"),
276                                                 saml.getShar(),
277                                                 resource));
278                         log.info("Got " + attrs.size() + " attributes for " + principal.getName());
279                         saml.respond(resp, attrs, null);
280                         log.info("Successfully responded about " + principal.getName());
281
282                 } catch (InvalidHandleException e) {
283                         log.info("Could not associate the Attribute Query Handle with a principal: " + e);
284                         try {
285                                 QName[] codes =
286                                         {
287                                                 SAMLException.REQUESTER,
288                                                 new QName(edu.internet2.middleware.shibboleth.common.XML.SHIB_NS, "InvalidHandle")};
289                                 if (configuration
290                                         .getProperty("edu.internet2.middleware.shibboleth.aa.AAServlet.passThruErrors", "false")
291                                         .equals("true")) {
292                                         saml.fail(
293                                                 resp,
294                                                 new SAMLException(
295                                                         Arrays.asList(codes),
296                                                         "The supplied Attribute Query Handle was unrecognized or expired.",
297                                                         e));
298
299                                 } else {
300                                         saml.fail(
301                                                 resp,
302                                                 new SAMLException(
303                                                         Arrays.asList(codes),
304                                                         "The supplied Attribute Query Handle was unrecognized or expired."));
305                                 }
306                                 return;
307                         } catch (Exception ee) {
308                                 log.fatal("Could not construct a SAML error response: " + ee);
309                                 throw new ServletException("Attribute Authority response failure.");
310                         }
311
312                 } catch (Exception e) {
313                         log.error("Error while processing request: " + e);
314                         try {
315                                 if (configuration
316                                         .getProperty("edu.internet2.middleware.shibboleth.aa.AAServlet.passThruErrors", "false")
317                                         .equals("true")) {
318                                         saml.fail(
319                                                 resp,
320                                                 new SAMLException(SAMLException.RESPONDER, "General error processing request.", e));
321                                 } else {
322                                         saml.fail(
323                                                 resp,
324                                                 new SAMLException(SAMLException.RESPONDER, "General error processing request."));
325                                 }
326                                 return;
327                         } catch (Exception ee) {
328                                 log.fatal("Could not construct a SAML error response: " + ee);
329                                 throw new ServletException("Attribute Authority response failure.");
330                         }
331
332                 }
333         }
334
335
336 }