1) The AA now validates service provider credentials and matches relying party config...
[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 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
6  * above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other
7  * materials provided with the distribution, if any, must include the following acknowledgment: "This product includes
8  * software developed by the University Corporation for Advanced Internet Development <http://www.ucaid.edu> Internet2
9  * Project. 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,
11  * nor 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
13  * contact shibboleth@shibboleth.org Products derived from this software may not be called Shibboleth, Internet2,
14  * UCAID, or the University Corporation for Advanced Internet Development, nor may Shibboleth appear in their name,
15  * without prior written permission of the University Corporation for Advanced Internet Development. THIS SOFTWARE IS
16  * PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND WITH ALL FAULTS. ANY EXPRESS OR IMPLIED WARRANTIES,
17  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND
18  * NON-INFRINGEMENT ARE DISCLAIMED AND THE ENTIRE RISK OF SATISFACTORY QUALITY, PERFORMANCE, ACCURACY, AND EFFORT IS
19  * WITH LICENSEE. IN NO EVENT SHALL THE COPYRIGHT OWNER, CONTRIBUTORS OR THE UNIVERSITY CORPORATION FOR ADVANCED
20  * INTERNET DEVELOPMENT, INC. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
23  * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
24  * POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 package edu.internet2.middleware.shibboleth.aa;
28
29 import java.io.IOException;
30 import java.net.URI;
31 import java.net.URISyntaxException;
32 import java.security.Principal;
33 import java.security.cert.X509Certificate;
34 import java.util.ArrayList;
35 import java.util.Arrays;
36 import java.util.Collections;
37 import java.util.Date;
38 import java.util.Iterator;
39 import java.util.regex.Matcher;
40 import java.util.regex.Pattern;
41
42 import javax.servlet.ServletException;
43 import javax.servlet.UnavailableException;
44 import javax.servlet.http.HttpServletRequest;
45 import javax.servlet.http.HttpServletResponse;
46
47 import org.apache.log4j.Logger;
48 import org.apache.log4j.MDC;
49 import org.apache.xml.security.exceptions.XMLSecurityException;
50 import org.apache.xml.security.keys.KeyInfo;
51 import org.apache.xml.security.signature.XMLSignature;
52 import org.opensaml.InvalidCryptoException;
53 import org.opensaml.SAMLAssertion;
54 import org.opensaml.SAMLAttribute;
55 import org.opensaml.SAMLAttributeQuery;
56 import org.opensaml.SAMLAttributeStatement;
57 import org.opensaml.SAMLAudienceRestrictionCondition;
58 import org.opensaml.SAMLBinding;
59 import org.opensaml.SAMLCondition;
60 import org.opensaml.SAMLException;
61 import org.opensaml.SAMLIdentifier;
62 import org.opensaml.SAMLRequest;
63 import org.opensaml.SAMLResponse;
64 import org.opensaml.SAMLStatement;
65 import org.opensaml.SAMLSubject;
66 import org.w3c.dom.Document;
67 import org.w3c.dom.Element;
68 import org.w3c.dom.NodeList;
69
70 import sun.misc.BASE64Decoder;
71 import edu.internet2.middleware.shibboleth.aa.arp.ArpEngine;
72 import edu.internet2.middleware.shibboleth.aa.arp.ArpException;
73 import edu.internet2.middleware.shibboleth.aa.attrresolv.AttributeResolver;
74 import edu.internet2.middleware.shibboleth.aa.attrresolv.AttributeResolverException;
75 import edu.internet2.middleware.shibboleth.common.AuthNPrincipal;
76 import edu.internet2.middleware.shibboleth.common.Credential;
77 import edu.internet2.middleware.shibboleth.common.Credentials;
78 import edu.internet2.middleware.shibboleth.common.InvalidNameIdentifierException;
79 import edu.internet2.middleware.shibboleth.common.NameIdentifierMapping;
80 import edu.internet2.middleware.shibboleth.common.NameIdentifierMappingException;
81 import edu.internet2.middleware.shibboleth.common.NameMapper;
82 import edu.internet2.middleware.shibboleth.common.OriginConfig;
83 import edu.internet2.middleware.shibboleth.common.RelyingParty;
84 import edu.internet2.middleware.shibboleth.common.SAMLBindingFactory;
85 import edu.internet2.middleware.shibboleth.common.ServiceProviderMapperException;
86 import edu.internet2.middleware.shibboleth.common.ShibbolethConfigurationException;
87 import edu.internet2.middleware.shibboleth.common.ShibbolethOriginConfig;
88 import edu.internet2.middleware.shibboleth.common.TargetFederationComponent;
89 import edu.internet2.middleware.shibboleth.metadata.AttributeConsumerRole;
90 import edu.internet2.middleware.shibboleth.metadata.KeyDescriptor;
91 import edu.internet2.middleware.shibboleth.metadata.Provider;
92 import edu.internet2.middleware.shibboleth.metadata.ProviderRole;
93
94 /**
95  * @author Walter Hoehn
96  */
97
98 public class AAServlet extends TargetFederationComponent {
99
100         private AAConfig                                configuration;
101         protected AAResponder                   responder;
102         private NameMapper                              nameMapper;
103         private SAMLBinding                             binding;
104         private static Logger                   transactionLog  = Logger.getLogger("Shibboleth-TRANSACTION");
105         private AAServiceProviderMapper targetMapper;
106
107         private static Logger                   log                             = Logger.getLogger(AAServlet.class.getName());
108         protected Pattern                               regex                   = Pattern.compile(".*CN=([^,/]+).*");
109
110         public void init() throws ServletException {
111                 super.init();
112
113                 MDC.put("serviceId", "[AA] Core");
114                 log.info("Initializing Attribute Authority.");
115
116                 try {
117                         nameMapper = new NameMapper();
118                         loadConfiguration();
119
120                         binding = SAMLBindingFactory.getInstance(SAMLBinding.SAML_SOAP_HTTPS);
121
122                         log.info("Attribute Authority initialization complete.");
123
124                 } catch (ShibbolethConfigurationException ae) {
125                         log.fatal("The AA could not be initialized: " + ae);
126                         throw new UnavailableException("Attribute Authority failed to initialize.");
127                 } catch (SAMLException se) {
128                         log.fatal("SAML SOAP binding could not be loaded: " + se);
129                         throw new UnavailableException("Attribute Authority failed to initialize.");
130                 }
131         }
132
133         protected void loadConfiguration() throws ShibbolethConfigurationException {
134
135                 Document originConfig = OriginConfig.getOriginConfig(this.getServletContext());
136
137                 //Load global configuration properties
138                 configuration = new AAConfig(originConfig.getDocumentElement());
139
140                 //Load name mappings
141                 NodeList itemElements = originConfig.getDocumentElement().getElementsByTagNameNS(
142                                 NameIdentifierMapping.mappingNamespace, "NameMapping");
143
144                 for (int i = 0; i < itemElements.getLength(); i++) {
145                         try {
146                                 nameMapper.addNameMapping((Element) itemElements.item(i));
147                         } catch (NameIdentifierMappingException e) {
148                                 log.error("Name Identifier mapping could not be loaded: " + e);
149                         }
150                 }
151
152                 //Load signing credentials
153                 itemElements = originConfig.getDocumentElement().getElementsByTagNameNS(Credentials.credentialsNamespace,
154                                 "Credentials");
155                 if (itemElements.getLength() < 1) {
156                         log.error("No credentials specified.");
157                 }
158                 if (itemElements.getLength() > 1) {
159                         log.error("Multiple Credentials specifications found, using first.");
160                 }
161                 Credentials credentials = new Credentials((Element) itemElements.item(0));
162
163                 //Load metadata
164                 itemElements = originConfig.getDocumentElement().getElementsByTagNameNS(
165                                 ShibbolethOriginConfig.originConfigNamespace, "FederationProvider");
166                 for (int i = 0; i < itemElements.getLength(); i++) {
167                         addFederationProvider((Element) itemElements.item(i));
168                 }
169                 if (providerCount() < 1) {
170                         log.error("No Federation Provider metadata loaded.");
171                         throw new ShibbolethConfigurationException("Could not load federation metadata.");
172                 }
173
174                 //Load relying party config
175                 try {
176                         targetMapper = new AAServiceProviderMapper(originConfig.getDocumentElement(), configuration, credentials,
177                                         this);
178                 } catch (ServiceProviderMapperException e) {
179                         log.error("Could not load origin configuration: " + e);
180                         throw new ShibbolethConfigurationException("Could not load origin configuration.");
181                 }
182
183                 try {
184                         //Startup Attribute Resolver
185                         AttributeResolver resolver = new AttributeResolver(configuration);
186
187                         //Startup ARP Engine
188                         ArpEngine arpEngine = null;
189                         itemElements = originConfig.getDocumentElement().getElementsByTagNameNS(
190                                         ShibbolethOriginConfig.originConfigNamespace, "ReleasePolicyEngine");
191
192                         if (itemElements.getLength() > 1) {
193                                 log.warn("Encountered multiple <ReleasePolicyEngine> configuration elements.  Using first...");
194                         }
195                         if (itemElements.getLength() < 1) {
196                                 arpEngine = new ArpEngine();
197                         } else {
198                                 arpEngine = new ArpEngine((Element) itemElements.item(0));
199                         }
200
201                         //Startup responder
202                         responder = new AAResponder(arpEngine, resolver);
203
204                 } catch (ArpException ae) {
205                         log.fatal("The AA could not be initialized due to a problem with the ARP Engine configuration: " + ae);
206                         throw new ShibbolethConfigurationException("Could not load ARP Engine.");
207                 } catch (AttributeResolverException ne) {
208                         log.fatal("The AA could not be initialized due to a problem with the Attribute Resolver configuration: "
209                                         + ne);
210                         throw new ShibbolethConfigurationException("Could not load Attribute Resolver.");
211                 }
212
213         }
214
215         public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
216
217                 MDC.put("serviceId", "[AA] " + new SAMLIdentifier().toString());
218                 MDC.put("remoteAddr", req.getRemoteAddr());
219                 log.info("Handling request.");
220
221                 AARelyingParty relyingParty = null;
222
223                 //Parse SOAP request
224                 SAMLRequest samlRequest = null;
225
226                 try {
227
228                         try {
229                                 samlRequest = binding.receive(req);
230
231                         } catch (SAMLException e) {
232                                 log.fatal("Unable to parse request: " + e);
233                                 throw new AAException("Invalid request data.");
234                         }
235
236                         if (samlRequest.getQuery() == null || !(samlRequest.getQuery() instanceof SAMLAttributeQuery)) {
237                                 throw new SAMLException(SAMLException.REQUESTER,
238                                                 "This SAML authority only responds to attribute queries.");
239                         }
240                         SAMLAttributeQuery attributeQuery = (SAMLAttributeQuery) samlRequest.getQuery();
241
242                         //Identify a Relying Party
243                         relyingParty = targetMapper.getRelyingParty(attributeQuery.getResource());
244
245                         //This is the requester name that will be passed to subsystems
246                         String effectiveName = getEffectiveName(req, relyingParty);
247
248                         //Map Subject to local principal
249                         if (relyingParty.getIdentityProvider().getProviderId() != null
250                                         && !relyingParty.getIdentityProvider().getProviderId().equals(
251                                                         attributeQuery.getSubject().getName().getNameQualifier())) {
252                                 log.error("The name qualifier for the referenced subject ("
253                                                 + attributeQuery.getSubject().getName().getNameQualifier()
254                                                 + ") is not valid for this identiy provider.");
255                                 throw new NameIdentifierMappingException("The name qualifier for the referenced subject ("
256                                                 + attributeQuery.getSubject().getName().getNameQualifier()
257                                                 + ") is not valid for this identiy provider.");
258                         }
259
260                         Principal principal = null;
261                         try {
262                                 // for testing
263                                 if (attributeQuery.getSubject().getName().getFormat().equals("urn:mace:shibboleth:test:nameIdentifier")) {
264                                         principal = new AuthNPrincipal("test-handle");
265                                 } else {
266                                         principal = nameMapper.getPrincipal(attributeQuery.getSubject().getName(), relyingParty,
267                                                         relyingParty.getIdentityProvider());
268                                 }
269                                 log.info("Request is for principal (" + principal.getName() + ").");
270
271                         } catch (InvalidNameIdentifierException invalidNameE) {
272                                 log.info("Could not associate the request subject with a principal: " + invalidNameE);
273                                 try {
274                                         if (relyingParty.passThruErrors()) {
275                                                 sendFailure(resp, samlRequest, new SAMLException(Arrays
276                                                                 .asList(invalidNameE.getSAMLErrorCodes()), "The supplied Subject was unrecognized.",
277                                                                 invalidNameE));
278
279                                         } else {
280                                                 sendFailure(resp, samlRequest, new SAMLException(Arrays
281                                                                 .asList(invalidNameE.getSAMLErrorCodes()), "The supplied Subject was unrecognized."));
282                                         }
283                                         return;
284                                 } catch (Exception ee) {
285                                         log.fatal("Could not construct a SAML error response: " + ee);
286                                         throw new ServletException("Attribute Authority response failure.");
287                                 }
288                         }
289
290                         SAMLAttribute[] attrs;
291                         Iterator requestedAttrsIterator = attributeQuery.getDesignators();
292                         if (requestedAttrsIterator.hasNext()) {
293                                 log.info("Request designates specific attributes, resolving this set.");
294                                 ArrayList requestedAttrs = new ArrayList();
295                                 while (requestedAttrsIterator.hasNext()) {
296                                         SAMLAttribute attribute = (SAMLAttribute) requestedAttrsIterator.next();
297                                         try {
298                                                 log.debug("Designated attribute: (" + attribute.getName() + ")");
299                                                 requestedAttrs.add(new URI(attribute.getName()));
300                                         } catch (URISyntaxException use) {
301                                                 log
302                                                                 .error("Request designated an attribute name that does not conform to the required URI syntax ("
303                                                                                 + attribute.getName() + ").  Ignoring this attribute");
304                                         }
305                                 }
306
307                                 attrs = responder.getReleaseAttributes(principal, effectiveName.toString(), null,
308                                                 (URI[]) requestedAttrs.toArray(new URI[0]));
309                         } else {
310                                 log.info("Request does not designate specific attributes, resolving all available.");
311                                 attrs = responder.getReleaseAttributes(principal, effectiveName.toString(), null);
312                         }
313
314                         log.info("Found " + attrs.length + " attribute(s) for " + principal.getName());
315                         sendResponse(resp, attrs, samlRequest, relyingParty, null);
316                         log.info("Successfully responded about " + principal.getName());
317
318                         //TODO place transaction log statement here
319
320                 } catch (Exception e) {
321                         log.error("Error while processing request: " + e);
322                         try {
323                                 if (relyingParty != null && relyingParty.passThruErrors()) {
324                                         sendFailure(resp, samlRequest, new SAMLException(SAMLException.RESPONDER,
325                                                         "General error processing request.", e));
326                                 } else if (configuration.passThruErrors()) {
327                                         sendFailure(resp, samlRequest, new SAMLException(SAMLException.RESPONDER,
328                                                         "General error processing request.", e));
329                                 } else {
330                                         sendFailure(resp, samlRequest, new SAMLException(SAMLException.RESPONDER,
331                                                         "General error processing request."));
332                                 }
333                                 return;
334                         } catch (Exception ee) {
335                                 log.fatal("Could not construct a SAML error response: " + ee);
336                                 throw new ServletException("Attribute Authority response failure.");
337                         }
338
339                 }
340         }
341
342         protected String getEffectiveName(HttpServletRequest req, AARelyingParty relyingParty) throws AAException {
343
344                 String credentialName = getCredentialName(req);
345                 if (credentialName == null || credentialName.toString().equals("")) {
346                         log.info("Request is from an unauthenticated service provider.");
347                         return null;
348
349                 } else {
350                         log.info("Request contains credential: (" + credentialName + ").");
351                         //Mockup old requester name for requests from < 1.2 targets
352                         if (fromLegacyProvider(req)) {
353                                 String legacyName = getLegacyRequesterName(credentialName);
354                                 log.info("Request from legacy service provider: (" + legacyName + ").");
355                                 return legacyName;
356
357                         } else {
358                                 //Make sure that the suppplied credential is valid for the selected relying party
359                                 if (isValidCredential(relyingParty, credentialName.toString())) {
360                                         log.info("Supplied credential validated for this provider.");
361                                         log.info("Request from service provider: (" + relyingParty.getProviderId() + ").");
362                                         return relyingParty.getProviderId();
363                                 } else {
364                                         log.error("Supplied credential (" + credentialName.toString() + ") is NOT valid for provider ("
365                                                         + relyingParty.getProviderId() + ").");
366                                         throw new AAException("Invalid credential.");
367                                 }
368                         }
369                 }
370         }
371
372         private String getLegacyRequesterName(String credentialName) {
373                 Matcher matches = regex.matcher(credentialName);
374                 if (!matches.find() || matches.groupCount() > 1) {
375                         log.error("Unable to extract legacy requester name from certificate subject.");
376                         return null;
377                 }
378                 return matches.group(1);
379         }
380
381         public void destroy() {
382                 log.info("Cleaning up resources.");
383                 responder.destroy();
384                 nameMapper.destroy();
385         }
386
387         public void sendResponse(HttpServletResponse resp, SAMLAttribute[] attrs, SAMLRequest samlRequest,
388                         RelyingParty relyingParty, SAMLException exception) throws IOException {
389
390                 SAMLException ourSE = null;
391                 SAMLResponse samlResponse = null;
392
393                 try {
394                         if (attrs == null || attrs.length == 0) {
395                                 //No attribute found
396                                 samlResponse = new SAMLResponse(samlRequest.getId(), null, null, exception);
397                         } else {
398
399                                 if (samlRequest.getQuery() == null || !(samlRequest.getQuery() instanceof SAMLAttributeQuery)) {
400                                         throw new SAMLException(SAMLException.REQUESTER,
401                                                         "This SAML authority only responds to attribute queries");
402                                 }
403                                 SAMLAttributeQuery attributeQuery = (SAMLAttributeQuery) samlRequest.getQuery();
404
405                                 //Reference requested subject
406                                 SAMLSubject rSubject = (SAMLSubject) attributeQuery.getSubject().clone();
407
408                                 //Set appropriate audience
409                                 ArrayList audiences = new ArrayList();
410                                 if (relyingParty.getProviderId() != null) {
411                                         audiences.add(relyingParty.getProviderId());
412                                 }
413                                 if (relyingParty.getName() != null && !relyingParty.getName().equals(relyingParty.getProviderId())) {
414                                         audiences.add(relyingParty.getName());
415                                 }
416                                 SAMLCondition condition = new SAMLAudienceRestrictionCondition(audiences);
417
418                                 //Put all attributes into an assertion
419                                 SAMLStatement statement = new SAMLAttributeStatement(rSubject, Arrays.asList(attrs));
420
421                                 //Set assertion expiration to longest attribute expiration
422                                 long max = 0;
423                                 for (int i = 0; i < attrs.length; i++) {
424                                         if (max < attrs[i].getLifetime()) {
425                                                 max = attrs[i].getLifetime();
426                                         }
427                                 }
428                                 Date now = new Date();
429                                 Date then = new Date(now.getTime() + max);
430
431                                 SAMLAssertion sAssertion = new SAMLAssertion(relyingParty.getIdentityProvider().getProviderId(), now,
432                                                 then, Collections.singleton(condition), null, Collections.singleton(statement));
433
434                                 samlResponse = new SAMLResponse(samlRequest.getId(), null, Collections.singleton(sAssertion), exception);
435                                 addSignatures(samlResponse, relyingParty);
436                         }
437                 } catch (SAMLException se) {
438                         ourSE = se;
439                 } catch (CloneNotSupportedException ex) {
440                         ourSE = new SAMLException(SAMLException.RESPONDER, ex);
441
442                 } finally {
443
444                         if (log.isDebugEnabled()) {
445                                 try {
446                                         log.debug("Dumping generated SAML Response:"
447                                                         + System.getProperty("line.separator")
448                                                         + new String(
449                                                                         new BASE64Decoder().decodeBuffer(new String(samlResponse.toBase64(), "ASCII")),
450                                                                         "UTF8"));
451                                 } catch (SAMLException e) {
452                                         log.error("Encountered an error while decoding SAMLReponse for logging purposes.");
453                                 } catch (IOException e) {
454                                         log.error("Encountered an error while decoding SAMLReponse for logging purposes.");
455                                 }
456                         }
457
458                         binding.respond(resp, samlResponse, ourSE);
459                 }
460         }
461
462         private void addSignatures(SAMLResponse reponse, RelyingParty relyingParty) throws SAMLException {
463
464                 //Sign the assertions, if appropriate
465                 if (relyingParty.getIdentityProvider().getAssertionSigningCredential() != null
466                                 && relyingParty.getIdentityProvider().getAssertionSigningCredential().getPrivateKey() != null) {
467
468                         String assertionAlgorithm;
469                         if (relyingParty.getIdentityProvider().getAssertionSigningCredential().getCredentialType() == Credential.RSA) {
470                                 assertionAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1;
471                         } else if (relyingParty.getIdentityProvider().getAssertionSigningCredential().getCredentialType() == Credential.DSA) {
472                                 assertionAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_DSA;
473                         } else {
474                                 throw new InvalidCryptoException(SAMLException.RESPONDER,
475                                                 "ShibPOSTProfile.prepare() currently only supports signing with RSA and DSA keys.");
476                         }
477
478                         ((SAMLAssertion) reponse.getAssertions().next()).sign(assertionAlgorithm, relyingParty
479                                         .getIdentityProvider().getAssertionSigningCredential().getPrivateKey(), Arrays.asList(relyingParty
480                                         .getIdentityProvider().getAssertionSigningCredential().getX509CertificateChain()));
481                 }
482
483                 //Sign the response, if appropriate
484                 if (relyingParty.getIdentityProvider().getResponseSigningCredential() != null
485                                 && relyingParty.getIdentityProvider().getResponseSigningCredential().getPrivateKey() != null) {
486
487                         String responseAlgorithm;
488                         if (relyingParty.getIdentityProvider().getResponseSigningCredential().getCredentialType() == Credential.RSA) {
489                                 responseAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1;
490                         } else if (relyingParty.getIdentityProvider().getResponseSigningCredential().getCredentialType() == Credential.DSA) {
491                                 responseAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_DSA;
492                         } else {
493                                 throw new InvalidCryptoException(SAMLException.RESPONDER,
494                                                 "ShibPOSTProfile.prepare() currently only supports signing with RSA and DSA keys.");
495                         }
496
497                         reponse.sign(responseAlgorithm, relyingParty.getIdentityProvider().getResponseSigningCredential()
498                                         .getPrivateKey(), Arrays.asList(relyingParty.getIdentityProvider().getResponseSigningCredential()
499                                         .getX509CertificateChain()));
500                 }
501         }
502
503         public void sendFailure(HttpServletResponse httpResponse, SAMLRequest samlRequest, SAMLException exception)
504                         throws IOException {
505                 try {
506                         SAMLResponse samlResponse = new SAMLResponse((samlRequest != null) ? samlRequest.getId() : null, null,
507                                         null, exception);
508                         if (log.isDebugEnabled()) {
509                                 try {
510                                         log.debug("Dumping generated SAML Error Response:"
511                                                         + System.getProperty("line.separator")
512                                                         + new String(
513                                                                         new BASE64Decoder().decodeBuffer(new String(samlResponse.toBase64(), "ASCII")),
514                                                                         "UTF8"));
515                                 } catch (IOException e) {
516                                         log.error("Encountered an error while decoding SAMLReponse for logging purposes.");
517                                 }
518                         }
519                         binding.respond(httpResponse, samlResponse, null);
520                         log.debug("Returning SAML Error Response.");
521                 } catch (SAMLException se) {
522                         binding.respond(httpResponse, null, exception);
523                         log.error("AA failed to make an error message: " + se);
524                 }
525         }
526
527         protected boolean isValidCredential(RelyingParty relyingParty, String credentialName) throws AAException {
528
529                 Provider provider = lookup(relyingParty.getProviderId());
530                 if (provider == null) {
531                         log.info("No metadata found for provider: (" + relyingParty.getProviderId() + ").");
532                         throw new AAException("Request is from an unkown Service Provider.");
533                 }
534
535                 ProviderRole[] roles = provider.getRoles();
536                 if (roles.length == 0) {
537                         log.info("Inappropriate metadata for provider.");
538                         return false;
539                 }
540
541                 for (int i = 0; roles.length > i; i++) {
542                         if (roles[i] instanceof AttributeConsumerRole) {
543                                 KeyDescriptor[] descriptors = roles[i].getKeyDescriptors();
544                                 for (int j = 0; descriptors.length > j; j++) {
545                                         KeyInfo[] keyInfo = descriptors[j].getKeyInfo();
546                                         for (int k = 0; keyInfo.length > k; k++) {
547                                                 for (int l = 0; keyInfo[k].lengthKeyName() > l; l++) {
548                                                         try {
549                                                                 if (credentialName.equals(keyInfo[k].itemKeyName(l).getKeyName())) {
550                                                                         return true;
551                                                                 }
552                                                         } catch (XMLSecurityException e) {
553                                                                 log.error("Encountered an error reading federation metadata: " + e);
554                                                         }
555                                                 }
556                                         }
557                                 }
558                         }
559                 }
560                 log.info("Supplied credential not found in metadata.");
561                 return false;
562         }
563
564         protected boolean fromLegacyProvider(HttpServletRequest request) {
565                 String version = request.getHeader("Shibboleth");
566                 if (version != null) {
567                         log.debug("Request from Shibboleth version: " + version);
568                         return false;
569                 }
570                 log.debug("No version header found.");
571                 return true;
572         }
573
574         protected String getCredentialName(HttpServletRequest req) {
575                 X509Certificate[] certArray = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate");
576                 if (certArray != null && certArray.length > 0) {
577                         return certArray[0].getSubjectDN().getName();
578                 }
579                 return null;
580         }
581
582 }