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