2 * The Shibboleth License, Version 1.
4 * University Corporation for Advanced Internet Development, Inc.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions are met:
11 * Redistributions of source code must retain the above copyright notice, this
12 * list of conditions and the following disclaimer.
14 * Redistributions in binary form must reproduce the above copyright notice,
15 * this list of conditions and the following disclaimer in the documentation
16 * and/or other materials provided with the distribution, if any, must include
17 * the following acknowledgment: "This product includes software developed by
18 * the University Corporation for Advanced Internet Development
19 * <http://www.ucaid.edu>Internet2 Project. Alternately, this acknowledegement
20 * may appear in the software itself, if and wherever such third-party
21 * acknowledgments normally appear.
23 * Neither the name of Shibboleth nor the names of its contributors, nor
24 * Internet2, nor the University Corporation for Advanced Internet Development,
25 * Inc., nor UCAID may be used to endorse or promote products derived from this
26 * software without specific prior written permission. For written permission,
27 * please contact shibboleth@shibboleth.org
29 * Products derived from this software may not be called Shibboleth, Internet2,
30 * UCAID, or the University Corporation for Advanced Internet Development, nor
31 * may Shibboleth appear in their name, without prior written permission of the
32 * University Corporation for Advanced Internet Development.
35 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
36 * AND WITH ALL FAULTS. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
37 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
38 * PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE DISCLAIMED AND THE ENTIRE RISK
39 * OF SATISFACTORY QUALITY, PERFORMANCE, ACCURACY, AND EFFORT IS WITH LICENSEE.
40 * IN NO EVENT SHALL THE COPYRIGHT OWNER, CONTRIBUTORS OR THE UNIVERSITY
41 * CORPORATION FOR ADVANCED INTERNET DEVELOPMENT, INC. BE LIABLE FOR ANY DIRECT,
42 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
43 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
44 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
45 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
46 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
47 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
52 * shib-ccache.cpp -- SHAR Credential Cache
54 * Originally from mod_shib
55 * Modified by: Derek Atkins <derek@ihtfp.com>
64 #include "shib-target.h"
65 #include "shib-threads.h"
67 #include <log4cpp/Category.hh>
72 #ifdef HAVE_LIBDMALLOCXX
78 using namespace shibboleth;
79 using namespace shibtarget;
84 ResourceEntry(SAMLResponse* response);
88 Iterator<SAMLAssertion*> getAssertions();
90 static vector<SAMLAssertion*> g_emptyVector;
93 SAMLResponse* m_response;
95 log4cpp::Category* log;
99 class InternalCCacheEntry : public CCacheEntry
102 InternalCCacheEntry(SAMLAuthenticationStatement *s, const char *client_addr);
103 ~InternalCCacheEntry();
105 virtual Iterator<SAMLAssertion*> getAssertions(Resource& resource);
106 virtual bool isSessionValid(time_t lifetime, time_t timeout);
107 virtual const char* getClientAddress() { return m_clientAddress.c_str(); }
109 void setCache(InternalCCache *cache) { m_cache = cache; }
110 time_t lastAccess() { Lock lock(access_lock); return m_lastAccess; }
113 ResourceEntry* populate(Resource& resource);
114 ResourceEntry* find(const char* resource);
115 void insert(const char* resource, ResourceEntry* entry);
116 void remove(const char* resource);
120 string m_clientAddress;
121 time_t m_sessionCreated;
125 const SAMLSubject* m_subject;
126 SAMLAuthenticationStatement* p_auth;
127 InternalCCache *m_cache;
129 map<string,ResourceEntry*> m_resources;
131 static saml::QName g_authorityKind;
132 static saml::QName g_respondWith;
134 log4cpp::Category* log;
136 // This is used to keep track of in-process "populate()" calls,
137 // to make sure that we don't try to populate the same resource
138 // in multiple threads.
139 map<string,Mutex*> populate_locks;
140 Mutex* pop_locks_lock;
143 RWLock* resource_lock;
148 ResourceLock(InternalCCacheEntry* entry, string resource);
152 Mutex* find(string& resource);
153 InternalCCacheEntry* entry;
158 class InternalCCache : public CCache
162 virtual ~InternalCCache();
164 virtual SAMLBinding* getBinding(const XMLCh* bindingProt);
165 virtual CCacheEntry* find(const char* key);
166 virtual void insert(const char* key, SAMLAuthenticationStatement *s,
167 const char *client_addr);
168 virtual void remove(const char* key);
172 SAMLBinding* m_SAMLBinding;
173 map<string,InternalCCacheEntry*> m_hashtable;
175 log4cpp::Category* log;
178 static void* cleanup_fcn(void*); // XXX Assumed an InternalCCache
180 CondWait* shutdown_wait;
181 Thread* cleanup_thread;
184 // Global Constructors & Destructors
185 CCache::~CCache() { }
187 CCache* CCache::getInstance(const char* type)
189 return (CCache*) new InternalCCache();
193 saml::QName InternalCCacheEntry::g_authorityKind(saml::XML::SAMLP_NS,L(AttributeQuery));
194 saml::QName InternalCCacheEntry::g_respondWith(saml::XML::SAML_NS,L(AttributeStatement));
195 vector<SAMLAssertion*> ResourceEntry::g_emptyVector;
198 /******************************************************************************/
199 /* InternalCCache: A Credential Cache */
200 /******************************************************************************/
202 InternalCCache::InternalCCache()
204 m_SAMLBinding=SAMLBindingFactory::getInstance();
205 string ctx="shibtarget.InternalCCache";
206 log = &(log4cpp::Category::getInstance(ctx));
207 lock = RWLock::create();
209 shutdown_wait = CondWait::create();
211 cleanup_thread = Thread::create(&cleanup_fcn, (void*)this);
214 InternalCCache::~InternalCCache()
216 // Shut down the cleanup thread and let it know...
218 shutdown_wait->signal();
219 cleanup_thread->join(NULL);
221 delete m_SAMLBinding;
222 for (map<string,InternalCCacheEntry*>::iterator i=m_hashtable.begin(); i!=m_hashtable.end(); i++)
225 delete shutdown_wait;
228 SAMLBinding* InternalCCache::getBinding(const XMLCh* bindingProt)
230 log->debug("looking for binding...");
231 if (!XMLString::compareString(bindingProt,SAMLBinding::SAML_SOAP_HTTPS)) {
232 log->debug("https binding found");
233 return m_SAMLBinding;
238 CCacheEntry* InternalCCache::find(const char* key)
240 log->debug("Find: \"%s\"", key);
241 ReadLock rwlock(lock);
243 map<string,InternalCCacheEntry*>::const_iterator i=m_hashtable.find(key);
244 if (i==m_hashtable.end()) {
245 log->debug("No Match found");
248 log->debug("Match Found.");
249 return dynamic_cast<CCacheEntry*>(i->second);
252 void InternalCCache::insert(const char* key, SAMLAuthenticationStatement *s,
253 const char *client_addr)
255 log->debug("caching new entry for \"%s\"", key);
257 InternalCCacheEntry* entry = new InternalCCacheEntry (s, client_addr);
258 entry->setCache(this);
261 m_hashtable[key]=entry;
265 void InternalCCache::remove(const char* key)
267 log->debug("removing cache entry \"key\"", key);
269 // XXX: FIXME? do we need to delete the CacheEntry?
272 m_hashtable.erase(key);
276 void InternalCCache::cleanup()
278 Mutex* mutex = Mutex::create();
282 while (shutdown == false) {
284 memset (&ts, 0, sizeof(ts));
285 ts.tv_sec = time(NULL) + 3600; // run every hour
287 shutdown_wait->timedwait(mutex, &ts);
289 if (shutdown == true)
292 // Ok, let's run through the cleanup process and clean out
293 // really old sessions. This is a two-pass process. The
294 // first pass is done holding a read-lock while we iterate over
295 // the database. The second pass doesn't need a lock because
296 // the 'deletes' will lock the database.
298 // Pass 1: iterate over the map and find all entries that have not been
300 vector<string> stale_keys;
301 time_t stale = time(NULL) - 8 * 3600; // XXX: 8 hour timeout.
304 for (map<string,InternalCCacheEntry*>::iterator i=m_hashtable.begin();
305 i != m_hashtable.end(); i++)
307 // If the last access was BEFORE the stale timeout...
308 if (i->second->lastAccess() < stale)
309 stale_keys.push_back(i->first);
313 // Pass 2: walk through the list of stale entries and remove them from
315 for (vector<string>::iterator i = stale_keys.begin();
316 i != stale_keys.end(); i++)
328 void* InternalCCache::cleanup_fcn(void* cache_p)
330 InternalCCache* cache = (InternalCCache*)cache_p;
332 // First, let's block all signals
334 sigfillset(&sigmask);
335 Thread::mask_signals(SIG_BLOCK, &sigmask, NULL);
337 // Now run the cleanup process.
341 /******************************************************************************/
342 /* InternalCCacheEntry: A Credential Cache Entry */
343 /******************************************************************************/
345 InternalCCacheEntry::InternalCCacheEntry(SAMLAuthenticationStatement *s, const char *client_addr)
346 : m_hasbinding(false)
348 string ctx = "shibtarget::InternalCCacheEntry";
349 log = &(log4cpp::Category::getInstance(ctx));
350 pop_locks_lock = Mutex::create();
351 access_lock = Mutex::create();
352 resource_lock = RWLock::create();
355 log->error("NULL auth statement");
356 throw runtime_error("InternalCCacheEntry() was passed an empty SAML Statement");
359 m_subject = s->getSubject();
361 xstring name = m_subject->getName();
362 xstring qual = m_subject->getNameQualifier();
364 auto_ptr<char> h(XMLString::transcode(name.c_str()));
365 auto_ptr<char> d(XMLString::transcode(qual.c_str()));
368 m_originSite = d.get();
370 Iterator<SAMLAuthorityBinding*> bindings = s->getBindings();
371 if (bindings.hasNext())
374 m_clientAddress = client_addr;
375 m_sessionCreated = m_lastAccess = time(NULL);
380 log->info("New Session Created...");
381 log->debug("Handle: \"%s\", Site: \"%s\", Address: %s", h.get(), d.get(),
385 InternalCCacheEntry::~InternalCCacheEntry()
387 log->debug("deleting entry for %s@%s", m_handle.c_str(), m_originSite.c_str());
389 for (map<string,ResourceEntry*>::iterator i=m_resources.begin();
390 i!=m_resources.end(); i++)
393 for (map<string,Mutex*>::iterator i=populate_locks.begin();
394 i!=populate_locks.end(); i++)
397 delete pop_locks_lock;
398 delete resource_lock;
402 bool InternalCCacheEntry::isSessionValid(time_t lifetime, time_t timeout)
404 saml::NDC ndc("isSessionValid");
405 log->debug("test session %s@%s, (lifetime=%ld, timeout=%ld)",
406 m_handle.c_str(), m_originSite.c_str(), lifetime, timeout);
407 time_t now=time(NULL);
408 if (lifetime > 0 && now > m_sessionCreated+lifetime) {
409 log->debug("session beyond lifetime");
413 // Lock the access-time from here until we return
414 Lock lock(access_lock);
415 if (timeout > 0 && now-m_lastAccess >= timeout) {
416 log->debug("session timed out");
423 Iterator<SAMLAssertion*> InternalCCacheEntry::getAssertions(Resource& resource)
425 saml::NDC ndc("getAssertions");
426 ResourceEntry* entry = populate(resource);
428 return entry->getAssertions();
429 return Iterator<SAMLAssertion*>(ResourceEntry::g_emptyVector);
432 ResourceEntry* InternalCCacheEntry::populate(Resource& resource)
434 saml::NDC ndc("populate");
435 log->debug("populating entry for %s (%s)",
436 resource.getResource(), resource.getURL());
438 // Lock the resource within this entry...
439 InternalCCacheEntry::ResourceLock lock(this, resource.getResource());
441 // Can we use what we have?
442 ResourceEntry *entry = find(resource.getResource());
444 log->debug("found resource");
445 if (entry->isValid())
448 // entry is invalid (expired) -- go fetch a new one.
449 log->debug("removing resource cache; assertion is invalid");
450 remove (resource.getResource());
454 // Nope, no entry.. Create a new resource entry
457 log->error("No binding!");
461 log->info("trying to request attributes for %s@%s -> %s",
462 m_handle.c_str(), m_originSite.c_str(), resource.getURL());
464 auto_ptr<XMLCh> resourceURL(XMLString::transcode(resource.getURL()));
465 Iterator<saml::QName> respond_withs = ArrayIterator<saml::QName>(&g_respondWith);
467 // Clone the subject...
468 // 1) I know the static_cast is safe from clone()
469 // 2) the AttributeQuery will destroy this new subject.
470 SAMLSubject* subject=static_cast<SAMLSubject*>(m_subject->clone());
472 // Build a SAML Request....
473 SAMLAttributeQuery* q=new SAMLAttributeQuery(subject,resourceURL.get(),
474 resource.getDesignators());
475 SAMLRequest* req=new SAMLRequest(respond_withs,q);
477 // Try this request against all the bindings in the AuthenticationStatement
478 // (i.e. send it to each AA in the list of bindings)
479 Iterator<SAMLAuthorityBinding*> bindings = p_auth->getBindings();
480 SAMLResponse* response = NULL;
482 while (!response && bindings.hasNext()) {
483 SAMLAuthorityBinding* binding = bindings.next();
485 log->debug("Trying binding...");
486 SAMLBinding* pBinding=m_cache->getBinding(binding->getBinding());
487 log->debug("Sending request");
488 response=pBinding->send(*binding,*req);
491 // ok, we can delete the request now.
494 // Make sure we got a response
496 log->info ("No Response");
500 entry = new ResourceEntry(response);
501 insert (resource.getResource(), entry);
503 log->info("fetched and stored SAML response");
507 ResourceEntry* InternalCCacheEntry::find(const char* resource_url)
509 ReadLock rwlock(resource_lock);
511 log->debug("find: %s", resource_url);
512 map<string,ResourceEntry*>::const_iterator i=m_resources.find(resource_url);
513 if (i==m_resources.end()) {
514 log->debug("no match found");
517 log->debug("match found");
521 void InternalCCacheEntry::insert(const char* resource, ResourceEntry* entry)
523 log->debug("inserting %s", resource);
525 resource_lock->wrlock();
526 m_resources[resource]=entry;
527 resource_lock->unlock();
530 void InternalCCacheEntry::remove(const char* resource)
532 log->debug("removing %s", resource);
534 resource_lock->wrlock();
535 m_resources.erase(resource);
536 resource_lock->unlock();
540 // a lock on a resource. This is a specific "table of locks" that
541 // will provide a mutex on a particular resource within a Cache Entry.
542 // Just instantiate a ResourceLock within scope of the function and it
543 // will obtain and hold the proper lock until it goes out of scope and
546 InternalCCacheEntry::ResourceLock::ResourceLock(InternalCCacheEntry* entry,
548 entry(entry), resource(resource)
550 Mutex *mutex = find(resource);
554 InternalCCacheEntry::ResourceLock::~ResourceLock()
556 Mutex *mutex = find(resource);
560 Mutex* InternalCCacheEntry::ResourceLock::find(string& resource)
562 Lock(entry->pop_locks_lock);
564 map<string,Mutex*>::const_iterator i=entry->populate_locks.find(resource);
565 if (i==entry->populate_locks.end()) {
566 Mutex* mutex = Mutex::create();
567 entry->populate_locks[resource] = mutex;
573 /******************************************************************************/
574 /* ResourceEntry: A Credential Cache Entry for a particular Resource URL */
575 /******************************************************************************/
577 ResourceEntry::ResourceEntry(SAMLResponse* response)
579 string ctx = "shibtarget::ResourceEntry";
580 log = &(log4cpp::Category::getInstance(ctx));
582 log->info("caching resource entry");
584 m_response = response;
587 ResourceEntry::~ResourceEntry()
592 Iterator<SAMLAssertion*> ResourceEntry::getAssertions()
594 saml::NDC ndc("getAssertions");
595 return m_response->getAssertions();
598 bool ResourceEntry::isValid()
600 saml::NDC ndc("isValid");
602 log->info("checking validity");
604 // This is awful, but the XMLDateTime class is truly horrible.
605 time_t now=time(NULL);
607 struct tm* ptime=gmtime(&now);
610 struct tm* ptime=gmtime_r(&now,&res);
613 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
614 auto_ptr<XMLCh> timeptr(XMLString::transcode(timebuf));
615 XMLDateTime curDateTime(timeptr.get());
617 Iterator<SAMLAssertion*> iter = getAssertions();
619 while (iter.hasNext()) {
620 SAMLAssertion* assertion = iter.next();
622 log->debug ("testing assertion...");
624 if (! assertion->getNotOnOrAfter()) {
625 log->debug ("getNotOnOrAfter failed.");
629 int result=XMLDateTime::compareOrder(&curDateTime,
630 assertion->getNotOnOrAfter());
631 if (result != XMLDateTime::LESS_THAN) {
632 log->debug("nope, not still valid");
637 log->debug("yep, all still valid");