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