fe493093561e8c2a7e176106d187d817f210e94e
[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.CertificateParsingException;
34 import java.security.cert.X509Certificate;
35 import java.util.ArrayList;
36 import java.util.Arrays;
37 import java.util.Collection;
38 import java.util.Collections;
39 import java.util.Date;
40 import java.util.Iterator;
41 import java.util.List;
42
43 import javax.security.auth.x500.X500Principal;
44 import javax.servlet.ServletException;
45 import javax.servlet.UnavailableException;
46 import javax.servlet.http.HttpServletRequest;
47 import javax.servlet.http.HttpServletResponse;
48
49 import org.apache.log4j.Logger;
50 import org.apache.log4j.MDC;
51 import org.apache.xml.security.exceptions.XMLSecurityException;
52 import org.apache.xml.security.keys.KeyInfo;
53 import org.apache.xml.security.signature.XMLSignature;
54 import org.opensaml.InvalidCryptoException;
55 import org.opensaml.SAMLAssertion;
56 import org.opensaml.SAMLAttribute;
57 import org.opensaml.SAMLAttributeQuery;
58 import org.opensaml.SAMLAttributeStatement;
59 import org.opensaml.SAMLAudienceRestrictionCondition;
60 import org.opensaml.SAMLBinding;
61 import org.opensaml.SAMLCondition;
62 import org.opensaml.SAMLException;
63 import org.opensaml.SAMLIdentifier;
64 import org.opensaml.SAMLRequest;
65 import org.opensaml.SAMLResponse;
66 import org.opensaml.SAMLStatement;
67 import org.opensaml.SAMLSubject;
68 import org.w3c.dom.Document;
69 import org.w3c.dom.Element;
70 import org.w3c.dom.NodeList;
71
72 import sun.misc.BASE64Decoder;
73 import edu.internet2.middleware.shibboleth.aa.arp.ArpEngine;
74 import edu.internet2.middleware.shibboleth.aa.arp.ArpException;
75 import edu.internet2.middleware.shibboleth.aa.attrresolv.AttributeResolver;
76 import edu.internet2.middleware.shibboleth.aa.attrresolv.AttributeResolverException;
77 import edu.internet2.middleware.shibboleth.common.Credential;
78 import edu.internet2.middleware.shibboleth.common.Credentials;
79 import edu.internet2.middleware.shibboleth.common.InvalidNameIdentifierException;
80 import edu.internet2.middleware.shibboleth.common.NameIdentifierMapping;
81 import edu.internet2.middleware.shibboleth.common.NameIdentifierMappingException;
82 import edu.internet2.middleware.shibboleth.common.NameMapper;
83 import edu.internet2.middleware.shibboleth.common.OriginConfig;
84 import edu.internet2.middleware.shibboleth.common.RelyingParty;
85 import edu.internet2.middleware.shibboleth.common.SAMLBindingFactory;
86 import edu.internet2.middleware.shibboleth.common.ServiceProviderMapperException;
87 import edu.internet2.middleware.shibboleth.common.ShibPOSTProfile;
88 import edu.internet2.middleware.shibboleth.common.ShibbolethConfigurationException;
89 import edu.internet2.middleware.shibboleth.common.ShibbolethOriginConfig;
90 import edu.internet2.middleware.shibboleth.common.TargetFederationComponent;
91 import edu.internet2.middleware.shibboleth.metadata.AttributeConsumerRole;
92 import edu.internet2.middleware.shibboleth.metadata.KeyDescriptor;
93 import edu.internet2.middleware.shibboleth.metadata.Provider;
94 import edu.internet2.middleware.shibboleth.metadata.ProviderRole;
95
96 /**
97  * @author Walter Hoehn
98  */
99
100 public class AAServlet extends TargetFederationComponent {
101
102         private AAConfig                                configuration;
103         protected AAResponder                   responder;
104         private NameMapper                              nameMapper;
105         private SAMLBinding                             binding;
106         private static Logger                   transactionLog  = Logger.getLogger("Shibboleth-TRANSACTION");
107         private AAServiceProviderMapper targetMapper;
108
109         private static Logger                   log                             = Logger.getLogger(AAServlet.class.getName());
110
111         public void init() throws ServletException {
112                 super.init();
113
114                 MDC.put("serviceId", "[AA] Core");
115                 log.info("Initializing Attribute Authority.");
116
117                 try {
118                         nameMapper = new NameMapper();
119                         loadConfiguration();
120
121                         binding = SAMLBindingFactory.getInstance(SAMLBinding.SAML_SOAP_HTTPS);
122
123                         log.info("Attribute Authority initialization complete.");
124
125                 } catch (ShibbolethConfigurationException ae) {
126                         log.fatal("The AA could not be initialized: " + ae);
127                         throw new UnavailableException("Attribute Authority failed to initialize.");
128                 } catch (SAMLException se) {
129                         log.fatal("SAML SOAP binding could not be loaded: " + se);
130                         throw new UnavailableException("Attribute Authority failed to initialize.");
131                 }
132         }
133
134         protected void loadConfiguration() throws ShibbolethConfigurationException {
135
136                 Document originConfig = OriginConfig.getOriginConfig(this.getServletContext());
137
138                 //Load global configuration properties
139                 configuration = new AAConfig(originConfig.getDocumentElement());
140
141                 //Load name mappings
142                 NodeList itemElements = originConfig.getDocumentElement().getElementsByTagNameNS(
143                                 NameIdentifierMapping.mappingNamespace, "NameMapping");
144
145                 for (int i = 0; i < itemElements.getLength(); i++) {
146                         try {
147                                 nameMapper.addNameMapping((Element) itemElements.item(i));
148                         } catch (NameIdentifierMappingException e) {
149                                 log.error("Name Identifier mapping could not be loaded: " + e);
150                         }
151                 }
152
153                 //Load signing credentials
154                 itemElements = originConfig.getDocumentElement().getElementsByTagNameNS(Credentials.credentialsNamespace,
155                                 "Credentials");
156                 if (itemElements.getLength() < 1) {
157                         log.error("No credentials specified.");
158                 }
159                 if (itemElements.getLength() > 1) {
160                         log.error("Multiple Credentials specifications found, using first.");
161                 }
162                 Credentials credentials = new Credentials((Element) itemElements.item(0));
163
164                 //Load metadata
165                 itemElements = originConfig.getDocumentElement().getElementsByTagNameNS(
166                                 ShibbolethOriginConfig.originConfigNamespace, "FederationProvider");
167                 for (int i = 0; i < itemElements.getLength(); i++) {
168                         addFederationProvider((Element) itemElements.item(i));
169                 }
170                 if (providerCount() < 1) {
171                         log.error("No Federation Provider metadata loaded.");
172                         throw new ShibbolethConfigurationException("Could not load federation metadata.");
173                 }
174
175                 //Load relying party config
176                 try {
177                         targetMapper = new AAServiceProviderMapper(originConfig.getDocumentElement(), configuration, credentials,
178                                         this);
179                 } catch (ServiceProviderMapperException e) {
180                         log.error("Could not load origin configuration: " + e);
181                         throw new ShibbolethConfigurationException("Could not load origin configuration.");
182                 }
183
184                 try {
185                         //Startup Attribute Resolver
186                         AttributeResolver resolver = new AttributeResolver(configuration);
187
188                         //Startup ARP Engine
189                         ArpEngine arpEngine = null;
190                         itemElements = originConfig.getDocumentElement().getElementsByTagNameNS(
191                                         ShibbolethOriginConfig.originConfigNamespace, "ReleasePolicyEngine");
192
193                         if (itemElements.getLength() > 1) {
194                                 log.warn("Encountered multiple <ReleasePolicyEngine> configuration elements.  Using first...");
195                         }
196                         if (itemElements.getLength() < 1) {
197                                 arpEngine = new ArpEngine();
198                         } else {
199                                 arpEngine = new ArpEngine((Element) itemElements.item(0));
200                         }
201
202                         //Startup responder
203                         responder = new AAResponder(arpEngine, resolver);
204
205                 } catch (ArpException ae) {
206                         log.fatal("The AA could not be initialized due to a problem with the ARP Engine configuration: " + ae);
207                         throw new ShibbolethConfigurationException("Could not load ARP Engine.");
208                 } catch (AttributeResolverException ne) {
209                         log.fatal("The AA could not be initialized due to a problem with the Attribute Resolver configuration: "
210                                         + ne);
211                         throw new ShibbolethConfigurationException("Could not load Attribute Resolver.");
212                 }
213
214         }
215
216         public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
217
218                 MDC.put("serviceId", "[AA] " + new SAMLIdentifier().toString());
219                 MDC.put("remoteAddr", req.getRemoteAddr());
220                 log.info("Handling request.");
221
222                 AARelyingParty relyingParty = null;
223
224                 //Parse SOAP request
225                 SAMLRequest samlRequest = null;
226
227                 try {
228
229                         try {
230                                 samlRequest = binding.receive(req);
231
232                         } catch (SAMLException e) {
233                                 log.fatal("Unable to parse request: " + e);
234                                 throw new AAException("Invalid request data.");
235                         }
236
237                         if (samlRequest.getQuery() == null || !(samlRequest.getQuery() instanceof SAMLAttributeQuery)) {
238                                 throw new SAMLException(SAMLException.REQUESTER,
239                                                 "This SAML authority only responds to attribute queries.");
240                         }
241                         SAMLAttributeQuery attributeQuery = (SAMLAttributeQuery) samlRequest.getQuery();
242
243                         if (!fromLegacyProvider(req)) {
244                                 log.info("Remote provider has identified itself as: (" + attributeQuery.getResource() + ").");
245                         }
246
247                         //This is the requester name that will be passed to subsystems
248                         String effectiveName = null;
249
250                         X509Certificate credential = getCredentialFromProvider(req);
251                         if (credential == null || credential.getSubjectX500Principal().getName(X500Principal.RFC2253).equals("")) {
252                                 log.info("Request is from an unauthenticated service provider.");
253                         } else {
254
255                                 //Identify a Relying Party
256                                 relyingParty = targetMapper.getRelyingParty(attributeQuery.getResource());
257
258                                 try {
259                                         effectiveName = getEffectiveName(req, relyingParty);
260                                 } catch (InvalidProviderCredentialException ipc) {
261                                         sendFailure(resp, samlRequest, new SAMLException(SAMLException.RESPONDER,
262                                                         "Invalid credentials for request."));
263                                         return;
264                                 }
265                         }
266
267                         if (effectiveName == null) {
268                                 log.debug("Using default Relying Party for unauthenticated provider.");
269                                 relyingParty = targetMapper.getRelyingParty(null);
270                         }
271
272                         //Fail if we can't honor SAML Subject Confirmation
273                         if (!fromLegacyProvider(req)) {
274                                 Iterator iterator = attributeQuery.getSubject().getConfirmationMethods();
275                                 boolean hasConfirmationMethod = false;
276                                 while (iterator.hasNext()) {
277                                         log.info("Request contains SAML Subject Confirmation method: (" + (String) iterator.next() + ").");
278                                 }
279                                 if (hasConfirmationMethod) {
280                                         throw new SAMLException(SAMLException.REQUESTER,
281                                                         "This SAML authority cannot honor requests containing the supplied SAML Subject Confirmation Method.");
282                                 }
283                         }
284
285                         //Map Subject to local principal
286                         Principal principal = null;
287                         try {
288                                 principal = nameMapper.getPrincipal(attributeQuery.getSubject().getName(), relyingParty,
289                                                         relyingParty.getIdentityProvider());
290                                 log.info("Request is for principal (" + principal.getName() + ").");
291
292                         } catch (InvalidNameIdentifierException invalidNameE) {
293                                 log.info("Could not associate the request subject with a principal: " + invalidNameE);
294                                 try {
295                                         if (relyingParty.passThruErrors()) {
296                                                 sendFailure(resp, samlRequest, new SAMLException(Arrays
297                                                                 .asList(invalidNameE.getSAMLErrorCodes()), "The supplied Subject was unrecognized.",
298                                                                 invalidNameE));
299
300                                         } else {
301                                                 sendFailure(resp, samlRequest, new SAMLException(Arrays
302                                                                 .asList(invalidNameE.getSAMLErrorCodes()), "The supplied Subject was unrecognized."));
303                                         }
304                                         return;
305                                 } catch (Exception ee) {
306                                         log.fatal("Could not construct a SAML error response: " + ee);
307                                         throw new ServletException("Attribute Authority response failure.");
308                                 }
309                         }
310
311                         SAMLAttribute[] attrs;
312                         Iterator requestedAttrsIterator = attributeQuery.getDesignators();
313                         if (requestedAttrsIterator.hasNext()) {
314                                 log.info("Request designates specific attributes, resolving this set.");
315                                 ArrayList requestedAttrs = new ArrayList();
316                                 while (requestedAttrsIterator.hasNext()) {
317                                         SAMLAttribute attribute = (SAMLAttribute) requestedAttrsIterator.next();
318                                         try {
319                                                 log.debug("Designated attribute: (" + attribute.getName() + ")");
320                                                 requestedAttrs.add(new URI(attribute.getName()));
321                                         } catch (URISyntaxException use) {
322                                                 log
323                                                                 .error("Request designated an attribute name that does not conform to the required URI syntax ("
324                                                                                 + attribute.getName() + ").  Ignoring this attribute");
325                                         }
326                                 }
327
328                                 attrs = responder.getReleaseAttributes(principal, effectiveName, null, (URI[]) requestedAttrs
329                                                 .toArray(new URI[0]));
330                         } else {
331                                 log.info("Request does not designate specific attributes, resolving all available.");
332                                 attrs = responder.getReleaseAttributes(principal, effectiveName, null);
333                         }
334
335                         log.info("Found " + attrs.length + " attribute(s) for " + principal.getName());
336                         sendResponse(resp, attrs, samlRequest, relyingParty, null);
337                         log.info("Successfully responded about " + principal.getName());
338
339                         if (effectiveName == null) {
340                                 if (fromLegacyProvider(req)) {
341                                         transactionLog.info("Attribute assertion issued to anonymous legacy provider at ("
342                                                         + req.getRemoteAddr() + ") on behalf of principal (" + principal.getName() + ").");
343                                 } else {
344                                         transactionLog.info("Attribute assertion issued to anonymous provider at (" + req.getRemoteAddr()
345                                                         + ") on behalf of principal (" + principal.getName() + ").");
346                                 }
347                         } else {
348                                 if (fromLegacyProvider(req)) {
349                                         transactionLog.info("Attribute assertion issued to legacy provider (" + effectiveName
350                                                         + ") on behalf of principal (" + principal.getName() + ").");
351                                 } else {
352                                         transactionLog.info("Attribute assertion issued to provider (" + effectiveName
353                                                         + ") on behalf of principal (" + principal.getName() + ").");
354                                 }
355                         }
356
357                 } catch (Exception e) {
358                         log.error("Error while processing request: " + e);
359                         try {
360                                 if (relyingParty != null && relyingParty.passThruErrors()) {
361                                         sendFailure(resp, samlRequest, new SAMLException(SAMLException.RESPONDER,
362                                                         "General error processing request.", e));
363                                 } else if (configuration.passThruErrors()) {
364                                         sendFailure(resp, samlRequest, new SAMLException(SAMLException.RESPONDER,
365                                                         "General error processing request.", e));
366                                 } else {
367                                         sendFailure(resp, samlRequest, new SAMLException(SAMLException.RESPONDER,
368                                                         "General error processing request."));
369                                 }
370                                 return;
371                         } catch (Exception ee) {
372                                 log.fatal("Could not construct a SAML error response: " + ee);
373                                 throw new ServletException("Attribute Authority response failure.");
374                         }
375
376                 }
377         }
378
379         protected String getEffectiveName(HttpServletRequest req, AARelyingParty relyingParty)
380                         throws InvalidProviderCredentialException {
381
382                 //X500Principal credentialName = getCredentialName(req);
383                 X509Certificate credential = getCredentialFromProvider(req);
384
385                 if (credential == null || credential.getSubjectX500Principal().getName(X500Principal.RFC2253).equals("")) {
386                         log.info("Request is from an unauthenticated service provider.");
387                         return null;
388
389                 } else {
390                         log.info("Request contains credential: ("
391                                         + credential.getSubjectX500Principal().getName(X500Principal.RFC2253) + ").");
392                         //Mockup old requester name for requests from < 1.2 targets
393                         if (fromLegacyProvider(req)) {
394                                 String legacyName = ShibPOSTProfile.getHostNameFromDN(credential.getSubjectX500Principal());
395                                 if (legacyName == null) {
396                                         log.error("Unable to extract legacy requester name from certificate subject.");
397                                 }
398
399                                 log.info("Request from legacy service provider: (" + legacyName + ").");
400                                 return legacyName;
401
402                         } else {
403
404                                 //See if we have metadata for this provider
405                                 Provider provider = lookup(relyingParty.getProviderId());
406                                 if (provider == null) {
407                                         log.info("No metadata found for provider: (" + relyingParty.getProviderId() + ").");
408                                         log.info("Treating remote provider as unauthenticated.");
409                                         return null;
410                                 }
411
412                                 //Make sure that the suppplied credential is valid for the selected relying party
413                                 if (isValidCredential(provider, credential)) {
414                                         log.info("Supplied credential validated for this provider.");
415                                         log.info("Request from service provider: (" + relyingParty.getProviderId() + ").");
416                                         return relyingParty.getProviderId();
417                                 } else {
418                                         log.error("Supplied credential ("
419                                                         + credential.getSubjectX500Principal().getName(X500Principal.RFC2253)
420                                                         + ") is NOT valid for provider (" + relyingParty.getProviderId() + ").");
421                                         throw new InvalidProviderCredentialException("Invalid credential.");
422                                 }
423                         }
424                 }
425         }
426
427         public void destroy() {
428                 log.info("Cleaning up resources.");
429                 responder.destroy();
430                 nameMapper.destroy();
431         }
432
433         public void sendResponse(HttpServletResponse resp, SAMLAttribute[] attrs, SAMLRequest samlRequest,
434                         RelyingParty relyingParty, SAMLException exception) throws IOException {
435
436                 SAMLException ourSE = null;
437                 SAMLResponse samlResponse = null;
438
439                 try {
440                         if (attrs == null || attrs.length == 0) {
441                                 //No attribute found
442                                 samlResponse = new SAMLResponse(samlRequest.getId(), null, null, exception);
443                         } else {
444
445                                 if (samlRequest.getQuery() == null || !(samlRequest.getQuery() instanceof SAMLAttributeQuery)) {
446                                         throw new SAMLException(SAMLException.REQUESTER,
447                                                         "This SAML authority only responds to attribute queries");
448                                 }
449                                 SAMLAttributeQuery attributeQuery = (SAMLAttributeQuery) samlRequest.getQuery();
450
451                                 //Reference requested subject
452                                 SAMLSubject rSubject = (SAMLSubject) attributeQuery.getSubject().clone();
453
454                                 //Set appropriate audience
455                                 ArrayList audiences = new ArrayList();
456                                 if (relyingParty.getProviderId() != null) {
457                                         audiences.add(relyingParty.getProviderId());
458                                 }
459                                 if (relyingParty.getName() != null && !relyingParty.getName().equals(relyingParty.getProviderId())) {
460                                         audiences.add(relyingParty.getName());
461                                 }
462                                 SAMLCondition condition = new SAMLAudienceRestrictionCondition(audiences);
463
464                                 //Put all attributes into an assertion
465                                 SAMLStatement statement = new SAMLAttributeStatement(rSubject, Arrays.asList(attrs));
466
467                                 //Set assertion expiration to longest attribute expiration
468                                 long max = 0;
469                                 for (int i = 0; i < attrs.length; i++) {
470                                         if (max < attrs[i].getLifetime()) {
471                                                 max = attrs[i].getLifetime();
472                                         }
473                                 }
474                                 Date now = new Date();
475                                 Date then = new Date(now.getTime() + (max * 1000)); //max is in seconds
476
477                                 SAMLAssertion sAssertion = new SAMLAssertion(relyingParty.getIdentityProvider().getProviderId(), now,
478                                                 then, Collections.singleton(condition), null, Collections.singleton(statement));
479
480                                 samlResponse = new SAMLResponse(samlRequest.getId(), null, Collections.singleton(sAssertion), exception);
481                                 addSignatures(samlResponse, relyingParty);
482                         }
483                 } catch (SAMLException se) {
484                         ourSE = se;
485                 } catch (CloneNotSupportedException ex) {
486                         ourSE = new SAMLException(SAMLException.RESPONDER, ex);
487
488                 } finally {
489
490                         if (log.isDebugEnabled()) {
491                                 try {
492                                         log.debug("Dumping generated SAML Response:"
493                                                         + System.getProperty("line.separator")
494                                                         + new String(
495                                                                         new BASE64Decoder().decodeBuffer(new String(samlResponse.toBase64(), "ASCII")),
496                                                                         "UTF8"));
497                                 } catch (SAMLException e) {
498                                         log.error("Encountered an error while decoding SAMLReponse for logging purposes.");
499                                 } catch (IOException e) {
500                                         log.error("Encountered an error while decoding SAMLReponse for logging purposes.");
501                                 }
502                         }
503
504                         binding.respond(resp, samlResponse, ourSE);
505                 }
506         }
507
508         private void addSignatures(SAMLResponse reponse, RelyingParty relyingParty) throws SAMLException {
509
510                 //Sign the assertions, if appropriate
511                 if (relyingParty.getIdentityProvider().getAssertionSigningCredential() != null
512                                 && relyingParty.getIdentityProvider().getAssertionSigningCredential().getPrivateKey() != null) {
513
514                         String assertionAlgorithm;
515                         if (relyingParty.getIdentityProvider().getAssertionSigningCredential().getCredentialType() == Credential.RSA) {
516                                 assertionAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1;
517                         } else if (relyingParty.getIdentityProvider().getAssertionSigningCredential().getCredentialType() == Credential.DSA) {
518                                 assertionAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_DSA;
519                         } else {
520                                 throw new InvalidCryptoException(SAMLException.RESPONDER,
521                                                 "ShibPOSTProfile.prepare() currently only supports signing with RSA and DSA keys.");
522                         }
523
524                         ((SAMLAssertion) reponse.getAssertions().next()).sign(assertionAlgorithm, relyingParty
525                                         .getIdentityProvider().getAssertionSigningCredential().getPrivateKey(), Arrays.asList(relyingParty
526                                         .getIdentityProvider().getAssertionSigningCredential().getX509CertificateChain()));
527                 }
528
529                 //Sign the response, if appropriate
530                 if (relyingParty.getIdentityProvider().getResponseSigningCredential() != null
531                                 && relyingParty.getIdentityProvider().getResponseSigningCredential().getPrivateKey() != null) {
532
533                         String responseAlgorithm;
534                         if (relyingParty.getIdentityProvider().getResponseSigningCredential().getCredentialType() == Credential.RSA) {
535                                 responseAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1;
536                         } else if (relyingParty.getIdentityProvider().getResponseSigningCredential().getCredentialType() == Credential.DSA) {
537                                 responseAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_DSA;
538                         } else {
539                                 throw new InvalidCryptoException(SAMLException.RESPONDER,
540                                                 "ShibPOSTProfile.prepare() currently only supports signing with RSA and DSA keys.");
541                         }
542
543                         reponse.sign(responseAlgorithm, relyingParty.getIdentityProvider().getResponseSigningCredential()
544                                         .getPrivateKey(), Arrays.asList(relyingParty.getIdentityProvider().getResponseSigningCredential()
545                                         .getX509CertificateChain()));
546                 }
547         }
548
549         public void sendFailure(HttpServletResponse httpResponse, SAMLRequest samlRequest, SAMLException exception)
550                         throws IOException {
551                 try {
552                         SAMLResponse samlResponse = new SAMLResponse((samlRequest != null) ? samlRequest.getId() : null, null,
553                                         null, exception);
554                         if (log.isDebugEnabled()) {
555                                 try {
556                                         log.debug("Dumping generated SAML Error Response:"
557                                                         + System.getProperty("line.separator")
558                                                         + new String(
559                                                                         new BASE64Decoder().decodeBuffer(new String(samlResponse.toBase64(), "ASCII")),
560                                                                         "UTF8"));
561                                 } catch (IOException e) {
562                                         log.error("Encountered an error while decoding SAMLReponse for logging purposes.");
563                                 }
564                         }
565                         binding.respond(httpResponse, samlResponse, null);
566                         log.debug("Returning SAML Error Response.");
567                 } catch (SAMLException se) {
568                         binding.respond(httpResponse, null, exception);
569                         log.error("AA failed to make an error message: " + se);
570                 }
571         }
572
573         protected boolean isValidCredential(Provider provider, X509Certificate certificate) {
574
575                 ProviderRole[] roles = provider.getRoles();
576                 if (roles.length == 0) {
577                         log.info("Inappropriate metadata for provider.");
578                         return false;
579                 }
580
581                 for (int i = 0; roles.length > i; i++) {
582                         if (roles[i] instanceof AttributeConsumerRole) {
583                                 KeyDescriptor[] descriptors = roles[i].getKeyDescriptors();
584                                 for (int j = 0; descriptors.length > j; j++) {
585                                         KeyInfo[] keyInfo = descriptors[j].getKeyInfo();
586                                         for (int k = 0; keyInfo.length > k; k++) {
587                                                 for (int l = 0; keyInfo[k].lengthKeyName() > l; l++) {
588                                                         try {
589
590                                                                 //First, try to match DN against metadata
591                                                                 try {
592                                                                         if (certificate.getSubjectX500Principal().getName(X500Principal.RFC2253).equals(
593                                                                                         new X500Principal(keyInfo[k].itemKeyName(l).getKeyName())
594                                                                                                         .getName(X500Principal.RFC2253))) {
595                                                                                 log.debug("Matched against DN.");
596                                                                                 return true;
597                                                                         }
598                                                                 } catch (IllegalArgumentException iae) {
599                                                                         //squelch this runtime exception, since this might be a valid case
600                                                                 }
601
602                                                                 //If that doesn't work, we try matching against some Subject Alt Names
603                                                                 try {
604                                                                         Collection altNames = certificate.getSubjectAlternativeNames();
605                                                                         if (altNames != null) {
606                                                                                 for (Iterator nameIterator = altNames.iterator(); nameIterator.hasNext();) {
607                                                                                         List altName = (List) nameIterator.next();
608                                                                                         if (altName.get(0).equals(new Integer(2))
609                                                                                                         || altName.get(0).equals(new Integer(6))) { //2 is DNS, 6 is URI
610                                                                                                 if (altName.get(1).equals(keyInfo[k].itemKeyName(l).getKeyName())) {
611                                                                                                         log.debug("Matched against SubjectAltName.");
612                                                                                                         return true;
613                                                                                                 }
614                                                                                         }
615                                                                                 }
616                                                                         }
617                                                                 } catch (CertificateParsingException e1) {
618                                                                         log
619                                                                                         .error("Encountered an problem trying to extract Subject Alternate Name from supplied certificate: "
620                                                                                                         + e1);
621                                                                 }
622
623                                                                 //If that doesn't work, try to match using SSL-style hostname matching
624                                                                 if (ShibPOSTProfile.getHostNameFromDN(certificate.getSubjectX500Principal()).equals(
625                                                                                 keyInfo[k].itemKeyName(l).getKeyName())) {
626                                                                         log.debug("Matched against hostname.");
627                                                                         return true;
628                                                                 }
629
630                                                         } catch (XMLSecurityException e) {
631                                                                 log.error("Encountered an error reading federation metadata: " + e);
632                                                         }
633                                                 }
634                                         }
635                                 }
636                         }
637                 }
638                 log.info("Supplied credential not found in metadata.");
639                 return false;
640         }
641
642         protected boolean fromLegacyProvider(HttpServletRequest request) {
643                 String version = request.getHeader("Shibboleth");
644                 if (version != null) {
645                         log.debug("Request from Shibboleth version: " + version);
646                         return false;
647                 }
648                 log.debug("No version header found.");
649                 return true;
650         }
651
652         protected X509Certificate getCredentialFromProvider(HttpServletRequest req) {
653                 X509Certificate[] certArray = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate");
654                 if (certArray != null && certArray.length > 0) {
655                         return certArray[0];
656                 }
657                 return null;
658         }
659
660         class InvalidProviderCredentialException extends Exception {
661
662                 public InvalidProviderCredentialException(String message) {
663                         super(message);
664                 }
665         }
666
667 }