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