Unifed NameMapper and HSNameMapper interfaces for use by the new IdPResponder servlet.
[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                         // Determine the request type
277                         Iterator artifacts = samlRequest.getArtifacts();
278                         if (artifacts.hasNext()) {
279                                 artifacts = null; // get rid of the iterator
280                                 log.info("Recieved a request to dereference an assertion artifact.");
281                                 processArtifactDereference(samlRequest, request, response);
282                                 return;
283                         }
284
285                         if (samlRequest.getQuery() != null && (samlRequest.getQuery() instanceof SAMLAttributeQuery)) {
286                                 log.info("Recieved an attribute query.");
287                                 processAttributeQuery(samlRequest, request, response);
288                                 return;
289                         }
290
291                         throw new SAMLException(SAMLException.REQUESTER,
292                                         "Identity Provider unable to respond to this SAML Request type.");
293
294                 } catch (InvalidNameIdentifierException invalidNameE) {
295                         log.info("Could not associate the request subject with a principal: " + invalidNameE);
296                         try {
297                                 //TODO once again, ifgure out passThruErrors
298                                 if (false) {
299                                         //if (relyingParty.passThruErrors()) {
300                                         sendSAMLFailureResponse(response, samlRequest, new SAMLException(Arrays.asList(invalidNameE
301                                                         .getSAMLErrorCodes()), "The supplied Subject was unrecognized.", invalidNameE));
302
303                                 } else {
304                                         sendSAMLFailureResponse(response, samlRequest, new SAMLException(Arrays.asList(invalidNameE
305                                                         .getSAMLErrorCodes()), "The supplied Subject was unrecognized."));
306                                 }
307                                 return;
308                         } catch (Exception ee) {
309                                 log.fatal("Could not construct a SAML error response: " + ee);
310                                 throw new ServletException("Identity Provider response failure.");
311                         }
312                 } catch (Exception e) {
313                         log.error("Error while processing request: " + e);
314                         try {
315                                 //TODO figure out how to implement the passThru error handling
316                                 // below
317                                 //if (relyingParty != null && relyingParty.passThruErrors()) {
318                                 if (false) {
319                                         sendSAMLFailureResponse(response, samlRequest, new SAMLException(SAMLException.RESPONDER,
320                                                         "General error processing request.", e));
321                                 } else if (configuration.passThruErrors()) {
322                                         sendSAMLFailureResponse(response, samlRequest, new SAMLException(SAMLException.RESPONDER,
323                                                         "General error processing request.", e));
324                                 } else {
325                                         sendSAMLFailureResponse(response, samlRequest, new SAMLException(SAMLException.RESPONDER,
326                                                         "General error processing request."));
327                                 }
328                                 return;
329                         } catch (Exception ee) {
330                                 log.fatal("Could not construct a SAML error response: " + ee);
331                                 throw new ServletException("Identity Provider response failure.");
332                         }
333                 }
334         }
335
336         //TODO get rid of this AAException thing
337         private void processAttributeQuery(SAMLRequest samlRequest, HttpServletRequest request, HttpServletResponse response)
338                         throws SAMLException, IOException, ServletException, AAException, InvalidNameIdentifierException,
339                         NameIdentifierMappingException {
340
341                 //TODO validate that the endpoint is valid for the request type
342
343                 AARelyingParty relyingParty = null;
344
345                 SAMLAttributeQuery attributeQuery = (SAMLAttributeQuery) samlRequest.getQuery();
346
347                 if (!fromLegacyProvider(request)) {
348                         log.info("Remote provider has identified itself as: (" + attributeQuery.getResource() + ").");
349                 }
350
351                 //This is the requester name that will be passed to subsystems
352                 String effectiveName = null;
353
354                 X509Certificate credential = getCredentialFromProvider(request);
355                 if (credential == null || credential.getSubjectX500Principal().getName(X500Principal.RFC2253).equals("")) {
356                         log.info("Request is from an unauthenticated service provider.");
357                 } else {
358
359                         //Identify a Relying Party
360                         relyingParty = targetMapper.getRelyingParty(attributeQuery.getResource());
361
362                         try {
363                                 effectiveName = getEffectiveName(request, relyingParty);
364                         } catch (InvalidProviderCredentialException ipc) {
365                                 sendSAMLFailureResponse(response, samlRequest, new SAMLException(SAMLException.RESPONDER,
366                                                 "Invalid credentials for request."));
367                                 return;
368                         }
369                 }
370
371                 if (effectiveName == null) {
372                         log.debug("Using default Relying Party for unauthenticated provider.");
373                         relyingParty = targetMapper.getRelyingParty(null);
374                 }
375
376                 //Fail if we can't honor SAML Subject Confirmation
377                 if (!fromLegacyProvider(request)) {
378                         Iterator iterator = attributeQuery.getSubject().getConfirmationMethods();
379                         boolean hasConfirmationMethod = false;
380                         while (iterator.hasNext()) {
381                                 log.info("Request contains SAML Subject Confirmation method: (" + (String) iterator.next() + ").");
382                         }
383                         if (hasConfirmationMethod) { throw new SAMLException(SAMLException.REQUESTER,
384                                         "This SAML authority cannot honor requests containing the supplied SAML Subject Confirmation Method."); }
385                 }
386
387                 //Map Subject to local principal
388                 Principal principal = nameMapper.getPrincipal(attributeQuery.getSubject().getName(), relyingParty, relyingParty
389                                 .getIdentityProvider());
390                 log.info("Request is for principal (" + principal.getName() + ").");
391
392                 SAMLAttribute[] attrs;
393                 Iterator requestedAttrsIterator = attributeQuery.getDesignators();
394                 if (requestedAttrsIterator.hasNext()) {
395                         log.info("Request designates specific attributes, resolving this set.");
396                         ArrayList requestedAttrs = new ArrayList();
397                         while (requestedAttrsIterator.hasNext()) {
398                                 SAMLAttributeDesignator attribute = (SAMLAttributeDesignator) requestedAttrsIterator.next();
399                                 try {
400                                         log.debug("Designated attribute: (" + attribute.getName() + ")");
401                                         requestedAttrs.add(new URI(attribute.getName()));
402                                 } catch (URISyntaxException use) {
403                                         log.error("Request designated an attribute name that does not conform to the required URI syntax ("
404                                                         + attribute.getName() + ").  Ignoring this attribute");
405                                 }
406                         }
407
408                         attrs = responder.getReleaseAttributes(principal, effectiveName, null, (URI[]) requestedAttrs
409                                         .toArray(new URI[0]));
410                 } else {
411                         log.info("Request does not designate specific attributes, resolving all available.");
412                         attrs = responder.getReleaseAttributes(principal, effectiveName, null);
413                 }
414
415                 log.info("Found " + attrs.length + " attribute(s) for " + principal.getName());
416                 sendSAMLResponse(response, attrs, samlRequest, relyingParty, null);
417                 log.info("Successfully responded about " + principal.getName());
418
419                 if (effectiveName == null) {
420                         if (fromLegacyProvider(request)) {
421                                 transactionLog.info("Attribute assertion issued to anonymous legacy provider at ("
422                                                 + request.getRemoteAddr() + ") on behalf of principal (" + principal.getName() + ").");
423                         } else {
424                                 transactionLog.info("Attribute assertion issued to anonymous provider at (" + request.getRemoteAddr()
425                                                 + ") on behalf of principal (" + principal.getName() + ").");
426                         }
427                 } else {
428                         if (fromLegacyProvider(request)) {
429                                 transactionLog.info("Attribute assertion issued to legacy provider (" + effectiveName
430                                                 + ") on behalf of principal (" + principal.getName() + ").");
431                         } else {
432                                 transactionLog.info("Attribute assertion issued to provider (" + effectiveName
433                                                 + ") on behalf of principal (" + principal.getName() + ").");
434                         }
435                 }
436
437         }
438
439         private void processArtifactDereference(SAMLRequest samlRequest, HttpServletRequest request,
440                         HttpServletResponse response) throws SAMLException, IOException {
441
442                 //TODO validate that the endpoint is valid for the request type
443                 //TODO how about signatures on artifact dereferencing
444
445                 // Pull credential from request
446                 X509Certificate credential = getCredentialFromProvider(request);
447                 if (credential == null || credential.getSubjectX500Principal().getName(X500Principal.RFC2253).equals("")) {
448                         //The spec says that mutual authentication is required for the
449                         // artifact profile
450                         log.info("Request is from an unauthenticated service provider.");
451                         throw new SAMLException(SAMLException.REQUESTER,
452                                         "SAML Artifacts cannot be dereferenced for unauthenticated requesters.");
453                 }
454
455                 log.info("Request contains credential: (" + credential.getSubjectX500Principal().getName(X500Principal.RFC2253)
456                                 + ").");
457
458                 ArrayList assertions = new ArrayList();
459                 Iterator artifacts = samlRequest.getArtifacts();
460
461                 int queriedArtifacts = 0;
462                 StringBuffer dereferencedArtifacts = new StringBuffer(); //for
463                 // transaction
464                 // log
465                 while (artifacts.hasNext()) {
466                         queriedArtifacts++;
467                         String artifact = (String) artifacts.next();
468                         log.debug("Attempting to dereference artifact: (" + artifact + ").");
469                         ArtifactMapping mapping = artifactMapper.recoverAssertion(artifact);
470                         if (mapping != null) {
471                                 SAMLAssertion assertion = mapping.getAssertion();
472
473                                 //See if we have metadata for this provider
474                                 Provider provider = lookup(mapping.getServiceProviderId());
475                                 if (provider == null) {
476                                         log.info("No metadata found for provider: (" + mapping.getServiceProviderId() + ").");
477                                         throw new SAMLException(SAMLException.REQUESTER, "Invalid service provider.");
478                                 }
479
480                                 //Make sure that the suppplied credential is valid for the
481                                 // provider to which the artifact was issued
482                                 if (!isValidCredential(provider, credential)) {
483                                         log.error("Supplied credential ("
484                                                         + credential.getSubjectX500Principal().getName(X500Principal.RFC2253)
485                                                         + ") is NOT valid for provider (" + mapping.getServiceProviderId()
486                                                         + "), to whom this artifact was issued.");
487                                         throw new SAMLException(SAMLException.REQUESTER, "Invalid credential.");
488                                 }
489
490                                 log.debug("Supplied credential validated for the provider to which this artifact was issued.");
491
492                                 assertions.add(assertion);
493                                 dereferencedArtifacts.append("(" + artifact + ")");
494                         }
495                 }
496
497                 //The spec requires that if any artifacts are dereferenced, they must
498                 // all be dereferenced
499                 if (assertions.size() > 0 && assertions.size() != queriedArtifacts) { throw new SAMLException(
500                                 SAMLException.REQUESTER, "Unable to successfully dereference all artifacts."); }
501
502                 //Create and send response
503                 // The spec says that we should send "success" in the case where no
504                 // artifacts match
505                 SAMLResponse samlResponse = new SAMLResponse(samlRequest.getId(), null, assertions, null);
506
507                 if (log.isDebugEnabled()) {
508                         try {
509                                 log.debug("Dumping generated SAML Response:"
510                                                 + System.getProperty("line.separator")
511                                                 + new String(new BASE64Decoder().decodeBuffer(new String(samlResponse.toBase64(), "ASCII")),
512                                                                 "UTF8"));
513                         } catch (SAMLException e) {
514                                 log.error("Encountered an error while decoding SAMLReponse for logging purposes.");
515                         } catch (IOException e) {
516                                 log.error("Encountered an error while decoding SAMLReponse for logging purposes.");
517                         }
518                 }
519
520                 binding.respond(response, samlResponse, null);
521
522                 transactionLog.info("Succesfully dereferenced the following artifacts: " + dereferencedArtifacts.toString());
523         }
524
525         public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
526
527                 MDC.put("serviceId", "[IdP] " + new SAMLIdentifier().toString());
528                 MDC.put("remoteAddr", request.getRemoteAddr());
529                 log.debug("Recieved a request via GET.");
530                 log.info("Handling authN request.");
531
532                 try {
533                         throttle.enter();
534
535                         //Ensure that we have the required data from the servlet container
536                         validateEngineData(request);
537
538                         //Determine which profile of SAML we are responding to (at this point, Shib vs. EAuth)
539                         SSOProfileHandler activeHandler = null;
540                         for (int i = 0; i < profileHandlers.length; i++) {
541                                 if (profileHandlers[i].validForRequest(request)) {
542                                         activeHandler = profileHandlers[i];
543                                         break;
544                                 }
545                         }
546                         if (activeHandler == null) { throw new InvalidClientDataException(
547                                         "The request did not contain sufficient parameter data to determine the protocol."); }
548
549                         //Run profile specific preprocessing
550                         if (activeHandler.preProcessHook(request, response)) { return; }
551
552                         //Get the authN info
553                         String username = hsConfiguration.getAuthHeaderName().equalsIgnoreCase("REMOTE_USER") ? request
554                                         .getRemoteUser() : request.getHeader(hsConfiguration.getAuthHeaderName());
555
556                         //Select the appropriate Relying Party configuration for the request
557                         HSRelyingParty relyingParty = null;
558                         String remoteProviderId = activeHandler.getRemoteProviderId(request);
559                         //If the target did not send a Provider Id, then assume it is a Shib
560                         // 1.1 or older target
561                         if (remoteProviderId == null) {
562                                 relyingParty = hsTargetMapper.getLegacyRelyingParty();
563                         } else if (remoteProviderId.equals("")) {
564                                 throw new InvalidClientDataException("Invalid service provider id.");
565                         } else {
566                                 log.debug("Remote provider has identified itself as: (" + remoteProviderId + ").");
567                                 relyingParty = hsTargetMapper.getRelyingParty(remoteProviderId);
568                         }
569
570                         //Grab the metadata for the provider
571                         Provider provider = lookup(relyingParty.getProviderId());
572
573                         //Use profile-specific method for determining the acceptance URL
574                         String acceptanceURL = activeHandler.getAcceptanceURL(request, relyingParty, provider);
575
576                         //Make sure that the selected relying party configuration is appropriate for this
577                         //acceptance URL
578                         if (!relyingParty.isLegacyProvider()) {
579
580                                 if (provider == null) {
581                                         log.info("No metadata found for provider: (" + relyingParty.getProviderId() + ").");
582                                         relyingParty = hsTargetMapper.getRelyingParty(null);
583
584                                 } else {
585
586                                         if (isValidAssertionConsumerURL(provider, acceptanceURL)) {
587                                                 log.info("Supplied consumer URL validated for this provider.");
588                                         } else {
589                                                 log.error("Assertion consumer service URL (" + acceptanceURL + ") is NOT valid for provider ("
590                                                                 + relyingParty.getProviderId() + ").");
591                                                 throw new InvalidClientDataException("Invalid assertion consumer service URL.");
592                                         }
593                                 }
594                         }
595
596                         //Create SAML Name Identifier
597                         SAMLNameIdentifier nameId = nameMapper.getNameIdentifierName(relyingParty.getHSNameFormatId(),
598                                         new AuthNPrincipal(username), relyingParty, relyingParty.getIdentityProvider());
599
600                         String authenticationMethod = request.getHeader("SAMLAuthenticationMethod");
601                         if (authenticationMethod == null || authenticationMethod.equals("")) {
602                                 authenticationMethod = relyingParty.getDefaultAuthMethod().toString();
603                                 log.debug("User was authenticated via the default method for this relying party ("
604                                                 + authenticationMethod + ").");
605                         } else {
606                                 log.debug("User was authenticated via the method (" + authenticationMethod + ").");
607                         }
608
609                         //We might someday want to provide a mechanism for the authenticator to specify the auth time
610                         SAMLAssertion[] assertions = activeHandler.processHook(request, relyingParty, provider, nameId,
611                                         authenticationMethod, new Date(System.currentTimeMillis()));
612
613                         // SAML Artifact profile
614                         if (useArtifactProfile(provider, acceptanceURL)) {
615                                 log.debug("Responding with Artifact profile.");
616
617                                 // Create artifacts for each assertion
618                                 ArrayList artifacts = new ArrayList();
619                                 for (int i = 0; i < assertions.length; i++) {
620                                         artifacts.add(artifactMapper.generateArtifact(assertions[i], relyingParty));
621                                 }
622
623                                 // Assemble the query string
624                                 StringBuffer destination = new StringBuffer(acceptanceURL);
625                                 destination.append("?TARGET=");
626                                 destination.append(URLEncoder.encode(activeHandler.getSAMLTargetParameter(request, relyingParty,
627                                                 provider), "UTF-8"));
628                                 Iterator iterator = artifacts.iterator();
629                                 StringBuffer artifactBuffer = new StringBuffer(); //Buffer for the transaction log
630                                 while (iterator.hasNext()) {
631                                         destination.append("&SAMLart=");
632                                         String artifact = (String) iterator.next();
633                                         destination.append(URLEncoder.encode(artifact, "UTF-8"));
634                                         artifactBuffer.append("(" + artifact + ")");
635                                 }
636                                 log.debug("Redirecting to (" + destination.toString() + ").");
637                                 response.sendRedirect(destination.toString()); //Redirect to the artifact receiver
638
639                                 transactionLog.info("Assertion artifact(s) (" + artifactBuffer.toString() + ") issued to provider ("
640                                                 + relyingParty.getIdentityProvider().getProviderId() + ") on behalf of principal (" + username
641                                                 + "). Name Identifier: (" + nameId.getName() + "). Name Identifier Format: ("
642                                                 + nameId.getFormat() + ").");
643
644                                 // SAML POST profile
645                         } else {
646                                 log.debug("Responding with POST profile.");
647                                 request.setAttribute("acceptanceURL", acceptanceURL);
648                                 request.setAttribute("target", activeHandler.getSAMLTargetParameter(request, relyingParty, provider));
649
650                                 SAMLResponse samlResponse = new SAMLResponse(null, acceptanceURL, Arrays.asList(assertions), null);
651                                 addSignatures(samlResponse, relyingParty);
652                                 createPOSTForm(request, response, samlResponse.toBase64());
653
654                                 // Make transaction log entry
655                                 if (relyingParty.isLegacyProvider()) {
656                                         transactionLog.info("Authentication assertion issued to legacy provider (SHIRE: "
657                                                         + request.getParameter("shire") + ") on behalf of principal (" + username
658                                                         + ") for resource (" + request.getParameter("target") + "). Name Identifier: ("
659                                                         + nameId.getName() + "). Name Identifier Format: (" + nameId.getFormat() + ").");
660                                 } else {
661                                         transactionLog.info("Authentication assertion issued to provider ("
662                                                         + relyingParty.getIdentityProvider().getProviderId() + ") on behalf of principal ("
663                                                         + username + "). Name Identifier: (" + nameId.getName() + "). Name Identifier Format: ("
664                                                         + nameId.getFormat() + ").");
665                                 }
666                         }
667
668                         //TODO profile specific error handling
669                 } catch (NameIdentifierMappingException ex) {
670                         log.error(ex);
671                         handleSSOError(request, response, ex);
672                         return;
673                 } catch (InvalidClientDataException ex) {
674                         log.error(ex);
675                         handleSSOError(request, response, ex);
676                         return;
677                 } catch (SAMLException ex) {
678                         log.error(ex);
679                         handleSSOError(request, response, ex);
680                         return;
681                 } catch (InterruptedException ex) {
682                         log.error(ex);
683                         handleSSOError(request, response, ex);
684                         return;
685                 } finally {
686                         throttle.exit();
687                 }
688
689         }
690
691         private static X509Certificate getCredentialFromProvider(HttpServletRequest req) {
692
693                 X509Certificate[] certArray = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate");
694                 if (certArray != null && certArray.length > 0) { return certArray[0]; }
695                 return null;
696         }
697
698         private static boolean isValidCredential(Provider provider, X509Certificate certificate) {
699
700                 ProviderRole[] roles = provider.getRoles();
701                 if (roles.length == 0) {
702                         log.info("Inappropriate metadata for provider.");
703                         return false;
704                 }
705                 //TODO figure out what to do about this role business here
706                 for (int i = 0; roles.length > i; i++) {
707                         if (roles[i] instanceof AttributeConsumerRole) {
708                                 KeyDescriptor[] descriptors = roles[i].getKeyDescriptors();
709                                 for (int j = 0; descriptors.length > j; j++) {
710                                         KeyInfo[] keyInfo = descriptors[j].getKeyInfo();
711                                         for (int k = 0; keyInfo.length > k; k++) {
712                                                 for (int l = 0; keyInfo[k].lengthKeyName() > l; l++) {
713                                                         try {
714
715                                                                 //First, try to match DN against metadata
716                                                                 try {
717                                                                         if (certificate.getSubjectX500Principal().getName(X500Principal.RFC2253).equals(
718                                                                                         new X500Principal(keyInfo[k].itemKeyName(l).getKeyName())
719                                                                                                         .getName(X500Principal.RFC2253))) {
720                                                                                 log.debug("Matched against DN.");
721                                                                                 return true;
722                                                                         }
723                                                                 } catch (IllegalArgumentException iae) {
724                                                                         //squelch this runtime exception, since
725                                                                         // this might be a valid case
726                                                                 }
727
728                                                                 //If that doesn't work, we try matching against
729                                                                 // some Subject Alt Names
730                                                                 try {
731                                                                         Collection altNames = certificate.getSubjectAlternativeNames();
732                                                                         if (altNames != null) {
733                                                                                 for (Iterator nameIterator = altNames.iterator(); nameIterator.hasNext();) {
734                                                                                         List altName = (List) nameIterator.next();
735                                                                                         if (altName.get(0).equals(new Integer(2))
736                                                                                                         || altName.get(0).equals(new Integer(6))) { //2 is
737                                                                                                 // DNS,
738                                                                                                 // 6 is
739                                                                                                 // URI
740                                                                                                 if (altName.get(1).equals(keyInfo[k].itemKeyName(l).getKeyName())) {
741                                                                                                         log.debug("Matched against SubjectAltName.");
742                                                                                                         return true;
743                                                                                                 }
744                                                                                         }
745                                                                                 }
746                                                                         }
747                                                                 } catch (CertificateParsingException e1) {
748                                                                         log
749                                                                                         .error("Encountered an problem trying to extract Subject Alternate Name from supplied certificate: "
750                                                                                                         + e1);
751                                                                 }
752
753                                                                 //If that doesn't work, try to match using
754                                                                 // SSL-style hostname matching
755                                                                 if (ShibPOSTProfile.getHostNameFromDN(certificate.getSubjectX500Principal()).equals(
756                                                                                 keyInfo[k].itemKeyName(l).getKeyName())) {
757                                                                         log.debug("Matched against hostname.");
758                                                                         return true;
759                                                                 }
760
761                                                         } catch (XMLSecurityException e) {
762                                                                 log.error("Encountered an error reading federation metadata: " + e);
763                                                         }
764                                                 }
765                                         }
766                                 }
767                         }
768                 }
769                 log.info("Supplied credential not found in metadata.");
770                 return false;
771         }
772
773         private void sendSAMLFailureResponse(HttpServletResponse httpResponse, SAMLRequest samlRequest,
774                         SAMLException exception) throws IOException {
775
776                 try {
777                         SAMLResponse samlResponse = new SAMLResponse((samlRequest != null) ? samlRequest.getId() : null, null,
778                                         null, exception);
779                         if (log.isDebugEnabled()) {
780                                 try {
781                                         log.debug("Dumping generated SAML Error Response:"
782                                                         + System.getProperty("line.separator")
783                                                         + new String(
784                                                                         new BASE64Decoder().decodeBuffer(new String(samlResponse.toBase64(), "ASCII")),
785                                                                         "UTF8"));
786                                 } catch (IOException e) {
787                                         log.error("Encountered an error while decoding SAMLReponse for logging purposes.");
788                                 }
789                         }
790                         binding.respond(httpResponse, samlResponse, null);
791                         log.debug("Returning SAML Error Response.");
792                 } catch (SAMLException se) {
793                         binding.respond(httpResponse, null, exception);
794                         log.error("Identity Provider failed to make an error message: " + se);
795                 }
796         }
797
798         private static boolean fromLegacyProvider(HttpServletRequest request) {
799
800                 String version = request.getHeader("Shibboleth");
801                 if (version != null) {
802                         log.debug("Request from Shibboleth version: " + version);
803                         return false;
804                 }
805                 log.debug("No version header found.");
806                 return true;
807         }
808
809         private String getEffectiveName(HttpServletRequest req, AARelyingParty relyingParty)
810                         throws InvalidProviderCredentialException {
811
812                 //X500Principal credentialName = getCredentialName(req);
813                 X509Certificate credential = getCredentialFromProvider(req);
814
815                 if (credential == null || credential.getSubjectX500Principal().getName(X500Principal.RFC2253).equals("")) {
816                         log.info("Request is from an unauthenticated service provider.");
817                         return null;
818
819                 } else {
820                         log.info("Request contains credential: ("
821                                         + credential.getSubjectX500Principal().getName(X500Principal.RFC2253) + ").");
822                         //Mockup old requester name for requests from < 1.2 targets
823                         if (fromLegacyProvider(req)) {
824                                 String legacyName = ShibPOSTProfile.getHostNameFromDN(credential.getSubjectX500Principal());
825                                 if (legacyName == null) {
826                                         log.error("Unable to extract legacy requester name from certificate subject.");
827                                 }
828
829                                 log.info("Request from legacy service provider: (" + legacyName + ").");
830                                 return legacyName;
831
832                         } else {
833
834                                 //See if we have metadata for this provider
835                                 Provider provider = lookup(relyingParty.getProviderId());
836                                 if (provider == null) {
837                                         log.info("No metadata found for provider: (" + relyingParty.getProviderId() + ").");
838                                         log.info("Treating remote provider as unauthenticated.");
839                                         return null;
840                                 }
841
842                                 //Make sure that the suppplied credential is valid for the
843                                 // selected relying party
844                                 if (isValidCredential(provider, credential)) {
845                                         log.info("Supplied credential validated for this provider.");
846                                         log.info("Request from service provider: (" + relyingParty.getProviderId() + ").");
847                                         return relyingParty.getProviderId();
848                                 } else {
849                                         log.error("Supplied credential ("
850                                                         + credential.getSubjectX500Principal().getName(X500Principal.RFC2253)
851                                                         + ") is NOT valid for provider (" + relyingParty.getProviderId() + ").");
852                                         throw new InvalidProviderCredentialException("Invalid credential.");
853                                 }
854                         }
855                 }
856         }
857
858         //TODO this should be renamed, since it is now only one type of response
859         // that we can send
860         public void sendSAMLResponse(HttpServletResponse resp, SAMLAttribute[] attrs, SAMLRequest samlRequest,
861                         RelyingParty relyingParty, SAMLException exception) throws IOException {
862
863                 SAMLException ourSE = null;
864                 SAMLResponse samlResponse = null;
865
866                 try {
867                         if (attrs == null || attrs.length == 0) {
868                                 //No attribute found
869                                 samlResponse = new SAMLResponse(samlRequest.getId(), null, null, exception);
870                         } else {
871
872                                 SAMLAttributeQuery attributeQuery = (SAMLAttributeQuery) samlRequest.getQuery();
873
874                                 //Reference requested subject
875                                 SAMLSubject rSubject = (SAMLSubject) attributeQuery.getSubject().clone();
876
877                                 //Set appropriate audience
878                                 ArrayList audiences = new ArrayList();
879                                 if (relyingParty.getProviderId() != null) {
880                                         audiences.add(relyingParty.getProviderId());
881                                 }
882                                 if (relyingParty.getName() != null && !relyingParty.getName().equals(relyingParty.getProviderId())) {
883                                         audiences.add(relyingParty.getName());
884                                 }
885                                 SAMLCondition condition = new SAMLAudienceRestrictionCondition(audiences);
886
887                                 //Put all attributes into an assertion
888                                 SAMLStatement statement = new SAMLAttributeStatement(rSubject, Arrays.asList(attrs));
889
890                                 //Set assertion expiration to longest attribute expiration
891                                 long max = 0;
892                                 for (int i = 0; i < attrs.length; i++) {
893                                         if (max < attrs[i].getLifetime()) {
894                                                 max = attrs[i].getLifetime();
895                                         }
896                                 }
897                                 Date now = new Date();
898                                 Date then = new Date(now.getTime() + (max * 1000)); //max is in
899                                 // seconds
900
901                                 SAMLAssertion sAssertion = new SAMLAssertion(relyingParty.getIdentityProvider().getProviderId(), now,
902                                                 then, Collections.singleton(condition), null, Collections.singleton(statement));
903
904                                 samlResponse = new SAMLResponse(samlRequest.getId(), null, Collections.singleton(sAssertion), exception);
905                                 addSignatures(samlResponse, relyingParty);
906                         }
907                 } catch (SAMLException se) {
908                         ourSE = se;
909                 } catch (CloneNotSupportedException ex) {
910                         ourSE = new SAMLException(SAMLException.RESPONDER, ex);
911
912                 } finally {
913
914                         if (log.isDebugEnabled()) {
915                                 try {
916                                         log.debug("Dumping generated SAML Response:"
917                                                         + System.getProperty("line.separator")
918                                                         + new String(
919                                                                         new BASE64Decoder().decodeBuffer(new String(samlResponse.toBase64(), "ASCII")),
920                                                                         "UTF8"));
921                                 } catch (SAMLException e) {
922                                         log.error("Encountered an error while decoding SAMLReponse for logging purposes.");
923                                 } catch (IOException e) {
924                                         log.error("Encountered an error while decoding SAMLReponse for logging purposes.");
925                                 }
926                         }
927
928                         binding.respond(resp, samlResponse, ourSE);
929                 }
930         }
931
932         private static void addSignatures(SAMLResponse reponse, RelyingParty relyingParty) throws SAMLException {
933
934                 //TODO make sure this signing optionally happens according to origin.xml params
935
936                 //Sign the assertions, if appropriate
937                 if (relyingParty.getIdentityProvider().getAssertionSigningCredential() != null
938                                 && relyingParty.getIdentityProvider().getAssertionSigningCredential().getPrivateKey() != null) {
939
940                         String assertionAlgorithm;
941                         if (relyingParty.getIdentityProvider().getAssertionSigningCredential().getCredentialType() == Credential.RSA) {
942                                 assertionAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1;
943                         } else if (relyingParty.getIdentityProvider().getAssertionSigningCredential().getCredentialType() == Credential.DSA) {
944                                 assertionAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_DSA;
945                         } else {
946                                 throw new InvalidCryptoException(SAMLException.RESPONDER,
947                                                 "The Shibboleth IdP currently only supports signing with RSA and DSA keys.");
948                         }
949
950                         ((SAMLAssertion) reponse.getAssertions().next()).sign(assertionAlgorithm, relyingParty
951                                         .getIdentityProvider().getAssertionSigningCredential().getPrivateKey(), Arrays.asList(relyingParty
952                                         .getIdentityProvider().getAssertionSigningCredential().getX509CertificateChain()));
953                 }
954
955                 //Sign the response, if appropriate
956                 if (relyingParty.getIdentityProvider().getResponseSigningCredential() != null
957                                 && relyingParty.getIdentityProvider().getResponseSigningCredential().getPrivateKey() != null) {
958
959                         String responseAlgorithm;
960                         if (relyingParty.getIdentityProvider().getResponseSigningCredential().getCredentialType() == Credential.RSA) {
961                                 responseAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1;
962                         } else if (relyingParty.getIdentityProvider().getResponseSigningCredential().getCredentialType() == Credential.DSA) {
963                                 responseAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_DSA;
964                         } else {
965                                 throw new InvalidCryptoException(SAMLException.RESPONDER,
966                                                 "The Shibboleth IdP currently only supports signing with RSA and DSA keys.");
967                         }
968
969                         reponse.sign(responseAlgorithm, relyingParty.getIdentityProvider().getResponseSigningCredential()
970                                         .getPrivateKey(), Arrays.asList(relyingParty.getIdentityProvider().getResponseSigningCredential()
971                                         .getX509CertificateChain()));
972                 }
973         }
974
975         private boolean useArtifactProfile(Provider provider, String acceptanceURL) {
976
977                 //Default to POST if we have no metadata
978                 if (provider == null) { return false; }
979
980                 //Default to POST if we have incomplete metadata
981                 ProviderRole[] roles = provider.getRoles();
982                 if (roles.length == 0) { return false; }
983
984                 for (int i = 0; roles.length > i; i++) {
985                         if (roles[i] instanceof SPProviderRole) {
986                                 Endpoint[] endpoints = ((SPProviderRole) roles[i]).getAssertionConsumerServiceURLs();
987
988                                 for (int j = 0; endpoints.length > j; j++) {
989                                         if (acceptanceURL.equals(endpoints[j].getLocation())
990                                                         && "urn:oasis:names:tc:SAML:1.0:profiles:artifact-01".equals(endpoints[j].getBinding())) { return true; }
991                                 }
992                         }
993                 }
994                 //Default to POST if we have incomplete metadata
995                 return false;
996         }
997
998         protected static void validateEngineData(HttpServletRequest req) throws InvalidClientDataException {
999
1000                 if ((req.getRemoteUser() == null) || (req.getRemoteUser().equals(""))) { throw new InvalidClientDataException(
1001                                 "Unable to authenticate remote user"); }
1002                 if ((req.getRemoteAddr() == null) || (req.getRemoteAddr().equals(""))) { throw new InvalidClientDataException(
1003                                 "Unable to obtain client address."); }
1004         }
1005
1006         protected static boolean isValidAssertionConsumerURL(Provider provider, String shireURL)
1007                         throws InvalidClientDataException {
1008
1009                 ProviderRole[] roles = provider.getRoles();
1010                 if (roles.length == 0) {
1011                         log.info("Inappropriate metadata for provider.");
1012                         return false;
1013                 }
1014
1015                 for (int i = 0; roles.length > i; i++) {
1016                         if (roles[i] instanceof SPProviderRole) {
1017                                 Endpoint[] endpoints = ((SPProviderRole) roles[i]).getAssertionConsumerServiceURLs();
1018                                 for (int j = 0; endpoints.length > j; j++) {
1019                                         if (shireURL.equals(endpoints[j].getLocation())) { return true; }
1020                                 }
1021                         }
1022                 }
1023                 log.info("Supplied consumer URL not found in metadata.");
1024                 return false;
1025         }
1026
1027         protected void createPOSTForm(HttpServletRequest req, HttpServletResponse res, byte[] buf) throws IOException,
1028                         ServletException {
1029
1030                 //Hardcoded to ASCII to ensure Base64 encoding compatibility
1031                 req.setAttribute("assertion", new String(buf, "ASCII"));
1032
1033                 if (log.isDebugEnabled()) {
1034                         try {
1035                                 log.debug("Dumping generated SAML Response:" + System.getProperty("line.separator")
1036                                                 + new String(new BASE64Decoder().decodeBuffer(new String(buf, "ASCII")), "UTF8"));
1037                         } catch (IOException e) {
1038                                 log.error("Encountered an error while decoding SAMLReponse for logging purposes.");
1039                         }
1040                 }
1041
1042                 //TODO rename from hs.jsp to more appropriate name
1043                 RequestDispatcher rd = req.getRequestDispatcher("/hs.jsp");
1044                 rd.forward(req, res);
1045         }
1046
1047         protected void handleSSOError(HttpServletRequest req, HttpServletResponse res, Exception e)
1048                         throws ServletException, IOException {
1049
1050                 req.setAttribute("errorText", e.toString());
1051                 req.setAttribute("requestURL", req.getRequestURI().toString());
1052                 RequestDispatcher rd = req.getRequestDispatcher("/hserror.jsp");
1053                 //TODO rename hserror.jsp to a more appropriate name
1054                 rd.forward(req, res);
1055         }
1056
1057         private class Semaphore {
1058
1059                 private int value;
1060
1061                 public Semaphore(int value) {
1062
1063                         this.value = value;
1064                 }
1065
1066                 public synchronized void enter() throws InterruptedException {
1067
1068                         --value;
1069                         if (value < 0) {
1070                                 wait();
1071                         }
1072                 }
1073
1074                 public synchronized void exit() {
1075
1076                         ++value;
1077                         notify();
1078                 }
1079         }
1080
1081         private class InvalidProviderCredentialException extends Exception {
1082
1083                 public InvalidProviderCredentialException(String message) {
1084
1085                         super(message);
1086                 }
1087         }
1088
1089         abstract class SSOProfileHandler {
1090
1091                 abstract String getHandlerName();
1092
1093                 abstract String getRemoteProviderId(HttpServletRequest req);
1094
1095                 abstract boolean validForRequest(HttpServletRequest request);
1096
1097                 abstract boolean preProcessHook(HttpServletRequest request, HttpServletResponse response) throws IOException;
1098
1099                 abstract SAMLAssertion[] processHook(HttpServletRequest request, HSRelyingParty relyingParty,
1100                                 Provider provider, SAMLNameIdentifier nameId, String authenticationMethod, Date authTime)
1101                                 throws SAMLException, IOException;
1102
1103                 abstract String getSAMLTargetParameter(HttpServletRequest request, HSRelyingParty relyingParty,
1104                                 Provider provider);
1105
1106                 abstract String getAcceptanceURL(HttpServletRequest request, HSRelyingParty relyingParty, Provider provider)
1107                                 throws InvalidClientDataException;
1108         }
1109
1110 }
1111
1112 class InvalidClientDataException extends Exception {
1113
1114         public InvalidClientDataException(String message) {
1115
1116                 super(message);
1117         }
1118
1119 }