e6ddeba7618e8ea78d4a5ed29254d6657146ad43
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / aa / AAServlet.java
1 /*
2  * The Shibboleth License, Version 1. Copyright (c) 2002 University Corporation for Advanced Internet Development, Inc.
3  * All rights reserved
4  * 
5  * 
6  * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
7  * following conditions are met:
8  * 
9  * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
10  * disclaimer.
11  * 
12  * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
13  * disclaimer in the documentation and/or other materials provided with the distribution, if any, must include the
14  * following acknowledgment: "This product includes software developed by the University Corporation for Advanced
15  * Internet Development <http://www.ucaid.edu> Internet2 Project. Alternately, this acknowledegement may appear in the
16  * software itself, if and wherever such third-party acknowledgments normally appear.
17  * 
18  * Neither the name of Shibboleth nor the names of its contributors, nor Internet2, nor the University Corporation for
19  * Advanced Internet Development, Inc., nor UCAID may be used to endorse or promote products derived from this software
20  * without specific prior written permission. For written permission, please contact shibboleth@shibboleth.org
21  * 
22  * Products derived from this software may not be called Shibboleth, Internet2, UCAID, or the University Corporation
23  * for Advanced Internet Development, nor may Shibboleth appear in their name, without prior written permission of the
24  * University Corporation for Advanced Internet Development.
25  * 
26  * 
27  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND WITH ALL FAULTS. ANY EXPRESS OR
28  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
29  * PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE DISCLAIMED AND THE ENTIRE RISK OF SATISFACTORY QUALITY, PERFORMANCE,
30  * ACCURACY, AND EFFORT IS WITH LICENSEE. IN NO EVENT SHALL THE COPYRIGHT OWNER, CONTRIBUTORS OR THE UNIVERSITY
31  * CORPORATION FOR ADVANCED INTERNET DEVELOPMENT, INC. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
32  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
33  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
35  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36  */
37
38 package edu.internet2.middleware.shibboleth.aa;
39
40 import java.io.IOException;
41 import java.net.URI;
42 import java.net.URISyntaxException;
43 import java.security.Principal;
44 import java.util.ArrayList;
45 import java.util.Arrays;
46 import java.util.Collections;
47 import java.util.Date;
48 import java.util.Iterator;
49
50 import javax.servlet.ServletException;
51 import javax.servlet.UnavailableException;
52 import javax.servlet.http.HttpServletRequest;
53 import javax.servlet.http.HttpServletResponse;
54
55 import org.apache.log4j.Logger;
56 import org.apache.log4j.MDC;
57 import org.opensaml.QName;
58 import org.opensaml.SAMLAssertion;
59 import org.opensaml.SAMLAttribute;
60 import org.opensaml.SAMLAttributeQuery;
61 import org.opensaml.SAMLAttributeStatement;
62 import org.opensaml.SAMLAudienceRestrictionCondition;
63 import org.opensaml.SAMLBinding;
64 import org.opensaml.SAMLCondition;
65 import org.opensaml.SAMLException;
66 import org.opensaml.SAMLIdentifier;
67 import org.opensaml.SAMLRequest;
68 import org.opensaml.SAMLResponse;
69 import org.opensaml.SAMLStatement;
70 import org.opensaml.SAMLSubject;
71 import org.w3c.dom.Document;
72 import org.w3c.dom.Element;
73 import org.w3c.dom.NodeList;
74
75 import sun.misc.BASE64Decoder;
76 import edu.internet2.middleware.shibboleth.aa.arp.ArpEngine;
77 import edu.internet2.middleware.shibboleth.aa.arp.ArpException;
78 import edu.internet2.middleware.shibboleth.aa.attrresolv.AttributeResolver;
79 import edu.internet2.middleware.shibboleth.aa.attrresolv.AttributeResolverException;
80 import edu.internet2.middleware.shibboleth.common.AuthNPrincipal;
81 import edu.internet2.middleware.shibboleth.common.NameIdentifierMapping;
82 import edu.internet2.middleware.shibboleth.common.NameIdentifierMappingException;
83 import edu.internet2.middleware.shibboleth.common.NameMapper;
84 import edu.internet2.middleware.shibboleth.common.OriginComponent;
85 import edu.internet2.middleware.shibboleth.common.RelyingParty;
86 import edu.internet2.middleware.shibboleth.common.SAMLBindingFactory;
87 import edu.internet2.middleware.shibboleth.common.ServiceProviderMapperException;
88 import edu.internet2.middleware.shibboleth.common.ShibbolethConfigurationException;
89 import edu.internet2.middleware.shibboleth.common.ShibbolethOriginConfig;
90
91 /**
92  * @author Walter Hoehn
93  */
94
95 public class AAServlet extends OriginComponent {
96
97         private AAConfig configuration;
98         protected AAResponder responder;
99         private NameMapper nameMapper;
100         private SAMLBinding binding;
101         private static Logger transactionLog = Logger.getLogger("Shibboleth-TRANSACTION");
102         private AAServiceProviderMapper targetMapper;
103
104         private static Logger log = Logger.getLogger(AAServlet.class.getName());
105
106         public void init() throws ServletException {
107                 super.init();
108
109                 MDC.put("serviceId", "[AA] Core");
110                 log.info("Initializing Attribute Authority.");
111
112                 try {
113                         nameMapper = new NameMapper();
114                         loadConfiguration();
115
116                         binding = SAMLBindingFactory.getInstance(SAMLBinding.SAML_SOAP_HTTPS);
117
118                         log.info("Attribute Authority initialization complete.");
119
120                 } catch (ShibbolethConfigurationException ae) {
121                         log.fatal("The AA could not be initialized: " + ae);
122                         throw new UnavailableException("Attribute Authority failed to initialize.");
123                 } catch (SAMLException se) {
124                         log.fatal("SAML SOAP binding could not be loaded: " + se);
125                         throw new UnavailableException("Attribute Authority failed to initialize.");
126                 }
127         }
128
129         protected void loadConfiguration() throws ShibbolethConfigurationException {
130
131                 Document originConfig = getOriginConfig();
132
133                 //Load global configuration properties
134                 configuration = new AAConfig(originConfig.getDocumentElement());
135
136                 //Load name mappings
137                 NodeList itemElements =
138                         originConfig.getDocumentElement().getElementsByTagNameNS(
139                                 NameIdentifierMapping.mappingNamespace,
140                                 "NameMapping");
141
142                 for (int i = 0; i < itemElements.getLength(); i++) {
143                         try {
144                                 nameMapper.addNameMapping((Element) itemElements.item(i));
145                         } catch (NameIdentifierMappingException e) {
146                                 log.error("Name Identifier mapping could not be loaded: " + e);
147                         }
148                 }
149
150                 //Load relying party config
151                 try {
152                         targetMapper = new AAServiceProviderMapper(originConfig.getDocumentElement(), configuration);
153                 } catch (ServiceProviderMapperException e) {
154                         log.error("Could not load origin configuration: " + e);
155                         throw new ShibbolethConfigurationException("Could not load origin configuration.");
156                 }
157
158                 try {
159                         //Startup Attribute Resolver
160                         AttributeResolver resolver = new AttributeResolver(configuration);
161
162                         //Startup ARP Engine
163                         ArpEngine arpEngine = null;
164                         itemElements =
165                                 originConfig.getDocumentElement().getElementsByTagNameNS(
166                                         ShibbolethOriginConfig.originConfigNamespace,
167                                         "ReleasePolicyEngine");
168
169                         if (itemElements.getLength() > 1) {
170                                 log.warn("Encountered multiple <ReleasePolicyEngine> configuration elements.  Using first...");
171                         }
172                         if (itemElements.getLength() < 1) {
173                                 arpEngine = new ArpEngine();
174                         } else {
175                                 arpEngine = new ArpEngine((Element) itemElements.item(0));
176                         }
177
178                         //Startup responder
179                         responder = new AAResponder(arpEngine, resolver);
180
181                 } catch (ArpException ae) {
182                         log.fatal("The AA could not be initialized due to a problem with the ARP Engine configuration: " + ae);
183                         throw new ShibbolethConfigurationException("Could not load ARP Engine.");
184                 } catch (AttributeResolverException ne) {
185                         log.fatal(
186                                 "The AA could not be initialized due to a problem with the Attribute Resolver configuration: " + ne);
187                         throw new ShibbolethConfigurationException("Could not load Attribute Resolver.");
188                 }
189
190         }
191         public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
192
193                 MDC.put("serviceId", "[AA] " + new SAMLIdentifier().toString());
194                 MDC.put("remoteAddr", req.getRemoteAddr());
195                 log.info("Handling request.");
196
197                 AARelyingParty relyingParty = null;
198
199                 //Parse SOAP request
200                 SAMLRequest samlRequest = null;
201                 StringBuffer credentialName = new StringBuffer();
202                 try {
203                         samlRequest = binding.receive(req, credentialName);
204
205                 } catch (SAMLException e) {
206                         log.fatal("Unable to parse request: " + e);
207                         throw new ServletException("Request failed.");
208                 }
209
210                 try {
211                         if (samlRequest.getQuery() == null || !(samlRequest.getQuery() instanceof SAMLAttributeQuery)) {
212                                 throw new SAMLException(
213                                         SAMLException.REQUESTER,
214                                         "This SAML authority only responds to attribute queries.");
215                         }
216                         SAMLAttributeQuery attributeQuery = (SAMLAttributeQuery) samlRequest.getQuery();
217
218                         //Identify a Relying Party
219                         if (attributeQuery.getResource() == null || attributeQuery.getResource().equals("")) {
220                                 log.error("Request from an unidentified service provider.");
221                         }
222                         log.info("Request from service provider: (" + attributeQuery.getResource() + ").");
223                         relyingParty = targetMapper.getRelyingParty(attributeQuery.getResource());
224
225                         //Map Subject to local principal
226                         if (relyingParty.getProviderId() != null
227                                 && !relyingParty.getProviderId().equals(attributeQuery.getSubject().getName().getNameQualifier())) {
228                                 log.error(
229                                         "The name qualifier for the referenced subject ("
230                                                 + attributeQuery.getSubject().getName().getNameQualifier()
231                                                 + ") is not valid for this identiy provider.");
232                                 throw new NameIdentifierMappingException(
233                                         "The name qualifier for the referenced subject ("
234                                                 + attributeQuery.getSubject().getName().getNameQualifier()
235                                                 + ") is not valid for this identiy provider.");
236                         }
237
238                         Principal principal = null;
239                         try {
240                                 if (attributeQuery.getSubject().getName().getName().equalsIgnoreCase("foo")) {
241                                         // for testing
242                                         principal = new AuthNPrincipal("test-handle");
243                                 } else {
244                                         principal =
245                                                 nameMapper.getPrincipal(
246                                                         attributeQuery.getSubject().getName(),
247                                                         relyingParty,
248                                                         relyingParty.getIdentityProvider());
249                                 }
250                                 log.info("Request is for principal (" + principal.getName() + ").");
251
252                                 //TODO Do something about these silly passthru errors
253
254                         } catch (NameIdentifierMappingException e) {
255                                 log.info("Could not associate the request subject with a principal: " + e);
256                                 try {
257                                         //TODO this doesn't always make sense anymore
258                                         QName[] codes =
259                                                 {
260                                                         SAMLException.REQUESTER,
261                                                         new QName(edu.internet2.middleware.shibboleth.common.XML.SHIB_NS, "InvalidHandle")};
262                                         if (relyingParty.passThruErrors()) {
263                                                 sendFailure(
264                                                         resp,
265                                                         samlRequest,
266                                                         new SAMLException(Arrays.asList(codes), "The supplied Subject was unrecognized.", e));
267
268                                         } else {
269                                                 sendFailure(
270                                                         resp,
271                                                         samlRequest,
272                                                         new SAMLException(Arrays.asList(codes), "The supplied Subject was unrecognized."));
273                                         }
274                                         return;
275                                 } catch (Exception ee) {
276                                         log.fatal("Could not construct a SAML error response: " + ee);
277                                         throw new ServletException("Attribute Authority response failure.");
278                                 }
279                         }
280
281                         if (credentialName == null || credentialName.toString().equals("")) {
282                                 log.info("Request is from an unauthenticated service provider.");
283                         } else {
284                                 log.info("Request is from service provider: (" + credentialName + ").");
285                         }
286
287                         SAMLAttribute[] attrs;
288                         Iterator requestedAttrsIterator = attributeQuery.getDesignators();
289                         if (requestedAttrsIterator.hasNext()) {
290                                 log.info("Request designates specific attributes, resolving this set.");
291                                 ArrayList requestedAttrs = new ArrayList();
292                                 while (requestedAttrsIterator.hasNext()) {
293                                         SAMLAttribute attribute = (SAMLAttribute) requestedAttrsIterator.next();
294                                         try {
295                                                 log.debug("Designated attribute: (" + attribute.getName() + ")");
296                                                 requestedAttrs.add(new URI(attribute.getName()));
297                                         } catch (URISyntaxException use) {
298                                                 log.error(
299                                                         "Request designated an attribute name that does not conform to the required URI syntax ("
300                                                                 + attribute.getName()
301                                                                 + ").  Ignoring this attribute");
302                                         }
303                                 }
304                                 attrs =
305                                         responder.getReleaseAttributes(
306                                                 principal,
307                                                 credentialName.toString(),
308                                                 null,
309                                                 (URI[]) requestedAttrs.toArray(new URI[0]));
310                         } else {
311                                 log.info("Request does not designate specific attributes, resolving all available.");
312                                 attrs = responder.getReleaseAttributes(principal, credentialName.toString(), null);
313                         }
314
315                         log.info("Found " + attrs.length + " attribute(s) for " + principal.getName());
316                         sendResponse(resp, attrs, samlRequest, relyingParty, null);
317                         log.info("Successfully responded about " + principal.getName());
318
319                         //TODO place transaction log statement here
320
321                 } catch (Exception e) {
322                         log.error("Error while processing request: " + e);
323                         try {
324                                 if (relyingParty != null && relyingParty.passThruErrors()) {
325                                         sendFailure(
326                                                 resp,
327                                                 samlRequest,
328                                                 new SAMLException(SAMLException.RESPONDER, "General error processing request.", e));
329                                 } else if (configuration.passThruErrors()) {
330                                         sendFailure(
331                                                 resp,
332                                                 samlRequest,
333                                                 new SAMLException(SAMLException.RESPONDER, "General error processing request.", e));
334                                 } else {
335                                         sendFailure(
336                                                 resp,
337                                                 samlRequest,
338                                                 new SAMLException(SAMLException.RESPONDER, "General error processing request."));
339                                 }
340                                 return;
341                         } catch (Exception ee) {
342                                 log.fatal("Could not construct a SAML error response: " + ee);
343                                 throw new ServletException("Attribute Authority response failure.");
344                         }
345
346                 }
347         }
348         
349         public void destroy() {
350                 log.info("Cleaning up resources.");
351                 responder.destroy();
352                 nameMapper.destroy();
353         }
354         public void sendResponse(
355                 HttpServletResponse resp,
356                 SAMLAttribute[] attrs,
357                 SAMLRequest samlRequest,
358                 RelyingParty relyingParty,
359                 SAMLException exception)
360                 throws IOException {
361
362                 SAMLException ourSE = null;
363                 SAMLResponse samlResponse = null;
364
365                 try {
366                         if (attrs == null || attrs.length == 0) {
367                                 //No attribute found
368                                 samlResponse = new SAMLResponse(samlRequest.getId(), null, null, exception);
369                         } else {
370
371                                 if (samlRequest.getQuery() == null || !(samlRequest.getQuery() instanceof SAMLAttributeQuery)) {
372                                         throw new SAMLException(
373                                                 SAMLException.REQUESTER,
374                                                 "This SAML authority only responds to attribute queries");
375                                 }
376                                 SAMLAttributeQuery attributeQuery = (SAMLAttributeQuery) samlRequest.getQuery();
377
378                                 //Reference requested subject
379                                 SAMLSubject rSubject = (SAMLSubject) attributeQuery.getSubject().clone();
380
381                                 //Set appropriate audience
382                                 ArrayList audiences = new ArrayList();
383                                 if (relyingParty.getProviderId() != null) {
384                                         audiences.add(relyingParty.getProviderId());
385                                 }
386                                 if (relyingParty.getName() != null && !relyingParty.getName().equals(relyingParty.getProviderId())) {
387                                         audiences.add(relyingParty.getName());
388                                 }
389                                 SAMLCondition condition = new SAMLAudienceRestrictionCondition(audiences);
390
391                                 //Put all attributes into an assertion
392                                 SAMLStatement statement = new SAMLAttributeStatement(rSubject, Arrays.asList(attrs));
393
394                                 //Set assertion expiration to longest attribute expiration
395                                 long max = 0;
396                                 for (int i = 0; i < attrs.length; i++) {
397                                         if (max < attrs[i].getLifetime()) {
398                                                 max = attrs[i].getLifetime();
399                                         }
400                                 }
401                                 Date now = new Date();
402                                 Date then = new Date(now.getTime() + max);
403
404                                 SAMLAssertion sAssertion =
405                                         new SAMLAssertion(
406                                                 relyingParty.getIdentityProvider().getProviderId(),
407                                                 now,
408                                                 then,
409                                                 Collections.singleton(condition),
410                                                 null,
411                                                 Collections.singleton(statement));
412
413                                 samlResponse =
414                                         new SAMLResponse(samlRequest.getId(), null, Collections.singleton(sAssertion), exception);
415                         }
416                 } catch (SAMLException se) {
417                         ourSE = se;
418                 } catch (CloneNotSupportedException ex) {
419                         ourSE = new SAMLException(SAMLException.RESPONDER, ex);
420
421                 } finally {
422
423                         if (log.isDebugEnabled()) {
424                                 try {
425                                         log.debug(
426                                                 "Dumping generated SAML Response:"
427                                                         + System.getProperty("line.separator")
428                                                         + new String(
429                                                                 new BASE64Decoder().decodeBuffer(new String(samlResponse.toBase64(), "ASCII")),
430                                                                 "UTF8"));
431                                 } catch (SAMLException e) {
432                                         log.error("Encountered an error while decoding SAMLReponse for logging purposes.");
433                                 } catch (IOException e) {
434                                         log.error("Encountered an error while decoding SAMLReponse for logging purposes.");
435                                 }
436                         }
437
438                         binding.respond(resp, samlResponse, ourSE);
439                 }
440         }
441
442         public void sendFailure(HttpServletResponse httpResponse, SAMLRequest samlRequest, SAMLException exception)
443                 throws IOException {
444                 try {
445                         SAMLResponse samlResponse =
446                                 new SAMLResponse((samlRequest != null) ? samlRequest.getId() : null, null, null, exception);
447                         if (log.isDebugEnabled()) {
448                                 try {
449                                         log.debug(
450                                                 "Dumping generated SAML Error Response:"
451                                                         + System.getProperty("line.separator")
452                                                         + new String(
453                                                                 new BASE64Decoder().decodeBuffer(new String(samlResponse.toBase64(), "ASCII")),
454                                                                 "UTF8"));
455                                 } catch (IOException e) {
456                                         log.error("Encountered an error while decoding SAMLReponse for logging purposes.");
457                                 }
458                         }
459                         binding.respond(httpResponse, samlResponse, null);
460                         log.debug("Returning SAML Error Response.");
461                 } catch (SAMLException se) {
462                         binding.respond(httpResponse, null, exception);
463                         log.error("AA failed to make an error message: " + se);
464                 }
465         }
466
467 }