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