[PATCH 3.4 085/107] KEYS: Fix race between key destruction and finding a keyring by name

From: lizf
Date: Wed Mar 16 2016 - 04:20:10 EST


From: David Howells <dhowells@xxxxxxxxxx>

3.4.111-rc1 review patch. If anyone has any objections, please let me know.

------------------


commit 94c4554ba07adbdde396748ee7ae01e86cf2d8d7 upstream.

There appears to be a race between:

(1) key_gc_unused_keys() which frees key->security and then calls
keyring_destroy() to unlink the name from the name list

(2) find_keyring_by_name() which calls key_permission(), thus accessing
key->security, on a key before checking to see whether the key usage is 0
(ie. the key is dead and might be cleaned up).

Fix this by calling ->destroy() before cleaning up the core key data -
including key->security.

Reported-by: Petr Matousek <pmatouse@xxxxxxxxxx>
Signed-off-by: David Howells <dhowells@xxxxxxxxxx>
[lizf: Backported to 3.4: adjust indentation]
Signed-off-by: Zefan Li <lizefan@xxxxxxxxxx>
---
security/keys/gc.c | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/security/keys/gc.c b/security/keys/gc.c
index 87632bd..f85d638 100644
--- a/security/keys/gc.c
+++ b/security/keys/gc.c
@@ -174,6 +174,10 @@ static noinline void key_gc_unused_key(struct key *key)
{
key_check(key);

+ /* Throw away the key data */
+ if (key->type->destroy)
+ key->type->destroy(key);
+
security_key_free(key);

/* deal with the user's key tracking and quota */
@@ -188,10 +192,6 @@ static noinline void key_gc_unused_key(struct key *key)
if (test_bit(KEY_FLAG_INSTANTIATED, &key->flags))
atomic_dec(&key->user->nikeys);

- /* now throw away the key memory */
- if (key->type->destroy)
- key->type->destroy(key);
-
key_user_put(key->user);

kfree(key->description);
--
1.9.1