Consolidated exception and status handling into a single class.
[shibboleth/sp.git] / shib-target / shibrpc-server.cpp
index 2cd636b..8e084aa 100644 (file)
@@ -1,4 +1,53 @@
 /*
+ * The Shibboleth License, Version 1.
+ * Copyright (c) 2002
+ * University Corporation for Advanced Internet Development, Inc.
+ * All rights reserved
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution, if any, must include
+ * the following acknowledgment: "This product includes software developed by
+ * the University Corporation for Advanced Internet Development
+ * <http://www.ucaid.edu>Internet2 Project. Alternately, this acknowledegement
+ * may appear in the software itself, if and wherever such third-party
+ * acknowledgments normally appear.
+ *
+ * Neither the name of Shibboleth nor the names of its contributors, nor
+ * Internet2, nor the University Corporation for Advanced Internet Development,
+ * Inc., nor UCAID may be used to endorse or promote products derived from this
+ * software without specific prior written permission. For written permission,
+ * please contact shibboleth@shibboleth.org
+ *
+ * Products derived from this software may not be called Shibboleth, Internet2,
+ * UCAID, or the University Corporation for Advanced Internet Development, nor
+ * may Shibboleth appear in their name, without prior written permission of the
+ * University Corporation for Advanced Internet Development.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND WITH ALL FAULTS. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE DISCLAIMED AND THE ENTIRE RISK
+ * OF SATISFACTORY QUALITY, PERFORMANCE, ACCURACY, AND EFFORT IS WITH LICENSEE.
+ * IN NO EVENT SHALL THE COPYRIGHT OWNER, CONTRIBUTORS OR THE UNIVERSITY
+ * CORPORATION FOR ADVANCED INTERNET DEVELOPMENT, INC. BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
  * shibrpc-server.cpp -- SHIBRPC Server implementation.  Originally created
  *                       as shibrpc-server-stubs.c; make sure that the function
  *                       prototypes here match those in shibrpc.x.
  * $Id$
  */
 
-#include "shib-target.h"
+#include "internal.h"
+
 #include "shibrpc.h"
-#include "ccache-utils.h"
 
-#include <log4cpp/Category.hh>
 #include <sstream>
 
 #ifdef HAVE_LIBDMALLOCXX
 #include <dmalloc.h>
 #endif
 
+#include <log4cpp/Category.hh>
+
 using namespace std;
+using namespace log4cpp;
 using namespace saml;
 using namespace shibboleth;
 using namespace shibtarget;
 
-static std::string get_threadid (const char* proc)
+static string get_threadid (const char* proc)
 {
   static u_long counter = 0;
   ostringstream buf;
@@ -32,379 +83,437 @@ static std::string get_threadid (const char* proc)
   return buf.str();
 }
 
-static log4cpp::Category& get_category (void)
+static Category& get_category (void)
 {
-  string ctx = "shibtarget.rpc-server";
-  return log4cpp::Category::getInstance(ctx);
+  return Category::getInstance("shibtarget.rpc-server");
 }
 
 extern "C" bool_t
-shibrpc_ping_1_svc(int *argp, int *result, struct svc_req *rqstp)
+shibrpc_ping_2_svc(int *argp, int *result, struct svc_req *rqstp)
 {
   *result = (*argp)+1;
   return TRUE;
 }
 
-void set_rpc_status(ShibRpcError *error, ShibRpcStatus status,
-                   const char* msg, const char* origin)
-{
-  error->status = status;
-  if (status) {
-    error->ShibRpcError_u.e.error = strdup(msg);
-    error->ShibRpcError_u.e.origin = strdup(origin);
-  }
-}
-
-void set_rpc_status_x(ShibRpcError *error, ShibRpcStatus status,
-                     const char* msg, const XMLCh* origin)
-{
-  if (!status)
-    return set_rpc_status(error, status, NULL, NULL);
-  auto_ptr<char> orig(XMLString::transcode(origin));
-  return set_rpc_status(error, status, msg, orig.get());
-}
-
 extern "C" bool_t
-shibrpc_session_is_valid_1_svc(shibrpc_session_is_valid_args_1 *argp,
-                              shibrpc_session_is_valid_ret_1 *result,
-                              struct svc_req *rqstp)
+shibrpc_get_session_2_svc(
+    shibrpc_get_session_args_2 *argp,
+    shibrpc_get_session_ret_2 *result,
+    struct svc_req *rqstp
+    )
 {
-  log4cpp::Category& log = get_category();
-  string ctx = get_threadid("session_is_valid");
-  saml::NDC ndc(ctx);
+    Category& log = get_category();
+    string ctx = get_threadid("get_session");
+    saml::NDC ndc(ctx);
 
-  if (!argp || !result) {
-    log.error ("RPC Argument Error");
-    return FALSE;
-  }
-
-  memset (result, 0, sizeof (*result));
-  
-  log.debug ("checking: %s@%s (checkAddr=%s)",
-            argp->cookie.cookie, argp->cookie.client_addr,
-            argp->checkIPAddress ? "true" : "false");
-
-  // See if the cookie exists...
-  CCacheEntry *entry = g_shibTargetCCache->find(argp->cookie.cookie);
-
-  // If not, leave now..
-  if (!entry) {
-    log.debug ("Not found");
-    set_rpc_status(&result->status, SHIBRPC_NO_SESSION,
-                  "No session exists for this cookie", "");
-    return TRUE;
-  }
-
-  // TEST the session...
-  try {
+    if (!argp || !result) {
+        log.error ("RPC Argument Error");
+        return FALSE;
+    }
 
-    // Grab the origin
-    const XMLCh* origin = entry->getStatement()->getSubject()->getNameQualifier();
+    memset (result, 0, sizeof (*result));
+    result->provider_id = strdup("");
+    result->auth_statement = strdup("");
+    result->attr_response_pre = strdup("");
+    result->attr_response_post = strdup("");
 
-    // Verify the address is the same
-    if (argp->checkIPAddress) {
-      log.debug ("Checking address against %s", entry->getClientAddress());
-      if (strcmp (argp->cookie.client_addr, entry->getClientAddress())) {
-       log.debug ("IP Address mismatch");
+    log.debug ("checking: %s@%s", argp->cookie, argp->client_addr);
 
-       throw ShibTargetException(SHIBRPC_IPADDR_MISMATCH,
-  "Your IP address does not match the address in the original authentication.",
-                                 origin);
-      }
+    // See if the session exists...
+  
+    IConfig* conf=ShibTargetConfig::getConfig().getINI();
+    Locker locker(conf);
+    log.debug ("application: %s", argp->application_id);
+    const IApplication* app=conf->getApplication(argp->application_id);
+    if (!app) {
+        // Something's horribly wrong.
+        log.error("couldn't find application for session");
+        SAMLException ex("Unable to locate application for session, deleted?");
+        ostringstream os;
+        os << ex;
+        result->status=strdup(os.str().c_str());
+        return TRUE;
     }
 
-    // and that the session is still valid...
-    if (!entry->isSessionValid(argp->lifetime, argp->timeout)) {
-      log.debug ("Session expired");
-      throw ShibTargetException(SHIBRPC_SESSION_EXPIRED,
-                               "Your session has expired.  Re-authenticate.",
-                               origin);
+    bool checkIPAddress=true;
+    int lifetime=0,timeout=0;
+    const IPropertySet* props=app->getPropertySet("Sessions");
+    if (props) {
+        pair<bool,unsigned int> p=props->getUnsignedInt("lifetime");
+        if (p.first)
+            lifetime = p.second;
+        p=props->getUnsignedInt("timeout");
+        if (p.first)
+            timeout = p.second;
+        pair<bool,bool> pcheck=props->getBool("checkAddress");
+        if (pcheck.first)
+            checkIPAddress = pcheck.second;
     }
-
-    // and now try to prefetch the attributes .. this could cause an
-    // "error", which is why we call it here.
-    try {
-      log.debug ("resource: %s", argp->url);
-      Resource r(argp->url);
-      entry->preFetch(r,15);   // give a 15-second window for the RM
-
-    } catch (SAMLException &e) {
-      log.debug ("prefetch failed with a SAML Exception: %s", e.what());
-      ostringstream os;
-      os << e;
-      throw ShibTargetException(SHIBRPC_SAML_EXCEPTION, os.str(), origin);
-
-    } catch (...) {
-      log.error ("prefetch caught an unknown exception");
-      throw ShibTargetException(SHIBRPC_UNKNOWN_ERROR,
-               "An unknown error occured while pre-fetching attributes.",
-                               origin);
+    
+    ISessionCacheEntry* entry = conf->getSessionCache()->find(argp->cookie,app);
+
+    // If not, leave now..
+    if (!entry) {
+        log.debug("session not found");
+        InvalidSessionException ex("No session exists for key value ($session_id)",namedparams(1,"session_id",argp->cookie));
+        ostringstream os;
+        os << ex;
+        result->status=strdup(os.str().c_str());
+        return TRUE;
     }
 
-  } catch (ShibTargetException &e) {
-    entry->release();
-    g_shibTargetCCache->remove (argp->cookie.cookie);
-    set_rpc_status_x(&result->status, e.which(), e.what(), e.where());
-    return TRUE;
-  }
-
-  // Ok, just release it.
-  entry->release();
-
-  // ok, we've succeeded..
-  set_rpc_status(&result->status, SHIBRPC_OK, NULL, NULL);
-  log.debug ("session ok");
-  return TRUE;
-}
-
-extern "C" bool_t
-shibrpc_new_session_1_svc(shibrpc_new_session_args_1 *argp,
-                         shibrpc_new_session_ret_1 *result, struct svc_req *rqstp)
-{
-  log4cpp::Category& log = get_category();
-  string ctx = get_threadid("new_session");
-  saml::NDC ndc(ctx);
-
-  if (!argp || !result) {
-    log.error ("Invalid RPC Arguments");
-    return FALSE;
-  }
-
-  // Initialize the result structure
-  memset (result, 0, sizeof(*result));
-  result->cookie = strdup ("");
-
-  log.debug ("creating session for %s", argp->client_addr);
-  log.debug ("shire location: %s", argp->shire_location);
-
-  XMLByte* post=reinterpret_cast<XMLByte*>(argp->saml_post);
-  auto_ptr<XMLCh> location(XMLString::transcode(argp->shire_location));
-
-  // Pull in the Policies
-  Iterator<const XMLCh*> policies=ShibTargetConfig::getConfig().getPolicies();
-
-  // And grab the Profile
-  // XXX: Create a "Global" POSTProfile instance per location...
-  log.debug ("create the POST profile (%d policies)", policies.size());
-  ShibPOSTProfile *profile =
-    ShibPOSTProfileFactory::getInstance(policies,
-                                       location.get(),
-                                       3600);
-
-  SAMLResponse* r = NULL;
-  SAMLAuthenticationStatement* auth_st = NULL;
-  XMLCh* origin = NULL;
-
-  try
-  {
-    try
-    {
-      // Make sure we've got a profile
-      if (!profile)
-       throw ShibTargetException(SHIBRPC_INTERNAL_ERROR,
-                                 "Failed to obtain the profile");
-
-      // Try and accept the response...
-      log.debug ("Trying to accept the post");
-      r = profile->accept(post, &origin);
-
-      // Make sure we got a response
-      if (!r)
-       throw ShibTargetException(SHIBRPC_RESPONSE_MISSING,
-                                 "Failed to accept the response.",
-                                 origin);
-
-      // Find the SSO Assertion
-      log.debug ("Get the SSOAssertion");
-      SAMLAssertion* ssoAssertion = profile->getSSOAssertion(*r);
-
-      // Check against the replay cache
-      log.debug ("check replay cache");
-      if (profile->checkReplayCache(*ssoAssertion) == false)
-       throw ShibTargetException(SHIBRPC_ASSERTION_REPLAYED,
-                                 "Duplicate assertion found.",
-                                 origin);
-
-      // Get the authentication statement we need.
-      log.debug ("get SSOStatement");
-      auth_st = profile->getSSOStatement(*ssoAssertion);
-
-      // Maybe verify the origin address....
-      if (argp->checkIPAddress) {
-       log.debug ("check IP Address");
-
-       // Verify the client address exists
-       const XMLCh* ip = auth_st->getSubjectIP();
-       if (!ip)
-         throw ShibTargetException(SHIBRPC_IPADDR_MISSING,
-                   "The IP Address provided by your origin site was missing.",
-                                   origin);
-       
-       log.debug ("verify client address");
-       // Verify the client address matches authentication
-       auto_ptr<char> this_ip(XMLString::transcode(ip));
-       if (strcmp (argp->client_addr, this_ip.get()))
-         throw ShibTargetException(SHIBRPC_IPADDR_MISMATCH,
-           "The IP address provided by your origin site did not match "
-           "your current address.  "
-           "To correct this problem you may need to bypass a local proxy server.",
-                                   origin);
-      }
+    // TEST the session...
+    try {
+        // Verify the address is the same
+        if (checkIPAddress) {
+            log.debug("Checking address against %s", entry->getClientAddress());
+            if (strcmp(argp->client_addr, entry->getClientAddress())) {
+                log.debug("client address mismatch");
+                InvalidSessionException ex(
+                    SESSION_E_ADDRESSMISMATCH,
+                    "Your IP address (%1) does not match the address recorded at the time the session was established.",
+                    params(1,argp->client_addr)
+                    );
+                Metadata m(app->getMetadataProviders());
+                annotateException(ex,m.lookup(entry->getProviderId())); // throws it
+            }
+        }
+
+        // and that the session is still valid...
+        if (!entry->isValid(lifetime,timeout)) {
+            log.debug("session expired");
+            InvalidSessionException ex(SESSION_E_EXPIRED, "Your session has expired, and you must re-authenticate.");
+            Metadata m(app->getMetadataProviders());
+            annotateException(ex,m.lookup(entry->getProviderId())); // throws it
+        }
+
+        // Set profile and provider
+        result->profile = entry->getProfile();
+        free(result->provider_id);
+        result->provider_id = strdup(entry->getProviderId());
+     
+        // Now grab the serialized authentication statement and responses
+        ostringstream os;
+        os << *(entry->getAuthnStatement());
+        free(result->auth_statement);
+        result->auth_statement = strdup(os.str().c_str());
+      
+        ISessionCacheEntry::CachedResponse responses=entry->getResponse();
+        if (!responses.empty()) {
+            os.str("");
+            os << *responses.unfiltered;
+            free(result->attr_response_pre);
+            result->attr_response_pre = strdup(os.str().c_str());
+
+            os.str("");
+            os << *responses.filtered;
+            free(result->attr_response_post);
+            result->attr_response_post = strdup(os.str().c_str());
+        }
     }
-    catch (SAMLException &e)    // XXX refine this handler to catch and log different profile exceptions
-    {
-      log.error ("received SAML exception: %s", e.what());
-      ostringstream os;
-      os << e;
-      throw ShibTargetException (SHIBRPC_SAML_EXCEPTION, os.str(), origin);
+    catch (SAMLException &e) {
+        entry->unlock();
+        log.error("caught SAML exception: %s", e.what());
+        conf->getSessionCache()->remove(argp->cookie);
+        ostringstream os;
+        os << e;
+        result->status = strdup(os.str().c_str());
+      
+        // Transaction Logging
+        STConfig& stc=static_cast<STConfig&>(ShibTargetConfig::getConfig());
+        stc.getTransactionLog().infoStream() <<
+            "Destroyed invalid session (ID: " <<
+                argp->cookie <<
+            ") with (applicationId: " <<
+                argp->application_id <<
+            "), request was from (ClientAddress: " <<
+                argp->client_addr <<
+            ")";
+        stc.releaseTransactionLog();
+        return TRUE;
     }
-    catch (XMLException &e)
-    {
-      log.error ("received XML exception");
-      auto_ptr<char> msg(XMLString::transcode(e.getMessage()));
-      throw ShibTargetException (SHIBRPC_XML_EXCEPTION, msg.get(), origin);
+#ifndef _DEBUG
+    catch (...) {
+        log.error("caught unknown exception");
+        InvalidSessionException ex("An unexpected error occurred while validating your session, and you must re-authenticate.");
+        Metadata m(app->getMetadataProviders());
+        annotateException(ex,m.lookup(entry->getProviderId()),false);
+        entry->unlock();
+        conf->getSessionCache()->remove(argp->cookie);
+        ostringstream os;
+        os << ex;
+        result->status = strdup(os.str().c_str());
+
+        // Transaction Logging
+        STConfig& stc=static_cast<STConfig&>(ShibTargetConfig::getConfig());
+        stc.getTransactionLog().infoStream() <<
+            "Destroyed invalid session (ID: " <<
+                argp->cookie <<
+            ") with (applicationId: " <<
+                argp->application_id <<
+            "), request was from (ClientAddress: " <<
+                argp->client_addr <<
+            ")";
+        stc.releaseTransactionLog();
+        return TRUE;
     }
-  }
-  catch (ShibTargetException &e)
-  {
-    log.info ("FAILED: %s", e.what());
-    if (r) delete r;
-    if (origin) delete origin;
-    set_rpc_status_x(&result->status, e.which(), e.what(), e.where());
-    return TRUE;
-  }
-#if 0
-  catch (...)
-  {
-    log.error ("Unknown error");
-    if (r) delete r;
-    if (origin) delete origin;
-    set_rpc_status(&result->status, SHIBRPC_UNKNOWN_ERROR,
-                  "An unknown exception occurred", "");
-    return TRUE;
-  }
 #endif
 
-  // It passes all our tests -- create a new session.
-  log.info ("Creating new session");
-
-  SAMLAuthenticationStatement* as=static_cast<SAMLAuthenticationStatement*>(auth_st->clone());
-
-  // Create a new cookie
-  SAMLIdentifier id;
-  auto_ptr<char> c(XMLString::transcode(id));
-  char *cookie = c.get();
-
-  // Cache this session with the cookie
-  g_shibTargetCCache->insert(cookie, as, argp->client_addr);
-
-  // Delete the response...
-  delete r;
-
-  // Delete the origin...
-  delete origin;
-
-  // And let the user know.
-  free (result->cookie);
-  result->cookie = strdup(cookie);
-  set_rpc_status(&result->status, SHIBRPC_OK, NULL, NULL);
-
-  log.debug ("new session id: %s", cookie);
-  return TRUE;
+    // Ok, just release it.
+    entry->unlock();
+    log.debug ("session ok");
+    result->status=strdup("");
+    return TRUE;
 }
 
 extern "C" bool_t
-shibrpc_get_assertions_1_svc(shibrpc_get_assertions_args_1 *argp,
-                       shibrpc_get_assertions_ret_1 *result, struct svc_req *rqstp)
+shibrpc_new_session_2_svc(
+    shibrpc_new_session_args_2 *argp,
+    shibrpc_new_session_ret_2 *result,
+    struct svc_req *rqstp
+    )
 {
-  log4cpp::Category& log = get_category();
-  string ctx = get_threadid("get_assertions");
-  saml::NDC ndc(ctx);
+    Category& log = get_category();
+    string ctx=get_threadid("new_session");
+    saml::NDC ndc(ctx);
 
-  if (!argp || !result) {
-    log.error ("Invalid RPC arguments");
-    return FALSE;
-  }
+    if (!argp || !result) {
+        log.error ("Invalid RPC Arguments");
+        return FALSE;
+    }
 
-  memset (result, 0, sizeof (*result));
+    // Initialize the result structure
+    memset (result, 0, sizeof(*result));
+    result->cookie = strdup ("");
+    result->target = strdup ("");
+
+    log.debug ("creating session for %s", argp->client_addr);
+    log.debug ("recipient: %s", argp->recipient);
+    log.debug ("application: %s", argp->application_id);
+
+    auto_ptr_XMLCh recipient(argp->recipient);
+
+    // Access the application config.
+    IConfig* conf=ShibTargetConfig::getConfig().getINI();
+    Locker locker(conf);
+    const IApplication* app=conf->getApplication(argp->application_id);
+    if (!app) {
+        // Something's horribly wrong. Flush the session.
+        log.error ("couldn't find application for session");
+        SAMLException ex("Unable to locate application for session, deleted?");
+        ostringstream os;
+        os << ex;
+        result->status=strdup(os.str().c_str());
+        return TRUE;
+    }
 
-  log.debug ("get attrs for client at %s", argp->cookie.client_addr);
-  log.debug ("cookie: %s", argp->cookie.cookie);
-  log.debug ("resource: %s", argp->url);
+    bool checkIPAddress=true;
+    const IPropertySet* props=app->getPropertySet("Sessions");
+    if (props) {
+        pair<bool,bool> pcheck=props->getBool("checkAddress");
+        if (pcheck.first)
+            checkIPAddress = pcheck.second;
+    }
 
-  // Find this session
-  CCacheEntry* entry = g_shibTargetCCache->find(argp->cookie.cookie);
+    pair<bool,bool> checkReplay=pair<bool,bool>(false,false);
+    props=app->getPropertySet("Sessions");
+    if (props)
+        checkReplay=props->getBool("checkReplay");
+    const IRoleDescriptor* role=NULL;
+    Metadata m(app->getMetadataProviders());
+    SAMLBrowserProfile::BrowserProfileResponse bpr;
+    try {
+        auto_ptr<SAMLBrowserProfile::ArtifactMapper> artifactMapper(app->getArtifactMapper());
+      
+        // Try and run the profile.
+        log.debug("executing browser profile...");
+        int allowed = 0;
+        if (argp->supported_profiles & SAML11_POST)
+            allowed |= SAMLBrowserProfile::Post;
+        if (argp->supported_profiles & SAML11_ARTIFACT)
+            allowed |= SAMLBrowserProfile::Artifact;
+        bpr=app->getBrowserProfile()->receive(
+            argp->packet,
+            recipient.get(),
+            allowed,
+            (!checkReplay.first || checkReplay.second) ? conf->getReplayCache() : NULL,
+            artifactMapper.get()
+            );
+
+        // Blow it away to clear any locks that might be held.
+        delete artifactMapper.release();
+
+        // Try and map to metadata (again).
+        // Once the metadata layer is in the SAML core, the repetition should be fixed.
+        const IEntityDescriptor* provider=m.lookup(bpr.assertion->getIssuer());
+        if (!provider && bpr.authnStatement->getSubject()->getNameIdentifier()->getNameQualifier())
+            provider=m.lookup(bpr.authnStatement->getSubject()->getNameIdentifier()->getNameQualifier());
+        if (provider) {
+            const IIDPSSODescriptor* IDP=provider->getIDPSSODescriptor(saml::XML::SAML11_PROTOCOL_ENUM);
+            role=IDP;
+        }
+        
+        // This isn't likely, since the profile must have found a role.
+        if (!role) {
+            MetadataException ex("Unable to locate role-specific metadata for identity provider.");
+            annotateException(ex,provider); // throws it
+        }
+    
+        // Maybe verify the origin address....
+        if (checkIPAddress) {
+            log.debug("verify client address");
+            // Verify the client address exists
+            const XMLCh* ip = bpr.authnStatement->getSubjectIP();
+            if (ip && *ip) {
+                // Verify the client address matches authentication
+                auto_ptr_char this_ip(ip);
+                if (strcmp(argp->client_addr, this_ip.get())) {
+                    FatalProfileException ex(
+                        SESSION_E_ADDRESSMISMATCH,
+                       "Your client's current address ($1) differs from the one used when you authenticated "
+                        "to your identity provider. To correct this problem, you may need to bypass a proxy server. "
+                        "Please contact your local support staff or help desk for assistance.",
+                        params(1,argp->client_addr)
+                        );
+                    annotateException(ex,role); // throws it
+                }
+            }
+        }
+      
+        // Verify condition(s) on authentication assertion.
+        // Attribute assertions get filtered later, essentially just like an AAP.
+        Iterator<SAMLCondition*> conditions=bpr.assertion->getConditions();
+        while (conditions.hasNext()) {
+            SAMLCondition* cond=conditions.next();
+            const SAMLAudienceRestrictionCondition* ac=dynamic_cast<const SAMLAudienceRestrictionCondition*>(cond);
+            if (!ac) {
+                ostringstream os;
+                os << *cond;
+                log.error("Unrecognized Condition in authentication assertion (%s), tossing it.",os.str().c_str());
+                FatalProfileException ex("Unable to create session due to unrecognized condition in authentication assertion.");
+                annotateException(ex,role); // throws it
+            }
+            else if (!ac->eval(app->getAudiences())) {
+                ostringstream os;
+                os << *ac;
+                log.error("Unacceptable AudienceRestrictionCondition in authentication assertion (%s), tossing it.",os.str().c_str());
+                FatalProfileException ex("Unable to create session due to unacceptable AudienceRestrictionCondition in authentication assertion.");
+                annotateException(ex,role); // throws it
+            }
+        }
+    }
+    catch (SAMLException& e) {
+        bpr.clear();
+        log.error("caught SAML exception: %s", e.what());
+        ostringstream os;
+        os << e;
+        result->status = strdup(os.str().c_str());
+        return TRUE;
+    }
+#ifndef _DEBUG
+    catch (...) {
+        log.error("unknown error");
+        bpr.clear();
+        SAMLException e("An unexpected error occurred while creating your session.");
+        annotateException(e,role,false);
+        ostringstream os;
+        os << e;
+        result->status = strdup(os.str().c_str());
+        return TRUE;
+    }
+#endif
 
-  // If it does not exist, leave now..
-  if (!entry) {
-    log.error ("No Session");
-    set_rpc_status(&result->status, SHIBRPC_NO_SESSION,
-                  "getattrs Internal error: no session", "");
-    return TRUE;
-  }
-
-  // Grab the origin
-  const XMLCh* origin = entry->getStatement()->getSubject()->getNameQualifier();
-
-  // Validate the client address (again?)
-  if (argp->checkIPAddress &&
-      strcmp (argp->cookie.client_addr, entry->getClientAddress())) {
-    log.error ("IP Mismatch");
-    set_rpc_status_x(&result->status, SHIBRPC_IPADDR_MISMATCH,
-   "Your IP address does not match the address in the original authentication.",
-                    origin);
-    entry->release();
-    return TRUE;
-  }
-
-  try {
-    // grab the attributes for this resource
-    Resource resource(argp->url);
-    Iterator<SAMLAssertion*> iter = entry->getAssertions(resource);
-    u_int size = iter.size();
-    result->assertions.assertions_len = size;
-
-    // if we have assertions...
-    if (size) {
-
-      // Build the response section
-      ShibRpcXML* av =
-       (ShibRpcXML*) malloc (size * sizeof (ShibRpcXML));
-      result->assertions.assertions_val = av;
-
-      // and then serialize them all...
-      u_int i = 0;
-      while (iter.hasNext()) {
-       SAMLAssertion* as = iter.next();
-       ostringstream os;
-       os << *as;
-       av[i++].xml_string = strdup(os.str().c_str());
-      }
+    // It passes all our tests -- create a new session.
+    log.info("creating new session");
+
+    // Create a new session key.
+    string cookie = conf->getSessionCache()->generateKey();
+
+    // Are attributes present?
+    bool attributesPushed=false;
+    Iterator<SAMLAssertion*> assertions=bpr.response->getAssertions();
+    while (!attributesPushed && assertions.hasNext()) {
+        Iterator<SAMLStatement*> statements=assertions.next()->getStatements();
+        while (!attributesPushed && statements.hasNext()) {
+            if (dynamic_cast<SAMLAttributeStatement*>(statements.next()))
+                attributesPushed=true;
+        }
     }
-  } catch (SAMLException& e) {
-    log.error ("received SAML exception: %s", e.what());
-    ostringstream os;
-    os << e;
-    set_rpc_status_x(&result->status, SHIBRPC_SAML_EXCEPTION,
-                    strdup(os.str().c_str()), origin);
-    entry->release();
-    return TRUE;
-  }
 
-  // Now grab the serialized authentication statement
-  result->auth_statement.xml_string = strdup(entry->getSerializedStatement());
+    auto_ptr_char oname(role->getEntityDescriptor()->getId());
+    auto_ptr_char hname(bpr.authnStatement->getSubject()->getNameIdentifier()->getName());
 
-  entry->release();
+    try {
+        // Insert into cache.
+        auto_ptr<SAMLAuthenticationStatement> as(static_cast<SAMLAuthenticationStatement*>(bpr.authnStatement->clone()));
+        conf->getSessionCache()->insert(
+            cookie.c_str(),
+            app,
+            argp->client_addr,
+            (bpr.profile==SAMLBrowserProfile::Post) ? SAML11_POST : SAML11_ARTIFACT,
+            oname.get(),
+            as.get(),
+            (attributesPushed ? bpr.response : NULL),
+            role
+            );
+        as.release();   // owned by cache now
+    }
+    catch (SAMLException& e) {
+        bpr.clear();
+        log.error("caught SAML exception: %s", e.what());
+        ostringstream os;
+        os << e;
+        result->status = strdup(os.str().c_str());
+        return TRUE;
+    }
+#ifndef _DEBUG
+    catch (...) {
+        log.error("unknown error");
+        bpr.clear();
+        SAMLException e("An unexpected error occurred while creating your session.");
+        annotateException(e,role,false);
+        ostringstream os;
+        os << e;
+        result->status = strdup(os.str().c_str());
+        return TRUE;
+    }
+#endif
 
-  // and let it fly
-  set_rpc_status(&result->status, SHIBRPC_OK, NULL, NULL);
+    // And let the user know.
+    if (result->cookie) free(result->cookie);
+    if (result->target) free(result->target);
+    result->cookie = strdup(cookie.c_str());
+    result->target = strdup(bpr.TARGET.c_str());
+    result->status = strdup("");
 
-  log.debug ("returning");
-  return TRUE;
+    // Maybe delete the response...
+    if (!attributesPushed)
+        bpr.clear();
+
+    log.debug("new session id: %s", cookie.c_str());
+  
+    // Transaction Logging
+    STConfig& stc=static_cast<STConfig&>(ShibTargetConfig::getConfig());
+    stc.getTransactionLog().infoStream() <<
+        "New session (ID: " <<
+            result->cookie <<
+        ") with (applicationId: " <<
+            argp->application_id <<
+        ") for principal from (IdP: " <<
+            oname.get() <<
+        ") at (ClientAddress: " <<
+            argp->client_addr <<
+        ") with (NameIdentifier: " <<
+            hname.get() <<
+        ")";
+
+    stc.releaseTransactionLog();
+    return TRUE;
 }
 
 extern "C" int
-shibrpc_prog_1_freeresult (SVCXPRT *transp, xdrproc_t xdr_result, caddr_t result)
+shibrpc_prog_2_freeresult (SVCXPRT *transp, xdrproc_t xdr_result, caddr_t result)
 {
        xdr_free (xdr_result, result);