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