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