Minimal transaction logging for the AA.
[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                         if (effectiveName == null) {
324                                 if (fromLegacyProvider(req)) {
325                                         transactionLog.info("Attribute assertion issued to anonymous legacy provider at ("
326                                                         + req.getRemoteAddr() + ").");
327                                 } else {
328                                         transactionLog.info("Attribute assertion issued to anonymous provider at (" + req.getRemoteAddr()
329                                                         + ").");
330                                 }
331                         } else {
332                                 if (fromLegacyProvider(req)) {
333                                         transactionLog.info("Attribute assertion issued to legacy provider: (" + effectiveName + ").");
334                                 } else {
335                                         transactionLog.info("Attribute assertion issued to provider: (" + effectiveName + ").");
336                                 }
337                         }
338
339                 } catch (Exception e) {
340                         log.error("Error while processing request: " + e);
341                         try {
342                                 if (relyingParty != null && relyingParty.passThruErrors()) {
343                                         sendFailure(resp, samlRequest, new SAMLException(SAMLException.RESPONDER,
344                                                         "General error processing request.", e));
345                                 } else if (configuration.passThruErrors()) {
346                                         sendFailure(resp, samlRequest, new SAMLException(SAMLException.RESPONDER,
347                                                         "General error processing request.", e));
348                                 } else {
349                                         sendFailure(resp, samlRequest, new SAMLException(SAMLException.RESPONDER,
350                                                         "General error processing request."));
351                                 }
352                                 return;
353                         } catch (Exception ee) {
354                                 log.fatal("Could not construct a SAML error response: " + ee);
355                                 throw new ServletException("Attribute Authority response failure.");
356                         }
357
358                 }
359         }
360
361         protected String getEffectiveName(HttpServletRequest req, AARelyingParty relyingParty) throws AAException {
362
363                 String credentialName = getCredentialName(req);
364                 if (credentialName == null || credentialName.toString().equals("")) {
365                         log.info("Request is from an unauthenticated service provider.");
366                         return null;
367
368                 } else {
369                         log.info("Request contains credential: (" + credentialName + ").");
370                         //Mockup old requester name for requests from < 1.2 targets
371                         if (fromLegacyProvider(req)) {
372                                 String legacyName = getLegacyRequesterName(credentialName);
373                                 log.info("Request from legacy service provider: (" + legacyName + ").");
374                                 return legacyName;
375
376                         } else {
377                                 //Make sure that the suppplied credential is valid for the selected relying party
378                                 if (isValidCredential(relyingParty, credentialName.toString())) {
379                                         log.info("Supplied credential validated for this provider.");
380                                         log.info("Request from service provider: (" + relyingParty.getProviderId() + ").");
381                                         return relyingParty.getProviderId();
382                                 } else {
383                                         log.error("Supplied credential (" + credentialName.toString() + ") is NOT valid for provider ("
384                                                         + relyingParty.getProviderId() + ").");
385                                         throw new AAException("Invalid credential.");
386                                 }
387                         }
388                 }
389         }
390
391         private String getLegacyRequesterName(String credentialName) {
392                 Matcher matches = regex.matcher(credentialName);
393                 if (!matches.find() || matches.groupCount() > 1) {
394                         log.error("Unable to extract legacy requester name from certificate subject.");
395                         return null;
396                 }
397                 return matches.group(1);
398         }
399
400         public void destroy() {
401                 log.info("Cleaning up resources.");
402                 responder.destroy();
403                 nameMapper.destroy();
404         }
405
406         public void sendResponse(HttpServletResponse resp, SAMLAttribute[] attrs, SAMLRequest samlRequest,
407                         RelyingParty relyingParty, SAMLException exception) throws IOException {
408
409                 SAMLException ourSE = null;
410                 SAMLResponse samlResponse = null;
411
412                 try {
413                         if (attrs == null || attrs.length == 0) {
414                                 //No attribute found
415                                 samlResponse = new SAMLResponse(samlRequest.getId(), null, null, exception);
416                         } else {
417
418                                 if (samlRequest.getQuery() == null || !(samlRequest.getQuery() instanceof SAMLAttributeQuery)) {
419                                         throw new SAMLException(SAMLException.REQUESTER,
420                                                         "This SAML authority only responds to attribute queries");
421                                 }
422                                 SAMLAttributeQuery attributeQuery = (SAMLAttributeQuery) samlRequest.getQuery();
423
424                                 //Reference requested subject
425                                 SAMLSubject rSubject = (SAMLSubject) attributeQuery.getSubject().clone();
426
427                                 //Set appropriate audience
428                                 ArrayList audiences = new ArrayList();
429                                 if (relyingParty.getProviderId() != null) {
430                                         audiences.add(relyingParty.getProviderId());
431                                 }
432                                 if (relyingParty.getName() != null && !relyingParty.getName().equals(relyingParty.getProviderId())) {
433                                         audiences.add(relyingParty.getName());
434                                 }
435                                 SAMLCondition condition = new SAMLAudienceRestrictionCondition(audiences);
436
437                                 //Put all attributes into an assertion
438                                 SAMLStatement statement = new SAMLAttributeStatement(rSubject, Arrays.asList(attrs));
439
440                                 //Set assertion expiration to longest attribute expiration
441                                 long max = 0;
442                                 for (int i = 0; i < attrs.length; i++) {
443                                         if (max < attrs[i].getLifetime()) {
444                                                 max = attrs[i].getLifetime();
445                                         }
446                                 }
447                                 Date now = new Date();
448                                 Date then = new Date(now.getTime() + max);
449
450                                 SAMLAssertion sAssertion = new SAMLAssertion(relyingParty.getIdentityProvider().getProviderId(), now,
451                                                 then, Collections.singleton(condition), null, Collections.singleton(statement));
452
453                                 samlResponse = new SAMLResponse(samlRequest.getId(), null, Collections.singleton(sAssertion), exception);
454                                 addSignatures(samlResponse, relyingParty);
455                         }
456                 } catch (SAMLException se) {
457                         ourSE = se;
458                 } catch (CloneNotSupportedException ex) {
459                         ourSE = new SAMLException(SAMLException.RESPONDER, ex);
460
461                 } finally {
462
463                         if (log.isDebugEnabled()) {
464                                 try {
465                                         log.debug("Dumping generated SAML Response:"
466                                                         + System.getProperty("line.separator")
467                                                         + new String(
468                                                                         new BASE64Decoder().decodeBuffer(new String(samlResponse.toBase64(), "ASCII")),
469                                                                         "UTF8"));
470                                 } catch (SAMLException e) {
471                                         log.error("Encountered an error while decoding SAMLReponse for logging purposes.");
472                                 } catch (IOException e) {
473                                         log.error("Encountered an error while decoding SAMLReponse for logging purposes.");
474                                 }
475                         }
476
477                         binding.respond(resp, samlResponse, ourSE);
478                 }
479         }
480
481         private void addSignatures(SAMLResponse reponse, RelyingParty relyingParty) throws SAMLException {
482
483                 //Sign the assertions, if appropriate
484                 if (relyingParty.getIdentityProvider().getAssertionSigningCredential() != null
485                                 && relyingParty.getIdentityProvider().getAssertionSigningCredential().getPrivateKey() != null) {
486
487                         String assertionAlgorithm;
488                         if (relyingParty.getIdentityProvider().getAssertionSigningCredential().getCredentialType() == Credential.RSA) {
489                                 assertionAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1;
490                         } else if (relyingParty.getIdentityProvider().getAssertionSigningCredential().getCredentialType() == Credential.DSA) {
491                                 assertionAlgorithm = 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                         ((SAMLAssertion) reponse.getAssertions().next()).sign(assertionAlgorithm, relyingParty
498                                         .getIdentityProvider().getAssertionSigningCredential().getPrivateKey(), Arrays.asList(relyingParty
499                                         .getIdentityProvider().getAssertionSigningCredential().getX509CertificateChain()));
500                 }
501
502                 //Sign the response, if appropriate
503                 if (relyingParty.getIdentityProvider().getResponseSigningCredential() != null
504                                 && relyingParty.getIdentityProvider().getResponseSigningCredential().getPrivateKey() != null) {
505
506                         String responseAlgorithm;
507                         if (relyingParty.getIdentityProvider().getResponseSigningCredential().getCredentialType() == Credential.RSA) {
508                                 responseAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1;
509                         } else if (relyingParty.getIdentityProvider().getResponseSigningCredential().getCredentialType() == Credential.DSA) {
510                                 responseAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_DSA;
511                         } else {
512                                 throw new InvalidCryptoException(SAMLException.RESPONDER,
513                                                 "ShibPOSTProfile.prepare() currently only supports signing with RSA and DSA keys.");
514                         }
515
516                         reponse.sign(responseAlgorithm, relyingParty.getIdentityProvider().getResponseSigningCredential()
517                                         .getPrivateKey(), Arrays.asList(relyingParty.getIdentityProvider().getResponseSigningCredential()
518                                         .getX509CertificateChain()));
519                 }
520         }
521
522         public void sendFailure(HttpServletResponse httpResponse, SAMLRequest samlRequest, SAMLException exception)
523                         throws IOException {
524                 try {
525                         SAMLResponse samlResponse = new SAMLResponse((samlRequest != null) ? samlRequest.getId() : null, null,
526                                         null, exception);
527                         if (log.isDebugEnabled()) {
528                                 try {
529                                         log.debug("Dumping generated SAML Error Response:"
530                                                         + System.getProperty("line.separator")
531                                                         + new String(
532                                                                         new BASE64Decoder().decodeBuffer(new String(samlResponse.toBase64(), "ASCII")),
533                                                                         "UTF8"));
534                                 } catch (IOException e) {
535                                         log.error("Encountered an error while decoding SAMLReponse for logging purposes.");
536                                 }
537                         }
538                         binding.respond(httpResponse, samlResponse, null);
539                         log.debug("Returning SAML Error Response.");
540                 } catch (SAMLException se) {
541                         binding.respond(httpResponse, null, exception);
542                         log.error("AA failed to make an error message: " + se);
543                 }
544         }
545
546         protected boolean isValidCredential(RelyingParty relyingParty, String credentialName) throws AAException {
547
548                 Provider provider = lookup(relyingParty.getProviderId());
549                 if (provider == null) {
550                         log.info("No metadata found for provider: (" + relyingParty.getProviderId() + ").");
551                         throw new AAException("Request is from an unkown Service Provider.");
552                 }
553
554                 ProviderRole[] roles = provider.getRoles();
555                 if (roles.length == 0) {
556                         log.info("Inappropriate metadata for provider.");
557                         return false;
558                 }
559
560                 for (int i = 0; roles.length > i; i++) {
561                         if (roles[i] instanceof AttributeConsumerRole) {
562                                 KeyDescriptor[] descriptors = roles[i].getKeyDescriptors();
563                                 for (int j = 0; descriptors.length > j; j++) {
564                                         KeyInfo[] keyInfo = descriptors[j].getKeyInfo();
565                                         for (int k = 0; keyInfo.length > k; k++) {
566                                                 for (int l = 0; keyInfo[k].lengthKeyName() > l; l++) {
567                                                         try {
568                                                                 if (credentialName.equals(keyInfo[k].itemKeyName(l).getKeyName())) {
569                                                                         return true;
570                                                                 }
571                                                         } catch (XMLSecurityException e) {
572                                                                 log.error("Encountered an error reading federation metadata: " + e);
573                                                         }
574                                                 }
575                                         }
576                                 }
577                         }
578                 }
579                 log.info("Supplied credential not found in metadata.");
580                 return false;
581         }
582
583         protected boolean fromLegacyProvider(HttpServletRequest request) {
584                 String version = request.getHeader("Shibboleth");
585                 if (version != null) {
586                         log.debug("Request from Shibboleth version: " + version);
587                         return false;
588                 }
589                 log.debug("No version header found.");
590                 return true;
591         }
592
593         protected String getCredentialName(HttpServletRequest req) {
594                 X509Certificate[] certArray = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate");
595                 if (certArray != null && certArray.length > 0) {
596                         return certArray[0].getSubjectDN().getName();
597                 }
598                 return null;
599         }
600
601 }