When the IdP is in DEBUG mode, dump SAML requests to the log.
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / idp / IdPResponder.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 above
6  * copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials
7  * provided with the distribution, if any, must include the following acknowledgment: "This product includes software
8  * developed by the University Corporation for Advanced Internet Development <http://www.ucaid.edu> Internet2 Project.
9  * 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, nor
11  * 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 contact
13  * shibboleth@shibboleth.org Products derived from this software may not be called Shibboleth, Internet2, UCAID, or the
14  * University Corporation for Advanced Internet Development, nor may Shibboleth appear in their name, without prior
15  * written permission of the University Corporation for Advanced Internet Development. THIS SOFTWARE IS PROVIDED BY THE
16  * COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND WITH ALL FAULTS. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE
18  * DISCLAIMED AND THE ENTIRE RISK OF SATISFACTORY QUALITY, PERFORMANCE, ACCURACY, AND EFFORT IS WITH LICENSEE. IN NO
19  * EVENT SHALL THE COPYRIGHT OWNER, CONTRIBUTORS OR THE UNIVERSITY CORPORATION FOR ADVANCED INTERNET DEVELOPMENT, INC.
20  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
21  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
23  * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 package edu.internet2.middleware.shibboleth.idp;
27
28 import java.io.IOException;
29 import java.net.URI;
30 import java.net.URISyntaxException;
31 import java.net.URLEncoder;
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.RequestDispatcher;
45 import javax.servlet.ServletException;
46 import javax.servlet.UnavailableException;
47 import javax.servlet.http.HttpServletRequest;
48 import javax.servlet.http.HttpServletResponse;
49
50 import org.apache.log4j.Logger;
51 import org.apache.log4j.MDC;
52 import org.apache.xml.security.exceptions.XMLSecurityException;
53 import org.apache.xml.security.keys.KeyInfo;
54 import org.apache.xml.security.signature.XMLSignature;
55 import org.opensaml.InvalidCryptoException;
56 import org.opensaml.SAMLAssertion;
57 import org.opensaml.SAMLAttribute;
58 import org.opensaml.SAMLAttributeDesignator;
59 import org.opensaml.SAMLAttributeQuery;
60 import org.opensaml.SAMLAttributeStatement;
61 import org.opensaml.SAMLAudienceRestrictionCondition;
62 import org.opensaml.SAMLBinding;
63 import org.opensaml.SAMLCondition;
64 import org.opensaml.SAMLException;
65 import org.opensaml.SAMLIdentifier;
66 import org.opensaml.SAMLNameIdentifier;
67 import org.opensaml.SAMLRequest;
68 import org.opensaml.SAMLResponse;
69 import org.opensaml.SAMLStatement;
70 import org.opensaml.SAMLSubject;
71 import org.w3c.dom.Document;
72 import org.w3c.dom.Element;
73 import org.w3c.dom.NodeList;
74
75 import sun.misc.BASE64Decoder;
76 import edu.internet2.middleware.shibboleth.aa.AAConfig;
77 import edu.internet2.middleware.shibboleth.aa.AAException;
78 import edu.internet2.middleware.shibboleth.aa.AARelyingParty;
79 import edu.internet2.middleware.shibboleth.aa.AAResponder;
80 import edu.internet2.middleware.shibboleth.aa.AAServiceProviderMapper;
81 import edu.internet2.middleware.shibboleth.aa.arp.ArpEngine;
82 import edu.internet2.middleware.shibboleth.aa.arp.ArpException;
83 import edu.internet2.middleware.shibboleth.aa.attrresolv.AttributeResolver;
84 import edu.internet2.middleware.shibboleth.aa.attrresolv.AttributeResolverException;
85 import edu.internet2.middleware.shibboleth.artifact.ArtifactMapper;
86 import edu.internet2.middleware.shibboleth.artifact.ArtifactMapping;
87 import edu.internet2.middleware.shibboleth.artifact.provider.MemoryArtifactMapper;
88 import edu.internet2.middleware.shibboleth.common.AuthNPrincipal;
89 import edu.internet2.middleware.shibboleth.common.Credential;
90 import edu.internet2.middleware.shibboleth.common.Credentials;
91 import edu.internet2.middleware.shibboleth.common.InvalidNameIdentifierException;
92 import edu.internet2.middleware.shibboleth.common.NameIdentifierMapping;
93 import edu.internet2.middleware.shibboleth.common.NameIdentifierMappingException;
94 import edu.internet2.middleware.shibboleth.common.NameMapper;
95 import edu.internet2.middleware.shibboleth.common.OriginConfig;
96 import edu.internet2.middleware.shibboleth.common.RelyingParty;
97 import edu.internet2.middleware.shibboleth.common.SAMLBindingFactory;
98 import edu.internet2.middleware.shibboleth.common.ServiceProviderMapperException;
99 import edu.internet2.middleware.shibboleth.common.ShibPOSTProfile;
100 import edu.internet2.middleware.shibboleth.common.ShibbolethConfigurationException;
101 import edu.internet2.middleware.shibboleth.common.ShibbolethOriginConfig;
102 import edu.internet2.middleware.shibboleth.common.TargetFederationComponent;
103 import edu.internet2.middleware.shibboleth.hs.HSConfig;
104 import edu.internet2.middleware.shibboleth.hs.HSRelyingParty;
105 import edu.internet2.middleware.shibboleth.hs.HSServiceProviderMapper;
106 import edu.internet2.middleware.shibboleth.metadata.AttributeConsumerRole;
107 import edu.internet2.middleware.shibboleth.metadata.Endpoint;
108 import edu.internet2.middleware.shibboleth.metadata.KeyDescriptor;
109 import edu.internet2.middleware.shibboleth.metadata.Provider;
110 import edu.internet2.middleware.shibboleth.metadata.ProviderRole;
111 import edu.internet2.middleware.shibboleth.metadata.SPProviderRole;
112
113 /**
114  * Primary entry point for requests to the SAML IdP. Listens on multiple endpoints, routes requests to the appropriate
115  * IdP processing components, and delivers proper protocol responses.
116  * 
117  * @author Walter Hoehn
118  */
119
120 public class IdPResponder extends TargetFederationComponent {
121
122         // TODO Maybe should rethink the inheritance here, since there is only one
123         // servlet
124
125         private static Logger transactionLog = Logger.getLogger("Shibboleth-TRANSACTION");
126         private static Logger log = Logger.getLogger(IdPResponder.class.getName());
127         private SAMLBinding binding;
128         private Semaphore throttle;
129         private ArtifactMapper artifactMapper;
130         private SSOProfileHandler[] profileHandlers;
131
132         // TODO Obviously this has got to be unified
133         private AAConfig configuration;
134         private HSConfig hsConfiguration;
135         private NameMapper nameMapper;
136
137         // TODO unify
138         private AAServiceProviderMapper targetMapper;
139         private HSServiceProviderMapper hsTargetMapper;
140
141         // TODO Need to rename, rework, and init
142         private AAResponder responder;
143
144         public void init() throws ServletException {
145
146                 super.init();
147                 MDC.put("serviceId", "[IdP] Core");
148                 log.info("Initializing Identity Provider.");
149
150                 try {
151                         binding = SAMLBindingFactory.getInstance(SAMLBinding.SAML_SOAP_HTTPS);
152                         nameMapper = new NameMapper();
153                         // TODO this needs to be pluggable
154                         artifactMapper = new MemoryArtifactMapper();
155                         loadConfiguration();
156                         log.info("Identity Provider initialization complete.");
157
158                 } catch (ShibbolethConfigurationException ae) {
159                         log.fatal("The Identity Provider could not be initialized: " + ae);
160                         throw new UnavailableException("Identity Provider failed to initialize.");
161                 } catch (SAMLException se) {
162                         log.fatal("SAML SOAP binding could not be loaded: " + se);
163                         throw new UnavailableException("Identity Provider failed to initialize.");
164                 }
165         }
166
167         private void loadConfiguration() throws ShibbolethConfigurationException {
168
169                 Document originConfig = OriginConfig.getOriginConfig(this.getServletContext());
170
171                 // TODO I think some of the failure cases here are different than in the
172                 // HS, so when the loadConfiguration() is unified, that must be taken
173                 // into account
174
175                 // TODO do we need to check active endpoints to determine which
176                 // components to load, for instance artifact repository, arp engine,
177                 // attribute resolver
178
179                 // Load global configuration properties
180                 // TODO make AA and HS config unified
181                 configuration = new AAConfig(originConfig.getDocumentElement());
182
183                 // Load name mappings
184                 NodeList itemElements = originConfig.getDocumentElement().getElementsByTagNameNS(
185                                 NameIdentifierMapping.mappingNamespace, "NameMapping");
186
187                 for (int i = 0; i < itemElements.getLength(); i++) {
188                         try {
189                                 nameMapper.addNameMapping((Element) itemElements.item(i));
190                         } catch (NameIdentifierMappingException e) {
191                                 log.error("Name Identifier mapping could not be loaded: " + e);
192                         }
193                 }
194
195                 // Load signing credentials
196                 itemElements = originConfig.getDocumentElement().getElementsByTagNameNS(Credentials.credentialsNamespace,
197                                 "Credentials");
198                 if (itemElements.getLength() < 1) {
199                         log.error("No credentials specified.");
200                 }
201                 if (itemElements.getLength() > 1) {
202                         log.error("Multiple Credentials specifications found, using first.");
203                 }
204                 Credentials credentials = new Credentials((Element) itemElements.item(0));
205
206                 // Load metadata
207                 itemElements = originConfig.getDocumentElement().getElementsByTagNameNS(
208                                 ShibbolethOriginConfig.originConfigNamespace, "FederationProvider");
209                 for (int i = 0; i < itemElements.getLength(); i++) {
210                         addFederationProvider((Element) itemElements.item(i));
211                 }
212                 if (providerCount() < 1) {
213                         log.error("No Federation Provider metadata loaded.");
214                         throw new ShibbolethConfigurationException("Could not load federation metadata.");
215                 }
216
217                 // Load relying party config
218                 try {
219                         // TODO unify the service provider mapper
220                         targetMapper = new AAServiceProviderMapper(originConfig.getDocumentElement(), configuration, credentials,
221                                         this);
222                 } catch (ServiceProviderMapperException e) {
223                         log.error("Could not load Identity Provider configuration: " + e);
224                         throw new ShibbolethConfigurationException("Could not load Identity Provider configuration.");
225                 }
226
227                 try {
228                         // Startup Attribute Resolver
229                         AttributeResolver resolver = new AttributeResolver(configuration);
230
231                         // Startup ARP Engine
232                         ArpEngine arpEngine = null;
233                         itemElements = originConfig.getDocumentElement().getElementsByTagNameNS(
234                                         ShibbolethOriginConfig.originConfigNamespace, "ReleasePolicyEngine");
235
236                         if (itemElements.getLength() > 1) {
237                                 log.warn("Encountered multiple <ReleasePolicyEngine> configuration elements.  Using first...");
238                         }
239                         if (itemElements.getLength() < 1) {
240                                 arpEngine = new ArpEngine();
241                         } else {
242                                 arpEngine = new ArpEngine((Element) itemElements.item(0));
243                         }
244
245                         // Startup responder
246                         responder = new AAResponder(arpEngine, resolver);
247
248                 } catch (ArpException ae) {
249                         log.fatal("The Identity Provider could not be initialized "
250                                         + "due to a problem with the ARP Engine configuration: " + ae);
251                         throw new ShibbolethConfigurationException("Could not load ARP Engine.");
252                 } catch (AttributeResolverException ne) {
253                         log.fatal("The Identity Provider could not be initialized due "
254                                         + "to a problem with the Attribute Resolver configuration: " + ne);
255                         throw new ShibbolethConfigurationException("Could not load Attribute Resolver.");
256                 }
257
258         }
259
260         public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
261
262                 MDC.put("serviceId", "[IdP] " + new SAMLIdentifier().toString());
263                 MDC.put("remoteAddr", request.getRemoteAddr());
264                 log.debug("Recieved a request via POST.");
265
266                 // Parse SOAP request and marshall SAML request object
267                 SAMLRequest samlRequest = null;
268                 try {
269                         try {
270                                 samlRequest = binding.receive(request);
271                         } catch (SAMLException e) {
272                                 log.fatal("Unable to parse request: " + e);
273                                 throw new SAMLException("Invalid request data.");
274                         }
275
276                         // If we have DEBUGing turned on, dump out the request to the log
277                         if (log.isDebugEnabled()) { // This takes some processing, so only do it if we need to
278                                 try {
279                                         log.debug("Dumping generated SAML Request:"
280                                                         + System.getProperty("line.separator")
281                                                         + new String(new BASE64Decoder().decodeBuffer(new String(samlRequest.toBase64(), "ASCII")),
282                                                                         "UTF8"));
283                                 } catch (SAMLException e) {
284                                         log.error("Encountered an error while decoding SAMLRequest for logging purposes.");
285                                 } catch (IOException e) {
286                                         log.error("Encountered an error while decoding SAMLRequest for logging purposes.");
287                                 }
288                         }
289
290                         // Determine the request type
291                         Iterator artifacts = samlRequest.getArtifacts();
292                         if (artifacts.hasNext()) {
293                                 artifacts = null; // get rid of the iterator
294                                 log.info("Recieved a request to dereference an assertion artifact.");
295                                 processArtifactDereference(samlRequest, request, response);
296                                 return;
297                         }
298
299                         if (samlRequest.getQuery() != null && (samlRequest.getQuery() instanceof SAMLAttributeQuery)) {
300                                 log.info("Recieved an attribute query.");
301                                 processAttributeQuery(samlRequest, request, response);
302                                 return;
303                         }
304
305                         throw new SAMLException(SAMLException.REQUESTER,
306                                         "Identity Provider unable to respond to this SAML Request type.");
307
308                 } catch (InvalidNameIdentifierException invalidNameE) {
309                         log.info("Could not associate the request subject with a principal: " + invalidNameE);
310                         try {
311                                 // TODO once again, ifgure out passThruErrors
312                                 if (false) {
313                                         // if (relyingParty.passThruErrors()) {
314                                         sendSAMLFailureResponse(response, samlRequest, new SAMLException(Arrays.asList(invalidNameE
315                                                         .getSAMLErrorCodes()), "The supplied Subject was unrecognized.", invalidNameE));
316
317                                 } else {
318                                         sendSAMLFailureResponse(response, samlRequest, new SAMLException(Arrays.asList(invalidNameE
319                                                         .getSAMLErrorCodes()), "The supplied Subject was unrecognized."));
320                                 }
321                                 return;
322                         } catch (Exception ee) {
323                                 log.fatal("Could not construct a SAML error response: " + ee);
324                                 throw new ServletException("Identity Provider response failure.");
325                         }
326                 } catch (Exception e) {
327                         log.error("Error while processing request: " + e);
328                         try {
329                                 // TODO figure out how to implement the passThru error handling
330                                 // below
331                                 // if (relyingParty != null && relyingParty.passThruErrors()) {
332                                 if (false) {
333                                         sendSAMLFailureResponse(response, samlRequest, new SAMLException(SAMLException.RESPONDER,
334                                                         "General error processing request.", e));
335                                 } else if (configuration.passThruErrors()) {
336                                         sendSAMLFailureResponse(response, samlRequest, new SAMLException(SAMLException.RESPONDER,
337                                                         "General error processing request.", e));
338                                 } else {
339                                         sendSAMLFailureResponse(response, samlRequest, new SAMLException(SAMLException.RESPONDER,
340                                                         "General error processing request."));
341                                 }
342                                 return;
343                         } catch (Exception ee) {
344                                 log.fatal("Could not construct a SAML error response: " + ee);
345                                 throw new ServletException("Identity Provider response failure.");
346                         }
347                 }
348         }
349
350         // TODO get rid of this AAException thing
351         private void processAttributeQuery(SAMLRequest samlRequest, HttpServletRequest request, HttpServletResponse response)
352                         throws SAMLException, IOException, ServletException, AAException, InvalidNameIdentifierException,
353                         NameIdentifierMappingException {
354
355                 // TODO validate that the endpoint is valid for the request type
356
357                 AARelyingParty relyingParty = null;
358
359                 SAMLAttributeQuery attributeQuery = (SAMLAttributeQuery) samlRequest.getQuery();
360
361                 if (!fromLegacyProvider(request)) {
362                         log.info("Remote provider has identified itself as: (" + attributeQuery.getResource() + ").");
363                 }
364
365                 // This is the requester name that will be passed to subsystems
366                 String effectiveName = null;
367
368                 X509Certificate credential = getCredentialFromProvider(request);
369                 if (credential == null || credential.getSubjectX500Principal().getName(X500Principal.RFC2253).equals("")) {
370                         log.info("Request is from an unauthenticated service provider.");
371                 } else {
372
373                         // Identify a Relying Party
374                         relyingParty = targetMapper.getRelyingParty(attributeQuery.getResource());
375
376                         try {
377                                 effectiveName = getEffectiveName(request, relyingParty);
378                         } catch (InvalidProviderCredentialException ipc) {
379                                 sendSAMLFailureResponse(response, samlRequest, new SAMLException(SAMLException.RESPONDER,
380                                                 "Invalid credentials for request."));
381                                 return;
382                         }
383                 }
384
385                 if (effectiveName == null) {
386                         log.debug("Using default Relying Party for unauthenticated provider.");
387                         relyingParty = targetMapper.getRelyingParty(null);
388                 }
389
390                 // Fail if we can't honor SAML Subject Confirmation
391                 if (!fromLegacyProvider(request)) {
392                         Iterator iterator = attributeQuery.getSubject().getConfirmationMethods();
393                         boolean hasConfirmationMethod = false;
394                         while (iterator.hasNext()) {
395                                 log.info("Request contains SAML Subject Confirmation method: (" + (String) iterator.next() + ").");
396                         }
397                         if (hasConfirmationMethod) { throw new SAMLException(SAMLException.REQUESTER,
398                                         "This SAML authority cannot honor requests containing the supplied SAML Subject Confirmation Method."); }
399                 }
400
401                 // Map Subject to local principal
402                 Principal principal = nameMapper.getPrincipal(attributeQuery.getSubject().getName(), relyingParty, relyingParty
403                                 .getIdentityProvider());
404                 log.info("Request is for principal (" + principal.getName() + ").");
405
406                 SAMLAttribute[] attrs;
407                 Iterator requestedAttrsIterator = attributeQuery.getDesignators();
408                 if (requestedAttrsIterator.hasNext()) {
409                         log.info("Request designates specific attributes, resolving this set.");
410                         ArrayList requestedAttrs = new ArrayList();
411                         while (requestedAttrsIterator.hasNext()) {
412                                 SAMLAttributeDesignator attribute = (SAMLAttributeDesignator) requestedAttrsIterator.next();
413                                 try {
414                                         log.debug("Designated attribute: (" + attribute.getName() + ")");
415                                         requestedAttrs.add(new URI(attribute.getName()));
416                                 } catch (URISyntaxException use) {
417                                         log.error("Request designated an attribute name that does not conform to the required URI syntax ("
418                                                         + attribute.getName() + ").  Ignoring this attribute");
419                                 }
420                         }
421
422                         attrs = responder.getReleaseAttributes(principal, effectiveName, null, (URI[]) requestedAttrs
423                                         .toArray(new URI[0]));
424                 } else {
425                         log.info("Request does not designate specific attributes, resolving all available.");
426                         attrs = responder.getReleaseAttributes(principal, effectiveName, null);
427                 }
428
429                 log.info("Found " + attrs.length + " attribute(s) for " + principal.getName());
430                 sendSAMLResponse(response, attrs, samlRequest, relyingParty, null);
431                 log.info("Successfully responded about " + principal.getName());
432
433                 if (effectiveName == null) {
434                         if (fromLegacyProvider(request)) {
435                                 transactionLog.info("Attribute assertion issued to anonymous legacy provider at ("
436                                                 + request.getRemoteAddr() + ") on behalf of principal (" + principal.getName() + ").");
437                         } else {
438                                 transactionLog.info("Attribute assertion issued to anonymous provider at (" + request.getRemoteAddr()
439                                                 + ") on behalf of principal (" + principal.getName() + ").");
440                         }
441                 } else {
442                         if (fromLegacyProvider(request)) {
443                                 transactionLog.info("Attribute assertion issued to legacy provider (" + effectiveName
444                                                 + ") on behalf of principal (" + principal.getName() + ").");
445                         } else {
446                                 transactionLog.info("Attribute assertion issued to provider (" + effectiveName
447                                                 + ") on behalf of principal (" + principal.getName() + ").");
448                         }
449                 }
450
451         }
452
453         private void processArtifactDereference(SAMLRequest samlRequest, HttpServletRequest request,
454                         HttpServletResponse response) throws SAMLException, IOException {
455
456                 // TODO validate that the endpoint is valid for the request type
457                 // TODO how about signatures on artifact dereferencing
458
459                 // Pull credential from request
460                 X509Certificate credential = getCredentialFromProvider(request);
461                 if (credential == null || credential.getSubjectX500Principal().getName(X500Principal.RFC2253).equals("")) {
462                         // The spec says that mutual authentication is required for the
463                         // artifact profile
464                         log.info("Request is from an unauthenticated service provider.");
465                         throw new SAMLException(SAMLException.REQUESTER,
466                                         "SAML Artifacts cannot be dereferenced for unauthenticated requesters.");
467                 }
468
469                 log.info("Request contains credential: (" + credential.getSubjectX500Principal().getName(X500Principal.RFC2253)
470                                 + ").");
471
472                 ArrayList assertions = new ArrayList();
473                 Iterator artifacts = samlRequest.getArtifacts();
474
475                 int queriedArtifacts = 0;
476                 StringBuffer dereferencedArtifacts = new StringBuffer(); // for
477                 // transaction
478                 // log
479                 while (artifacts.hasNext()) {
480                         queriedArtifacts++;
481                         String artifact = (String) artifacts.next();
482                         log.debug("Attempting to dereference artifact: (" + artifact + ").");
483                         ArtifactMapping mapping = artifactMapper.recoverAssertion(artifact);
484                         if (mapping != null) {
485                                 SAMLAssertion assertion = mapping.getAssertion();
486
487                                 // See if we have metadata for this provider
488                                 Provider provider = lookup(mapping.getServiceProviderId());
489                                 if (provider == null) {
490                                         log.info("No metadata found for provider: (" + mapping.getServiceProviderId() + ").");
491                                         throw new SAMLException(SAMLException.REQUESTER, "Invalid service provider.");
492                                 }
493
494                                 // Make sure that the suppplied credential is valid for the
495                                 // provider to which the artifact was issued
496                                 if (!isValidCredential(provider, credential)) {
497                                         log.error("Supplied credential ("
498                                                         + credential.getSubjectX500Principal().getName(X500Principal.RFC2253)
499                                                         + ") is NOT valid for provider (" + mapping.getServiceProviderId()
500                                                         + "), to whom this artifact was issued.");
501                                         throw new SAMLException(SAMLException.REQUESTER, "Invalid credential.");
502                                 }
503
504                                 log.debug("Supplied credential validated for the provider to which this artifact was issued.");
505
506                                 assertions.add(assertion);
507                                 dereferencedArtifacts.append("(" + artifact + ")");
508                         }
509                 }
510
511                 // The spec requires that if any artifacts are dereferenced, they must
512                 // all be dereferenced
513                 if (assertions.size() > 0 && assertions.size() != queriedArtifacts) { throw new SAMLException(
514                                 SAMLException.REQUESTER, "Unable to successfully dereference all artifacts."); }
515
516                 // Create and send response
517                 // The spec says that we should send "success" in the case where no
518                 // artifacts match
519                 SAMLResponse samlResponse = new SAMLResponse(samlRequest.getId(), null, assertions, null);
520
521                 if (log.isDebugEnabled()) {
522                         try {
523                                 log.debug("Dumping generated SAML Response:"
524                                                 + System.getProperty("line.separator")
525                                                 + new String(new BASE64Decoder().decodeBuffer(new String(samlResponse.toBase64(), "ASCII")),
526                                                                 "UTF8"));
527                         } catch (SAMLException e) {
528                                 log.error("Encountered an error while decoding SAMLReponse for logging purposes.");
529                         } catch (IOException e) {
530                                 log.error("Encountered an error while decoding SAMLReponse for logging purposes.");
531                         }
532                 }
533
534                 binding.respond(response, samlResponse, null);
535
536                 transactionLog.info("Succesfully dereferenced the following artifacts: " + dereferencedArtifacts.toString());
537         }
538
539         public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
540
541                 MDC.put("serviceId", "[IdP] " + new SAMLIdentifier().toString());
542                 MDC.put("remoteAddr", request.getRemoteAddr());
543                 log.debug("Recieved a request via GET.");
544                 log.info("Handling authN request.");
545
546                 try {
547                         throttle.enter();
548
549                         // Ensure that we have the required data from the servlet container
550                         validateEngineData(request);
551
552                         // Determine which profile of SAML we are responding to (at this point, Shib vs. EAuth)
553                         SSOProfileHandler activeHandler = null;
554                         for (int i = 0; i < profileHandlers.length; i++) {
555                                 if (profileHandlers[i].validForRequest(request)) {
556                                         activeHandler = profileHandlers[i];
557                                         break;
558                                 }
559                         }
560                         if (activeHandler == null) { throw new InvalidClientDataException(
561                                         "The request did not contain sufficient parameter data to determine the protocol."); }
562
563                         // Run profile specific preprocessing
564                         if (activeHandler.preProcessHook(request, response)) { return; }
565
566                         // Get the authN info
567                         String username = hsConfiguration.getAuthHeaderName().equalsIgnoreCase("REMOTE_USER") ? request
568                                         .getRemoteUser() : request.getHeader(hsConfiguration.getAuthHeaderName());
569
570                         // Select the appropriate Relying Party configuration for the request
571                         HSRelyingParty relyingParty = null;
572                         String remoteProviderId = activeHandler.getRemoteProviderId(request);
573                         // If the target did not send a Provider Id, then assume it is a Shib
574                         // 1.1 or older target
575                         if (remoteProviderId == null) {
576                                 relyingParty = hsTargetMapper.getLegacyRelyingParty();
577                         } else if (remoteProviderId.equals("")) {
578                                 throw new InvalidClientDataException("Invalid service provider id.");
579                         } else {
580                                 log.debug("Remote provider has identified itself as: (" + remoteProviderId + ").");
581                                 relyingParty = hsTargetMapper.getRelyingParty(remoteProviderId);
582                         }
583
584                         // Grab the metadata for the provider
585                         Provider provider = lookup(relyingParty.getProviderId());
586
587                         // Use profile-specific method for determining the acceptance URL
588                         String acceptanceURL = activeHandler.getAcceptanceURL(request, relyingParty, provider);
589
590                         // Make sure that the selected relying party configuration is appropriate for this
591                         // acceptance URL
592                         if (!relyingParty.isLegacyProvider()) {
593
594                                 if (provider == null) {
595                                         log.info("No metadata found for provider: (" + relyingParty.getProviderId() + ").");
596                                         relyingParty = hsTargetMapper.getRelyingParty(null);
597
598                                 } else {
599
600                                         if (isValidAssertionConsumerURL(provider, acceptanceURL)) {
601                                                 log.info("Supplied consumer URL validated for this provider.");
602                                         } else {
603                                                 log.error("Assertion consumer service URL (" + acceptanceURL + ") is NOT valid for provider ("
604                                                                 + relyingParty.getProviderId() + ").");
605                                                 throw new InvalidClientDataException("Invalid assertion consumer service URL.");
606                                         }
607                                 }
608                         }
609
610                         // Create SAML Name Identifier
611                         SAMLNameIdentifier nameId = nameMapper.getNameIdentifierName(relyingParty.getHSNameFormatId(),
612                                         new AuthNPrincipal(username), relyingParty, relyingParty.getIdentityProvider());
613
614                         String authenticationMethod = request.getHeader("SAMLAuthenticationMethod");
615                         if (authenticationMethod == null || authenticationMethod.equals("")) {
616                                 authenticationMethod = relyingParty.getDefaultAuthMethod().toString();
617                                 log.debug("User was authenticated via the default method for this relying party ("
618                                                 + authenticationMethod + ").");
619                         } else {
620                                 log.debug("User was authenticated via the method (" + authenticationMethod + ").");
621                         }
622
623                         // We might someday want to provide a mechanism for the authenticator to specify the auth time
624                         SAMLAssertion[] assertions = activeHandler.processHook(request, relyingParty, provider, nameId,
625                                         authenticationMethod, new Date(System.currentTimeMillis()));
626
627                         // SAML Artifact profile
628                         if (useArtifactProfile(provider, acceptanceURL)) {
629                                 log.debug("Responding with Artifact profile.");
630
631                                 // Create artifacts for each assertion
632                                 ArrayList artifacts = new ArrayList();
633                                 for (int i = 0; i < assertions.length; i++) {
634                                         artifacts.add(artifactMapper.generateArtifact(assertions[i], relyingParty));
635                                 }
636
637                                 // Assemble the query string
638                                 StringBuffer destination = new StringBuffer(acceptanceURL);
639                                 destination.append("?TARGET=");
640                                 destination.append(URLEncoder.encode(activeHandler.getSAMLTargetParameter(request, relyingParty,
641                                                 provider), "UTF-8"));
642                                 Iterator iterator = artifacts.iterator();
643                                 StringBuffer artifactBuffer = new StringBuffer(); // Buffer for the transaction log
644                                 while (iterator.hasNext()) {
645                                         destination.append("&SAMLart=");
646                                         String artifact = (String) iterator.next();
647                                         destination.append(URLEncoder.encode(artifact, "UTF-8"));
648                                         artifactBuffer.append("(" + artifact + ")");
649                                 }
650                                 log.debug("Redirecting to (" + destination.toString() + ").");
651                                 response.sendRedirect(destination.toString()); // Redirect to the artifact receiver
652
653                                 transactionLog.info("Assertion artifact(s) (" + artifactBuffer.toString() + ") issued to provider ("
654                                                 + relyingParty.getIdentityProvider().getProviderId() + ") on behalf of principal (" + username
655                                                 + "). Name Identifier: (" + nameId.getName() + "). Name Identifier Format: ("
656                                                 + nameId.getFormat() + ").");
657
658                                 // SAML POST profile
659                         } else {
660                                 log.debug("Responding with POST profile.");
661                                 request.setAttribute("acceptanceURL", acceptanceURL);
662                                 request.setAttribute("target", activeHandler.getSAMLTargetParameter(request, relyingParty, provider));
663
664                                 SAMLResponse samlResponse = new SAMLResponse(null, acceptanceURL, Arrays.asList(assertions), null);
665                                 addSignatures(samlResponse, relyingParty);
666                                 createPOSTForm(request, response, samlResponse.toBase64());
667
668                                 // Make transaction log entry
669                                 if (relyingParty.isLegacyProvider()) {
670                                         transactionLog.info("Authentication assertion issued to legacy provider (SHIRE: "
671                                                         + request.getParameter("shire") + ") on behalf of principal (" + username
672                                                         + ") for resource (" + request.getParameter("target") + "). Name Identifier: ("
673                                                         + nameId.getName() + "). Name Identifier Format: (" + nameId.getFormat() + ").");
674                                 } else {
675                                         transactionLog.info("Authentication assertion issued to provider ("
676                                                         + relyingParty.getIdentityProvider().getProviderId() + ") on behalf of principal ("
677                                                         + username + "). Name Identifier: (" + nameId.getName() + "). Name Identifier Format: ("
678                                                         + nameId.getFormat() + ").");
679                                 }
680                         }
681
682                         // TODO profile specific error handling
683                 } catch (NameIdentifierMappingException ex) {
684                         log.error(ex);
685                         handleSSOError(request, response, ex);
686                         return;
687                 } catch (InvalidClientDataException ex) {
688                         log.error(ex);
689                         handleSSOError(request, response, ex);
690                         return;
691                 } catch (SAMLException ex) {
692                         log.error(ex);
693                         handleSSOError(request, response, ex);
694                         return;
695                 } catch (InterruptedException ex) {
696                         log.error(ex);
697                         handleSSOError(request, response, ex);
698                         return;
699                 } finally {
700                         throttle.exit();
701                 }
702
703         }
704
705         private static X509Certificate getCredentialFromProvider(HttpServletRequest req) {
706
707                 X509Certificate[] certArray = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate");
708                 if (certArray != null && certArray.length > 0) { return certArray[0]; }
709                 return null;
710         }
711
712         private static boolean isValidCredential(Provider provider, X509Certificate certificate) {
713
714                 ProviderRole[] roles = provider.getRoles();
715                 if (roles.length == 0) {
716                         log.info("Inappropriate metadata for provider.");
717                         return false;
718                 }
719                 // TODO figure out what to do about this role business here
720                 for (int i = 0; roles.length > i; i++) {
721                         if (roles[i] instanceof AttributeConsumerRole) {
722                                 KeyDescriptor[] descriptors = roles[i].getKeyDescriptors();
723                                 for (int j = 0; descriptors.length > j; j++) {
724                                         KeyInfo[] keyInfo = descriptors[j].getKeyInfo();
725                                         for (int k = 0; keyInfo.length > k; k++) {
726                                                 for (int l = 0; keyInfo[k].lengthKeyName() > l; l++) {
727                                                         try {
728
729                                                                 // First, try to match DN against metadata
730                                                                 try {
731                                                                         if (certificate.getSubjectX500Principal().getName(X500Principal.RFC2253).equals(
732                                                                                         new X500Principal(keyInfo[k].itemKeyName(l).getKeyName())
733                                                                                                         .getName(X500Principal.RFC2253))) {
734                                                                                 log.debug("Matched against DN.");
735                                                                                 return true;
736                                                                         }
737                                                                 } catch (IllegalArgumentException iae) {
738                                                                         // squelch this runtime exception, since
739                                                                         // this might be a valid case
740                                                                 }
741
742                                                                 // If that doesn't work, we try matching against
743                                                                 // some Subject Alt Names
744                                                                 try {
745                                                                         Collection altNames = certificate.getSubjectAlternativeNames();
746                                                                         if (altNames != null) {
747                                                                                 for (Iterator nameIterator = altNames.iterator(); nameIterator.hasNext();) {
748                                                                                         List altName = (List) nameIterator.next();
749                                                                                         if (altName.get(0).equals(new Integer(2))
750                                                                                                         || altName.get(0).equals(new Integer(6))) { // 2 is
751                                                                                                 // DNS,
752                                                                                                 // 6 is
753                                                                                                 // URI
754                                                                                                 if (altName.get(1).equals(keyInfo[k].itemKeyName(l).getKeyName())) {
755                                                                                                         log.debug("Matched against SubjectAltName.");
756                                                                                                         return true;
757                                                                                                 }
758                                                                                         }
759                                                                                 }
760                                                                         }
761                                                                 } catch (CertificateParsingException e1) {
762                                                                         log
763                                                                                         .error("Encountered an problem trying to extract Subject Alternate Name from supplied certificate: "
764                                                                                                         + e1);
765                                                                 }
766
767                                                                 // If that doesn't work, try to match using
768                                                                 // SSL-style hostname matching
769                                                                 if (ShibPOSTProfile.getHostNameFromDN(certificate.getSubjectX500Principal()).equals(
770                                                                                 keyInfo[k].itemKeyName(l).getKeyName())) {
771                                                                         log.debug("Matched against hostname.");
772                                                                         return true;
773                                                                 }
774
775                                                         } catch (XMLSecurityException e) {
776                                                                 log.error("Encountered an error reading federation metadata: " + e);
777                                                         }
778                                                 }
779                                         }
780                                 }
781                         }
782                 }
783                 log.info("Supplied credential not found in metadata.");
784                 return false;
785         }
786
787         private void sendSAMLFailureResponse(HttpServletResponse httpResponse, SAMLRequest samlRequest,
788                         SAMLException exception) throws IOException {
789
790                 try {
791                         SAMLResponse samlResponse = new SAMLResponse((samlRequest != null) ? samlRequest.getId() : null, null,
792                                         null, exception);
793                         if (log.isDebugEnabled()) {
794                                 try {
795                                         log.debug("Dumping generated SAML Error Response:"
796                                                         + System.getProperty("line.separator")
797                                                         + new String(
798                                                                         new BASE64Decoder().decodeBuffer(new String(samlResponse.toBase64(), "ASCII")),
799                                                                         "UTF8"));
800                                 } catch (IOException e) {
801                                         log.error("Encountered an error while decoding SAMLReponse for logging purposes.");
802                                 }
803                         }
804                         binding.respond(httpResponse, samlResponse, null);
805                         log.debug("Returning SAML Error Response.");
806                 } catch (SAMLException se) {
807                         binding.respond(httpResponse, null, exception);
808                         log.error("Identity Provider failed to make an error message: " + se);
809                 }
810         }
811
812         private static boolean fromLegacyProvider(HttpServletRequest request) {
813
814                 String version = request.getHeader("Shibboleth");
815                 if (version != null) {
816                         log.debug("Request from Shibboleth version: " + version);
817                         return false;
818                 }
819                 log.debug("No version header found.");
820                 return true;
821         }
822
823         private String getEffectiveName(HttpServletRequest req, AARelyingParty relyingParty)
824                         throws InvalidProviderCredentialException {
825
826                 // X500Principal credentialName = getCredentialName(req);
827                 X509Certificate credential = getCredentialFromProvider(req);
828
829                 if (credential == null || credential.getSubjectX500Principal().getName(X500Principal.RFC2253).equals("")) {
830                         log.info("Request is from an unauthenticated service provider.");
831                         return null;
832
833                 } else {
834                         log.info("Request contains credential: ("
835                                         + credential.getSubjectX500Principal().getName(X500Principal.RFC2253) + ").");
836                         // Mockup old requester name for requests from < 1.2 targets
837                         if (fromLegacyProvider(req)) {
838                                 String legacyName = ShibPOSTProfile.getHostNameFromDN(credential.getSubjectX500Principal());
839                                 if (legacyName == null) {
840                                         log.error("Unable to extract legacy requester name from certificate subject.");
841                                 }
842
843                                 log.info("Request from legacy service provider: (" + legacyName + ").");
844                                 return legacyName;
845
846                         } else {
847
848                                 // See if we have metadata for this provider
849                                 Provider provider = lookup(relyingParty.getProviderId());
850                                 if (provider == null) {
851                                         log.info("No metadata found for provider: (" + relyingParty.getProviderId() + ").");
852                                         log.info("Treating remote provider as unauthenticated.");
853                                         return null;
854                                 }
855
856                                 // Make sure that the suppplied credential is valid for the
857                                 // selected relying party
858                                 if (isValidCredential(provider, credential)) {
859                                         log.info("Supplied credential validated for this provider.");
860                                         log.info("Request from service provider: (" + relyingParty.getProviderId() + ").");
861                                         return relyingParty.getProviderId();
862                                 } else {
863                                         log.error("Supplied credential ("
864                                                         + credential.getSubjectX500Principal().getName(X500Principal.RFC2253)
865                                                         + ") is NOT valid for provider (" + relyingParty.getProviderId() + ").");
866                                         throw new InvalidProviderCredentialException("Invalid credential.");
867                                 }
868                         }
869                 }
870         }
871
872         // TODO this should be renamed, since it is now only one type of response
873         // that we can send
874         public void sendSAMLResponse(HttpServletResponse resp, SAMLAttribute[] attrs, SAMLRequest samlRequest,
875                         RelyingParty relyingParty, SAMLException exception) throws IOException {
876
877                 SAMLException ourSE = null;
878                 SAMLResponse samlResponse = null;
879
880                 try {
881                         if (attrs == null || attrs.length == 0) {
882                                 // No attribute found
883                                 samlResponse = new SAMLResponse(samlRequest.getId(), null, null, exception);
884                         } else {
885
886                                 SAMLAttributeQuery attributeQuery = (SAMLAttributeQuery) samlRequest.getQuery();
887
888                                 // Reference requested subject
889                                 SAMLSubject rSubject = (SAMLSubject) attributeQuery.getSubject().clone();
890
891                                 // Set appropriate audience
892                                 ArrayList audiences = new ArrayList();
893                                 if (relyingParty.getProviderId() != null) {
894                                         audiences.add(relyingParty.getProviderId());
895                                 }
896                                 if (relyingParty.getName() != null && !relyingParty.getName().equals(relyingParty.getProviderId())) {
897                                         audiences.add(relyingParty.getName());
898                                 }
899                                 SAMLCondition condition = new SAMLAudienceRestrictionCondition(audiences);
900
901                                 // Put all attributes into an assertion
902                                 SAMLStatement statement = new SAMLAttributeStatement(rSubject, Arrays.asList(attrs));
903
904                                 // Set assertion expiration to longest attribute expiration
905                                 long max = 0;
906                                 for (int i = 0; i < attrs.length; i++) {
907                                         if (max < attrs[i].getLifetime()) {
908                                                 max = attrs[i].getLifetime();
909                                         }
910                                 }
911                                 Date now = new Date();
912                                 Date then = new Date(now.getTime() + (max * 1000)); // max is in
913                                 // seconds
914
915                                 SAMLAssertion sAssertion = new SAMLAssertion(relyingParty.getIdentityProvider().getProviderId(), now,
916                                                 then, Collections.singleton(condition), null, Collections.singleton(statement));
917
918                                 samlResponse = new SAMLResponse(samlRequest.getId(), null, Collections.singleton(sAssertion), exception);
919                                 addSignatures(samlResponse, relyingParty);
920                         }
921                 } catch (SAMLException se) {
922                         ourSE = se;
923                 } catch (CloneNotSupportedException ex) {
924                         ourSE = new SAMLException(SAMLException.RESPONDER, ex);
925
926                 } finally {
927
928                         if (log.isDebugEnabled()) { // This takes some processing, so only do it if we need to
929                                 try {
930                                         log.debug("Dumping generated SAML Response:"
931                                                         + System.getProperty("line.separator")
932                                                         + new String(
933                                                                         new BASE64Decoder().decodeBuffer(new String(samlResponse.toBase64(), "ASCII")),
934                                                                         "UTF8"));
935                                 } catch (SAMLException e) {
936                                         log.error("Encountered an error while decoding SAMLReponse for logging purposes.");
937                                 } catch (IOException e) {
938                                         log.error("Encountered an error while decoding SAMLReponse for logging purposes.");
939                                 }
940                         }
941
942                         binding.respond(resp, samlResponse, ourSE);
943                 }
944         }
945
946         private static void addSignatures(SAMLResponse reponse, RelyingParty relyingParty) throws SAMLException {
947
948                 // TODO make sure this signing optionally happens according to origin.xml params
949
950                 // Sign the assertions, if appropriate
951                 if (relyingParty.getIdentityProvider().getAssertionSigningCredential() != null
952                                 && relyingParty.getIdentityProvider().getAssertionSigningCredential().getPrivateKey() != null) {
953
954                         String assertionAlgorithm;
955                         if (relyingParty.getIdentityProvider().getAssertionSigningCredential().getCredentialType() == Credential.RSA) {
956                                 assertionAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1;
957                         } else if (relyingParty.getIdentityProvider().getAssertionSigningCredential().getCredentialType() == Credential.DSA) {
958                                 assertionAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_DSA;
959                         } else {
960                                 throw new InvalidCryptoException(SAMLException.RESPONDER,
961                                                 "The Shibboleth IdP currently only supports signing with RSA and DSA keys.");
962                         }
963
964                         ((SAMLAssertion) reponse.getAssertions().next()).sign(assertionAlgorithm, relyingParty
965                                         .getIdentityProvider().getAssertionSigningCredential().getPrivateKey(), Arrays.asList(relyingParty
966                                         .getIdentityProvider().getAssertionSigningCredential().getX509CertificateChain()));
967                 }
968
969                 // Sign the response, if appropriate
970                 if (relyingParty.getIdentityProvider().getResponseSigningCredential() != null
971                                 && relyingParty.getIdentityProvider().getResponseSigningCredential().getPrivateKey() != null) {
972
973                         String responseAlgorithm;
974                         if (relyingParty.getIdentityProvider().getResponseSigningCredential().getCredentialType() == Credential.RSA) {
975                                 responseAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1;
976                         } else if (relyingParty.getIdentityProvider().getResponseSigningCredential().getCredentialType() == Credential.DSA) {
977                                 responseAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_DSA;
978                         } else {
979                                 throw new InvalidCryptoException(SAMLException.RESPONDER,
980                                                 "The Shibboleth IdP currently only supports signing with RSA and DSA keys.");
981                         }
982
983                         reponse.sign(responseAlgorithm, relyingParty.getIdentityProvider().getResponseSigningCredential()
984                                         .getPrivateKey(), Arrays.asList(relyingParty.getIdentityProvider().getResponseSigningCredential()
985                                         .getX509CertificateChain()));
986                 }
987         }
988
989         private boolean useArtifactProfile(Provider provider, String acceptanceURL) {
990
991                 // Default to POST if we have no metadata
992                 if (provider == null) { return false; }
993
994                 // Default to POST if we have incomplete metadata
995                 ProviderRole[] roles = provider.getRoles();
996                 if (roles.length == 0) { return false; }
997
998                 for (int i = 0; roles.length > i; i++) {
999                         if (roles[i] instanceof SPProviderRole) {
1000                                 Endpoint[] endpoints = ((SPProviderRole) roles[i]).getAssertionConsumerServiceURLs();
1001
1002                                 for (int j = 0; endpoints.length > j; j++) {
1003                                         if (acceptanceURL.equals(endpoints[j].getLocation())
1004                                                         && "urn:oasis:names:tc:SAML:1.0:profiles:artifact-01".equals(endpoints[j].getBinding())) { return true; }
1005                                 }
1006                         }
1007                 }
1008                 // Default to POST if we have incomplete metadata
1009                 return false;
1010         }
1011
1012         protected static void validateEngineData(HttpServletRequest req) throws InvalidClientDataException {
1013
1014                 if ((req.getRemoteUser() == null) || (req.getRemoteUser().equals(""))) { throw new InvalidClientDataException(
1015                                 "Unable to authenticate remote user"); }
1016                 if ((req.getRemoteAddr() == null) || (req.getRemoteAddr().equals(""))) { throw new InvalidClientDataException(
1017                                 "Unable to obtain client address."); }
1018         }
1019
1020         protected static boolean isValidAssertionConsumerURL(Provider provider, String shireURL)
1021                         throws InvalidClientDataException {
1022
1023                 ProviderRole[] roles = provider.getRoles();
1024                 if (roles.length == 0) {
1025                         log.info("Inappropriate metadata for provider.");
1026                         return false;
1027                 }
1028
1029                 for (int i = 0; roles.length > i; i++) {
1030                         if (roles[i] instanceof SPProviderRole) {
1031                                 Endpoint[] endpoints = ((SPProviderRole) roles[i]).getAssertionConsumerServiceURLs();
1032                                 for (int j = 0; endpoints.length > j; j++) {
1033                                         if (shireURL.equals(endpoints[j].getLocation())) { return true; }
1034                                 }
1035                         }
1036                 }
1037                 log.info("Supplied consumer URL not found in metadata.");
1038                 return false;
1039         }
1040
1041         protected void createPOSTForm(HttpServletRequest req, HttpServletResponse res, byte[] buf) throws IOException,
1042                         ServletException {
1043
1044                 // Hardcoded to ASCII to ensure Base64 encoding compatibility
1045                 req.setAttribute("assertion", new String(buf, "ASCII"));
1046
1047                 if (log.isDebugEnabled()) {
1048                         try {
1049                                 log.debug("Dumping generated SAML Response:" + System.getProperty("line.separator")
1050                                                 + new String(new BASE64Decoder().decodeBuffer(new String(buf, "ASCII")), "UTF8"));
1051                         } catch (IOException e) {
1052                                 log.error("Encountered an error while decoding SAMLReponse for logging purposes.");
1053                         }
1054                 }
1055
1056                 // TODO rename from hs.jsp to more appropriate name
1057                 RequestDispatcher rd = req.getRequestDispatcher("/hs.jsp");
1058                 rd.forward(req, res);
1059         }
1060
1061         protected void handleSSOError(HttpServletRequest req, HttpServletResponse res, Exception e)
1062                         throws ServletException, IOException {
1063
1064                 req.setAttribute("errorText", e.toString());
1065                 req.setAttribute("requestURL", req.getRequestURI().toString());
1066                 RequestDispatcher rd = req.getRequestDispatcher("/hserror.jsp");
1067                 // TODO rename hserror.jsp to a more appropriate name
1068                 rd.forward(req, res);
1069         }
1070
1071         private class Semaphore {
1072
1073                 private int value;
1074
1075                 public Semaphore(int value) {
1076
1077                         this.value = value;
1078                 }
1079
1080                 public synchronized void enter() throws InterruptedException {
1081
1082                         --value;
1083                         if (value < 0) {
1084                                 wait();
1085                         }
1086                 }
1087
1088                 public synchronized void exit() {
1089
1090                         ++value;
1091                         notify();
1092                 }
1093         }
1094
1095         private class InvalidProviderCredentialException extends Exception {
1096
1097                 public InvalidProviderCredentialException(String message) {
1098
1099                         super(message);
1100                 }
1101         }
1102
1103         abstract class SSOProfileHandler {
1104
1105                 abstract String getHandlerName();
1106
1107                 abstract String getRemoteProviderId(HttpServletRequest req);
1108
1109                 abstract boolean validForRequest(HttpServletRequest request);
1110
1111                 abstract boolean preProcessHook(HttpServletRequest request, HttpServletResponse response) throws IOException;
1112
1113                 abstract SAMLAssertion[] processHook(HttpServletRequest request, HSRelyingParty relyingParty,
1114                                 Provider provider, SAMLNameIdentifier nameId, String authenticationMethod, Date authTime)
1115                                 throws SAMLException, IOException;
1116
1117                 abstract String getSAMLTargetParameter(HttpServletRequest request, HSRelyingParty relyingParty,
1118                                 Provider provider);
1119
1120                 abstract String getAcceptanceURL(HttpServletRequest request, HSRelyingParty relyingParty, Provider provider)
1121                                 throws InvalidClientDataException;
1122         }
1123
1124 }
1125
1126 class InvalidClientDataException extends Exception {
1127
1128         public InvalidClientDataException(String message) {
1129
1130                 super(message);
1131         }
1132
1133 }