Home | History | Annotate | Download | only in socket
      1 // Copyright 2013 The Chromium Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style license that can be
      3 // found in the LICENSE file.
      4 
      5 #include "net/socket/ssl_session_cache_openssl.h"
      6 
      7 #include <list>
      8 #include <map>
      9 
     10 #include <openssl/rand.h>
     11 #include <openssl/ssl.h>
     12 
     13 #include "base/containers/hash_tables.h"
     14 #include "base/lazy_instance.h"
     15 #include "base/logging.h"
     16 #include "base/synchronization/lock.h"
     17 
     18 namespace net {
     19 
     20 namespace {
     21 
     22 // A helper class to lazily create a new EX_DATA index to map SSL_CTX handles
     23 // to their corresponding SSLSessionCacheOpenSSLImpl object.
     24 class SSLContextExIndex {
     25 public:
     26   SSLContextExIndex() {
     27     context_index_ = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, NULL);
     28     DCHECK_NE(-1, context_index_);
     29     session_index_ = SSL_SESSION_get_ex_new_index(0, NULL, NULL, NULL, NULL);
     30     DCHECK_NE(-1, session_index_);
     31   }
     32 
     33   int context_index() const { return context_index_; }
     34   int session_index() const { return session_index_; }
     35 
     36  private:
     37   int context_index_;
     38   int session_index_;
     39 };
     40 
     41 // static
     42 base::LazyInstance<SSLContextExIndex>::Leaky s_ssl_context_ex_instance =
     43     LAZY_INSTANCE_INITIALIZER;
     44 
     45 // Retrieve the global EX_DATA index, created lazily on first call, to
     46 // be used with SSL_CTX_set_ex_data() and SSL_CTX_get_ex_data().
     47 static int GetSSLContextExIndex() {
     48   return s_ssl_context_ex_instance.Get().context_index();
     49 }
     50 
     51 // Retrieve the global EX_DATA index, created lazily on first call, to
     52 // be used with SSL_SESSION_set_ex_data() and SSL_SESSION_get_ex_data().
     53 static int GetSSLSessionExIndex() {
     54   return s_ssl_context_ex_instance.Get().session_index();
     55 }
     56 
     57 // Helper struct used to store session IDs in a SessionIdIndex container
     58 // (see definition below). To save memory each entry only holds a pointer
     59 // to the session ID buffer, which must outlive the entry itself. On the
     60 // other hand, a hash is included to minimize the number of hashing
     61 // computations during cache operations.
     62 struct SessionId {
     63   SessionId(const unsigned char* a_id, unsigned a_id_len)
     64       : id(a_id), id_len(a_id_len), hash(ComputeHash(a_id, a_id_len)) {}
     65 
     66   explicit SessionId(const SessionId& other)
     67       : id(other.id), id_len(other.id_len), hash(other.hash) {}
     68 
     69   explicit SessionId(SSL_SESSION* session)
     70       : id(session->session_id),
     71         id_len(session->session_id_length),
     72         hash(ComputeHash(session->session_id, session->session_id_length)) {}
     73 
     74   bool operator==(const SessionId& other) const {
     75     return hash == other.hash && id_len == other.id_len &&
     76            !memcmp(id, other.id, id_len);
     77   }
     78 
     79   const unsigned char* id;
     80   unsigned id_len;
     81   size_t hash;
     82 
     83  private:
     84   // Session ID are random strings of bytes. This happens to compute the same
     85   // value as std::hash<std::string> without the extra string copy. See
     86   // base/containers/hash_tables.h. Other hashing computations are possible,
     87   // this one is just simple enough to do the job.
     88   size_t ComputeHash(const unsigned char* id, unsigned id_len) {
     89     size_t result = 0;
     90     for (unsigned n = 0; n < id_len; ++n)
     91       result += 131 * id[n];
     92     return result;
     93   }
     94 };
     95 
     96 }  // namespace
     97 
     98 }  // namespace net
     99 
    100 namespace BASE_HASH_NAMESPACE {
    101 
    102 template <>
    103 struct hash<net::SessionId> {
    104   std::size_t operator()(const net::SessionId& entry) const {
    105     return entry.hash;
    106   }
    107 };
    108 
    109 }  // namespace BASE_HASH_NAMESPACE
    110 
    111 namespace net {
    112 
    113 // Implementation of the real SSLSessionCache.
    114 //
    115 // The implementation is inspired by base::MRUCache, except that the deletor
    116 // also needs to remove the entry from other containers. In a nutshell, this
    117 // uses several basic containers:
    118 //
    119 //   |ordering_| is a doubly-linked list of SSL_SESSION handles, ordered in
    120 //   MRU order.
    121 //
    122 //   |key_index_| is a hash table mapping unique cache keys (e.g. host/port
    123 //   values) to a single iterator of |ordering_|. It is used to efficiently
    124 //   find the cached session associated with a given key.
    125 //
    126 //   |id_index_| is a hash table mapping SessionId values to iterators
    127 //   of |key_index_|. If is used to efficiently remove sessions from the cache,
    128 //   as well as check for the existence of a session ID value in the cache.
    129 //
    130 //   SSL_SESSION objects are reference-counted, and owned by the cache. This
    131 //   means that their reference count is incremented when they are added, and
    132 //   decremented when they are removed.
    133 //
    134 // Assuming an average key size of 100 characters, each node requires the
    135 // following memory usage on 32-bit Android, when linked against STLport:
    136 //
    137 //      12   (ordering_ node, including SSL_SESSION handle)
    138 //     100   (key characters)
    139 //    + 24   (std::string header/minimum size)
    140 //    +  8   (key_index_ node, excluding the 2 lines above for the key).
    141 //    + 20   (id_index_ node)
    142 //  --------
    143 //     164   bytes/node
    144 //
    145 // Hence, 41 KiB for a full cache with a maximum of 1024 entries, excluding
    146 // the size of SSL_SESSION objects and heap fragmentation.
    147 //
    148 
    149 class SSLSessionCacheOpenSSLImpl {
    150  public:
    151   // Construct new instance. This registers various hooks into the SSL_CTX
    152   // context |ctx|. OpenSSL will call back during SSL connection
    153   // operations. |key_func| is used to map a SSL handle to a unique cache
    154   // string, according to the client's preferences.
    155   SSLSessionCacheOpenSSLImpl(SSL_CTX* ctx,
    156                              const SSLSessionCacheOpenSSL::Config& config)
    157       : ctx_(ctx), config_(config), expiration_check_(0) {
    158     DCHECK(ctx);
    159 
    160     // NO_INTERNAL_STORE disables OpenSSL's builtin cache, and
    161     // NO_AUTO_CLEAR disables the call to SSL_CTX_flush_sessions
    162     // every 256 connections (this number is hard-coded in the library
    163     // and can't be changed).
    164     SSL_CTX_set_session_cache_mode(ctx_,
    165                                    SSL_SESS_CACHE_CLIENT |
    166                                        SSL_SESS_CACHE_NO_INTERNAL_STORE |
    167                                        SSL_SESS_CACHE_NO_AUTO_CLEAR);
    168 
    169     SSL_CTX_sess_set_new_cb(ctx_, NewSessionCallbackStatic);
    170     SSL_CTX_sess_set_remove_cb(ctx_, RemoveSessionCallbackStatic);
    171     SSL_CTX_set_generate_session_id(ctx_, GenerateSessionIdStatic);
    172     SSL_CTX_set_timeout(ctx_, config_.timeout_seconds);
    173 
    174     SSL_CTX_set_ex_data(ctx_, GetSSLContextExIndex(), this);
    175   }
    176 
    177   // Destroy this instance. Must happen before |ctx_| is destroyed.
    178   ~SSLSessionCacheOpenSSLImpl() {
    179     Flush();
    180     SSL_CTX_set_ex_data(ctx_, GetSSLContextExIndex(), NULL);
    181     SSL_CTX_sess_set_new_cb(ctx_, NULL);
    182     SSL_CTX_sess_set_remove_cb(ctx_, NULL);
    183     SSL_CTX_set_generate_session_id(ctx_, NULL);
    184   }
    185 
    186   // Return the number of items in this cache.
    187   size_t size() const { return key_index_.size(); }
    188 
    189   // Retrieve the cache key from |ssl| and look for a corresponding
    190   // cached session ID. If one is found, call SSL_set_session() to associate
    191   // it with the |ssl| connection.
    192   //
    193   // Will also check for expired sessions every |expiration_check_count|
    194   // calls.
    195   //
    196   // Return true if a cached session ID was found, false otherwise.
    197   bool SetSSLSession(SSL* ssl) {
    198     std::string cache_key = config_.key_func(ssl);
    199     if (cache_key.empty())
    200       return false;
    201 
    202     return SetSSLSessionWithKey(ssl, cache_key);
    203   }
    204 
    205   // Variant of SetSSLSession to be used when the client already has computed
    206   // the cache key. Avoid a call to the configuration's |key_func| function.
    207   bool SetSSLSessionWithKey(SSL* ssl, const std::string& cache_key) {
    208     base::AutoLock locked(lock_);
    209 
    210     DCHECK_EQ(config_.key_func(ssl), cache_key);
    211 
    212     if (++expiration_check_ >= config_.expiration_check_count) {
    213       expiration_check_ = 0;
    214       FlushExpiredSessionsLocked();
    215     }
    216 
    217     KeyIndex::iterator it = key_index_.find(cache_key);
    218     if (it == key_index_.end())
    219       return false;
    220 
    221     SSL_SESSION* session = *it->second;
    222     DCHECK(session);
    223 
    224     DVLOG(2) << "Lookup session: " << session << " for " << cache_key;
    225 
    226     void* session_is_good =
    227         SSL_SESSION_get_ex_data(session, GetSSLSessionExIndex());
    228     if (!session_is_good)
    229       return false;  // Session has not yet been marked good. Treat as a miss.
    230 
    231     // Move to front of MRU list.
    232     ordering_.push_front(session);
    233     ordering_.erase(it->second);
    234     it->second = ordering_.begin();
    235 
    236     return SSL_set_session(ssl, session) == 1;
    237   }
    238 
    239   void MarkSSLSessionAsGood(SSL* ssl) {
    240     SSL_SESSION* session = SSL_get_session(ssl);
    241     if (!session)
    242       return;
    243 
    244     // Mark the session as good, allowing it to be used for future connections.
    245     SSL_SESSION_set_ex_data(
    246         session, GetSSLSessionExIndex(), reinterpret_cast<void*>(1));
    247   }
    248 
    249   // Flush all entries from the cache.
    250   void Flush() {
    251     base::AutoLock lock(lock_);
    252     id_index_.clear();
    253     key_index_.clear();
    254     while (!ordering_.empty()) {
    255       SSL_SESSION* session = ordering_.front();
    256       ordering_.pop_front();
    257       SSL_SESSION_free(session);
    258     }
    259   }
    260 
    261  private:
    262   // Type for list of SSL_SESSION handles, ordered in MRU order.
    263   typedef std::list<SSL_SESSION*> MRUSessionList;
    264   // Type for a dictionary from unique cache keys to session list nodes.
    265   typedef base::hash_map<std::string, MRUSessionList::iterator> KeyIndex;
    266   // Type for a dictionary from SessionId values to key index nodes.
    267   typedef base::hash_map<SessionId, KeyIndex::iterator> SessionIdIndex;
    268 
    269   // Return the key associated with a given session, or the empty string if
    270   // none exist. This shall only be used for debugging.
    271   std::string SessionKey(SSL_SESSION* session) {
    272     if (!session)
    273       return std::string("<null-session>");
    274 
    275     if (session->session_id_length == 0)
    276       return std::string("<empty-session-id>");
    277 
    278     SessionIdIndex::iterator it = id_index_.find(SessionId(session));
    279     if (it == id_index_.end())
    280       return std::string("<unknown-session>");
    281 
    282     return it->second->first;
    283   }
    284 
    285   // Remove a given |session| from the cache. Lock must be held.
    286   void RemoveSessionLocked(SSL_SESSION* session) {
    287     lock_.AssertAcquired();
    288     DCHECK(session);
    289     DCHECK_GT(session->session_id_length, 0U);
    290     SessionId session_id(session);
    291     SessionIdIndex::iterator id_it = id_index_.find(session_id);
    292     if (id_it == id_index_.end()) {
    293       LOG(ERROR) << "Trying to remove unknown session from cache: " << session;
    294       return;
    295     }
    296     KeyIndex::iterator key_it = id_it->second;
    297     DCHECK(key_it != key_index_.end());
    298     DCHECK_EQ(session, *key_it->second);
    299 
    300     id_index_.erase(session_id);
    301     ordering_.erase(key_it->second);
    302     key_index_.erase(key_it);
    303 
    304     SSL_SESSION_free(session);
    305 
    306     DCHECK_EQ(key_index_.size(), id_index_.size());
    307   }
    308 
    309   // Used internally to flush expired sessions. Lock must be held.
    310   void FlushExpiredSessionsLocked() {
    311     lock_.AssertAcquired();
    312 
    313     // Unfortunately, OpenSSL initializes |session->time| with a time()
    314     // timestamps, which makes mocking / unit testing difficult.
    315     long timeout_secs = static_cast<long>(::time(NULL));
    316     MRUSessionList::iterator it = ordering_.begin();
    317     while (it != ordering_.end()) {
    318       SSL_SESSION* session = *it++;
    319 
    320       // Important, use <= instead of < here to allow unit testing to
    321       // work properly. That's because unit tests that check the expiration
    322       // behaviour will use a session timeout of 0 seconds.
    323       if (session->time + session->timeout <= timeout_secs) {
    324         DVLOG(2) << "Expiring session " << session << " for "
    325                  << SessionKey(session);
    326         RemoveSessionLocked(session);
    327       }
    328     }
    329   }
    330 
    331   // Retrieve the cache associated with a given SSL context |ctx|.
    332   static SSLSessionCacheOpenSSLImpl* GetCache(SSL_CTX* ctx) {
    333     DCHECK(ctx);
    334     void* result = SSL_CTX_get_ex_data(ctx, GetSSLContextExIndex());
    335     DCHECK(result);
    336     return reinterpret_cast<SSLSessionCacheOpenSSLImpl*>(result);
    337   }
    338 
    339   // Called by OpenSSL when a new |session| was created and added to a given
    340   // |ssl| connection. Note that the session's reference count was already
    341   // incremented before the function is entered. The function must return 1
    342   // to indicate that it took ownership of the session, i.e. that the caller
    343   // should not decrement its reference count after completion.
    344   static int NewSessionCallbackStatic(SSL* ssl, SSL_SESSION* session) {
    345     GetCache(ssl->ctx)->OnSessionAdded(ssl, session);
    346     return 1;
    347   }
    348 
    349   // Called by OpenSSL to indicate that a session must be removed from the
    350   // cache. This happens when SSL_CTX is destroyed.
    351   static void RemoveSessionCallbackStatic(SSL_CTX* ctx, SSL_SESSION* session) {
    352     GetCache(ctx)->OnSessionRemoved(session);
    353   }
    354 
    355   // Called by OpenSSL to generate a new session ID. This happens during a
    356   // SSL connection operation, when the SSL object doesn't have a session yet.
    357   //
    358   // A session ID is a random string of bytes used to uniquely identify the
    359   // session between a client and a server.
    360   //
    361   // |ssl| is a SSL connection handle. Ignored here.
    362   // |id| is the target buffer where the ID must be generated.
    363   // |*id_len| is, on input, the size of the desired ID. It will be 16 for
    364   // SSLv2, and 32 for anything else. OpenSSL allows an implementation
    365   // to change it on output, but this will not happen here.
    366   //
    367   // The function must ensure the generated ID is really unique, i.e. that
    368   // another session in the cache doesn't already use the same value. It must
    369   // return 1 to indicate success, or 0 for failure.
    370   static int GenerateSessionIdStatic(const SSL* ssl,
    371                                      unsigned char* id,
    372                                      unsigned* id_len) {
    373     if (!GetCache(ssl->ctx)->OnGenerateSessionId(id, *id_len))
    374       return 0;
    375 
    376     return 1;
    377   }
    378 
    379   // Add |session| to the cache in association with |cache_key|. If a session
    380   // already exists, it is replaced with the new one. This assumes that the
    381   // caller already incremented the session's reference count.
    382   void OnSessionAdded(SSL* ssl, SSL_SESSION* session) {
    383     base::AutoLock locked(lock_);
    384     DCHECK(ssl);
    385     DCHECK_GT(session->session_id_length, 0U);
    386     std::string cache_key = config_.key_func(ssl);
    387     KeyIndex::iterator it = key_index_.find(cache_key);
    388     if (it == key_index_.end()) {
    389       DVLOG(2) << "Add session " << session << " for " << cache_key;
    390       // This is a new session. Add it to the cache.
    391       ordering_.push_front(session);
    392       std::pair<KeyIndex::iterator, bool> ret =
    393           key_index_.insert(std::make_pair(cache_key, ordering_.begin()));
    394       DCHECK(ret.second);
    395       it = ret.first;
    396       DCHECK(it != key_index_.end());
    397     } else {
    398       // An existing session exists for this key, so replace it if needed.
    399       DVLOG(2) << "Replace session " << *it->second << " with " << session
    400                << " for " << cache_key;
    401       SSL_SESSION* old_session = *it->second;
    402       if (old_session != session) {
    403         id_index_.erase(SessionId(old_session));
    404         SSL_SESSION_free(old_session);
    405       }
    406       ordering_.erase(it->second);
    407       ordering_.push_front(session);
    408       it->second = ordering_.begin();
    409     }
    410 
    411     id_index_[SessionId(session)] = it;
    412 
    413     if (key_index_.size() > config_.max_entries)
    414       ShrinkCacheLocked();
    415 
    416     DCHECK_EQ(key_index_.size(), id_index_.size());
    417     DCHECK_LE(key_index_.size(), config_.max_entries);
    418   }
    419 
    420   // Shrink the cache to ensure no more than config_.max_entries entries,
    421   // starting with older entries first. Lock must be acquired.
    422   void ShrinkCacheLocked() {
    423     lock_.AssertAcquired();
    424     DCHECK_EQ(key_index_.size(), ordering_.size());
    425     DCHECK_EQ(key_index_.size(), id_index_.size());
    426 
    427     while (key_index_.size() > config_.max_entries) {
    428       MRUSessionList::reverse_iterator it = ordering_.rbegin();
    429       DCHECK(it != ordering_.rend());
    430 
    431       SSL_SESSION* session = *it;
    432       DCHECK(session);
    433       DVLOG(2) << "Evicting session " << session << " for "
    434                << SessionKey(session);
    435       RemoveSessionLocked(session);
    436     }
    437   }
    438 
    439   // Remove |session| from the cache.
    440   void OnSessionRemoved(SSL_SESSION* session) {
    441     base::AutoLock locked(lock_);
    442     DVLOG(2) << "Remove session " << session << " for " << SessionKey(session);
    443     RemoveSessionLocked(session);
    444   }
    445 
    446   // See GenerateSessionIdStatic for a description of what this function does.
    447   bool OnGenerateSessionId(unsigned char* id, unsigned id_len) {
    448     base::AutoLock locked(lock_);
    449     // This mimics def_generate_session_id() in openssl/ssl/ssl_sess.cc,
    450     // I.e. try to generate a pseudo-random bit string, and check that no
    451     // other entry in the cache has the same value.
    452     const size_t kMaxTries = 10;
    453     for (size_t tries = 0; tries < kMaxTries; ++tries) {
    454       if (RAND_pseudo_bytes(id, id_len) <= 0) {
    455         DLOG(ERROR) << "Couldn't generate " << id_len
    456                     << " pseudo random bytes?";
    457         return false;
    458       }
    459       if (id_index_.find(SessionId(id, id_len)) == id_index_.end())
    460         return true;
    461     }
    462     DLOG(ERROR) << "Couldn't generate unique session ID of " << id_len
    463                 << "bytes after " << kMaxTries << " tries.";
    464     return false;
    465   }
    466 
    467   SSL_CTX* ctx_;
    468   SSLSessionCacheOpenSSL::Config config_;
    469 
    470   // method to get the index which can later be used with SSL_CTX_get_ex_data()
    471   // or SSL_CTX_set_ex_data().
    472   base::Lock lock_;  // Protects access to containers below.
    473 
    474   MRUSessionList ordering_;
    475   KeyIndex key_index_;
    476   SessionIdIndex id_index_;
    477 
    478   size_t expiration_check_;
    479 };
    480 
    481 SSLSessionCacheOpenSSL::~SSLSessionCacheOpenSSL() { delete impl_; }
    482 
    483 size_t SSLSessionCacheOpenSSL::size() const { return impl_->size(); }
    484 
    485 void SSLSessionCacheOpenSSL::Reset(SSL_CTX* ctx, const Config& config) {
    486   if (impl_)
    487     delete impl_;
    488 
    489   impl_ = new SSLSessionCacheOpenSSLImpl(ctx, config);
    490 }
    491 
    492 bool SSLSessionCacheOpenSSL::SetSSLSession(SSL* ssl) {
    493   return impl_->SetSSLSession(ssl);
    494 }
    495 
    496 bool SSLSessionCacheOpenSSL::SetSSLSessionWithKey(
    497     SSL* ssl,
    498     const std::string& cache_key) {
    499   return impl_->SetSSLSessionWithKey(ssl, cache_key);
    500 }
    501 
    502 void SSLSessionCacheOpenSSL::MarkSSLSessionAsGood(SSL* ssl) {
    503   return impl_->MarkSSLSessionAsGood(ssl);
    504 }
    505 
    506 void SSLSessionCacheOpenSSL::Flush() { impl_->Flush(); }
    507 
    508 }  // namespace net
    509