Add integration browser tests for settings hardening.
[chromium-blink-merge.git] / net / socket / ssl_session_cache_openssl.cc
blob5bb0d16a31c8383e1d6d5367a01e8e03529789ed
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/callback.h"
14 #include "base/containers/hash_tables.h"
15 #include "base/lazy_instance.h"
16 #include "base/logging.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 += 131 * id[n];
93 return result;
97 } // namespace
99 } // namespace net
101 namespace BASE_HASH_NAMESPACE {
103 template <>
104 struct hash<net::SessionId> {
105 std::size_t operator()(const net::SessionId& entry) const {
106 return entry.hash;
110 } // namespace BASE_HASH_NAMESPACE
112 namespace net {
114 // Implementation of the real SSLSessionCache.
116 // The implementation is inspired by base::MRUCache, except that the deletor
117 // also needs to remove the entry from other containers. In a nutshell, this
118 // uses several basic containers:
120 // |ordering_| is a doubly-linked list of SSL_SESSION handles, ordered in
121 // MRU order.
123 // |key_index_| is a hash table mapping unique cache keys (e.g. host/port
124 // values) to a single iterator of |ordering_|. It is used to efficiently
125 // find the cached session associated with a given key.
127 // |id_index_| is a hash table mapping SessionId values to iterators
128 // of |key_index_|. If is used to efficiently remove sessions from the cache,
129 // as well as check for the existence of a session ID value in the cache.
131 // SSL_SESSION objects are reference-counted, and owned by the cache. This
132 // means that their reference count is incremented when they are added, and
133 // decremented when they are removed.
135 // Assuming an average key size of 100 characters, each node requires the
136 // following memory usage on 32-bit Android, when linked against STLport:
138 // 12 (ordering_ node, including SSL_SESSION handle)
139 // 100 (key characters)
140 // + 24 (std::string header/minimum size)
141 // + 8 (key_index_ node, excluding the 2 lines above for the key).
142 // + 20 (id_index_ node)
143 // --------
144 // 164 bytes/node
146 // Hence, 41 KiB for a full cache with a maximum of 1024 entries, excluding
147 // the size of SSL_SESSION objects and heap fragmentation.
150 class SSLSessionCacheOpenSSLImpl {
151 public:
152 // Construct new instance. This registers various hooks into the SSL_CTX
153 // context |ctx|. OpenSSL will call back during SSL connection
154 // operations. |key_func| is used to map a SSL handle to a unique cache
155 // string, according to the client's preferences.
156 SSLSessionCacheOpenSSLImpl(SSL_CTX* ctx,
157 const SSLSessionCacheOpenSSL::Config& config)
158 : ctx_(ctx), config_(config), expiration_check_(0) {
159 DCHECK(ctx);
161 // NO_INTERNAL_STORE disables OpenSSL's builtin cache, and
162 // NO_AUTO_CLEAR disables the call to SSL_CTX_flush_sessions
163 // every 256 connections (this number is hard-coded in the library
164 // and can't be changed).
165 SSL_CTX_set_session_cache_mode(ctx_,
166 SSL_SESS_CACHE_CLIENT |
167 SSL_SESS_CACHE_NO_INTERNAL_STORE |
168 SSL_SESS_CACHE_NO_AUTO_CLEAR);
170 SSL_CTX_sess_set_new_cb(ctx_, NewSessionCallbackStatic);
171 SSL_CTX_sess_set_remove_cb(ctx_, RemoveSessionCallbackStatic);
172 SSL_CTX_set_generate_session_id(ctx_, GenerateSessionIdStatic);
173 SSL_CTX_set_timeout(ctx_, config_.timeout_seconds);
175 SSL_CTX_set_ex_data(ctx_, GetSSLContextExIndex(), this);
178 // Destroy this instance. Must happen before |ctx_| is destroyed.
179 ~SSLSessionCacheOpenSSLImpl() {
180 Flush();
181 SSL_CTX_set_ex_data(ctx_, GetSSLContextExIndex(), NULL);
182 SSL_CTX_sess_set_new_cb(ctx_, NULL);
183 SSL_CTX_sess_set_remove_cb(ctx_, NULL);
184 SSL_CTX_set_generate_session_id(ctx_, NULL);
187 // Return the number of items in this cache.
188 size_t size() const { return key_index_.size(); }
190 // Retrieve the cache key from |ssl| and look for a corresponding
191 // cached session ID. If one is found, call SSL_set_session() to associate
192 // it with the |ssl| connection.
194 // Will also check for expired sessions every |expiration_check_count|
195 // calls.
197 // Return true if a cached session ID was found, false otherwise.
198 bool SetSSLSession(SSL* ssl) {
199 std::string cache_key = config_.key_func(ssl);
200 if (cache_key.empty())
201 return false;
203 return SetSSLSessionWithKey(ssl, cache_key);
206 // Variant of SetSSLSession to be used when the client already has computed
207 // the cache key. Avoid a call to the configuration's |key_func| function.
208 bool SetSSLSessionWithKey(SSL* ssl, const std::string& cache_key) {
209 base::AutoLock locked(lock_);
211 DCHECK_EQ(config_.key_func(ssl), cache_key);
213 if (++expiration_check_ >= config_.expiration_check_count) {
214 expiration_check_ = 0;
215 FlushExpiredSessionsLocked();
218 KeyIndex::iterator it = key_index_.find(cache_key);
219 if (it == key_index_.end())
220 return false;
222 SSL_SESSION* session = *it->second;
223 DCHECK(session);
225 DVLOG(2) << "Lookup session: " << session << " for " << cache_key;
227 void* session_is_good =
228 SSL_SESSION_get_ex_data(session, GetSSLSessionExIndex());
229 if (!session_is_good)
230 return false; // Session has not yet been marked good. Treat as a miss.
232 // Move to front of MRU list.
233 ordering_.push_front(session);
234 ordering_.erase(it->second);
235 it->second = ordering_.begin();
237 return SSL_set_session(ssl, session) == 1;
240 // Return true iff a cached session was associated with the given |cache_key|.
241 bool SSLSessionIsInCache(const std::string& cache_key) const {
242 base::AutoLock locked(lock_);
243 KeyIndex::const_iterator it = key_index_.find(cache_key);
244 if (it == key_index_.end())
245 return false;
247 SSL_SESSION* session = *it->second;
248 DCHECK(session);
250 void* session_is_good =
251 SSL_SESSION_get_ex_data(session, GetSSLSessionExIndex());
253 return session_is_good;
256 void SetSessionAddedCallback(SSL* ssl, const base::Closure& callback) {
257 // Add |ssl| to the SSLToCallbackMap.
258 ssl_to_callback_map_.insert(SSLToCallbackMap::value_type(
259 ssl, CallbackAndCompletionCount(callback, 0)));
262 // Determines if the session for |ssl| is in the cache, and calls the
263 // appropriate callback if that is the case.
265 // The session must be both MarkedAsGood and Added in order for the
266 // callback to be run. These two events can occur in either order.
267 void CheckIfSessionFinished(SSL* ssl) {
268 SSLToCallbackMap::iterator it = ssl_to_callback_map_.find(ssl);
269 if (it == ssl_to_callback_map_.end())
270 return;
271 // Increment the session's completion count.
272 if (++it->second.count == 2) {
273 base::Closure callback = it->second.callback;
274 ssl_to_callback_map_.erase(it);
275 callback.Run();
279 void RemoveSessionAddedCallback(SSL* ssl) { ssl_to_callback_map_.erase(ssl); }
281 void MarkSSLSessionAsGood(SSL* ssl) {
282 SSL_SESSION* session = SSL_get_session(ssl);
283 CHECK(session);
285 // Mark the session as good, allowing it to be used for future connections.
286 SSL_SESSION_set_ex_data(
287 session, GetSSLSessionExIndex(), reinterpret_cast<void*>(1));
289 CheckIfSessionFinished(ssl);
292 // Flush all entries from the cache.
293 void Flush() {
294 base::AutoLock lock(lock_);
295 id_index_.clear();
296 key_index_.clear();
297 while (!ordering_.empty()) {
298 SSL_SESSION* session = ordering_.front();
299 ordering_.pop_front();
300 SSL_SESSION_free(session);
304 private:
305 // CallbackAndCompletionCounts are used to group a callback that should be
306 // run when a certain sesssion is added to the session cache with an integer
307 // indicating the status of that session.
308 struct CallbackAndCompletionCount {
309 CallbackAndCompletionCount(const base::Closure& completion_callback,
310 int completion_count)
311 : callback(completion_callback), count(completion_count) {}
313 const base::Closure callback;
314 // |count| < 2 means that the ssl session associated with this object
315 // has not been added to the session cache or has not been marked as good.
316 // |count| is incremented when a session is added to the cache or marked as
317 // good, thus |count| == 2 means that the session is ready for use.
318 int count;
321 // Type for list of SSL_SESSION handles, ordered in MRU order.
322 typedef std::list<SSL_SESSION*> MRUSessionList;
323 // Type for a dictionary from unique cache keys to session list nodes.
324 typedef base::hash_map<std::string, MRUSessionList::iterator> KeyIndex;
325 // Type for a dictionary from SessionId values to key index nodes.
326 typedef base::hash_map<SessionId, KeyIndex::iterator> SessionIdIndex;
327 // Type for a map from SSL* to associated callbacks
328 typedef std::map<SSL*, CallbackAndCompletionCount> SSLToCallbackMap;
330 // Return the key associated with a given session, or the empty string if
331 // none exist. This shall only be used for debugging.
332 std::string SessionKey(SSL_SESSION* session) {
333 if (!session)
334 return std::string("<null-session>");
336 if (session->session_id_length == 0)
337 return std::string("<empty-session-id>");
339 SessionIdIndex::iterator it = id_index_.find(SessionId(session));
340 if (it == id_index_.end())
341 return std::string("<unknown-session>");
343 return it->second->first;
346 // Remove a given |session| from the cache. Lock must be held.
347 void RemoveSessionLocked(SSL_SESSION* session) {
348 lock_.AssertAcquired();
349 DCHECK(session);
350 DCHECK_GT(session->session_id_length, 0U);
351 SessionId session_id(session);
352 SessionIdIndex::iterator id_it = id_index_.find(session_id);
353 if (id_it == id_index_.end()) {
354 LOG(ERROR) << "Trying to remove unknown session from cache: " << session;
355 return;
357 KeyIndex::iterator key_it = id_it->second;
358 DCHECK(key_it != key_index_.end());
359 DCHECK_EQ(session, *key_it->second);
361 id_index_.erase(session_id);
362 ordering_.erase(key_it->second);
363 key_index_.erase(key_it);
365 SSL_SESSION_free(session);
367 DCHECK_EQ(key_index_.size(), id_index_.size());
370 // Used internally to flush expired sessions. Lock must be held.
371 void FlushExpiredSessionsLocked() {
372 lock_.AssertAcquired();
374 // Unfortunately, OpenSSL initializes |session->time| with a time()
375 // timestamps, which makes mocking / unit testing difficult.
376 long timeout_secs = static_cast<long>(::time(NULL));
377 MRUSessionList::iterator it = ordering_.begin();
378 while (it != ordering_.end()) {
379 SSL_SESSION* session = *it++;
381 // Important, use <= instead of < here to allow unit testing to
382 // work properly. That's because unit tests that check the expiration
383 // behaviour will use a session timeout of 0 seconds.
384 if (session->time + session->timeout <= timeout_secs) {
385 DVLOG(2) << "Expiring session " << session << " for "
386 << SessionKey(session);
387 RemoveSessionLocked(session);
392 // Retrieve the cache associated with a given SSL context |ctx|.
393 static SSLSessionCacheOpenSSLImpl* GetCache(SSL_CTX* ctx) {
394 DCHECK(ctx);
395 void* result = SSL_CTX_get_ex_data(ctx, GetSSLContextExIndex());
396 DCHECK(result);
397 return reinterpret_cast<SSLSessionCacheOpenSSLImpl*>(result);
400 // Called by OpenSSL when a new |session| was created and added to a given
401 // |ssl| connection. Note that the session's reference count was already
402 // incremented before the function is entered. The function must return 1
403 // to indicate that it took ownership of the session, i.e. that the caller
404 // should not decrement its reference count after completion.
405 static int NewSessionCallbackStatic(SSL* ssl, SSL_SESSION* session) {
406 SSLSessionCacheOpenSSLImpl* cache = GetCache(ssl->ctx);
407 cache->OnSessionAdded(ssl, session);
408 cache->CheckIfSessionFinished(ssl);
409 return 1;
412 // Called by OpenSSL to indicate that a session must be removed from the
413 // cache. This happens when SSL_CTX is destroyed.
414 static void RemoveSessionCallbackStatic(SSL_CTX* ctx, SSL_SESSION* session) {
415 GetCache(ctx)->OnSessionRemoved(session);
418 // Called by OpenSSL to generate a new session ID. This happens during a
419 // SSL connection operation, when the SSL object doesn't have a session yet.
421 // A session ID is a random string of bytes used to uniquely identify the
422 // session between a client and a server.
424 // |ssl| is a SSL connection handle. Ignored here.
425 // |id| is the target buffer where the ID must be generated.
426 // |*id_len| is, on input, the size of the desired ID. It will be 16 for
427 // SSLv2, and 32 for anything else. OpenSSL allows an implementation
428 // to change it on output, but this will not happen here.
430 // The function must ensure the generated ID is really unique, i.e. that
431 // another session in the cache doesn't already use the same value. It must
432 // return 1 to indicate success, or 0 for failure.
433 static int GenerateSessionIdStatic(const SSL* ssl,
434 unsigned char* id,
435 unsigned* id_len) {
436 if (!GetCache(ssl->ctx)->OnGenerateSessionId(id, *id_len))
437 return 0;
439 return 1;
442 // Add |session| to the cache in association with |cache_key|. If a session
443 // already exists, it is replaced with the new one. This assumes that the
444 // caller already incremented the session's reference count.
445 void OnSessionAdded(SSL* ssl, SSL_SESSION* session) {
446 base::AutoLock locked(lock_);
447 DCHECK(ssl);
448 DCHECK_GT(session->session_id_length, 0U);
449 std::string cache_key = config_.key_func(ssl);
450 KeyIndex::iterator it = key_index_.find(cache_key);
451 if (it == key_index_.end()) {
452 DVLOG(2) << "Add session " << session << " for " << cache_key;
453 // This is a new session. Add it to the cache.
454 ordering_.push_front(session);
455 std::pair<KeyIndex::iterator, bool> ret =
456 key_index_.insert(std::make_pair(cache_key, ordering_.begin()));
457 DCHECK(ret.second);
458 it = ret.first;
459 DCHECK(it != key_index_.end());
460 } else {
461 // An existing session exists for this key, so replace it if needed.
462 DVLOG(2) << "Replace session " << *it->second << " with " << session
463 << " for " << cache_key;
464 SSL_SESSION* old_session = *it->second;
465 if (old_session != session) {
466 id_index_.erase(SessionId(old_session));
467 SSL_SESSION_free(old_session);
469 ordering_.erase(it->second);
470 ordering_.push_front(session);
471 it->second = ordering_.begin();
474 id_index_[SessionId(session)] = it;
476 if (key_index_.size() > config_.max_entries)
477 ShrinkCacheLocked();
479 DCHECK_EQ(key_index_.size(), id_index_.size());
480 DCHECK_LE(key_index_.size(), config_.max_entries);
483 // Shrink the cache to ensure no more than config_.max_entries entries,
484 // starting with older entries first. Lock must be acquired.
485 void ShrinkCacheLocked() {
486 lock_.AssertAcquired();
487 DCHECK_EQ(key_index_.size(), ordering_.size());
488 DCHECK_EQ(key_index_.size(), id_index_.size());
490 while (key_index_.size() > config_.max_entries) {
491 MRUSessionList::reverse_iterator it = ordering_.rbegin();
492 DCHECK(it != ordering_.rend());
494 SSL_SESSION* session = *it;
495 DCHECK(session);
496 DVLOG(2) << "Evicting session " << session << " for "
497 << SessionKey(session);
498 RemoveSessionLocked(session);
502 // Remove |session| from the cache.
503 void OnSessionRemoved(SSL_SESSION* session) {
504 base::AutoLock locked(lock_);
505 DVLOG(2) << "Remove session " << session << " for " << SessionKey(session);
506 RemoveSessionLocked(session);
509 // See GenerateSessionIdStatic for a description of what this function does.
510 bool OnGenerateSessionId(unsigned char* id, unsigned id_len) {
511 base::AutoLock locked(lock_);
512 // This mimics def_generate_session_id() in openssl/ssl/ssl_sess.cc,
513 // I.e. try to generate a pseudo-random bit string, and check that no
514 // other entry in the cache has the same value.
515 const size_t kMaxTries = 10;
516 for (size_t tries = 0; tries < kMaxTries; ++tries) {
517 if (RAND_pseudo_bytes(id, id_len) <= 0) {
518 DLOG(ERROR) << "Couldn't generate " << id_len
519 << " pseudo random bytes?";
520 return false;
522 if (id_index_.find(SessionId(id, id_len)) == id_index_.end())
523 return true;
525 DLOG(ERROR) << "Couldn't generate unique session ID of " << id_len
526 << "bytes after " << kMaxTries << " tries.";
527 return false;
530 SSL_CTX* ctx_;
531 SSLSessionCacheOpenSSL::Config config_;
532 SSLToCallbackMap ssl_to_callback_map_;
534 // method to get the index which can later be used with SSL_CTX_get_ex_data()
535 // or SSL_CTX_set_ex_data().
536 mutable base::Lock lock_; // Protects access to containers below.
538 MRUSessionList ordering_;
539 KeyIndex key_index_;
540 SessionIdIndex id_index_;
542 size_t expiration_check_;
545 SSLSessionCacheOpenSSL::~SSLSessionCacheOpenSSL() { delete impl_; }
547 size_t SSLSessionCacheOpenSSL::size() const { return impl_->size(); }
549 void SSLSessionCacheOpenSSL::Reset(SSL_CTX* ctx, const Config& config) {
550 if (impl_)
551 delete impl_;
553 impl_ = new SSLSessionCacheOpenSSLImpl(ctx, config);
556 bool SSLSessionCacheOpenSSL::SetSSLSession(SSL* ssl) {
557 return impl_->SetSSLSession(ssl);
560 bool SSLSessionCacheOpenSSL::SetSSLSessionWithKey(
561 SSL* ssl,
562 const std::string& cache_key) {
563 return impl_->SetSSLSessionWithKey(ssl, cache_key);
566 bool SSLSessionCacheOpenSSL::SSLSessionIsInCache(
567 const std::string& cache_key) const {
568 return impl_->SSLSessionIsInCache(cache_key);
571 void SSLSessionCacheOpenSSL::RemoveSessionAddedCallback(SSL* ssl) {
572 impl_->RemoveSessionAddedCallback(ssl);
575 void SSLSessionCacheOpenSSL::SetSessionAddedCallback(SSL* ssl,
576 const base::Closure& cb) {
577 impl_->SetSessionAddedCallback(ssl, cb);
580 void SSLSessionCacheOpenSSL::MarkSSLSessionAsGood(SSL* ssl) {
581 return impl_->MarkSSLSessionAsGood(ssl);
584 void SSLSessionCacheOpenSSL::Flush() { impl_->Flush(); }
586 } // namespace net