6eb803718d892266ce7c4bfe6e108d5b5fa6a32f
[shibboleth/sp.git] / shib-target / shib-ccache.cpp
1 /*
2  *  Copyright 2001-2007 Internet2
3  * 
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /*
18  * shib-ccache.cpp -- in-memory session cache plugin
19  *
20  * $Id$
21  */
22
23 #include "internal.h"
24
25 #if HAVE_UNISTD_H
26 # include <unistd.h>
27 #endif
28
29 #include <ctime>
30 #include <algorithm>
31 #include <sstream>
32 #include <stdexcept>
33 #include <shibsp/SPConfig.h>
34
35 #ifdef HAVE_LIBDMALLOCXX
36 #include <dmalloc.h>
37 #endif
38
39 using namespace shibsp;
40 using namespace shibtarget;
41 using namespace saml;
42 using namespace opensaml::saml2md;
43 using namespace xmltooling;
44 using namespace log4cpp;
45 using namespace std;
46 using xmlsignature::CredentialResolver;
47
48 static const XMLCh cleanupInterval[] =
49 { chLatin_c, chLatin_l, chLatin_e, chLatin_a, chLatin_n, chLatin_u, chLatin_p,
50   chLatin_I, chLatin_n, chLatin_t, chLatin_e, chLatin_r, chLatin_v, chLatin_a, chLatin_l, chNull
51 };
52 static const XMLCh cacheTimeout[] =
53 { chLatin_c, chLatin_a, chLatin_c, chLatin_h, chLatin_e,
54   chLatin_T, chLatin_i, chLatin_m, chLatin_e, chLatin_o, chLatin_u, chLatin_t, chNull
55 };
56 static const XMLCh AAConnectTimeout[] =
57 { chLatin_A, chLatin_A, chLatin_C, chLatin_o, chLatin_n, chLatin_n, chLatin_e, chLatin_c, chLatin_t,
58   chLatin_T, chLatin_i, chLatin_m, chLatin_e, chLatin_o, chLatin_u, chLatin_t, chNull
59 };
60 static const XMLCh AATimeout[] =
61 { chLatin_A, chLatin_A, chLatin_T, chLatin_i, chLatin_m, chLatin_e, chLatin_o, chLatin_u, chLatin_t, chNull };
62
63 static const XMLCh defaultLifetime[] =
64 { chLatin_d, chLatin_e, chLatin_f, chLatin_a, chLatin_u, chLatin_l, chLatin_t,
65   chLatin_L, chLatin_i, chLatin_f, chLatin_e, chLatin_t, chLatin_i, chLatin_m, chLatin_e, chNull
66 };
67 static const XMLCh retryInterval[] =
68 { chLatin_r, chLatin_e, chLatin_t, chLatin_r, chLatin_y,
69   chLatin_I, chLatin_n, chLatin_t, chLatin_e, chLatin_r, chLatin_v, chLatin_a, chLatin_l, chNull
70 };
71 static const XMLCh strictValidity[] =
72 { chLatin_s, chLatin_t, chLatin_r, chLatin_i, chLatin_c, chLatin_t,
73   chLatin_V, chLatin_a, chLatin_l, chLatin_i, chLatin_d, chLatin_i, chLatin_t, chLatin_y, chNull
74 };
75 static const XMLCh propagateErrors[] =
76 { chLatin_p, chLatin_r, chLatin_o, chLatin_p, chLatin_a, chLatin_g, chLatin_a, chLatin_t, chLatin_e,
77   chLatin_E, chLatin_r, chLatin_r, chLatin_o, chLatin_r, chLatin_s, chNull
78 };
79 static const XMLCh writeThrough[] =
80 { chLatin_w, chLatin_r, chLatin_i, chLatin_t, chLatin_e,
81   chLatin_T, chLatin_h, chLatin_r, chLatin_o, chLatin_u, chLatin_g, chLatin_h, chNull
82 };
83
84
85 /*
86  * Stubbed out, inproc version of an ISessionCacheEntry
87  */
88 class StubCacheEntry : public virtual ISessionCacheEntry
89 {
90 public:
91     StubCacheEntry(Category* log) : m_log(log), m_pSubject(NULL), m_pUnfiltered(NULL), m_pFiltered(NULL) {}
92     StubCacheEntry(DDF& obj, Category* log)
93         : m_log(log), m_obj(obj), m_pSubject(NULL), m_pUnfiltered(NULL), m_pFiltered(NULL) {}
94     ~StubCacheEntry() { m_obj.destroy(); delete m_pSubject; delete m_pUnfiltered; delete m_pFiltered; }
95     void lock() {}
96     void unlock() { delete this; }
97     const char* getClientAddress() const { return m_obj["client_address"].string(); }
98     const char* getProviderId() const { return m_obj["provider_id"].string(); }
99     const char* getAuthnContext() const { return m_obj["authn_context"].string(); }
100     pair<const char*,const SAMLSubject*> getSubject(bool xml=true, bool obj=false) const;
101     pair<const char*,const SAMLResponse*> getTokens(bool xml=true, bool obj=false) const;
102     pair<const char*,const SAMLResponse*> getFilteredTokens(bool xml=true, bool obj=false) const;
103
104 protected:
105     Category* m_log;
106     mutable DDF m_obj;
107     mutable SAMLSubject* m_pSubject;
108     mutable SAMLResponse* m_pUnfiltered;
109     mutable SAMLResponse* m_pFiltered;
110 };
111
112 pair<const char*,const SAMLSubject*> StubCacheEntry::getSubject(bool xml, bool obj) const
113 {
114     const char* raw=m_obj["subject"].string();
115     pair<const char*,const SAMLSubject*> ret=pair<const char*,const SAMLSubject*>(NULL,NULL);
116     if (xml)
117         ret.first=raw;
118     if (obj) {
119         if (!m_pSubject) {
120             istringstream in(raw);
121             m_log->debugStream() << "decoding subject: " << (raw ? raw : "(none)") << CategoryStream::ENDLINE;
122             m_pSubject=raw ? new SAMLSubject(in) : NULL;
123         }
124         ret.second=m_pSubject;
125     }
126     return ret;
127 }
128
129 pair<const char*,const SAMLResponse*> StubCacheEntry::getTokens(bool xml, bool obj) const
130 {
131     const char* unfiltered=m_obj["tokens.unfiltered"].string();
132     pair<const char*,const SAMLResponse*> ret = pair<const char*,const SAMLResponse*>(NULL,NULL);
133     if (xml)
134         ret.first=unfiltered;
135     if (obj) {
136         if (!m_pUnfiltered) {
137             if (unfiltered) {
138                 istringstream in(unfiltered);
139                 m_log->debugStream() << "decoding unfiltered tokens: " << unfiltered << CategoryStream::ENDLINE;
140                 m_pUnfiltered=new SAMLResponse(in,m_obj["minor_version"].integer());
141             }
142         }
143         ret.second=m_pUnfiltered;
144     }
145     return ret;
146 }
147
148 pair<const char*,const SAMLResponse*> StubCacheEntry::getFilteredTokens(bool xml, bool obj) const
149 {
150     const char* filtered=m_obj["tokens.filtered"].string();
151     if (!filtered)
152         return getTokens(xml,obj);
153     pair<const char*,const SAMLResponse*> ret = pair<const char*,const SAMLResponse*>(NULL,NULL);
154     if (xml)
155         ret.first=filtered;
156     if (obj) {
157         if (!m_pFiltered) {
158             istringstream in(filtered);
159             m_log->debugStream() << "decoding filtered tokens: " << filtered << CategoryStream::ENDLINE;
160             m_pFiltered=new SAMLResponse(in,m_obj["minor_version"].integer());
161         }
162         ret.second=m_pFiltered;
163     }
164     return ret;
165 }
166
167 /*
168  * Remoting front-half of session cache, drops out in single process deployments.
169  *  TODO: Add buffering of frequently-used entries.
170  */
171 class StubCache : public virtual ISessionCache
172 {
173 public:
174     StubCache(const DOMElement* e);
175
176     string insert(
177         const IApplication* application,
178         const RoleDescriptor* role,
179         const char* client_addr,
180         const SAMLSubject* subject,
181         const char* authnContext,
182         const SAMLResponse* tokens
183     );
184     ISessionCacheEntry* find(const char* key, const IApplication* application, const char* client_addr);
185     void remove(const char* key, const IApplication* application, const char* client_addr);
186
187     bool setBackingStore(ISessionCacheStore*) { return false; }
188
189 private:
190     Category* m_log;
191 };
192
193 StubCache::StubCache(const DOMElement* e) : m_log(&Category::getInstance(SHIBT_LOGCAT".SessionCache")) {}
194
195 /*
196  * The public methods are remoted using the message passing system.
197  * In practice, insert is unlikely to be used remotely, but just in case...
198  */
199
200 string StubCache::insert(
201     const IApplication* application,
202     const RoleDescriptor* role,
203     const char* client_addr,
204     const SAMLSubject* subject,
205     const char* authnContext,
206     const SAMLResponse* tokens
207     )
208 {
209     DDF in("SessionCache::insert"),out;
210     DDFJanitor jin(in),jout(out);
211     in.structure();
212     in.addmember("application_id").string(application->getId());
213     in.addmember("client_address").string(client_addr);
214     xmltooling::auto_ptr_char provid(dynamic_cast<EntityDescriptor*>(role->getParent())->getEntityID());
215     in.addmember("provider_id").string(provid.get());
216     in.addmember("major_version").integer(1);
217     in.addmember("minor_version").integer(tokens->getMinorVersion());
218     in.addmember("authn_context").string(authnContext);
219     
220     ostringstream os;
221     os << *subject;
222     in.addmember("subject").string(os.str().c_str());
223     os.str("");
224     os << *tokens;
225     in.addmember("tokens.unfiltered").string(os.str().c_str());
226
227     out=SPConfig::getConfig().getServiceProvider()->getListenerService()->send(in);
228     if (out["key"].isstring())
229         return out["key"].string();
230     throw opensaml::RetryableProfileException("A remoted cache insertion operation did not return a usable session key.");
231 }
232
233 ISessionCacheEntry* StubCache::find(const char* key, const IApplication* application, const char* client_addr)
234 {
235     DDF in("SessionCache::find"),out;
236     DDFJanitor jin(in);
237     in.structure();
238     in.addmember("key").string(key);
239     in.addmember("application_id").string(application->getId());
240     in.addmember("client_address").string(client_addr);
241     
242     try {
243         out=SPConfig::getConfig().getServiceProvider()->getListenerService()->send(in);
244         if (!out.isstruct()) {
245             out.destroy();
246             return NULL;
247         }
248         
249         // Wrap the results in a stub entry and return it to the caller.
250         return new StubCacheEntry(out,m_log);
251     }
252     catch (...) {
253         out.destroy();
254         throw;
255     }
256 }
257
258 void StubCache::remove(const char* key, const IApplication* application, const char* client_addr)
259 {
260     DDF in("SessionCache::remove");
261     DDFJanitor jin(in);
262     in.structure();
263     in.addmember("key").string(key);
264     in.addmember("application_id").string(application->getId());
265     in.addmember("client_address").string(client_addr);
266     
267     SPConfig::getConfig().getServiceProvider()->getListenerService()->send(in);
268 }
269
270 /*
271  * Long-lived cache entries that store the actual sessions and
272  * wrap attribute query/refresh/filtering
273  */
274 class MemorySessionCache;
275 class MemorySessionCacheEntry : public virtual ISessionCacheEntry, public virtual StubCacheEntry
276 {
277 public:
278     MemorySessionCacheEntry(
279         MemorySessionCache* cache,
280         const char* key,
281         const IApplication* application,
282         const RoleDescriptor* role,
283         const char* client_addr,
284         const SAMLSubject* subject,
285         const char* authnContext,
286         const SAMLResponse* tokens
287         );
288     MemorySessionCacheEntry(
289         MemorySessionCache* cache,
290         const char* key,
291         const IApplication* application,
292         const RoleDescriptor* role,
293         const char* client_addr,
294         const char* subject,
295         const char* authnContext,
296         const char* tokens,
297         int majorVersion,
298         int minorVersion,
299         time_t created,
300         time_t accessed
301         );
302     ~MemorySessionCacheEntry();
303
304     void lock() { m_lock->lock(); }
305     void unlock() { m_lock->unlock(); }
306     
307     HRESULT isValid(const IApplication* application, const char* client_addr) const;
308     void populate(const IApplication* application, const EntityDescriptor* source, bool initial=false) const;
309     bool checkApplication(const IApplication* application) { return (m_obj["application_id"]==application->getId()); }
310     time_t created() const { return m_sessionCreated; }
311     time_t lastAccess() const { return m_lastAccess; }
312     const DDF& getDDF() const { return m_obj; }
313   
314 private:
315     bool hasAttributes(const SAMLResponse& r) const;
316     time_t calculateExpiration(const SAMLResponse& r) const;
317     pair<SAMLResponse*,SAMLResponse*> getNewResponse(const IApplication* application, const EntityDescriptor* source) const;
318     SAMLResponse* filter(const SAMLResponse* r, const IApplication* application, const RoleDescriptor* role) const;
319   
320     time_t m_sessionCreated;
321     mutable time_t m_responseExpiration, m_lastAccess, m_lastRetry;
322
323     MemorySessionCache* m_cache;
324     Mutex* m_lock;
325 };
326
327 /*
328  * The actual in-memory session cache implementation.
329  */
330 class MemorySessionCache : public virtual ISessionCache, public virtual Remoted
331 {
332 public:
333     MemorySessionCache(const DOMElement* e);
334     virtual ~MemorySessionCache();
335
336     DDF receive(const DDF& in);
337
338     string insert(
339         const IApplication* application,
340         const RoleDescriptor* role,
341         const char* client_addr,
342         const SAMLSubject* subject,
343         const char* authnContext,
344         const SAMLResponse* tokens
345     );
346     ISessionCacheEntry* find(const char* key, const IApplication* application, const char* client_addr);
347     void remove(const char* key, const IApplication* application, const char* client_addr);
348
349     void cleanup();
350
351     bool setBackingStore(ISessionCacheStore* store);
352
353 private:
354     const DOMElement* m_root;         // Only valid during initialization
355     RWLock* m_lock;
356     map<string,MemorySessionCacheEntry*> m_hashtable;
357
358     Category* m_log;
359     Remoted* restoreInsert;
360     Remoted* restoreFind;
361     Remoted* restoreRemove;
362     ISessionCacheStore* m_sink;
363
364     void dormant(const char* key);
365     static void* cleanup_fcn(void*);
366     bool shutdown;
367     CondWait* shutdown_wait;
368     Thread* cleanup_thread;
369   
370     // extracted config settings
371     unsigned int m_AATimeout,m_AAConnectTimeout;
372     unsigned int m_defaultLifetime,m_retryInterval;
373     bool m_strictValidity,m_propagateErrors,m_writeThrough;
374     friend class MemorySessionCacheEntry;
375 };
376
377 MemorySessionCacheEntry::MemorySessionCacheEntry(
378     MemorySessionCache* cache,
379     const char* key,
380     const IApplication* application,
381     const RoleDescriptor* role,
382     const char* client_addr,
383     const SAMLSubject* subject,
384     const char* authnContext,
385     const SAMLResponse* tokens
386     ) : StubCacheEntry(cache->m_log), m_cache(cache), m_responseExpiration(0), m_lastRetry(0)
387 {
388     m_sessionCreated = m_lastAccess = time(NULL);
389
390     // Store session properties in DDF.
391     m_obj=DDF(NULL).structure();
392     m_obj.addmember("key").string(key);
393     m_obj.addmember("client_address").string(client_addr);
394     m_obj.addmember("application_id").string(application->getId());
395     xmltooling::auto_ptr_char pid(dynamic_cast<EntityDescriptor*>(role->getParent())->getEntityID());
396     m_obj.addmember("provider_id").string(pid.get());
397     m_obj.addmember("major_version").integer(1);
398     m_obj.addmember("minor_version").integer(tokens->getMinorVersion());
399
400     // Save the subject as XML.
401     ostringstream os;
402     os << *subject;
403     m_obj.addmember("subject").string(os.str().c_str());
404     
405     // Save the authn method.
406     m_obj.addmember("authn_context").string(authnContext);
407
408     // Serialize unfiltered assertions.
409     os.str("");
410     os << *tokens;
411     m_obj.addmember("tokens.unfiltered").string(os.str().c_str());
412
413     if (hasAttributes(*tokens)) {
414         // Filter attributes in the response.
415         auto_ptr<SAMLResponse> filtered(filter(tokens, application, role));
416         
417         // Calculate expiration.
418         m_responseExpiration=calculateExpiration(*(filtered.get()));
419         
420         // Serialize filtered assertions (if changes were made).
421         os.str("");
422         os << *(filtered.get());
423         string fstr=os.str();
424         if (fstr.length() != m_obj["tokens.unfiltered"].strlen())
425             m_obj.addmember("tokens.filtered").string(fstr.c_str());
426
427         // Save actual objects only if we're running inprocess. The subject needs to be
428         // owned by the entry, so we'll defer creation of a cloned copy.
429         if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
430             if (m_obj["tokens.filtered"].isstring())
431                 m_pFiltered=filtered.release();
432         }
433     }
434     
435     m_lock = Mutex::create();
436
437     if (m_log->isDebugEnabled()) {
438         m_log->debug("new cache entry created: SessionID (%s) IdP (%s) Address (%s)", key, pid.get(), client_addr);
439     }
440
441     // Transaction Logging
442     xmltooling::auto_ptr_char hname(subject->getNameIdentifier()->getName());
443     STConfig& stc=static_cast<STConfig&>(ShibTargetConfig::getConfig());
444     stc.getTransactionLog().infoStream() <<
445         "New session (ID: " <<
446             key <<
447         ") with (applicationId: " <<
448             application->getId() <<
449         ") for principal from (IdP: " <<
450             pid.get() <<
451         ") at (ClientAddress: " <<
452             client_addr <<
453         ") with (NameIdentifier: " <<
454             hname.get() <<
455         ")";
456     stc.releaseTransactionLog();
457 }
458
459 MemorySessionCacheEntry::MemorySessionCacheEntry(
460     MemorySessionCache* cache,
461     const char* key,
462     const IApplication* application,
463     const RoleDescriptor* role,
464     const char* client_addr,
465     const char* subject,
466     const char* authnContext,
467     const char* tokens,
468     int majorVersion,
469     int minorVersion,
470     time_t created,
471     time_t accessed
472     ) : StubCacheEntry(cache->m_log), m_cache(cache), m_responseExpiration(0), m_lastRetry(0)
473 {
474     m_sessionCreated = created;
475     m_lastAccess = accessed;
476
477     // Reconstitute the tokens for filtering.
478     istringstream is(tokens);
479     auto_ptr<SAMLResponse> unfiltered(new SAMLResponse(is,minorVersion));
480
481     // Store session properties in DDF.
482     m_obj=DDF(NULL).structure();
483     m_obj.addmember("key").string(key);
484     m_obj.addmember("client_address").string(client_addr);
485     m_obj.addmember("application_id").string(application->getId());
486     xmltooling::auto_ptr_char pid(dynamic_cast<EntityDescriptor*>(role->getParent())->getEntityID());
487     m_obj.addmember("provider_id").string(pid.get());
488     m_obj.addmember("subject").string(subject);
489     m_obj.addmember("authn_context").string(authnContext);
490     m_obj.addmember("tokens.unfiltered").string(tokens);
491     m_obj.addmember("major_version").integer(majorVersion);
492     m_obj.addmember("minor_version").integer(minorVersion);
493
494     if (hasAttributes(*(unfiltered.get()))) {
495         auto_ptr<SAMLResponse> filtered(filter(unfiltered.get(), application, role));
496     
497         // Calculate expiration.
498         m_responseExpiration=calculateExpiration(*(filtered.get()));
499     
500         // Serialize filtered assertions (if changes were made).
501         ostringstream os;
502         os << *(filtered.get());
503         string fstr=os.str();
504         if (fstr.length() != strlen(tokens))
505             m_obj.addmember("tokens.filtered").string(fstr.c_str());
506
507         // Save actual objects only if we're running inprocess.
508         if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
509             m_pUnfiltered=unfiltered.release();
510             if (m_obj["tokens.filtered"].isstring())
511                 m_pFiltered=filtered.release();
512         }
513     }
514     
515     m_lock = Mutex::create();
516
517     if (m_log->isDebugEnabled())
518         m_log->debug("session loaded from secondary cache (ID: %s)", key);
519 }
520
521
522 MemorySessionCacheEntry::~MemorySessionCacheEntry()
523 {
524     delete m_lock;
525 }
526
527 HRESULT MemorySessionCacheEntry::isValid(const IApplication* app, const char* client_addr) const
528 {
529 #ifdef _DEBUG
530     xmltooling::NDC ndc("isValid");
531 #endif
532
533     // Obtain validation rules from application settings.
534     bool consistentIPAddress=true;
535     int lifetime=0,timeout=0;
536     const PropertySet* props=app->getPropertySet("Sessions");
537     if (props) {
538         pair<bool,unsigned int> p=props->getUnsignedInt("lifetime");
539         if (p.first)
540             lifetime = p.second;
541         p=props->getUnsignedInt("timeout");
542         if (p.first)
543             timeout = p.second;
544         pair<bool,bool> pcheck=props->getBool("consistentIPAddress");
545         if (pcheck.first)
546             consistentIPAddress = pcheck.second;
547     }
548     
549     if (m_log->isDebugEnabled())
550         m_log->debug("checking validity of session (ID: %s)", m_obj["key"].string());
551     
552     time_t now=time(NULL);
553     if (lifetime > 0 && now > m_sessionCreated+lifetime) {
554         if (m_log->isInfoEnabled())
555             m_log->info("session expired (ID: %s)", m_obj["key"].string());
556         return SESSION_E_EXPIRED;
557     }
558
559     if (timeout > 0 && now-m_lastAccess >= timeout) {
560         // May need to query sink first to find out if another cluster member has been used.
561         if (m_cache->m_sink && m_cache->m_writeThrough) {
562             if (NOERROR!=m_cache->m_sink->onRead(m_obj["key"].string(),m_lastAccess))
563                 m_log->error("cache store failed to return last access timestamp");
564             if (now-m_lastAccess >= timeout) {
565                 m_log->info("session timed out (ID: %s)", m_obj["key"].string());
566                 return SESSION_E_EXPIRED;
567             }
568         }
569         else {
570             m_log->info("session timed out (ID: %s)", m_obj["key"].string());
571             return SESSION_E_EXPIRED;
572         }
573     }
574
575     if (consistentIPAddress) {
576         if (m_log->isDebugEnabled())
577             m_log->debug("comparing client address %s against %s", client_addr, getClientAddress());
578         if (strcmp(client_addr, getClientAddress())) {
579             m_log->debug("client address mismatch");
580             return SESSION_E_ADDRESSMISMATCH;
581         }
582     }
583
584     m_lastAccess=now;
585
586     if (m_cache->m_sink && m_cache->m_writeThrough && timeout > 0) {
587         // Update sink with last access data, if possible.
588         if (FAILED(m_cache->m_sink->onUpdate(m_obj["key"].string(),NULL,m_lastAccess)))
589             m_log->error("cache store failed to update last access timestamp");
590     }
591
592     return NOERROR;
593 }
594
595 bool MemorySessionCacheEntry::hasAttributes(const SAMLResponse& r) const
596 {
597     Iterator<SAMLAssertion*> assertions=r.getAssertions();
598     while (assertions.hasNext()) {
599         Iterator<SAMLStatement*> statements=assertions.next()->getStatements();
600         while (statements.hasNext()) {
601             if (dynamic_cast<SAMLAttributeStatement*>(statements.next()))
602                 return true;
603         }
604     }
605     return false;
606 }
607
608 time_t MemorySessionCacheEntry::calculateExpiration(const SAMLResponse& r) const
609 {
610     time_t expiration=0;
611     Iterator<SAMLAssertion*> assertions = r.getAssertions();
612     while (assertions.hasNext()) {
613         SAMLAssertion* assertion = assertions.next();
614         
615         // Only examine this assertion if it contains an attribute statement.
616         // We know at least one such statement exists, or this is a query response.
617         Iterator<SAMLStatement*> statements = assertion->getStatements();
618         while (statements.hasNext()) {
619             if (dynamic_cast<SAMLAttributeStatement*>(statements.next())) {
620                 const SAMLDateTime* thistime = assertion->getNotOnOrAfter();
621         
622                 // If there is no time, then just continue and ignore this assertion.
623                 if (thistime) {    
624                     // If this is a tighter expiration, cache it.   
625                     if (expiration == 0 || thistime->getEpoch() < expiration)
626                         expiration = thistime->getEpoch();
627                 }
628
629                 // No need to continue with this assertion.
630                 break;
631             }
632         }
633     }
634
635     // If we didn't find any assertions with times, then use the default.
636     if (expiration == 0)
637         expiration = time(NULL) + m_cache->m_defaultLifetime;
638   
639     return expiration;
640 }
641
642 void MemorySessionCacheEntry::populate(const IApplication* application, const EntityDescriptor* source, bool initial) const
643 {
644 #ifdef _DEBUG
645     xmltooling::NDC ndc("populate");
646 #endif
647
648     // Do we have any attribute data cached?
649     if (m_responseExpiration > 0) {
650         // Can we use what we have?
651         if (time(NULL) < m_responseExpiration)
652             return;
653         
654         // Possibly check the sink in case another cluster member already refreshed it.
655         if (m_cache->m_sink && m_cache->m_writeThrough) {
656             string tokensFromSink;
657             HRESULT hr=m_cache->m_sink->onRead(m_obj["key"].string(),tokensFromSink);
658             if (FAILED(hr))
659                 m_log->error("cache store failed to return updated tokens");
660             else if (hr==NOERROR && tokensFromSink!=m_obj["tokens.unfiltered"].string()) {
661
662                 // Bah...find role again.
663                 const RoleDescriptor* role=source->getAttributeAuthorityDescriptor(samlconstants::SAML11_PROTOCOL_ENUM);
664                 if (!role)
665                     role=source->getAttributeAuthorityDescriptor(samlconstants::SAML10_PROTOCOL_ENUM);
666                 if (!role)
667                     role=source->getIDPSSODescriptor(samlconstants::SAML11_PROTOCOL_ENUM);
668                 if (!role)
669                     role=source->getIDPSSODescriptor(samlconstants::SAML10_PROTOCOL_ENUM);
670                 if (!role) {
671                     throw MetadataException("Unable to locate attribute-issuing role in metadata.");
672                 }
673
674                 // The tokens in the sink were different.
675                 istringstream is(tokensFromSink);
676                 auto_ptr<SAMLResponse> respFromSink(new SAMLResponse(is,m_obj["minor_version"].integer()));
677                 auto_ptr<SAMLResponse> filteredFromSink(filter(respFromSink.get(),application,role));
678                 time_t expFromSink=calculateExpiration(*(filteredFromSink.get()));
679                 
680                 // Recheck to see if the new tokens are valid.
681                 if (expFromSink < time(NULL)) {
682                     m_log->info("loading replacement tokens into memory from cache store");
683                     m_obj["tokens"].destroy();
684                     delete m_pUnfiltered;
685                     delete m_pFiltered;
686                     m_pUnfiltered=m_pFiltered=NULL;
687                     m_obj.addmember("tokens.unfiltered").string(tokensFromSink.c_str());
688
689                     // Serialize filtered assertions (if changes were made).
690                     ostringstream os;
691                     os << *(filteredFromSink.get());
692                     string fstr=os.str();
693                     if (fstr.length() != m_obj.getmember("tokens.unfiltered").strlen())
694                         m_obj.addmember("tokens.filtered").string(fstr.c_str());
695                     
696                     // Save actual objects only if we're running inprocess.
697                     if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
698                         m_pUnfiltered=respFromSink.release();
699                         if (m_obj["tokens.filtered"].isstring())
700                             m_pFiltered=filteredFromSink.release();
701                     }
702
703                     m_responseExpiration=expFromSink;
704                     m_lastRetry=0;
705                     return;
706                 }
707             }
708         }
709
710         // If we're being strict, dump what we have and reset timestamps.
711         if (m_cache->m_strictValidity) {
712             m_log->info("strictly enforcing attribute validity, dumping expired data");
713             m_obj["tokens"].destroy();
714             delete m_pUnfiltered;
715             delete m_pFiltered;
716             m_pUnfiltered=m_pFiltered=NULL;
717             m_responseExpiration=0;
718             m_lastRetry=0;
719             if (m_cache->m_sink) {
720                 if (FAILED(m_cache->m_sink->onUpdate(m_obj["key"].string(),"")))
721                     m_log->error("cache store returned failure while clearing tokens from entry");
722             }
723         }
724     }
725
726     try {
727         pair<SAMLResponse*,SAMLResponse*> new_responses=getNewResponse(application,source);
728         auto_ptr<SAMLResponse> r1(new_responses.first),r2(new_responses.second);
729         if (new_responses.first) {
730             m_obj["tokens"].destroy();
731             delete m_pUnfiltered;
732             delete m_pFiltered;
733             m_pUnfiltered=m_pFiltered=NULL;
734             m_responseExpiration=0;
735             
736             // Serialize unfiltered assertions.
737             ostringstream os;
738             os << *new_responses.first;
739             m_obj.addmember("tokens.unfiltered").string(os.str().c_str());
740             
741             // Serialize filtered assertions (if changes were made).
742             os.str("");
743             os << *new_responses.second;
744             string fstr=os.str();
745             if (fstr.length() != m_obj.getmember("tokens.unfiltered").strlen())
746                 m_obj.addmember("tokens.filtered").string(fstr.c_str());
747             
748             // Update expiration.
749             m_responseExpiration=calculateExpiration(*new_responses.second);
750
751             // Save actual objects only if we're running inprocess.
752             if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
753                 m_pUnfiltered=r1.release();
754                 if (m_obj["tokens.filtered"].isstring())
755                     m_pFiltered=r2.release();
756             }
757
758             // Update backing store.
759             if (!initial && m_cache->m_sink) {
760                 if (FAILED(m_cache->m_sink->onUpdate(m_obj["key"].string(),m_obj["tokens.unfiltered"].string())))
761                     m_log->error("cache store returned failure while updating tokens in entry");
762             }
763
764             m_lastRetry=0;
765             m_log->debug("fetched and stored new response");
766             STConfig& stc=static_cast<STConfig&>(ShibTargetConfig::getConfig());
767             stc.getTransactionLog().infoStream() <<  "Successful attribute query for session (ID: " << m_obj["key"].string() << ")";
768             stc.releaseTransactionLog();
769         }
770     }
771     catch (exception&) {
772         if (m_cache->m_propagateErrors)
773             throw;
774         m_log->warn("suppressed exception caught while trying to fetch attributes");
775     }
776 #ifndef _DEBUG
777     catch (...) {
778         if (m_cache->m_propagateErrors)
779             throw;
780         m_log->warn("suppressed unknown exception caught while trying to fetch attributes");
781     }
782 #endif
783 }
784
785 pair<SAMLResponse*,SAMLResponse*> MemorySessionCacheEntry::getNewResponse(
786     const IApplication* application, const EntityDescriptor* source
787     ) const
788 {
789 #ifdef _DEBUG
790     xmltooling::NDC ndc("getNewResponse");
791 #endif
792
793     // The retryInterval determines how often to poll an AA that might be down.
794     time_t now=time(NULL);
795     if ((now - m_lastRetry) < m_cache->m_retryInterval)
796         return pair<SAMLResponse*,SAMLResponse*>(NULL,NULL);
797     if (m_lastRetry)
798         m_log->debug("retry interval exceeded, trying for attributes again");
799     m_lastRetry=now;
800
801     m_log->info("trying to get new attributes for session (ID: %s)", m_obj["key"].string());
802     
803     // Transaction Logging
804     STConfig& stc=static_cast<STConfig&>(ShibTargetConfig::getConfig());
805     stc.getTransactionLog().infoStream() <<
806         "Making attribute query for session (ID: " <<
807             m_obj["key"].string() <<
808         ") on (applicationId: " <<
809             m_obj["application_id"].string() <<
810         ") for principal from (IdP: " <<
811             m_obj["provider_id"].string() <<
812         ")";
813     stc.releaseTransactionLog();
814
815
816     pair<bool,const XMLCh*> providerID=application->getXMLString("providerId");
817     if (!providerID.first) {
818         m_log->crit("unable to determine ProviderID for application, not set?");
819         throw ConfigurationException("Unable to determine ProviderID for application, not set?");
820     }
821
822     // Try to locate an AA role.
823     const AttributeAuthorityDescriptor* AA=source->getAttributeAuthorityDescriptor(
824         m_obj["minor_version"].integer()==1 ? samlconstants::SAML11_PROTOCOL_ENUM : samlconstants::SAML10_PROTOCOL_ENUM
825         );
826     if (!AA) {
827         m_log->warn("unable to locate metadata for identity provider's Attribute Authority");
828         return pair<SAMLResponse*,SAMLResponse*>(NULL,NULL);
829     }
830
831     // Get protocol signing policy.
832     const PropertySet* credUse=application->getCredentialUse(source);
833     pair<bool,bool> signRequest=credUse ? credUse->getBool("signRequest") : make_pair(false,false);
834     pair<bool,const char*> signatureAlg=credUse ? credUse->getString("signatureAlg") : pair<bool,const char*>(false,NULL);
835     if (!signatureAlg.first)
836         signatureAlg.second=URI_ID_RSA_SHA1;
837     pair<bool,const char*> digestAlg=credUse ? credUse->getString("digestAlg") : pair<bool,const char*>(false,NULL);
838     if (!digestAlg.first)
839         digestAlg.second=URI_ID_SHA1;
840     pair<bool,bool> signedResponse=credUse ? credUse->getBool("signedResponse") : make_pair(false,false);
841     pair<bool,const char*> signingCred=credUse ? credUse->getString("Signing") : pair<bool,const char*>(false,NULL);
842     
843     SAMLResponse* response = NULL;
844     try {
845         // Copy NameID from subject (may need to reconstitute it).
846         SAMLNameIdentifier* nameid=NULL;
847         if (m_pSubject)
848             nameid=static_cast<SAMLNameIdentifier*>(m_pSubject->getNameIdentifier()->clone());
849         else {
850             istringstream instr(m_obj["subject"].string());
851             auto_ptr<SAMLSubject> sub(new SAMLSubject(instr));
852             nameid=static_cast<SAMLNameIdentifier*>(sub->getNameIdentifier()->clone());
853         }
854
855         // Build a SAML Request....
856         SAMLAttributeQuery* q=new SAMLAttributeQuery(
857             new SAMLSubject(nameid),
858             providerID.second
859             );
860         auto_ptr<SAMLRequest> req(new SAMLRequest(q));
861         req->setMinorVersion(m_obj["minor_version"].integer());
862         
863         // Sign it?
864         if (signRequest.first && signRequest.second && signingCred.first) {
865             if (req->getMinorVersion()==1) {
866                 CredentialResolver* cr=SPConfig::getConfig().getServiceProvider()->getCredentialResolver(signingCred.second);
867                 if (cr) {
868                     xmltooling::Locker locker(cr);
869                     req->sign(cr->getKey(),cr->getCertificates(),signatureAlg.second,digestAlg.second);
870                 }
871                 else
872                     m_log->error("unable to sign attribute query, specified credential (%s) was not found",signingCred.second);
873             }
874             else
875                 m_log->error("unable to sign SAML 1.0 attribute query, only SAML 1.1 defines signing adequately");
876         }
877             
878         m_log->debug("trying to query an AA...");
879
880         // Call context object
881         ShibHTTPHook::ShibHTTPHookCallContext ctx(credUse,AA);
882         
883         // Use metadata to locate endpoints.
884         const vector<AttributeService*>& endpoints=AA->getAttributeServices();
885         for (vector<AttributeService*>::const_iterator ep=endpoints.begin(); !response && ep!=endpoints.end(); ++ep) {
886             try {
887                 // Get a binding object for this protocol.
888                 const SAMLBinding* binding = application->getBinding((*ep)->getBinding());
889                 if (!binding) {
890                     xmltooling::auto_ptr_char prot((*ep)->getBinding());
891                     m_log->warn("skipping binding on unsupported protocol (%s)", prot.get());
892                     continue;
893                 }
894                 static const XMLCh https[] = {chLatin_h, chLatin_t, chLatin_t, chLatin_p, chLatin_s, chColon, chNull};
895                 auto_ptr<SAMLResponse> r(binding->send((*ep)->getLocation(), *(req.get()), &ctx));
896                 if (r->isSigned()) {
897                     // TODO: trust stuff will be changing anyway...
898                     //if (!t.validate(*r,AA))
899                     //    throw TrustException("Unable to verify signed response message.");
900                 }
901                 else if (!ctx.isAuthenticated() || XMLString::compareNString((*ep)->getLocation(),https,6))
902                     throw XMLSecurityException("Response message was unauthenticated.");
903                 response = r.release();
904             }
905             catch (exception& e) {
906                 m_log->error("caught exception during SAML attribute query: %s", e.what());
907             }
908         }
909
910         if (response) {
911             if (signedResponse.first && signedResponse.second && !response->isSigned()) {
912                 delete response;
913                 m_log->error("unsigned response obtained, but we were told it must be signed.");
914                 throw XMLSecurityException("Unable to obtain a signed response message.");
915             }
916             
917             // Iterate over the tokens and apply basic validation.
918             time_t now=time(NULL);
919             Iterator<SAMLAssertion*> assertions=response->getAssertions();
920             for (unsigned int a=0; a<assertions.size();) {
921                 // Discard any assertions not issued by the right entity.
922                 if (XMLString::compareString(source->getEntityID(),assertions[a]->getIssuer())) {
923                     xmltooling::auto_ptr_char bad(assertions[a]->getIssuer());
924                     m_log->warn("discarding assertion not issued by (%s), instead by (%s)",m_obj["provider_id"].string(),bad.get());
925                     response->removeAssertion(a);
926                     continue;
927                 }
928
929                 // Validate the token.
930                 try {
931                     application->validateToken(assertions[a],now,AA,application->getTrustEngine());
932                     a++;
933                 }
934                 catch (exception&) {
935                     m_log->warn("assertion failed to validate, removing it from response");
936                     response->removeAssertion(a);
937                 }
938             }
939
940             // Run it through the filter.
941             return make_pair(response,filter(response,application,AA));
942         }
943     }
944     catch (exception& e) {
945         m_log->error("caught exception during query to AA: %s", e.what());
946         throw;
947     }
948     
949     m_log->error("no response obtained");
950     return pair<SAMLResponse*,SAMLResponse*>(NULL,NULL);
951 }
952
953 SAMLResponse* MemorySessionCacheEntry::filter(
954     const SAMLResponse* r, const IApplication* application, const RoleDescriptor* role
955     ) const
956 {
957 #ifdef _DEBUG
958     xmltooling::NDC ndc("filter");
959 #endif
960
961     // Make a copy of the original and process that against the AAP.
962     auto_ptr<SAMLResponse> copy(static_cast<SAMLResponse*>(r->clone()));
963     copy->toDOM();
964
965     Iterator<SAMLAssertion*> copies=copy->getAssertions();
966     for (unsigned long j=0; j < copies.size();) {
967         try {
968             // Finally, filter the content.
969             shibboleth::AAP::apply(application->getAAPProviders(),*(copies[j]),role);
970             j++;
971
972         }
973         catch (exception&) {
974             m_log->info("no statements remain after AAP, removing assertion");
975             copy->removeAssertion(j);
976         }
977     }
978
979     // Audit the results.    
980     STConfig& stc=static_cast<STConfig&>(ShibTargetConfig::getConfig());
981     Category& tran=stc.getTransactionLog();
982     if (tran.isInfoEnabled()) {
983         tran.infoStream() <<
984             "Caching the following attributes after AAP applied for session (ID: " <<
985                 m_obj["key"].string() <<
986             ") on (applicationId: " <<
987                 m_obj["application_id"].string() <<
988             ") for principal from (IdP: " <<
989                 m_obj["provider_id"].string() <<
990             ") {";
991
992         Iterator<SAMLAssertion*> loggies=copy->getAssertions();
993         while (loggies.hasNext()) {
994             SAMLAssertion* logit=loggies.next();
995             Iterator<SAMLStatement*> states=logit->getStatements();
996             while (states.hasNext()) {
997                 SAMLAttributeStatement* state=dynamic_cast<SAMLAttributeStatement*>(states.next());
998                 Iterator<SAMLAttribute*> attrs=state ? state->getAttributes() : EMPTY(SAMLAttribute*);
999                 while (attrs.hasNext()) {
1000                     SAMLAttribute* attr=attrs.next();
1001                     xmltooling::auto_ptr_char attrname(attr->getName());
1002                     tran.infoStream() << "\t" << attrname.get() << " (" << attr->getValues().size() << " values)";
1003                 }
1004             }
1005         }
1006         tran.info("}");
1007     }
1008     stc.releaseTransactionLog();
1009     
1010     return copy.release();
1011 }
1012
1013 MemorySessionCache::MemorySessionCache(const DOMElement* e)
1014     : m_root(e), m_AATimeout(30), m_AAConnectTimeout(15), m_defaultLifetime(1800), m_retryInterval(300),
1015         m_strictValidity(true), m_propagateErrors(false), m_writeThrough(false), m_lock(RWLock::create()),
1016         m_log(&Category::getInstance(SHIBT_LOGCAT".SessionCache")),
1017         restoreInsert(NULL), restoreFind(NULL), restoreRemove(NULL), m_sink(NULL)
1018 {
1019     if (m_root) {
1020         const XMLCh* tag=m_root->getAttributeNS(NULL,AATimeout);
1021         if (tag && *tag) {
1022             m_AATimeout = XMLString::parseInt(tag);
1023             if (!m_AATimeout)
1024                 m_AATimeout=30;
1025         }
1026
1027         tag=m_root->getAttributeNS(NULL,AAConnectTimeout);
1028         if (tag && *tag) {
1029             m_AAConnectTimeout = XMLString::parseInt(tag);
1030             if (!m_AAConnectTimeout)
1031                 m_AAConnectTimeout=15;
1032         }
1033         
1034         tag=m_root->getAttributeNS(NULL,defaultLifetime);
1035         if (tag && *tag) {
1036             m_defaultLifetime = XMLString::parseInt(tag);
1037             if (!m_defaultLifetime)
1038                 m_defaultLifetime=1800;
1039         }
1040
1041         tag=m_root->getAttributeNS(NULL,retryInterval);
1042         if (tag && *tag) {
1043             m_retryInterval = XMLString::parseInt(tag);
1044             if (!m_retryInterval)
1045                 m_retryInterval=300;
1046         }
1047         
1048         tag=m_root->getAttributeNS(NULL,strictValidity);
1049         if (tag && (*tag==chDigit_0 || *tag==chLatin_f))
1050             m_strictValidity=false;
1051             
1052         tag=m_root->getAttributeNS(NULL,propagateErrors);
1053         if (tag && (*tag==chDigit_1 || *tag==chLatin_t))
1054             m_propagateErrors=true;
1055
1056         tag=m_root->getAttributeNS(NULL,writeThrough);
1057         if (tag && (*tag==chDigit_1 || *tag==chLatin_t))
1058             m_writeThrough=true;
1059     }
1060
1061     SAMLConfig::getConfig().timeout = m_AATimeout;
1062     SAMLConfig::getConfig().conn_timeout = m_AAConnectTimeout;
1063
1064     // Register for remoted messages.
1065     ListenerService* listener=SPConfig::getConfig().getServiceProvider()->getListenerService(false);
1066     if (listener && SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
1067         restoreInsert=listener->regListener("SessionCache::insert",this);
1068         restoreFind=listener->regListener("SessionCache::find",this);
1069         restoreRemove=listener->regListener("SessionCache::remove",this);
1070     }
1071     else
1072         m_log->info("no listener interface available, cache remoting is disabled");
1073
1074     shutdown_wait = CondWait::create();
1075     shutdown = false;
1076     cleanup_thread = Thread::create(&cleanup_fcn, (void*)this);
1077 }
1078
1079 MemorySessionCache::~MemorySessionCache()
1080 {
1081     // Shut down the cleanup thread and let it know...
1082     shutdown = true;
1083     shutdown_wait->signal();
1084     cleanup_thread->join(NULL);
1085
1086     // Unregister remoted messages.
1087     ListenerService* listener=SPConfig::getConfig().getServiceProvider()->getListenerService(false);
1088     if (listener && SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
1089         listener->unregListener("SessionCache::insert",this,restoreInsert);
1090         listener->unregListener("SessionCache::find",this,restoreFind);
1091         listener->unregListener("SessionCache::remove",this,restoreRemove);
1092     }
1093
1094     for_each(m_hashtable.begin(),m_hashtable.end(),xmltooling::cleanup_pair<string,MemorySessionCacheEntry>());
1095     delete m_lock;
1096     delete shutdown_wait;
1097 }
1098
1099 bool MemorySessionCache::setBackingStore(ISessionCacheStore* store)
1100 {
1101     if (m_sink && store!=m_sink)
1102         return false;
1103     m_sink=store;
1104     return true;
1105 }
1106
1107 /*
1108  * IPC message definitions:
1109  * 
1110  *  SessionCache::insert
1111  * 
1112  *      IN
1113  *      application_id
1114  *      client_address
1115  *      provider_id
1116  *      major_version
1117  *      minor_version
1118  *      authn_context
1119  *      subject
1120  *      tokens.unfiltered
1121  * 
1122  *      OUT
1123  *      key
1124  * 
1125  *  SessionCache::find
1126  * 
1127  *      IN
1128  *      key
1129  *      application_id
1130  *      client_address
1131  * 
1132  *      OUT
1133  *      client_address
1134  *      provider_id
1135  *      major_version
1136  *      minor_version
1137  *      authn_context
1138  *      subject
1139  *      tokens.unfiltered
1140  *      tokens.filtered
1141  * 
1142  *  SessionCache::remove
1143  * 
1144  *      IN
1145  *      key
1146  *      application_id
1147  *      client_address
1148  */
1149
1150 DDF MemorySessionCache::receive(const DDF& in)
1151 {
1152 #ifdef _DEBUG
1153     xmltooling::NDC ndc("receive");
1154 #endif
1155
1156     // Find application.
1157     xmltooling::Locker confLocker(SPConfig::getConfig().getServiceProvider());
1158     const char* aid=in["application_id"].string();
1159     const IApplication* app=aid ? dynamic_cast<const IApplication*>(SPConfig::getConfig().getServiceProvider()->getApplication(aid)) : NULL;
1160     if (!app) {
1161         // Something's horribly wrong.
1162         m_log->error("couldn't find application (%s) for session", aid ? aid : "(missing)");
1163         throw ConfigurationException("Unable to locate application for session, deleted?");
1164     }
1165
1166     if (!strcmp(in.name(),"SessionCache::find")) {
1167         // Check required parameters.
1168         const char* key=in["key"].string();
1169         const char* client_address=in["client_address"].string();
1170         if (!key || !client_address)
1171             throw SAMLException("Required parameters missing in call to SessionCache::find");
1172         
1173         try {        
1174             // Lookup the session and cast down to the internal type.
1175             MemorySessionCacheEntry* entry=dynamic_cast<MemorySessionCacheEntry*>(find(key,app,client_address));
1176             if (!entry)
1177                 return DDF();
1178             DDF dup=entry->getDDF().copy();
1179             entry->unlock();
1180             return dup;
1181         }
1182         catch (exception&) {
1183             remove(key,app,client_address);
1184             throw;
1185         }
1186     }
1187     else if (!strcmp(in.name(),"SessionCache::remove")) {
1188         // Check required parameters.
1189         const char* key=in["key"].string();
1190         const char* client_address=in["client_address"].string();
1191         if (!key || !client_address)
1192             throw SAMLException("Required parameters missing in call to SessionCache::remove");
1193         
1194         remove(key,app,client_address);
1195         return DDF();
1196     }
1197     else if (!strcmp(in.name(),"SessionCache::insert")) {
1198         // Check required parameters.
1199         const char* client_address=in["client_address"].string();
1200         const char* provider_id=in["provider_id"].string();
1201         const char* authn_context=in["authn_context"].string();
1202         const char* subject=in["subject"].string();
1203         const char* tokens=in["tokens.unfiltered"].string();
1204         if (!client_address || !provider_id || !authn_context || !subject || !tokens)
1205             throw SAMLException("Required parameters missing in call to SessionCache::insert");
1206         int minor=in["minor_version"].integer();
1207         
1208         // Locate entity descriptor to use in filtering.
1209         MetadataProvider* m=app->getMetadataProvider();
1210         xmltooling::Locker locker(m);
1211         const EntityDescriptor* site=m->getEntityDescriptor(provider_id);
1212         if (!site) {
1213             m_log->error("unable to locate issuing identity provider's metadata");
1214             throw MetadataException("Unable to locate identity provider's metadata.");
1215         }
1216         const RoleDescriptor* role=site->getAttributeAuthorityDescriptor(samlconstants::SAML11_PROTOCOL_ENUM);
1217         if (!role)
1218             role=site->getAttributeAuthorityDescriptor(samlconstants::SAML10_PROTOCOL_ENUM);
1219         if (!role)
1220             role=site->getIDPSSODescriptor(samlconstants::SAML11_PROTOCOL_ENUM);
1221         if (!role)
1222             role=site->getIDPSSODescriptor(samlconstants::SAML10_PROTOCOL_ENUM);
1223         if (!role) {
1224             m_log->error("unable to locate attribute-issuing role in identity provider's metadata");
1225             throw MetadataException("Unable to locate attribute-issuing role in identity provider's metadata.");
1226         }
1227
1228         // Deserialize XML for insert method.
1229         istringstream subis(subject);
1230         auto_ptr<SAMLSubject> pSubject(new SAMLSubject(subis));
1231         istringstream tokis(tokens);
1232         auto_ptr<SAMLResponse> pTokens(new SAMLResponse(tokis,minor));
1233         
1234         // Insert the data and return the cache key.
1235         string key=insert(app,role,client_address,pSubject.get(),authn_context,pTokens.get());
1236         
1237         DDF out(NULL);
1238         out.structure();
1239         out.addmember("key").string(key.c_str());
1240         return out;
1241     }
1242     throw ListenerException("Unsupported operation ($1)",xmltooling::params(1,in.name()));
1243 }
1244
1245 string MemorySessionCache::insert(
1246     const IApplication* application,
1247     const RoleDescriptor* role,
1248     const char* client_addr,
1249     const SAMLSubject* subject,
1250     const char* authnContext,
1251     const SAMLResponse* tokens
1252     )
1253 {
1254 #ifdef _DEBUG
1255     xmltooling::NDC ndc("insert");
1256 #endif
1257
1258     SAMLIdentifier id;
1259     xmltooling::auto_ptr_char key(id);
1260
1261     if (m_log->isDebugEnabled())
1262         m_log->debug("creating new cache entry for application %s: \"%s\"", application->getId(), key.get());
1263
1264     auto_ptr<MemorySessionCacheEntry> entry(
1265         new MemorySessionCacheEntry(
1266             this,
1267             key.get(),
1268             application,
1269             role,
1270             client_addr,
1271             subject,
1272             authnContext,
1273             tokens
1274             )
1275         );
1276     entry->populate(application,dynamic_cast<EntityDescriptor*>(role->getParent()),true);
1277
1278     if (m_sink) {
1279         HRESULT hr=m_sink->onCreate(key.get(),application,entry.get(),1,tokens->getMinorVersion(),entry->created());
1280         if (FAILED(hr)) {
1281             m_log->error("cache store returned failure while storing new entry");
1282             throw IOException("Unable to record new session in cache store.");
1283         }
1284     }
1285
1286     m_lock->wrlock();
1287     m_hashtable[key.get()]=entry.release();
1288     m_lock->unlock();
1289
1290     return key.get();
1291 }
1292
1293 ISessionCacheEntry* MemorySessionCache::find(const char* key, const IApplication* application, const char* client_addr)
1294 {
1295 #ifdef _DEBUG
1296     xmltooling::NDC ndc("find");
1297 #endif
1298
1299     m_log->debug("searching memory cache for key (%s)", key);
1300     m_lock->rdlock();
1301
1302     map<string,MemorySessionCacheEntry*>::const_iterator i=m_hashtable.find(key);
1303     if (i==m_hashtable.end()) {
1304         m_lock->unlock();
1305         m_log->debug("no match found");
1306         if (!m_sink)
1307             return NULL;    // no backing store to search
1308
1309         m_log->debug("searching backing store");
1310         string appid,addr,pid,sub,ac,tokens;
1311         int major,minor;
1312         time_t created,accessed;
1313         HRESULT hr=m_sink->onRead(key,appid,addr,pid,sub,ac,tokens,major,minor,created,accessed);
1314         if (hr==S_FALSE)
1315             return NULL;
1316         else if (FAILED(hr)) {
1317             m_log->error("cache store returned failure during search");
1318             return NULL;
1319         }
1320         const IApplication* eapp=dynamic_cast<const IApplication*>(SPConfig::getConfig().getServiceProvider()->getApplication(appid.c_str()));
1321         if (!eapp) {
1322             // Something's horribly wrong.
1323             m_log->error("couldn't find application (%s) for session", appid.c_str());
1324             if (FAILED(m_sink->onDelete(key)))
1325                 m_log->error("cache store returned failure during delete");
1326             return NULL;
1327         }
1328         if (m_log->isDebugEnabled())
1329             m_log->debug("loading cache entry (ID: %s) back into memory for application (%s)", key, appid.c_str());
1330
1331         // Locate role to use in filtering.
1332         MetadataProvider* m=eapp->getMetadataProvider();
1333         xmltooling::Locker locker(m);
1334         const EntityDescriptor* site=m->getEntityDescriptor(pid.c_str());
1335         if (!site) {
1336             m_log->error("unable to locate issuing identity provider's metadata");
1337             if (FAILED(m_sink->onDelete(key)))
1338                 m_log->error("cache store returned failure during delete");
1339             return NULL;
1340         }
1341         const RoleDescriptor* role=site->getAttributeAuthorityDescriptor(samlconstants::SAML11_PROTOCOL_ENUM);
1342         if (!role)
1343             role=site->getAttributeAuthorityDescriptor(samlconstants::SAML10_PROTOCOL_ENUM);
1344         if (!role)
1345             role=site->getIDPSSODescriptor(samlconstants::SAML11_PROTOCOL_ENUM);
1346         if (!role)
1347             role=site->getIDPSSODescriptor(samlconstants::SAML10_PROTOCOL_ENUM);
1348         if (!role) {
1349             m_log->error("unable to locate attribute-issuing role in identity provider's metadata");
1350             if (FAILED(m_sink->onDelete(key)))
1351                 m_log->error("cache store returned failure during delete");
1352             return NULL;
1353         }
1354
1355         MemorySessionCacheEntry* entry = new MemorySessionCacheEntry(
1356             this,
1357             key,
1358             eapp,
1359             role,
1360             addr.c_str(),
1361             sub.c_str(),
1362             ac.c_str(),
1363             tokens.c_str(),
1364             major,
1365             minor,
1366             created,
1367             accessed
1368             );
1369         m_lock->wrlock();
1370         m_hashtable[key]=entry;
1371         m_lock->unlock();
1372
1373         // Downgrade to a read lock and repeat the initial search.
1374         m_lock->rdlock();
1375         i=m_hashtable.find(key);
1376         if (i==m_hashtable.end()) {
1377             m_lock->unlock();
1378             m_log->warn("cache entry was loaded from backing store, but disappeared after lock downgrade");
1379             return NULL;
1380         }
1381     }
1382     else
1383         m_log->debug("match found");
1384
1385     // Check for application mismatch (could also do this with partitioned caches by application ID)
1386     if (!i->second->checkApplication(application)) {
1387         m_lock->unlock();
1388         m_log->crit("An application (%s) attempted to access another application's session!", application->getId());
1389         return NULL;
1390     }
1391     
1392     // Check for timeouts, expiration, address mismatch, etc (also updates last access)
1393     // Use the return code to assign specific error messages.
1394     try {
1395         HRESULT hr=i->second->isValid(application, client_addr);
1396         if (FAILED(hr)) {
1397             MetadataProvider* m=application->getMetadataProvider();
1398             xmltooling::Locker locker(m);
1399             switch (hr) {
1400                 case SESSION_E_EXPIRED: {
1401                     opensaml::RetryableProfileException ex("Your session has expired, and you must re-authenticate.");
1402                     annotateException(&ex,m->getEntityDescriptor(i->second->getProviderId(),false)); // throws it
1403                 }
1404                 
1405                 case SESSION_E_ADDRESSMISMATCH: {
1406                     opensaml::RetryableProfileException ex(
1407                         "Your IP address ($1) does not match the address recorded at the time the session was established.",
1408                         xmltooling::params(1,client_addr)
1409                         );
1410                     annotateException(&ex,m->getEntityDescriptor(i->second->getProviderId(),false)); // throws it
1411                 }
1412                 
1413                 default: {
1414                     opensaml::RetryableProfileException ex("Your session is invalid.");
1415                     annotateException(&ex,m->getEntityDescriptor(i->second->getProviderId(),false)); // throws it
1416                 }
1417             }
1418         }
1419     }
1420     catch (...) {
1421         m_lock->unlock();
1422         throw;
1423     }
1424
1425     // Lock the cache entry for the caller -- they have to unlock it.
1426     i->second->lock();
1427     m_lock->unlock();
1428
1429     try {
1430         // Make sure the entry has valid tokens.
1431         MetadataProvider* m=application->getMetadataProvider();
1432         xmltooling::Locker locker(m);
1433         i->second->populate(application,m->getEntityDescriptor(i->second->getProviderId()));
1434     }
1435     catch (...) {
1436         i->second->unlock();
1437         throw;
1438     }
1439
1440     return i->second;
1441 }
1442
1443 void MemorySessionCache::remove(const char* key, const IApplication* application, const char* client_addr)
1444 {
1445 #ifdef _DEBUG
1446     xmltooling::NDC ndc("remove");
1447 #endif
1448
1449     m_log->debug("removing cache entry with key (%s)", key);
1450
1451     // lock the cache for writing, which means we know nobody is sitting in find()
1452     m_lock->wrlock();
1453
1454     // grab the entry from the database.
1455     map<string,MemorySessionCacheEntry*>::const_iterator i=m_hashtable.find(key);
1456     if (i==m_hashtable.end()) {
1457         m_lock->unlock();
1458         return;
1459     }
1460
1461     // ok, remove the entry and lock it
1462     MemorySessionCacheEntry* entry=i->second;
1463     m_hashtable.erase(key);
1464     entry->lock();
1465     
1466     // unlock the cache
1467     m_lock->unlock();
1468
1469     entry->unlock();
1470
1471     // Notify sink. Smart ptr will make sure entry gets deleted.
1472     auto_ptr<ISessionCacheEntry> entrywrap(entry);
1473     if (m_sink) {
1474         if (FAILED(m_sink->onDelete(key)))
1475             m_log->error("cache store failed to delete entry");
1476     }
1477
1478     // Transaction Logging
1479     STConfig& stc=static_cast<STConfig&>(ShibTargetConfig::getConfig());
1480     stc.getTransactionLog().infoStream() << "Destroyed session (ID: " << key << ")";
1481     stc.releaseTransactionLog();
1482 }
1483
1484 void MemorySessionCache::dormant(const char* key)
1485 {
1486 #ifdef _DEBUG
1487     xmltooling::NDC ndc("dormant");
1488 #endif
1489
1490     m_log->debug("purging old cache entry with key (%s)", key);
1491
1492     // lock the cache for writing, which means we know nobody is sitting in find()
1493     m_lock->wrlock();
1494
1495     // grab the entry from the database.
1496     map<string,MemorySessionCacheEntry*>::const_iterator i=m_hashtable.find(key);
1497     if (i==m_hashtable.end()) {
1498         m_lock->unlock();
1499         return;
1500     }
1501
1502     // ok, remove the entry and lock it
1503     MemorySessionCacheEntry* entry=i->second;
1504     m_hashtable.erase(key);
1505     entry->lock();
1506     
1507     // unlock the cache
1508     m_lock->unlock();
1509
1510     // we can release the cache entry lock because we know we're not in the cache anymore
1511     entry->unlock();
1512
1513     auto_ptr<ISessionCacheEntry> entrywrap(entry);
1514     if (m_sink && !m_writeThrough) {
1515         // Update sink with last access data. Wrapper will make sure entry gets deleted.
1516         if (FAILED(m_sink->onUpdate(key,NULL,entry->lastAccess())))
1517             m_log->error("cache store failed to update last access timestamp");
1518     }
1519 }
1520
1521 void MemorySessionCache::cleanup()
1522 {
1523 #ifdef _DEBUG
1524     xmltooling::NDC ndc("cleanup()");
1525 #endif
1526
1527     int rerun_timer = 0;
1528     int timeout_life = 0;
1529     Mutex* mutex = Mutex::create();
1530   
1531     // Load our configuration details...
1532     const XMLCh* tag=m_root->getAttributeNS(NULL,cleanupInterval);
1533     if (tag && *tag)
1534         rerun_timer = XMLString::parseInt(tag);
1535
1536     tag=m_root->getAttributeNS(NULL,cacheTimeout);
1537     if (tag && *tag)
1538         timeout_life = XMLString::parseInt(tag);
1539   
1540     if (rerun_timer <= 0)
1541         rerun_timer = 300;        // rerun every 5 minutes
1542
1543     if (timeout_life <= 0)
1544         timeout_life = 28800; // timeout after 8 hours
1545
1546     mutex->lock();
1547
1548     m_log->info("cleanup thread started...Run every %d secs; timeout after %d secs", rerun_timer, timeout_life);
1549
1550     while (!shutdown) {
1551         shutdown_wait->timedwait(mutex,rerun_timer);
1552         if (shutdown)
1553             break;
1554
1555         // Ok, let's run through the cleanup process and clean out
1556         // really old sessions.  This is a two-pass process.  The
1557         // first pass is done holding a read-lock while we iterate over
1558         // the cache.  The second pass doesn't need a lock because
1559         // the 'deletes' will lock the cache.
1560     
1561         // Pass 1: iterate over the map and find all entries that have not been
1562         // used in X hours
1563         vector<string> stale_keys;
1564         time_t stale = time(NULL) - timeout_life;
1565     
1566         m_lock->rdlock();
1567         for (map<string,MemorySessionCacheEntry*>::const_iterator i=m_hashtable.begin(); i!=m_hashtable.end(); i++)
1568         {
1569             // If the last access was BEFORE the stale timeout...
1570             i->second->lock();
1571             time_t last=i->second->lastAccess();
1572             i->second->unlock();
1573             if (last < stale)
1574                 stale_keys.push_back(i->first);
1575         }
1576         m_lock->unlock();
1577     
1578         if (!stale_keys.empty()) {
1579             m_log->info("purging %d old sessions", stale_keys.size());
1580     
1581             // Pass 2: walk through the list of stale entries and remove them from the cache
1582             for (vector<string>::const_iterator j = stale_keys.begin(); j != stale_keys.end(); j++)
1583                 dormant(j->c_str());
1584         }
1585     }
1586
1587     m_log->info("cleanup thread finished.");
1588
1589     mutex->unlock();
1590     delete mutex;
1591     Thread::exit(NULL);
1592 }
1593
1594 void* MemorySessionCache::cleanup_fcn(void* cache_p)
1595 {
1596     MemorySessionCache* cache = reinterpret_cast<MemorySessionCache*>(cache_p);
1597
1598 #ifndef WIN32
1599     // First, let's block all signals 
1600     Thread::mask_all_signals();
1601 #endif
1602
1603     // Now run the cleanup process.
1604     cache->cleanup();
1605     return NULL;
1606 }
1607
1608 SessionCache* MemoryCacheFactory(const DOMElement* const & e)
1609 {
1610     // If this is a long-lived process, we return the "real" cache.
1611     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess))
1612         return new MemorySessionCache(e);
1613     // Otherwise, we return a stubbed front-end that remotes calls to the real cache.
1614     return new StubCache(e);
1615 }