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