shib-ccache.cpp:
[shibboleth/cpp-sp.git] / shib-target / shib-ccache.cpp
1 /*
2  * The Shibboleth License, Version 1.
3  * Copyright (c) 2002
4  * University Corporation for Advanced Internet Development, Inc.
5  * All rights reserved
6  *
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions are met:
10  *
11  * Redistributions of source code must retain the above copyright notice, this
12  * list of conditions and the following disclaimer.
13  *
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.
22  *
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
28  *
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.
33  *
34  *
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.
48  */
49
50
51 /*
52  * shib-ccache.cpp -- SHAR Credential Cache
53  *
54  * Originally from mod_shib
55  * Modified by: Derek Atkins <derek@ihtfp.com>
56  *
57  * $Id$
58  */
59
60 #ifndef WIN32
61 # include <unistd.h>
62 #endif
63
64 #include "shib-target.h"
65 #include "shib-threads.h"
66
67 #include <log4cpp/Category.hh>
68
69 #include <sstream>
70 #include <stdexcept>
71
72 #ifdef HAVE_LIBDMALLOCXX
73 #include <dmalloc.h>
74 #endif
75
76 using namespace std;
77 using namespace saml;
78 using namespace shibboleth;
79 using namespace shibtarget;
80
81 class ResourceEntry
82 {
83 public:
84   ResourceEntry(SAMLResponse* response);
85   ~ResourceEntry();
86
87   bool isValid();
88   Iterator<SAMLAssertion*> getAssertions();
89
90   static vector<SAMLAssertion*> g_emptyVector;
91
92 private:
93   SAMLResponse* m_response;
94
95   log4cpp::Category* log;
96 };
97
98 class InternalCCache;
99 class InternalCCacheEntry : public CCacheEntry
100 {
101 public:
102   InternalCCacheEntry(SAMLAuthenticationStatement *s, const char *client_addr);
103   ~InternalCCacheEntry();
104
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(); }
108
109   void setCache(InternalCCache *cache) { m_cache = cache; }
110   time_t lastAccess() { Lock lock(access_lock); return m_lastAccess; }
111
112 private:
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);
117
118   string m_originSite;
119   string m_handle;
120   string m_clientAddress;
121   time_t m_sessionCreated;
122   time_t m_lastAccess;
123   bool m_hasbinding;
124
125   const SAMLSubject* m_subject;
126   SAMLAuthenticationStatement* p_auth;
127   InternalCCache *m_cache;
128
129   map<string,ResourceEntry*> m_resources;
130
131   static saml::QName g_authorityKind;
132   static saml::QName g_respondWith;
133
134   log4cpp::Category* log;
135
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;
141
142   Mutex*        access_lock;
143   RWLock*       resource_lock;
144
145   class ResourceLock
146   {
147   public:
148     ResourceLock(InternalCCacheEntry* entry, string resource);
149     ~ResourceLock();
150
151   private:
152     Mutex*                      find(string& resource);
153     InternalCCacheEntry*        entry;
154     string                      resource;
155   };
156 };
157
158 class InternalCCache : public CCache
159 {
160 public:
161   InternalCCache();
162   virtual ~InternalCCache();
163
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);
169
170   void  cleanup();
171 private:
172   SAMLBinding* m_SAMLBinding;
173   map<string,InternalCCacheEntry*> m_hashtable;
174
175   log4cpp::Category* log;
176   RWLock *lock;
177
178   static void*  cleanup_fcn(void*); // XXX Assumed an InternalCCache
179   bool          shutdown;
180   CondWait*     shutdown_wait;
181   Thread*       cleanup_thread;
182 };
183
184 // Global Constructors & Destructors
185 CCache::~CCache() { }
186
187 CCache* CCache::getInstance(const char* type)
188 {
189   return (CCache*) new InternalCCache();
190 }
191
192 // static members
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;
196
197
198 /******************************************************************************/
199 /* InternalCCache:  A Credential Cache                                        */
200 /******************************************************************************/
201
202 InternalCCache::InternalCCache()
203 {
204   m_SAMLBinding=SAMLBindingFactory::getInstance();
205   string ctx="shibtarget.InternalCCache";
206   log = &(log4cpp::Category::getInstance(ctx));
207   lock = RWLock::create();
208
209   shutdown_wait = CondWait::create();
210   shutdown = false;
211   cleanup_thread = Thread::create(&cleanup_fcn, (void*)this);
212 }
213
214 InternalCCache::~InternalCCache()
215 {
216   // Shut down the cleanup thread and let it know...
217   shutdown = true;
218   shutdown_wait->signal();
219   cleanup_thread->join(NULL);
220
221   delete m_SAMLBinding;
222   for (map<string,InternalCCacheEntry*>::iterator i=m_hashtable.begin(); i!=m_hashtable.end(); i++)
223     delete i->second;
224   delete lock;
225   delete shutdown_wait;
226 }
227
228 SAMLBinding* InternalCCache::getBinding(const XMLCh* bindingProt)
229 {
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;
234   }
235   return NULL;
236 }
237
238 CCacheEntry* InternalCCache::find(const char* key)
239 {
240   log->debug("Find: \"%s\"", key);
241   ReadLock rwlock(lock);
242
243   map<string,InternalCCacheEntry*>::const_iterator i=m_hashtable.find(key);
244   if (i==m_hashtable.end()) {
245     log->debug("No Match found");
246     return NULL;
247   }
248   log->debug("Match Found.");
249   return dynamic_cast<CCacheEntry*>(i->second);
250 }
251
252 void InternalCCache::insert(const char* key, SAMLAuthenticationStatement *s,
253                             const char *client_addr)
254 {
255   log->debug("caching new entry for \"%s\"", key);
256
257   InternalCCacheEntry* entry = new InternalCCacheEntry (s, client_addr);
258   entry->setCache(this);
259
260   lock->wrlock();
261   m_hashtable[key]=entry;
262   lock->unlock();
263 }
264
265 void InternalCCache::remove(const char* key)
266 {
267   log->debug("removing cache entry \"key\"", key);
268
269   // XXX: FIXME? do we need to delete the CacheEntry?
270
271   lock->wrlock();
272   m_hashtable.erase(key);
273   lock->unlock();
274 }
275
276 void InternalCCache::cleanup()
277 {
278   Mutex* mutex = Mutex::create();
279
280   mutex->lock();
281
282   while (shutdown == false) {
283     struct timespec ts;
284     memset (&ts, 0, sizeof(ts));
285     ts.tv_sec = time(NULL) + 3600;      // run every hour
286
287     shutdown_wait->timedwait(mutex, &ts);
288
289     if (shutdown == true)
290       break;
291
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.
297
298     // Pass 1: iterate over the map and find all entries that have not been
299     // used in X hours
300     vector<string> stale_keys;
301     time_t stale = time(NULL) - 8 * 3600; // XXX: 8 hour timeout.
302
303     lock->rdlock();
304     for (map<string,InternalCCacheEntry*>::iterator i=m_hashtable.begin();
305          i != m_hashtable.end(); i++)
306     {
307       // If the last access was BEFORE the stale timeout...
308       if (i->second->lastAccess() < stale)
309         stale_keys.push_back(i->first);
310     }
311     lock->unlock();
312
313     // Pass 2: walk through the list of stale entries and remove them from
314     // the database
315     for (vector<string>::iterator i = stale_keys.begin();
316          i != stale_keys.end(); i++)
317     {
318       remove (i->c_str());
319     }
320
321   }
322
323   mutex->unlock();
324   delete mutex;
325   Thread::exit(NULL);
326 }
327
328 void* InternalCCache::cleanup_fcn(void* cache_p)
329 {
330   InternalCCache* cache = (InternalCCache*)cache_p;
331
332   // First, let's block all signals
333   sigset_t sigmask;
334   sigfillset(&sigmask);
335   Thread::mask_signals(SIG_BLOCK, &sigmask, NULL);
336
337   // Now run the cleanup process.
338   cache->cleanup();
339 }
340
341 /******************************************************************************/
342 /* InternalCCacheEntry:  A Credential Cache Entry                             */
343 /******************************************************************************/
344
345 InternalCCacheEntry::InternalCCacheEntry(SAMLAuthenticationStatement *s, const char *client_addr)
346   : m_hasbinding(false)
347 {
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();
353
354   if (s == NULL) {
355     log->error("NULL auth statement");
356     throw runtime_error("InternalCCacheEntry() was passed an empty SAML Statement");
357   }
358
359   m_subject = s->getSubject();
360
361   xstring name = m_subject->getName();
362   xstring qual = m_subject->getNameQualifier();
363
364   auto_ptr<char> h(XMLString::transcode(name.c_str()));
365   auto_ptr<char> d(XMLString::transcode(qual.c_str()));
366
367   m_handle = h.get();
368   m_originSite = d.get();
369
370   Iterator<SAMLAuthorityBinding*> bindings = s->getBindings();
371   if (bindings.hasNext())
372     m_hasbinding = true;
373
374   m_clientAddress = client_addr;
375   m_sessionCreated = m_lastAccess = time(NULL);
376
377   // Save for later.
378   p_auth = s;
379
380   log->info("New Session Created...");
381   log->debug("Handle: \"%s\", Site: \"%s\", Address: %s", h.get(), d.get(),
382              client_addr);
383 }
384
385 InternalCCacheEntry::~InternalCCacheEntry()
386 {
387   log->debug("deleting entry for %s@%s", m_handle.c_str(), m_originSite.c_str());
388   delete p_auth;
389   for (map<string,ResourceEntry*>::iterator i=m_resources.begin();
390        i!=m_resources.end(); i++)
391     delete i->second;
392
393   for (map<string,Mutex*>::iterator i=populate_locks.begin();
394        i!=populate_locks.end(); i++)
395     delete i->second;
396
397   delete pop_locks_lock;
398   delete resource_lock;
399   delete access_lock;
400 }
401
402 bool InternalCCacheEntry::isSessionValid(time_t lifetime, time_t timeout)
403 {
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");
410     return false;
411   }
412
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");
417     return false;
418   }
419   m_lastAccess=now;
420   return true;
421 }
422
423 Iterator<SAMLAssertion*> InternalCCacheEntry::getAssertions(Resource& resource)
424 {
425   saml::NDC ndc("getAssertions");
426   ResourceEntry* entry = populate(resource);
427   if (entry)
428     return entry->getAssertions();
429   return Iterator<SAMLAssertion*>(ResourceEntry::g_emptyVector);
430 }
431
432 ResourceEntry* InternalCCacheEntry::populate(Resource& resource)
433 {
434   saml::NDC ndc("populate");
435   log->debug("populating entry for %s (%s)",
436              resource.getResource(), resource.getURL());
437
438   // Lock the resource within this entry...
439   InternalCCacheEntry::ResourceLock lock(this, resource.getResource());
440
441   // Can we use what we have?
442   ResourceEntry *entry = find(resource.getResource());
443   if (entry) {
444     log->debug("found resource");
445     if (entry->isValid())
446       return entry;
447
448     // entry is invalid (expired) -- go fetch a new one.
449     log->debug("removing resource cache; assertion is invalid");
450     remove (resource.getResource());
451     delete entry;
452   }
453
454   // Nope, no entry.. Create a new resource entry
455
456   if (!m_hasbinding) {
457     log->error("No binding!");
458     return NULL;
459   }
460
461   log->info("trying to request attributes for %s@%s -> %s",
462             m_handle.c_str(), m_originSite.c_str(), resource.getURL());
463
464   auto_ptr<XMLCh> resourceURL(XMLString::transcode(resource.getURL()));
465   Iterator<saml::QName> respond_withs = ArrayIterator<saml::QName>(&g_respondWith);
466
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());
471
472   // Build a SAML Request....
473   SAMLAttributeQuery* q=new SAMLAttributeQuery(subject,resourceURL.get(),
474                                                resource.getDesignators());
475   SAMLRequest* req=new SAMLRequest(respond_withs,q);
476
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;
481
482   while (!response && bindings.hasNext()) {
483     SAMLAuthorityBinding* binding = bindings.next();
484
485     log->debug("Trying binding...");
486     SAMLBinding* pBinding=m_cache->getBinding(binding->getBinding());
487     log->debug("Sending request");
488     response=pBinding->send(*binding,*req);
489   }
490
491   // ok, we can delete the request now.
492   delete req;
493
494   // Make sure we got a response
495   if (!response) {
496     log->info ("No Response");
497     return NULL;
498   }
499
500   entry = new ResourceEntry(response);
501   insert (resource.getResource(), entry);
502
503   log->info("fetched and stored SAML response");
504   return entry;
505 }
506
507 ResourceEntry* InternalCCacheEntry::find(const char* resource_url)
508 {
509   ReadLock rwlock(resource_lock);
510
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");
515     return NULL;
516   }
517   log->debug("match found");
518   return i->second;
519 }
520
521 void InternalCCacheEntry::insert(const char* resource, ResourceEntry* entry)
522 {
523   log->debug("inserting %s", resource);
524
525   resource_lock->wrlock();
526   m_resources[resource]=entry;
527   resource_lock->unlock();
528 }
529
530 void InternalCCacheEntry::remove(const char* resource)
531 {
532   log->debug("removing %s", resource);
533
534   resource_lock->wrlock();
535   m_resources.erase(resource);
536   resource_lock->unlock();
537 }
538
539
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
544 // deconstructs.
545
546 InternalCCacheEntry::ResourceLock::ResourceLock(InternalCCacheEntry* entry,
547                                                 string resource) :
548   entry(entry), resource(resource)
549 {
550   Mutex *mutex = find(resource);
551   mutex->lock();
552 }
553
554 InternalCCacheEntry::ResourceLock::~ResourceLock()
555 {
556   Mutex *mutex = find(resource);
557   mutex->unlock();
558 }
559
560 Mutex* InternalCCacheEntry::ResourceLock::find(string& resource)
561 {
562   Lock(entry->pop_locks_lock);
563   
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;
568     return mutex;
569   }
570   return i->second;
571 }
572
573 /******************************************************************************/
574 /* ResourceEntry:  A Credential Cache Entry for a particular Resource URL     */
575 /******************************************************************************/
576
577 ResourceEntry::ResourceEntry(SAMLResponse* response)
578 {
579   string ctx = "shibtarget::ResourceEntry";
580   log = &(log4cpp::Category::getInstance(ctx));
581
582   log->info("caching resource entry");
583
584   m_response = response;
585 }
586
587 ResourceEntry::~ResourceEntry()
588 {
589   delete m_response;
590 }
591
592 Iterator<SAMLAssertion*> ResourceEntry::getAssertions()
593 {
594   saml::NDC ndc("getAssertions");
595   return m_response->getAssertions();
596 }
597
598 bool ResourceEntry::isValid()
599 {
600   saml::NDC ndc("isValid");
601
602   log->info("checking validity");
603
604   // This is awful, but the XMLDateTime class is truly horrible.
605   time_t now=time(NULL);
606 #ifdef WIN32
607   struct tm* ptime=gmtime(&now);
608 #else
609   struct tm res;
610   struct tm* ptime=gmtime_r(&now,&res);
611 #endif
612   char timebuf[32];
613   strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
614   auto_ptr<XMLCh> timeptr(XMLString::transcode(timebuf));
615   XMLDateTime curDateTime(timeptr.get());
616
617   Iterator<SAMLAssertion*> iter = getAssertions();
618
619   while (iter.hasNext()) {
620     SAMLAssertion* assertion = iter.next();
621
622     log->debug ("testing assertion...");
623
624     if (! assertion->getNotOnOrAfter()) {
625       log->debug ("getNotOnOrAfter failed.");
626       return false;
627     }
628
629     int result=XMLDateTime::compareOrder(&curDateTime,
630                                          assertion->getNotOnOrAfter());
631     if (result != XMLDateTime::LESS_THAN) {
632       log->debug("nope, not still valid");
633       return false;
634     }
635   } // while
636
637   log->debug("yep, all still valid");
638   return true;
639 }