cred-encoding: Avoid potential use after free when caching encodings

The pattern currently is to call get_cache(), generate the encoding
if that failed and then store it with cache().  The latter adopts the
passed encoding and frees any stored encoding.  However, the latter means
that if two threads concurrently fail to get a cached encoding and then
both generate and store one, one of the threads might use an encoding
that was freed by the other thread.

Since encodings are not expected to change, we can avoid this issue by
not replacing an existing cache entry and instead return that (while
freeing the passed value instead of the cached one).

Closes strongswan/strongswan#1231
This commit is contained in:
Tobias Brunner
2022-09-20 09:53:13 +02:00
parent 724b1a8ae8
commit 48e9267d7a
13 changed files with 45 additions and 47 deletions
+29 -33
View File
@@ -115,6 +115,34 @@ METHOD(cred_encoding_t, get_cache, bool,
return !!chunk;
}
METHOD(cred_encoding_t, cache, void,
private_cred_encoding_t *this, cred_encoding_type_t type, void *cache,
chunk_t *encoding)
{
chunk_t *chunk;
if (type >= CRED_ENCODING_MAX || (int)type < 0)
{
free(encoding->ptr);
return;
}
this->lock->write_lock(this->lock);
chunk = this->cache[type]->get(this->cache[type], cache);
if (chunk)
{
free(encoding->ptr);
*encoding = *chunk;
}
else
{
chunk = malloc_thing(chunk_t);
*chunk = *encoding;
this->cache[type]->put(this->cache[type], cache, chunk);
}
this->lock->unlock(this->lock);
}
/**
* Implementation of cred_encoding_t.encode
*/
@@ -160,43 +188,11 @@ static bool encode(private_cred_encoding_t *this, cred_encoding_type_t type,
if (success && cache)
{
chunk = malloc_thing(chunk_t);
*chunk = *encoding;
this->lock->write_lock(this->lock);
chunk = this->cache[type]->put(this->cache[type], cache, chunk);
this->lock->unlock(this->lock);
if (chunk)
{
free(chunk->ptr);
free(chunk);
}
_cache(this, type, cache, encoding);
}
return success;
}
METHOD(cred_encoding_t, cache, void,
private_cred_encoding_t *this, cred_encoding_type_t type, void *cache,
chunk_t encoding)
{
chunk_t *chunk;
if (type >= CRED_ENCODING_MAX || (int)type < 0)
{
return free(encoding.ptr);
}
chunk = malloc_thing(chunk_t);
*chunk = encoding;
this->lock->write_lock(this->lock);
chunk = this->cache[type]->put(this->cache[type], cache, chunk);
this->lock->unlock(this->lock);
/* free an encoding already associated to the cache */
if (chunk)
{
free(chunk->ptr);
free(chunk);
}
}
METHOD(cred_encoding_t, clear_cache, void,
private_cred_encoding_t *this, void *cache)
{