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"
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"
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
{
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_
; }
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.
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
;
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
) {
91 for (unsigned n
= 0; n
< id_len
; ++n
) {
92 result
= (result
* 131) + id
[n
];
102 namespace BASE_HASH_NAMESPACE
{
105 struct hash
<net::SessionId
> {
106 std::size_t operator()(const net::SessionId
& entry
) const {
111 } // namespace BASE_HASH_NAMESPACE
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
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)
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
{
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"));
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() {
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|
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())
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())
238 SSL_SESSION
* session
= *it
->second
;
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 // Return true iff a cached session was associated with the given |cache_key|.
257 bool SSLSessionIsInCache(const std::string
& cache_key
) const {
258 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
259 tracked_objects::ScopedTracker
tracking_profile(
260 FROM_HERE_WITH_EXPLICIT_FUNCTION(
261 "424386 SSLSessionCacheOpenSSLImpl::SSLSessionIsInCache"));
263 base::AutoLock
locked(lock_
);
264 KeyIndex::const_iterator it
= key_index_
.find(cache_key
);
265 if (it
== key_index_
.end())
268 SSL_SESSION
* session
= *it
->second
;
271 void* session_is_good
=
272 SSL_SESSION_get_ex_data(session
, GetSSLSessionExIndex());
274 return session_is_good
!= NULL
;
277 void MarkSSLSessionAsGood(SSL
* ssl
) {
278 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
279 tracked_objects::ScopedTracker
tracking_profile(
280 FROM_HERE_WITH_EXPLICIT_FUNCTION(
281 "424386 SSLSessionCacheOpenSSLImpl::MarkSSLSessionAsGood"));
283 SSL_SESSION
* session
= SSL_get_session(ssl
);
286 // Mark the session as good, allowing it to be used for future connections.
287 SSL_SESSION_set_ex_data(
288 session
, GetSSLSessionExIndex(), reinterpret_cast<void*>(1));
291 // Flush all entries from the cache.
293 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
294 tracked_objects::ScopedTracker
tracking_profile(
295 FROM_HERE_WITH_EXPLICIT_FUNCTION(
296 "424386 SSLSessionCacheOpenSSLImpl::Flush"));
298 base::AutoLock
lock(lock_
);
301 while (!ordering_
.empty()) {
302 SSL_SESSION
* session
= ordering_
.front();
303 ordering_
.pop_front();
304 SSL_SESSION_free(session
);
309 // Type for list of SSL_SESSION handles, ordered in MRU order.
310 typedef std::list
<SSL_SESSION
*> MRUSessionList
;
311 // Type for a dictionary from unique cache keys to session list nodes.
312 typedef base::hash_map
<std::string
, MRUSessionList::iterator
> KeyIndex
;
313 // Type for a dictionary from SessionId values to key index nodes.
314 typedef base::hash_map
<SessionId
, KeyIndex::iterator
> SessionIdIndex
;
316 // Return the key associated with a given session, or the empty string if
317 // none exist. This shall only be used for debugging.
318 std::string
SessionKey(SSL_SESSION
* session
) {
320 return std::string("<null-session>");
322 if (session
->session_id_length
== 0)
323 return std::string("<empty-session-id>");
325 SessionIdIndex::iterator it
= id_index_
.find(SessionId(session
));
326 if (it
== id_index_
.end())
327 return std::string("<unknown-session>");
329 return it
->second
->first
;
332 // Remove a given |session| from the cache. Lock must be held.
333 void RemoveSessionLocked(SSL_SESSION
* session
) {
334 lock_
.AssertAcquired();
336 DCHECK_GT(session
->session_id_length
, 0U);
337 SessionId
session_id(session
);
338 SessionIdIndex::iterator id_it
= id_index_
.find(session_id
);
339 if (id_it
== id_index_
.end()) {
340 LOG(ERROR
) << "Trying to remove unknown session from cache: " << session
;
343 KeyIndex::iterator key_it
= id_it
->second
;
344 DCHECK(key_it
!= key_index_
.end());
345 DCHECK_EQ(session
, *key_it
->second
);
347 id_index_
.erase(session_id
);
348 ordering_
.erase(key_it
->second
);
349 key_index_
.erase(key_it
);
351 SSL_SESSION_free(session
);
353 DCHECK_EQ(key_index_
.size(), id_index_
.size());
356 // Used internally to flush expired sessions. Lock must be held.
357 void FlushExpiredSessionsLocked() {
358 lock_
.AssertAcquired();
360 // Unfortunately, OpenSSL initializes |session->time| with a time()
361 // timestamps, which makes mocking / unit testing difficult.
362 long timeout_secs
= static_cast<long>(::time(NULL
));
363 MRUSessionList::iterator it
= ordering_
.begin();
364 while (it
!= ordering_
.end()) {
365 SSL_SESSION
* session
= *it
++;
367 // Important, use <= instead of < here to allow unit testing to
368 // work properly. That's because unit tests that check the expiration
369 // behaviour will use a session timeout of 0 seconds.
370 if (session
->time
+ session
->timeout
<= timeout_secs
) {
371 DVLOG(2) << "Expiring session " << session
<< " for "
372 << SessionKey(session
);
373 RemoveSessionLocked(session
);
378 // Retrieve the cache associated with a given SSL context |ctx|.
379 static SSLSessionCacheOpenSSLImpl
* GetCache(SSL_CTX
* ctx
) {
381 void* result
= SSL_CTX_get_ex_data(ctx
, GetSSLContextExIndex());
383 return reinterpret_cast<SSLSessionCacheOpenSSLImpl
*>(result
);
386 // Called by OpenSSL when a new |session| was created and added to a given
387 // |ssl| connection. Note that the session's reference count was already
388 // incremented before the function is entered. The function must return 1
389 // to indicate that it took ownership of the session, i.e. that the caller
390 // should not decrement its reference count after completion.
391 static int NewSessionCallbackStatic(SSL
* ssl
, SSL_SESSION
* session
) {
392 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
393 tracked_objects::ScopedTracker
tracking_profile(
394 FROM_HERE_WITH_EXPLICIT_FUNCTION(
395 "424386 SSLSessionCacheOpenSSLImpl::NewSessionCallbackStatic"));
397 SSLSessionCacheOpenSSLImpl
* cache
= GetCache(ssl
->ctx
);
398 cache
->OnSessionAdded(ssl
, session
);
402 // Called by OpenSSL to indicate that a session must be removed from the
403 // cache. This happens when SSL_CTX is destroyed.
404 static void RemoveSessionCallbackStatic(SSL_CTX
* ctx
, SSL_SESSION
* session
) {
405 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
406 tracked_objects::ScopedTracker
tracking_profile(
407 FROM_HERE_WITH_EXPLICIT_FUNCTION(
408 "424386 SSLSessionCacheOpenSSLImpl::RemoveSessionCallbackStatic"));
410 GetCache(ctx
)->OnSessionRemoved(session
);
413 // Called by OpenSSL to generate a new session ID. This happens during a
414 // SSL connection operation, when the SSL object doesn't have a session yet.
416 // A session ID is a random string of bytes used to uniquely identify the
417 // session between a client and a server.
419 // |ssl| is a SSL connection handle. Ignored here.
420 // |id| is the target buffer where the ID must be generated.
421 // |*id_len| is, on input, the size of the desired ID. It will be 16 for
422 // SSLv2, and 32 for anything else. OpenSSL allows an implementation
423 // to change it on output, but this will not happen here.
425 // The function must ensure the generated ID is really unique, i.e. that
426 // another session in the cache doesn't already use the same value. It must
427 // return 1 to indicate success, or 0 for failure.
428 static int GenerateSessionIdStatic(const SSL
* ssl
,
431 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
432 tracked_objects::ScopedTracker
tracking_profile(
433 FROM_HERE_WITH_EXPLICIT_FUNCTION(
434 "424386 SSLSessionCacheOpenSSLImpl::GenerateSessionIdStatic"));
436 if (!GetCache(ssl
->ctx
)->OnGenerateSessionId(id
, *id_len
))
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_
);
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()));
459 DCHECK(it
!= key_index_
.end());
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
)
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
;
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?";
522 if (id_index_
.find(SessionId(id
, id_len
)) == id_index_
.end())
525 DLOG(ERROR
) << "Couldn't generate unique session ID of " << id_len
526 << "bytes after " << kMaxTries
<< " tries.";
531 SSLSessionCacheOpenSSL::Config config_
;
533 // method to get the index which can later be used with SSL_CTX_get_ex_data()
534 // or SSL_CTX_set_ex_data().
535 mutable base::Lock lock_
; // Protects access to containers below.
537 MRUSessionList ordering_
;
539 SessionIdIndex id_index_
;
541 size_t expiration_check_
;
544 SSLSessionCacheOpenSSL::~SSLSessionCacheOpenSSL() { delete impl_
; }
546 size_t SSLSessionCacheOpenSSL::size() const { return impl_
->size(); }
548 void SSLSessionCacheOpenSSL::Reset(SSL_CTX
* ctx
, const Config
& config
) {
552 impl_
= new SSLSessionCacheOpenSSLImpl(ctx
, config
);
555 bool SSLSessionCacheOpenSSL::SetSSLSession(SSL
* ssl
) {
556 return impl_
->SetSSLSession(ssl
);
559 bool SSLSessionCacheOpenSSL::SetSSLSessionWithKey(
561 const std::string
& cache_key
) {
562 return impl_
->SetSSLSessionWithKey(ssl
, cache_key
);
565 bool SSLSessionCacheOpenSSL::SSLSessionIsInCache(
566 const std::string
& cache_key
) const {
567 return impl_
->SSLSessionIsInCache(cache_key
);
570 void SSLSessionCacheOpenSSL::MarkSSLSessionAsGood(SSL
* ssl
) {
571 return impl_
->MarkSSLSessionAsGood(ssl
);
574 void SSLSessionCacheOpenSSL::Flush() { impl_
->Flush(); }