e8f549b83a1c608b68f3233cfb244907bc34a9fd
[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                         if (effectiveName == null) {
249                                 log.debug("Using default Relying Party for unauthenticated provider.");
250                                 relyingParty = targetMapper.getRelyingParty(null);
251                         }
252
253                         //Map Subject to local principal
254                         if (relyingParty.getIdentityProvider().getProviderId() != null
255                                         && !relyingParty.getIdentityProvider().getProviderId().equals(
256                                                         attributeQuery.getSubject().getName().getNameQualifier())) {
257                                 log.error("The name qualifier for the referenced subject ("
258                                                 + attributeQuery.getSubject().getName().getNameQualifier()
259                                                 + ") is not valid for this identiy provider.");
260                                 throw new NameIdentifierMappingException("The name qualifier for the referenced subject ("
261                                                 + attributeQuery.getSubject().getName().getNameQualifier()
262                                                 + ") is not valid for this identiy provider.");
263                         }
264
265                         Principal principal = null;
266                         try {
267                                 // for testing
268                                 if (attributeQuery.getSubject().getName().getFormat().equals("urn:mace:shibboleth:test:nameIdentifier")) {
269                                         principal = new AuthNPrincipal("test-handle");
270                                 } else {
271                                         principal = nameMapper.getPrincipal(attributeQuery.getSubject().getName(), relyingParty,
272                                                         relyingParty.getIdentityProvider());
273                                 }
274                                 log.info("Request is for principal (" + principal.getName() + ").");
275
276                         } catch (InvalidNameIdentifierException invalidNameE) {
277                                 log.info("Could not associate the request subject with a principal: " + invalidNameE);
278                                 try {
279                                         if (relyingParty.passThruErrors()) {
280                                                 sendFailure(resp, samlRequest, new SAMLException(Arrays
281                                                                 .asList(invalidNameE.getSAMLErrorCodes()), "The supplied Subject was unrecognized.",
282                                                                 invalidNameE));
283
284                                         } else {
285                                                 sendFailure(resp, samlRequest, new SAMLException(Arrays
286                                                                 .asList(invalidNameE.getSAMLErrorCodes()), "The supplied Subject was unrecognized."));
287                                         }
288                                         return;
289                                 } catch (Exception ee) {
290                                         log.fatal("Could not construct a SAML error response: " + ee);
291                                         throw new ServletException("Attribute Authority response failure.");
292                                 }
293                         }
294
295                         SAMLAttribute[] attrs;
296                         Iterator requestedAttrsIterator = attributeQuery.getDesignators();
297                         if (requestedAttrsIterator.hasNext()) {
298                                 log.info("Request designates specific attributes, resolving this set.");
299                                 ArrayList requestedAttrs = new ArrayList();
300                                 while (requestedAttrsIterator.hasNext()) {
301                                         SAMLAttribute attribute = (SAMLAttribute) requestedAttrsIterator.next();
302                                         try {
303                                                 log.debug("Designated attribute: (" + attribute.getName() + ")");
304                                                 requestedAttrs.add(new URI(attribute.getName()));
305                                         } catch (URISyntaxException use) {
306                                                 log
307                                                                 .error("Request designated an attribute name that does not conform to the required URI syntax ("
308                                                                                 + attribute.getName() + ").  Ignoring this attribute");
309                                         }
310                                 }
311
312                                 attrs = responder.getReleaseAttributes(principal, effectiveName, null, (URI[]) requestedAttrs
313                                                 .toArray(new URI[0]));
314                         } else {
315                                 log.info("Request does not designate specific attributes, resolving all available.");
316                                 attrs = responder.getReleaseAttributes(principal, effectiveName, null);
317                         }
318
319                         log.info("Found " + attrs.length + " attribute(s) for " + principal.getName());
320                         sendResponse(resp, attrs, samlRequest, relyingParty, null);
321                         log.info("Successfully responded about " + principal.getName());
322
323                         //TODO place transaction log statement here
324
325                 } catch (Exception e) {
326                         log.error("Error while processing request: " + e);
327                         try {
328                                 if (relyingParty != null && relyingParty.passThruErrors()) {
329                                         sendFailure(resp, samlRequest, new SAMLException(SAMLException.RESPONDER,
330                                                         "General error processing request.", e));
331                                 } else if (configuration.passThruErrors()) {
332                                         sendFailure(resp, samlRequest, new SAMLException(SAMLException.RESPONDER,
333                                                         "General error processing request.", e));
334                                 } else {
335                                         sendFailure(resp, samlRequest, new SAMLException(SAMLException.RESPONDER,
336                                                         "General error processing request."));
337                                 }
338                                 return;
339                         } catch (Exception ee) {
340                                 log.fatal("Could not construct a SAML error response: " + ee);
341                                 throw new ServletException("Attribute Authority response failure.");
342                         }
343
344                 }
345         }
346
347         protected String getEffectiveName(HttpServletRequest req, AARelyingParty relyingParty) throws AAException {
348
349                 String credentialName = getCredentialName(req);
350                 if (credentialName == null || credentialName.toString().equals("")) {
351                         log.info("Request is from an unauthenticated service provider.");
352                         return null;
353
354                 } else {
355                         log.info("Request contains credential: (" + credentialName + ").");
356                         //Mockup old requester name for requests from < 1.2 targets
357                         if (fromLegacyProvider(req)) {
358                                 String legacyName = getLegacyRequesterName(credentialName);
359                                 log.info("Request from legacy service provider: (" + legacyName + ").");
360                                 return legacyName;
361
362                         } else {
363                                 //Make sure that the suppplied credential is valid for the selected relying party
364                                 if (isValidCredential(relyingParty, credentialName.toString())) {
365                                         log.info("Supplied credential validated for this provider.");
366                                         log.info("Request from service provider: (" + relyingParty.getProviderId() + ").");
367                                         return relyingParty.getProviderId();
368                                 } else {
369                                         log.error("Supplied credential (" + credentialName.toString() + ") is NOT valid for provider ("
370                                                         + relyingParty.getProviderId() + ").");
371                                         throw new AAException("Invalid credential.");
372                                 }
373                         }
374                 }
375         }
376
377         private String getLegacyRequesterName(String credentialName) {
378                 Matcher matches = regex.matcher(credentialName);
379                 if (!matches.find() || matches.groupCount() > 1) {
380                         log.error("Unable to extract legacy requester name from certificate subject.");
381                         return null;
382                 }
383                 return matches.group(1);
384         }
385
386         public void destroy() {
387                 log.info("Cleaning up resources.");
388                 responder.destroy();
389                 nameMapper.destroy();
390         }
391
392         public void sendResponse(HttpServletResponse resp, SAMLAttribute[] attrs, SAMLRequest samlRequest,
393                         RelyingParty relyingParty, SAMLException exception) throws IOException {
394
395                 SAMLException ourSE = null;
396                 SAMLResponse samlResponse = null;
397
398                 try {
399                         if (attrs == null || attrs.length == 0) {
400                                 //No attribute found
401                                 samlResponse = new SAMLResponse(samlRequest.getId(), null, null, exception);
402                         } else {
403
404                                 if (samlRequest.getQuery() == null || !(samlRequest.getQuery() instanceof SAMLAttributeQuery)) {
405                                         throw new SAMLException(SAMLException.REQUESTER,
406                                                         "This SAML authority only responds to attribute queries");
407                                 }
408                                 SAMLAttributeQuery attributeQuery = (SAMLAttributeQuery) samlRequest.getQuery();
409
410                                 //Reference requested subject
411                                 SAMLSubject rSubject = (SAMLSubject) attributeQuery.getSubject().clone();
412
413                                 //Set appropriate audience
414                                 ArrayList audiences = new ArrayList();
415                                 if (relyingParty.getProviderId() != null) {
416                                         audiences.add(relyingParty.getProviderId());
417                                 }
418                                 if (relyingParty.getName() != null && !relyingParty.getName().equals(relyingParty.getProviderId())) {
419                                         audiences.add(relyingParty.getName());
420                                 }
421                                 SAMLCondition condition = new SAMLAudienceRestrictionCondition(audiences);
422
423                                 //Put all attributes into an assertion
424                                 SAMLStatement statement = new SAMLAttributeStatement(rSubject, Arrays.asList(attrs));
425
426                                 //Set assertion expiration to longest attribute expiration
427                                 long max = 0;
428                                 for (int i = 0; i < attrs.length; i++) {
429                                         if (max < attrs[i].getLifetime()) {
430                                                 max = attrs[i].getLifetime();
431                                         }
432                                 }
433                                 Date now = new Date();
434                                 Date then = new Date(now.getTime() + max);
435
436                                 SAMLAssertion sAssertion = new SAMLAssertion(relyingParty.getIdentityProvider().getProviderId(), now,
437                                                 then, Collections.singleton(condition), null, Collections.singleton(statement));
438
439                                 samlResponse = new SAMLResponse(samlRequest.getId(), null, Collections.singleton(sAssertion), exception);
440                                 addSignatures(samlResponse, relyingParty);
441                         }
442                 } catch (SAMLException se) {
443                         ourSE = se;
444                 } catch (CloneNotSupportedException ex) {
445                         ourSE = new SAMLException(SAMLException.RESPONDER, ex);
446
447                 } finally {
448
449                         if (log.isDebugEnabled()) {
450                                 try {
451                                         log.debug("Dumping generated SAML Response:"
452                                                         + System.getProperty("line.separator")
453                                                         + new String(
454                                                                         new BASE64Decoder().decodeBuffer(new String(samlResponse.toBase64(), "ASCII")),
455                                                                         "UTF8"));
456                                 } catch (SAMLException e) {
457                                         log.error("Encountered an error while decoding SAMLReponse for logging purposes.");
458                                 } catch (IOException e) {
459                                         log.error("Encountered an error while decoding SAMLReponse for logging purposes.");
460                                 }
461                         }
462
463                         binding.respond(resp, samlResponse, ourSE);
464                 }
465         }
466
467         private void addSignatures(SAMLResponse reponse, RelyingParty relyingParty) throws SAMLException {
468
469                 //Sign the assertions, if appropriate
470                 if (relyingParty.getIdentityProvider().getAssertionSigningCredential() != null
471                                 && relyingParty.getIdentityProvider().getAssertionSigningCredential().getPrivateKey() != null) {
472
473                         String assertionAlgorithm;
474                         if (relyingParty.getIdentityProvider().getAssertionSigningCredential().getCredentialType() == Credential.RSA) {
475                                 assertionAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1;
476                         } else if (relyingParty.getIdentityProvider().getAssertionSigningCredential().getCredentialType() == Credential.DSA) {
477                                 assertionAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_DSA;
478                         } else {
479                                 throw new InvalidCryptoException(SAMLException.RESPONDER,
480                                                 "ShibPOSTProfile.prepare() currently only supports signing with RSA and DSA keys.");
481                         }
482
483                         ((SAMLAssertion) reponse.getAssertions().next()).sign(assertionAlgorithm, relyingParty
484                                         .getIdentityProvider().getAssertionSigningCredential().getPrivateKey(), Arrays.asList(relyingParty
485                                         .getIdentityProvider().getAssertionSigningCredential().getX509CertificateChain()));
486                 }
487
488                 //Sign the response, if appropriate
489                 if (relyingParty.getIdentityProvider().getResponseSigningCredential() != null
490                                 && relyingParty.getIdentityProvider().getResponseSigningCredential().getPrivateKey() != null) {
491
492                         String responseAlgorithm;
493                         if (relyingParty.getIdentityProvider().getResponseSigningCredential().getCredentialType() == Credential.RSA) {
494                                 responseAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1;
495                         } else if (relyingParty.getIdentityProvider().getResponseSigningCredential().getCredentialType() == Credential.DSA) {
496                                 responseAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_DSA;
497                         } else {
498                                 throw new InvalidCryptoException(SAMLException.RESPONDER,
499                                                 "ShibPOSTProfile.prepare() currently only supports signing with RSA and DSA keys.");
500                         }
501
502                         reponse.sign(responseAlgorithm, relyingParty.getIdentityProvider().getResponseSigningCredential()
503                                         .getPrivateKey(), Arrays.asList(relyingParty.getIdentityProvider().getResponseSigningCredential()
504                                         .getX509CertificateChain()));
505                 }
506         }
507
508         public void sendFailure(HttpServletResponse httpResponse, SAMLRequest samlRequest, SAMLException exception)
509                         throws IOException {
510                 try {
511                         SAMLResponse samlResponse = new SAMLResponse((samlRequest != null) ? samlRequest.getId() : null, null,
512                                         null, exception);
513                         if (log.isDebugEnabled()) {
514                                 try {
515                                         log.debug("Dumping generated SAML Error Response:"
516                                                         + System.getProperty("line.separator")
517                                                         + new String(
518                                                                         new BASE64Decoder().decodeBuffer(new String(samlResponse.toBase64(), "ASCII")),
519                                                                         "UTF8"));
520                                 } catch (IOException e) {
521                                         log.error("Encountered an error while decoding SAMLReponse for logging purposes.");
522                                 }
523                         }
524                         binding.respond(httpResponse, samlResponse, null);
525                         log.debug("Returning SAML Error Response.");
526                 } catch (SAMLException se) {
527                         binding.respond(httpResponse, null, exception);
528                         log.error("AA failed to make an error message: " + se);
529                 }
530         }
531
532         protected boolean isValidCredential(RelyingParty relyingParty, String credentialName) throws AAException {
533
534                 Provider provider = lookup(relyingParty.getProviderId());
535                 if (provider == null) {
536                         log.info("No metadata found for provider: (" + relyingParty.getProviderId() + ").");
537                         throw new AAException("Request is from an unkown Service Provider.");
538                 }
539
540                 ProviderRole[] roles = provider.getRoles();
541                 if (roles.length == 0) {
542                         log.info("Inappropriate metadata for provider.");
543                         return false;
544                 }
545
546                 for (int i = 0; roles.length > i; i++) {
547                         if (roles[i] instanceof AttributeConsumerRole) {
548                                 KeyDescriptor[] descriptors = roles[i].getKeyDescriptors();
549                                 for (int j = 0; descriptors.length > j; j++) {
550                                         KeyInfo[] keyInfo = descriptors[j].getKeyInfo();
551                                         for (int k = 0; keyInfo.length > k; k++) {
552                                                 for (int l = 0; keyInfo[k].lengthKeyName() > l; l++) {
553                                                         try {
554                                                                 if (credentialName.equals(keyInfo[k].itemKeyName(l).getKeyName())) {
555                                                                         return true;
556                                                                 }
557                                                         } catch (XMLSecurityException e) {
558                                                                 log.error("Encountered an error reading federation metadata: " + e);
559                                                         }
560                                                 }
561                                         }
562                                 }
563                         }
564                 }
565                 log.info("Supplied credential not found in metadata.");
566                 return false;
567         }
568
569         protected boolean fromLegacyProvider(HttpServletRequest request) {
570                 String version = request.getHeader("Shibboleth");
571                 if (version != null) {
572                         log.debug("Request from Shibboleth version: " + version);
573                         return false;
574                 }
575                 log.debug("No version header found.");
576                 return true;
577         }
578
579         protected String getCredentialName(HttpServletRequest req) {
580                 X509Certificate[] certArray = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate");
581                 if (certArray != null && certArray.length > 0) {
582                         return certArray[0].getSubjectDN().getName();
583                 }
584                 return null;
585         }
586
587 }