The Linux Kernel Mailing List
 help / color / mirror / Atom feed
* [PATCH] KEYS: Protect the instantiate method against type removal
@ 2026-11-24  5:33 Guicai Ma
  2026-11-24  9:12 ` [PATCH v2] KEYS: Protect key instantiation and rejection " Guicai Ma
  0 siblings, 1 reply; 9+ messages in thread
From: Guicai Ma @ 2026-11-24  5:33 UTC (permalink / raw)
  To: David Howells, Jarkko Sakkinen
  Cc: keyrings, linux-security-module, linux-kernel, Paul Moore,
	James Morris, Serge E . Hallyn, Guicai Ma

key_instantiate_and_link() reads key->type->def_datalen and ->preparse
and calls ->instantiate without holding key->sem. A reference on the
key keeps it alive, but does not pin the module that provides its type.

unregister_key_type() waits for the key GC to process every remaining
key of the type. For each such key the GC takes key->sem for writing,
switches key->type to key_type_dead and destroys the payload. A key
that is still under construction is retyped as well: it stays in
KEY_IS_UNINSTANTIATED and its authorisation key remains valid, so
KEYCTL_INSTANTIATE from the upcall helper reaches
__key_instantiate_and_link() and calls key_type_dead.instantiate,
which is NULL:

  Unable to handle kernel NULL pointer dereference at
  virtual address 0000000000000000
  Internal error: Oops: 0000000086000006 [#1] SMP
  pc : 0x0
  lr : __key_instantiate_and_link+0xb8/0x2f8
  Call trace:
   0x0 (P)
   key_instantiate_and_link+0x2e8/0x36c
   keyctl_instantiate_key_common+0x1cc/0x338
   keyctl_instantiate_key+0xbc/0x120
   __arm64_sys_keyctl+0x218/0x3f0

If the module is unloaded while ->preparse or ->instantiate is running,
execution can also return into freed module text, or skip
->free_preparse after the key is retyped and leak the preparsed
payload. While the request_key() syscall holds key_types_sem across the
upcall, in-kernel request_key() callers such as dns_query() do not, so
unregister_key_type() can run before KEYCTL_INSTANTIATE.

Hold key->sem for reading across key_instantiate_and_link() and return
-EOPNOTSUPP if the type has no ->instantiate method. Since
keyring_alloc() links a new keyring into a destination keyring with the
new keyring's semaphore held at subclass 0, take the destination
keyring's semaphore at subclass 1 in __key_link_lock(), matching the
0 -> 1 order in __key_move_lock().

Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2")
Cc: stable@vger.kernel.org
Signed-off-by: Guicai Ma <maguicai@kylinos.cn>
---
Tested on 7.4.0-rc3 arm64 in QEMU with KASAN and lockdep enabled by
unloading a test key-type module between an in-kernel request_key()
upcall and KEYCTL_INSTANTIATE. Unpatched Oopses at pc=0 on the first
round; patched returns -EOPNOTSUPP and passes 20 concurrent
instantiate-vs-unload rounds and nested keyring creation cleanly.

 security/keys/key.c     | 39 +++++++++++++++++++++++++++++----------
 security/keys/keyring.c |  9 ++++++++-
 2 files changed, 37 insertions(+), 11 deletions(-)

diff --git a/security/keys/key.c b/security/keys/key.c
index 3f1f0fc13710..12cbca31824c 100644
--- a/security/keys/key.c
+++ b/security/keys/key.c
@@ -422,9 +422,10 @@ static void mark_key_instantiated(struct key *key, int reject_error)
 
 /*
  * Instantiate a key and link it into the target keyring atomically.  Must be
- * called with the target keyring's semaphore writelocked.  The target key's
- * semaphore need not be locked as instantiation is serialised by
- * key_construction_mutex.
+ * called with the target keyring's semaphore writelocked.  Either the target
+ * key's semaphore or key_types_sem must be held for reading so that the
+ * garbage collector cannot retype the key to key_type_dead while the type's
+ * methods are in use.
  */
 static int __key_instantiate_and_link(struct key *key,
 				      struct key_preparsed_payload *prep,
@@ -496,7 +497,8 @@ static int __key_instantiate_and_link(struct key *key,
  *
  * If successful, 0 is returned, the authorisation token is revoked and anyone
  * waiting for the key is woken up.  If the key was already instantiated,
- * -EBUSY will be returned.
+ * -EBUSY will be returned.  If the key type no longer provides an instantiate
+ * method, -EOPNOTSUPP will be returned.
  */
 int key_instantiate_and_link(struct key *key,
 			     const void *data,
@@ -509,6 +511,20 @@ int key_instantiate_and_link(struct key *key,
 	int ret;
 
 	memset(&prep, 0, sizeof(prep));
+
+	/*
+	 * A reference on the key does not pin the module that provides its
+	 * type.  unregister_key_type() waits for the garbage collector to
+	 * retype every remaining key of the type to key_type_dead, whose
+	 * ->instantiate is NULL, so the type must not change from here to the
+	 * instantiate call.
+	 */
+	down_read(&key->sem);
+
+	ret = -EOPNOTSUPP;
+	if (!key->type->instantiate)
+		goto out;
+
 	prep.orig_description = key->description;
 	prep.data = data;
 	prep.datalen = datalen;
@@ -517,17 +533,17 @@ int key_instantiate_and_link(struct key *key,
 	if (key->type->preparse) {
 		ret = key->type->preparse(&prep);
 		if (ret < 0)
-			goto error;
+			goto out_free_preparse;
 	}
 
 	if (keyring) {
 		ret = __key_link_lock(keyring, &key->index_key);
 		if (ret < 0)
-			goto error;
+			goto out_free_preparse;
 
 		ret = __key_link_begin(keyring, &key->index_key, &edit);
 		if (ret < 0)
-			goto error_link_end;
+			goto out_link_end;
 
 		if (keyring->restrict_link && keyring->restrict_link->check) {
 			struct key_restriction *keyres = keyring->restrict_link;
@@ -535,19 +551,22 @@ int key_instantiate_and_link(struct key *key,
 			ret = keyres->check(keyring, key->type, &prep.payload,
 					    keyres->key);
 			if (ret < 0)
-				goto error_link_end;
+				goto out_link_end;
 		}
 	}
 
 	ret = __key_instantiate_and_link(key, &prep, keyring, authkey, &edit);
 
-error_link_end:
+out_link_end:
 	if (keyring)
 		__key_link_end(keyring, &key->index_key, edit);
 
-error:
+out_free_preparse:
 	if (key->type->preparse)
 		key->type->free_preparse(&prep);
+
+out:
+	up_read(&key->sem);
 	return ret;
 }
 
diff --git a/security/keys/keyring.c b/security/keys/keyring.c
index 357f56360810..f545f56c84e7 100644
--- a/security/keys/keyring.c
+++ b/security/keys/keyring.c
@@ -1262,7 +1262,14 @@ int __key_link_lock(struct key *keyring,
 	if (keyring->type != &key_type_keyring)
 		return -ENOTDIR;
 
-	down_write(&keyring->sem);
+	/*
+	 * key_instantiate_and_link() links a newly allocated keyring into this
+	 * one while holding the new keyring's semaphore for reading as
+	 * subclass 0, so take the destination keyring at subclass 1 to keep
+	 * the same 0 -> 1 order that __key_move_lock() uses.  None of the
+	 * other callers of this function hold a key semaphore.
+	 */
+	down_write_nested(&keyring->sem, 1);
 
 	/* Serialise link/link calls to prevent parallel calls causing a cycle
 	 * when linking two keyring in opposite orders.
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 9+ messages in thread

* [PATCH v2] KEYS: Protect key instantiation and rejection against type removal
  2026-11-24  5:33 [PATCH] KEYS: Protect the instantiate method against type removal Guicai Ma
@ 2026-11-24  9:12 ` Guicai Ma
  2026-11-24 16:27   ` Jarkko Sakkinen
  2026-11-25  3:26   ` [PATCH v3] " Guicai Ma
  0 siblings, 2 replies; 9+ messages in thread
From: Guicai Ma @ 2026-11-24  9:12 UTC (permalink / raw)
  To: David Howells, Jarkko Sakkinen
  Cc: Paul Moore, James Morris, Serge E . Hallyn, keyrings,
	linux-security-module, linux-kernel, Guicai Ma

key_instantiate_and_link() reads key->type->def_datalen and ->preparse,
passes key->type to restrict_link->check(), and invokes ->instantiate()
and ->free_preparse() without synchronizing against key type removal.
A reference on the key keeps the key object alive, but does not pin the
module that provides its type.

unregister_key_type() removes the type from key_types_list and waits for
key_garbage_collector() to run three passes: pass 1 sets KEY_FLAG_DEAD
and clears key->perm, pass 2 unlinks dead keys from keyrings, and pass 3
takes key->sem for writing, retypes key->type to &key_type_dead, and
destroys the payload. A key still under construction stays in
KEY_IS_UNINSTANTIATED with a valid authorisation key, so an upcall
helper calling KEYCTL_INSTANTIATE after pass 3 reaches
__key_instantiate_and_link() and jumps to key_type_dead.instantiate,
which is NULL:

  Unable to handle kernel NULL pointer dereference at
  virtual address 0000000000000000
  Internal error: Oops: 0000000086000006 [#1] SMP
  pc : 0x0
  lr : __key_instantiate_and_link+0xb8/0x2f8
  Call trace:
   0x0 (P)
   key_instantiate_and_link+0x2e8/0x36c
   keyctl_instantiate_key_common+0x1cc/0x338
   keyctl_instantiate_key+0xbc/0x120
   __arm64_sys_keyctl+0x218/0x3f0

If the module unloads while ->preparse() or ->instantiate() is running,
execution can also return into freed module text or skip
->free_preparse(). While the request_key() syscall holds key_types_sem
across the upcall, in-kernel request_key() callers do not, so
unregister_key_type() can run before KEYCTL_INSTANTIATE or
KEYCTL_REJECT.

key_reject_and_link() shares the same window: it links the key into
@keyring and calls key_set_expiry() (which reads key->type->flags)
without checking KEY_FLAG_DEAD. Linking a dead key between GC pass 2 and
pass 3 leaves it in the keyring's assoc_array while pass 3 overwrites
key->type (which aliases key->index_key.type) in place.

Neither key->sem nor key_types_sem can be taken here: holding key->sem
across __key_link_lock() and __key_instantiate_and_link() inverts lock
order against encrypted_instantiate() (which locks the master key's
semaphore under keyring->sem and key_construction_mutex), and
key_instantiate_and_link() is already called with key_types_sem held for
reading (e.g. from request_key_auth_new()).

Add key_type_srcu and call synchronize_srcu(&key_type_srcu) at the end
of GC pass 1 (KEY_GC_REAPING_DEAD_1) whenever dead keys were marked.
SRCU rather than RCU because ->preparse() and ->instantiate() may sleep.
Hold key_type_srcu across the full body of key_instantiate_and_link()
and key_reject_and_link() and check KEY_FLAG_DEAD:

- Callers that observe !KEY_FLAG_DEAD finish all key->type accesses and
  any keyring linking before pass 2 unlinks dead keys and pass 3 retypes
  them to key_type_dead.
- Callers entering after synchronize_srcu() observe KEY_FLAG_DEAD:
  key_instantiate_and_link() returns -EKEYREVOKED (matching
  key_validate()), and key_reject_and_link() skips linking (returning
  -EKEYREVOKED if @keyring was given) and key_set_expiry() while still
  completing negative instantiation so waiters wake up and @authkey is
  invalidated.

Also return -EOPNOTSUPP in key_instantiate_and_link() if a live key type
does not provide ->instantiate().

Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2")
Cc: stable@vger.kernel.org
Signed-off-by: Guicai Ma <maguicai@kylinos.cn>
---
Changes since v1:
- Replace down_read(&key->sem) with a dedicated SRCU (key_type_srcu)
  synchronized at the end of GC pass 1, avoiding the ABBA lock inversion
  with encrypted_instantiate() and avoiding locking key->sem on dead
  modular keys whose lockdep class was freed on module unload.
- Revert the down_write_nested(&keyring->sem, 1) change in
  security/keys/keyring.c, which is no longer needed.
- Check KEY_FLAG_DEAD (returning -EKEYREVOKED) in
  key_instantiate_and_link() and protect key_reject_and_link() under the
  same SRCU so dead keys are not linked between GC pass 2 and pass 3 and
  key_set_expiry() does not race with type removal.

Testing (7.4.0-rc3 arm64 KVM, KASAN + lockdep + CONFIG_ENCRYPTED_KEYS=y):
- Deterministic rmmod before KEYCTL_INSTANTIATE (ringid=0 and session
  keyring): returns -EKEYREVOKED with 0 lockdep unlock-imbalance or
  KASAN warnings (unpatched Oopses at pc=0).
- KEYCTL_REJECT on a dead key: ringid=0 returns 0, ringid=session
  returns -EKEYREVOKED without linking into the keyring; request_key()
  waiter wakes up with -ENOKEY and no WARN_ON.
- Instantiating a user key via request_key() upcall followed by
  add_key("encrypted", ..., "load ..."): passes with 0 lockdep warnings.
- Nested keyring creation and 200 concurrent instantiate/reject vs rmmod
  rounds with jitter: 0 errors, debug_locks remains 1.

 security/keys/gc.c       |  13 +++++
 security/keys/internal.h |   2 +
 security/keys/key.c      | 108 +++++++++++++++++++++++++++++----------
 3 files changed, 95 insertions(+), 28 deletions(-)

diff --git a/security/keys/gc.c b/security/keys/gc.c
index eda445f815d4..61cb2b9a7aaf 100644
--- a/security/keys/gc.c
+++ b/security/keys/gc.c
@@ -35,6 +35,8 @@ static unsigned long key_gc_flags;
 #define KEY_GC_REAP_KEYTYPE	1	/* A keytype is being unregistered */
 #define KEY_GC_REAPING_KEYTYPE	2	/* Cleared when keytype reaped */
 
+DEFINE_SRCU(key_type_srcu);
+
 
 /*
  * Any key whose type gets unregistered will be re-typed to this if it can't be
@@ -286,6 +288,17 @@ static void key_garbage_collector(struct work_struct *work)
 		key_schedule_gc(new_timer);
 	}
 
+	if (unlikely((gc_state & KEY_GC_REAPING_DEAD_1) &&
+		     (gc_state & KEY_GC_FOUND_DEAD_KEY))) {
+		/* Wait for any in-flight key_instantiate_and_link() or
+		 * key_reject_and_link() calls that did not observe
+		 * KEY_FLAG_DEAD before pass 2 unlinks dead keys from keyrings
+		 * and pass 3 retypes them to key_type_dead.
+		 */
+		kdebug("gc dead type sync");
+		synchronize_srcu(&key_type_srcu);
+	}
+
 	if (unlikely(gc_state & KEY_GC_REAPING_DEAD_2) ||
 	    !list_empty(&graveyard)) {
 		/* Make sure that all pending keyring payload destructions are
diff --git a/security/keys/internal.h b/security/keys/internal.h
index b7b622bc36a1..73d71de274c2 100644
--- a/security/keys/internal.h
+++ b/security/keys/internal.h
@@ -19,6 +19,7 @@
 #include <linux/compat.h>
 #include <linux/mm.h>
 #include <linux/vmalloc.h>
+#include <linux/srcu.h>
 
 struct iovec;
 
@@ -86,6 +87,7 @@ extern struct kmem_cache *key_jar;
 extern struct rb_root key_serial_tree;
 extern spinlock_t key_serial_lock;
 extern struct mutex key_construction_mutex;
+extern struct srcu_struct key_type_srcu;
 extern wait_queue_head_t request_key_conswq;
 
 extern void key_set_index_key(struct keyring_index_key *index_key);
diff --git a/security/keys/key.c b/security/keys/key.c
index 3f1f0fc13710..9e51cb2b1d34 100644
--- a/security/keys/key.c
+++ b/security/keys/key.c
@@ -422,9 +422,10 @@ static void mark_key_instantiated(struct key *key, int reject_error)
 
 /*
  * Instantiate a key and link it into the target keyring atomically.  Must be
- * called with the target keyring's semaphore writelocked.  The target key's
- * semaphore need not be locked as instantiation is serialised by
- * key_construction_mutex.
+ * called with the target keyring's semaphore writelocked.  The caller must
+ * hold key_type_srcu (after checking !KEY_FLAG_DEAD) or key_types_sem for
+ * reading via key_type_lookup(), so the type cannot be retyped to
+ * key_type_dead or its module unloaded while its methods run.
  */
 static int __key_instantiate_and_link(struct key *key,
 				      struct key_preparsed_payload *prep,
@@ -496,7 +497,9 @@ static int __key_instantiate_and_link(struct key *key,
  *
  * If successful, 0 is returned, the authorisation token is revoked and anyone
  * waiting for the key is woken up.  If the key was already instantiated,
- * -EBUSY will be returned.
+ * -EBUSY will be returned.  If the key's type has been removed, -EKEYREVOKED
+ * will be returned.  If the key type does not provide an instantiate method,
+ * -EOPNOTSUPP will be returned.
  */
 int key_instantiate_and_link(struct key *key,
 			     const void *data,
@@ -506,7 +509,28 @@ int key_instantiate_and_link(struct key *key,
 {
 	struct key_preparsed_payload prep;
 	struct assoc_array_edit *edit = NULL;
-	int ret;
+	int ret, srcu_idx;
+
+	/*
+	 * A reference on the key does not pin the module that provides its
+	 * type.  Hold key_type_srcu across every use of key->type
+	 * (def_datalen, preparse, restrict_link->check, instantiate and
+	 * free_preparse) and across linking into @keyring.  Pass 1 of
+	 * key_garbage_collector() sets KEY_FLAG_DEAD and waits for
+	 * synchronize_srcu(&key_type_srcu) before pass 2 unlinks dead keys
+	 * and pass 3 retypes them to key_type_dead.
+	 */
+	srcu_idx = srcu_read_lock(&key_type_srcu);
+
+	if (test_bit(KEY_FLAG_DEAD, &key->flags)) {
+		ret = -EKEYREVOKED;
+		goto out;
+	}
+
+	if (!key->type->instantiate) {
+		ret = -EOPNOTSUPP;
+		goto out;
+	}
 
 	memset(&prep, 0, sizeof(prep));
 	prep.orig_description = key->description;
@@ -517,17 +541,17 @@ int key_instantiate_and_link(struct key *key,
 	if (key->type->preparse) {
 		ret = key->type->preparse(&prep);
 		if (ret < 0)
-			goto error;
+			goto out_free_preparse;
 	}
 
 	if (keyring) {
 		ret = __key_link_lock(keyring, &key->index_key);
 		if (ret < 0)
-			goto error;
+			goto out_free_preparse;
 
 		ret = __key_link_begin(keyring, &key->index_key, &edit);
 		if (ret < 0)
-			goto error_link_end;
+			goto out_link_end;
 
 		if (keyring->restrict_link && keyring->restrict_link->check) {
 			struct key_restriction *keyres = keyring->restrict_link;
@@ -535,19 +559,22 @@ int key_instantiate_and_link(struct key *key,
 			ret = keyres->check(keyring, key->type, &prep.payload,
 					    keyres->key);
 			if (ret < 0)
-				goto error_link_end;
+				goto out_link_end;
 		}
 	}
 
 	ret = __key_instantiate_and_link(key, &prep, keyring, authkey, &edit);
 
-error_link_end:
+out_link_end:
 	if (keyring)
 		__key_link_end(keyring, &key->index_key, edit);
 
-error:
+out_free_preparse:
 	if (key->type->preparse)
 		key->type->free_preparse(&prep);
+
+out:
+	srcu_read_unlock(&key_type_srcu, srcu_idx);
 	return ret;
 }
 
@@ -581,7 +608,8 @@ int key_reject_and_link(struct key *key,
 			struct key *authkey)
 {
 	struct assoc_array_edit *edit = NULL;
-	int ret, awaken, link_ret = 0;
+	int ret, awaken, link_ret = 0, srcu_idx;
+	bool dead;
 
 	key_check(key);
 	key_check(keyring);
@@ -589,22 +617,42 @@ int key_reject_and_link(struct key *key,
 	awaken = 0;
 	ret = -EBUSY;
 
+	/*
+	 * Hold key_type_srcu across linking into @keyring and
+	 * key_set_expiry() (which reads key->type->flags).  If the key is
+	 * already marked dead, skip linking and expiry but still complete
+	 * negative instantiation so waiters are woken and @authkey is
+	 * invalidated.
+	 */
+	srcu_idx = srcu_read_lock(&key_type_srcu);
+	dead = test_bit(KEY_FLAG_DEAD, &key->flags);
+
 	if (keyring) {
-		link_ret = __key_link_lock(keyring, &key->index_key);
-		if (link_ret == 0) {
-			/*
-			 * Check the restriction under the keyring semaphore.
-			 * keyring_restrict() installs it while holding the
-			 * semaphore, so testing it beforehand races with a
-			 * concurrent restriction install.
-			 */
-			if (keyring->restrict_link) {
-				__key_link_end(keyring, &key->index_key, edit);
-				return -EPERM;
+		if (dead) {
+			link_ret = -EKEYREVOKED;
+		} else {
+			link_ret = __key_link_lock(keyring, &key->index_key);
+			if (link_ret == 0) {
+				/*
+				 * Check the restriction under the keyring
+				 * semaphore. keyring_restrict() installs it
+				 * while holding the semaphore, so testing it
+				 * beforehand races with a concurrent
+				 * restriction install.
+				 */
+				if (keyring->restrict_link) {
+					__key_link_end(keyring, &key->index_key,
+						       edit);
+					ret = -EPERM;
+					goto out;
+				}
+				link_ret = __key_link_begin(keyring,
+							    &key->index_key,
+							    &edit);
+				if (link_ret < 0)
+					__key_link_end(keyring, &key->index_key,
+						       edit);
 			}
-			link_ret = __key_link_begin(keyring, &key->index_key, &edit);
-			if (link_ret < 0)
-				__key_link_end(keyring, &key->index_key, edit);
 		}
 	}
 
@@ -616,7 +664,8 @@ int key_reject_and_link(struct key *key,
 		atomic_inc(&key->user->nikeys);
 		mark_key_instantiated(key, -error);
 		notify_key(key, NOTIFY_KEY_INSTANTIATED, -error);
-		key_set_expiry(key, ktime_get_real_seconds() + timeout);
+		if (!dead)
+			key_set_expiry(key, ktime_get_real_seconds() + timeout);
 
 		if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags))
 			awaken = 1;
@@ -641,7 +690,10 @@ int key_reject_and_link(struct key *key,
 	if (awaken)
 		wake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT);
 
-	return ret == 0 ? link_ret : ret;
+	ret = ret == 0 ? link_ret : ret;
+out:
+	srcu_read_unlock(&key_type_srcu, srcu_idx);
+	return ret;
 }
 EXPORT_SYMBOL(key_reject_and_link);
 
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 9+ messages in thread

* Re: [PATCH v2] KEYS: Protect key instantiation and rejection against type removal
  2026-11-24  9:12 ` [PATCH v2] KEYS: Protect key instantiation and rejection " Guicai Ma
@ 2026-11-24 16:27   ` Jarkko Sakkinen
  2026-11-25  3:26   ` [PATCH v3] " Guicai Ma
  1 sibling, 0 replies; 9+ messages in thread
From: Jarkko Sakkinen @ 2026-11-24 16:27 UTC (permalink / raw)
  To: Guicai Ma
  Cc: David Howells, Paul Moore, James Morris, Serge E . Hallyn,
	keyrings, linux-security-module, linux-kernel

On Tue, Nov 24, 2026 at 04:12:43AM -0500, Guicai Ma wrote:
> key_instantiate_and_link() reads key->type->def_datalen and ->preparse,
> passes key->type to restrict_link->check(), and invokes ->instantiate()
> and ->free_preparse() without synchronizing against key type removal.
> A reference on the key keeps the key object alive, but does not pin the
> module that provides its type.
> 
> unregister_key_type() removes the type from key_types_list and waits for
> key_garbage_collector() to run three passes: pass 1 sets KEY_FLAG_DEAD
> and clears key->perm, pass 2 unlinks dead keys from keyrings, and pass 3
> takes key->sem for writing, retypes key->type to &key_type_dead, and
> destroys the payload. A key still under construction stays in
> KEY_IS_UNINSTANTIATED with a valid authorisation key, so an upcall
> helper calling KEYCTL_INSTANTIATE after pass 3 reaches
> __key_instantiate_and_link() and jumps to key_type_dead.instantiate,
> which is NULL:
> 
>   Unable to handle kernel NULL pointer dereference at
>   virtual address 0000000000000000
>   Internal error: Oops: 0000000086000006 [#1] SMP
>   pc : 0x0
>   lr : __key_instantiate_and_link+0xb8/0x2f8
>   Call trace:
>    0x0 (P)
>    key_instantiate_and_link+0x2e8/0x36c
>    keyctl_instantiate_key_common+0x1cc/0x338
>    keyctl_instantiate_key+0xbc/0x120
>    __arm64_sys_keyctl+0x218/0x3f0
> 
> If the module unloads while ->preparse() or ->instantiate() is running,
> execution can also return into freed module text or skip
> ->free_preparse(). While the request_key() syscall holds key_types_sem
> across the upcall, in-kernel request_key() callers do not, so
> unregister_key_type() can run before KEYCTL_INSTANTIATE or
> KEYCTL_REJECT.
> 
> key_reject_and_link() shares the same window: it links the key into
> @keyring and calls key_set_expiry() (which reads key->type->flags)
> without checking KEY_FLAG_DEAD. Linking a dead key between GC pass 2 and
> pass 3 leaves it in the keyring's assoc_array while pass 3 overwrites
> key->type (which aliases key->index_key.type) in place.
> 
> Neither key->sem nor key_types_sem can be taken here: holding key->sem
> across __key_link_lock() and __key_instantiate_and_link() inverts lock
> order against encrypted_instantiate() (which locks the master key's
> semaphore under keyring->sem and key_construction_mutex), and
> key_instantiate_and_link() is already called with key_types_sem held for
> reading (e.g. from request_key_auth_new()).
> 
> Add key_type_srcu and call synchronize_srcu(&key_type_srcu) at the end
> of GC pass 1 (KEY_GC_REAPING_DEAD_1) whenever dead keys were marked.
> SRCU rather than RCU because ->preparse() and ->instantiate() may sleep.
> Hold key_type_srcu across the full body of key_instantiate_and_link()
> and key_reject_and_link() and check KEY_FLAG_DEAD:
> 
> - Callers that observe !KEY_FLAG_DEAD finish all key->type accesses and
>   any keyring linking before pass 2 unlinks dead keys and pass 3 retypes
>   them to key_type_dead.
> - Callers entering after synchronize_srcu() observe KEY_FLAG_DEAD:
>   key_instantiate_and_link() returns -EKEYREVOKED (matching
>   key_validate()), and key_reject_and_link() skips linking (returning
>   -EKEYREVOKED if @keyring was given) and key_set_expiry() while still
>   completing negative instantiation so waiters wake up and @authkey is
>   invalidated.
> 
> Also return -EOPNOTSUPP in key_instantiate_and_link() if a live key type
> does not provide ->instantiate().

The commit message is incomprehensible.

Br, Jarkko

^ permalink raw reply	[flat|nested] 9+ messages in thread

* [PATCH v3] KEYS: Protect key instantiation and rejection against type removal
  2026-11-24  9:12 ` [PATCH v2] KEYS: Protect key instantiation and rejection " Guicai Ma
  2026-11-24 16:27   ` Jarkko Sakkinen
@ 2026-11-25  3:26   ` Guicai Ma
  2026-11-25 17:19     ` Jarkko Sakkinen
  2026-11-26  2:39     ` [PATCH v4] " Guicai Ma
  1 sibling, 2 replies; 9+ messages in thread
From: Guicai Ma @ 2026-11-25  3:26 UTC (permalink / raw)
  To: David Howells, Jarkko Sakkinen
  Cc: Paul Moore, James Morris, Serge E . Hallyn, keyrings,
	linux-security-module, linux-kernel, Guicai Ma

key_instantiate_and_link() and key_reject_and_link() access key->type
and link keys without synchronizing against unregister_key_type(). If
the type is removed while a key is under construction, GC retypes it to
key_type_dead (where ->instantiate is NULL) or links a dead key before
pass 3 rewrites key->type.

key->sem cannot be used here because it inverts lock order against
encrypted_instantiate() and references a freed lockdep class after a
modular type unloads, while callers may already hold key_types_sem and
->preparse() or ->instantiate() may sleep. Guard both paths with
key_type_srcu and a KEY_FLAG_DEAD check, and wait for in-flight calls
with synchronize_srcu(&key_type_srcu) at the end of GC pass 1.

Fixes: 0c061b5707ab ("KEYS: Correctly destroy key payloads when their keytype is removed")
Cc: stable@vger.kernel.org
Signed-off-by: Guicai Ma <maguicai@kylinos.cn>
---
v3:
- Shorten the commit message and focus on why SRCU is used.
- Change Fixes tag to 0c061b5707ab.
- No code changes.

v2:
- Switch from key->sem to key_type_srcu and check KEY_FLAG_DEAD in
  key_instantiate_and_link() and key_reject_and_link().

 security/keys/gc.c       |  13 +++++
 security/keys/internal.h |   2 +
 security/keys/key.c      | 108 +++++++++++++++++++++++++++++----------
 3 files changed, 95 insertions(+), 28 deletions(-)

diff --git a/security/keys/gc.c b/security/keys/gc.c
index eda445f815d4..61cb2b9a7aaf 100644
--- a/security/keys/gc.c
+++ b/security/keys/gc.c
@@ -35,6 +35,8 @@ static unsigned long key_gc_flags;
 #define KEY_GC_REAP_KEYTYPE	1	/* A keytype is being unregistered */
 #define KEY_GC_REAPING_KEYTYPE	2	/* Cleared when keytype reaped */
 
+DEFINE_SRCU(key_type_srcu);
+
 
 /*
  * Any key whose type gets unregistered will be re-typed to this if it can't be
@@ -286,6 +288,17 @@ static void key_garbage_collector(struct work_struct *work)
 		key_schedule_gc(new_timer);
 	}
 
+	if (unlikely((gc_state & KEY_GC_REAPING_DEAD_1) &&
+		     (gc_state & KEY_GC_FOUND_DEAD_KEY))) {
+		/* Wait for any in-flight key_instantiate_and_link() or
+		 * key_reject_and_link() calls that did not observe
+		 * KEY_FLAG_DEAD before pass 2 unlinks dead keys from keyrings
+		 * and pass 3 retypes them to key_type_dead.
+		 */
+		kdebug("gc dead type sync");
+		synchronize_srcu(&key_type_srcu);
+	}
+
 	if (unlikely(gc_state & KEY_GC_REAPING_DEAD_2) ||
 	    !list_empty(&graveyard)) {
 		/* Make sure that all pending keyring payload destructions are
diff --git a/security/keys/internal.h b/security/keys/internal.h
index b7b622bc36a1..73d71de274c2 100644
--- a/security/keys/internal.h
+++ b/security/keys/internal.h
@@ -19,6 +19,7 @@
 #include <linux/compat.h>
 #include <linux/mm.h>
 #include <linux/vmalloc.h>
+#include <linux/srcu.h>
 
 struct iovec;
 
@@ -86,6 +87,7 @@ extern struct kmem_cache *key_jar;
 extern struct rb_root key_serial_tree;
 extern spinlock_t key_serial_lock;
 extern struct mutex key_construction_mutex;
+extern struct srcu_struct key_type_srcu;
 extern wait_queue_head_t request_key_conswq;
 
 extern void key_set_index_key(struct keyring_index_key *index_key);
diff --git a/security/keys/key.c b/security/keys/key.c
index 3f1f0fc13710..d923ddf457e9 100644
--- a/security/keys/key.c
+++ b/security/keys/key.c
@@ -422,9 +422,10 @@ static void mark_key_instantiated(struct key *key, int reject_error)
 
 /*
  * Instantiate a key and link it into the target keyring atomically.  Must be
- * called with the target keyring's semaphore writelocked.  The target key's
- * semaphore need not be locked as instantiation is serialised by
- * key_construction_mutex.
+ * called with the target keyring's semaphore writelocked.  The caller must
+ * hold key_type_srcu (after checking !KEY_FLAG_DEAD) or key_types_sem for
+ * reading via key_type_lookup(), so the type cannot be retyped to
+ * key_type_dead or its module unloaded while its methods run.
  */
 static int __key_instantiate_and_link(struct key *key,
 				      struct key_preparsed_payload *prep,
@@ -496,7 +497,9 @@ static int __key_instantiate_and_link(struct key *key,
  *
  * If successful, 0 is returned, the authorisation token is revoked and anyone
  * waiting for the key is woken up.  If the key was already instantiated,
- * -EBUSY will be returned.
+ * -EBUSY will be returned.  If the key's type has been removed, -EKEYREVOKED
+ * will be returned.  If the key type does not provide an instantiate method,
+ * -EOPNOTSUPP will be returned.
  */
 int key_instantiate_and_link(struct key *key,
 			     const void *data,
@@ -506,7 +509,28 @@ int key_instantiate_and_link(struct key *key,
 {
 	struct key_preparsed_payload prep;
 	struct assoc_array_edit *edit = NULL;
-	int ret;
+	int ret, srcu_idx;
+
+	/*
+	 * A reference on the key does not pin the module that provides its
+	 * type.  Hold key_type_srcu across every use of key->type
+	 * (def_datalen, preparse, restrict_link->check, instantiate and
+	 * free_preparse) and across linking into @keyring.  Pass 1 of
+	 * key_garbage_collector() sets KEY_FLAG_DEAD and waits for
+	 * synchronize_srcu(&key_type_srcu) before pass 2 unlinks dead keys
+	 * and pass 3 retypes them to key_type_dead.
+	 */
+	srcu_idx = srcu_read_lock(&key_type_srcu);
+
+	if (test_bit(KEY_FLAG_DEAD, &key->flags)) {
+		ret = -EKEYREVOKED;
+		goto out;
+	}
+
+	if (!key->type->instantiate) {
+		ret = -EOPNOTSUPP;
+		goto out;
+	}
 
 	memset(&prep, 0, sizeof(prep));
 	prep.orig_description = key->description;
@@ -517,17 +541,17 @@ int key_instantiate_and_link(struct key *key,
 	if (key->type->preparse) {
 		ret = key->type->preparse(&prep);
 		if (ret < 0)
-			goto error;
+			goto out_free_preparse;
 	}
 
 	if (keyring) {
 		ret = __key_link_lock(keyring, &key->index_key);
 		if (ret < 0)
-			goto error;
+			goto out_free_preparse;
 
 		ret = __key_link_begin(keyring, &key->index_key, &edit);
 		if (ret < 0)
-			goto error_link_end;
+			goto out_link_end;
 
 		if (keyring->restrict_link && keyring->restrict_link->check) {
 			struct key_restriction *keyres = keyring->restrict_link;
@@ -535,19 +559,22 @@ int key_instantiate_and_link(struct key *key,
 			ret = keyres->check(keyring, key->type, &prep.payload,
 					    keyres->key);
 			if (ret < 0)
-				goto error_link_end;
+				goto out_link_end;
 		}
 	}
 
 	ret = __key_instantiate_and_link(key, &prep, keyring, authkey, &edit);
 
-error_link_end:
+out_link_end:
 	if (keyring)
 		__key_link_end(keyring, &key->index_key, edit);
 
-error:
+out_free_preparse:
 	if (key->type->preparse)
 		key->type->free_preparse(&prep);
+
+out:
+	srcu_read_unlock(&key_type_srcu, srcu_idx);
 	return ret;
 }
 
@@ -581,7 +608,8 @@ int key_reject_and_link(struct key *key,
 			struct key *authkey)
 {
 	struct assoc_array_edit *edit = NULL;
-	int ret, awaken, link_ret = 0;
+	int ret, awaken, link_ret = 0, srcu_idx;
+	bool dead;
 
 	key_check(key);
 	key_check(keyring);
@@ -589,22 +617,42 @@ int key_reject_and_link(struct key *key,
 	awaken = 0;
 	ret = -EBUSY;
 
+	/*
+	 * Hold key_type_srcu across linking into @keyring and
+	 * key_set_expiry() (which reads key->type->flags).  If the key is
+	 * already marked dead, skip linking and expiry but still complete
+	 * negative instantiation so waiters are woken and @authkey is
+	 * invalidated.
+	 */
+	srcu_idx = srcu_read_lock(&key_type_srcu);
+	dead = test_bit(KEY_FLAG_DEAD, &key->flags);
+
 	if (keyring) {
-		link_ret = __key_link_lock(keyring, &key->index_key);
-		if (link_ret == 0) {
-			/*
-			 * Check the restriction under the keyring semaphore.
-			 * keyring_restrict() installs it while holding the
-			 * semaphore, so testing it beforehand races with a
-			 * concurrent restriction install.
-			 */
-			if (keyring->restrict_link) {
-				__key_link_end(keyring, &key->index_key, edit);
-				return -EPERM;
+		if (dead) {
+			link_ret = -EKEYREVOKED;
+		} else {
+			link_ret = __key_link_lock(keyring, &key->index_key);
+			if (link_ret == 0) {
+				/*
+				 * Check the restriction under the keyring
+				 * semaphore. keyring_restrict() installs it
+				 * while holding the semaphore, so testing it
+				 * beforehand races with a concurrent
+				 * restriction install.
+				 */
+				if (keyring->restrict_link) {
+					__key_link_end(keyring, &key->index_key,
+						       edit);
+					ret = -EPERM;
+					goto out;
+				}
+				link_ret = __key_link_begin(keyring,
+							    &key->index_key,
+							    &edit);
+				if (link_ret < 0)
+					__key_link_end(keyring, &key->index_key,
+						       edit);
 			}
-			link_ret = __key_link_begin(keyring, &key->index_key, &edit);
-			if (link_ret < 0)
-				__key_link_end(keyring, &key->index_key, edit);
 		}
 	}
 
@@ -616,7 +664,8 @@ int key_reject_and_link(struct key *key,
 		atomic_inc(&key->user->nikeys);
 		mark_key_instantiated(key, -error);
 		notify_key(key, NOTIFY_KEY_INSTANTIATED, -error);
-		key_set_expiry(key, ktime_get_real_seconds() + timeout);
+		if (!dead)
+			key_set_expiry(key, ktime_get_real_seconds() + timeout);
 
 		if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags))
 			awaken = 1;
@@ -641,7 +690,10 @@ int key_reject_and_link(struct key *key,
 	if (awaken)
 		wake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT);
 
-	return ret == 0 ? link_ret : ret;
+	ret = ret == 0 ? link_ret : ret;
+out:
+	srcu_read_unlock(&key_type_srcu, srcu_idx);
+	return ret;
 }
 EXPORT_SYMBOL(key_reject_and_link);
 
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 9+ messages in thread

* Re: [PATCH v3] KEYS: Protect key instantiation and rejection against type removal
  2026-11-25  3:26   ` [PATCH v3] " Guicai Ma
@ 2026-11-25 17:19     ` Jarkko Sakkinen
  2026-11-26  2:39     ` [PATCH v4] " Guicai Ma
  1 sibling, 0 replies; 9+ messages in thread
From: Jarkko Sakkinen @ 2026-11-25 17:19 UTC (permalink / raw)
  To: Guicai Ma
  Cc: David Howells, Paul Moore, James Morris, Serge E . Hallyn,
	keyrings, linux-security-module, linux-kernel

On Tue, Nov 24, 2026 at 10:26:05PM -0500, Guicai Ma wrote:
> key_instantiate_and_link() and key_reject_and_link() access key->type
> and link keys without synchronizing against unregister_key_type(). If
> the type is removed while a key is under construction, GC retypes it to
> key_type_dead (where ->instantiate is NULL) or links a dead key before
> pass 3 rewrites key->type.
> 
> key->sem cannot be used here because it inverts lock order against
> encrypted_instantiate() and references a freed lockdep class after a
> modular type unloads, while callers may already hold key_types_sem and
> ->preparse() or ->instantiate() may sleep. Guard both paths with
> key_type_srcu and a KEY_FLAG_DEAD check, and wait for in-flight calls
> with synchronize_srcu(&key_type_srcu) at the end of GC pass 1.
> 
> Fixes: 0c061b5707ab ("KEYS: Correctly destroy key payloads when their keytype is removed")
> Cc: stable@vger.kernel.org
> Signed-off-by: Guicai Ma <maguicai@kylinos.cn>
> ---
> v3:
> - Shorten the commit message and focus on why SRCU is used.
> - Change Fixes tag to 0c061b5707ab.
> - No code changes.
> 
> v2:
> - Switch from key->sem to key_type_srcu and check KEY_FLAG_DEAD in
>   key_instantiate_and_link() and key_reject_and_link().
> 
>  security/keys/gc.c       |  13 +++++
>  security/keys/internal.h |   2 +
>  security/keys/key.c      | 108 +++++++++++++++++++++++++++++----------
>  3 files changed, 95 insertions(+), 28 deletions(-)
> 
> diff --git a/security/keys/gc.c b/security/keys/gc.c
> index eda445f815d4..61cb2b9a7aaf 100644
> --- a/security/keys/gc.c
> +++ b/security/keys/gc.c
> @@ -35,6 +35,8 @@ static unsigned long key_gc_flags;
>  #define KEY_GC_REAP_KEYTYPE	1	/* A keytype is being unregistered */
>  #define KEY_GC_REAPING_KEYTYPE	2	/* Cleared when keytype reaped */
>  
> +DEFINE_SRCU(key_type_srcu);
> +
>  
>  /*
>   * Any key whose type gets unregistered will be re-typed to this if it can't be
> @@ -286,6 +288,17 @@ static void key_garbage_collector(struct work_struct *work)
>  		key_schedule_gc(new_timer);
>  	}
>  
> +	if (unlikely((gc_state & KEY_GC_REAPING_DEAD_1) &&
> +		     (gc_state & KEY_GC_FOUND_DEAD_KEY))) {
> +		/* Wait for any in-flight key_instantiate_and_link() or
> +		 * key_reject_and_link() calls that did not observe
> +		 * KEY_FLAG_DEAD before pass 2 unlinks dead keys from keyrings
> +		 * and pass 3 retypes them to key_type_dead.
> +		 */
> +		kdebug("gc dead type sync");
> +		synchronize_srcu(&key_type_srcu);
> +	}
> +
>  	if (unlikely(gc_state & KEY_GC_REAPING_DEAD_2) ||
>  	    !list_empty(&graveyard)) {
>  		/* Make sure that all pending keyring payload destructions are
> diff --git a/security/keys/internal.h b/security/keys/internal.h
> index b7b622bc36a1..73d71de274c2 100644
> --- a/security/keys/internal.h
> +++ b/security/keys/internal.h
> @@ -19,6 +19,7 @@
>  #include <linux/compat.h>
>  #include <linux/mm.h>
>  #include <linux/vmalloc.h>
> +#include <linux/srcu.h>
>  
>  struct iovec;
>  
> @@ -86,6 +87,7 @@ extern struct kmem_cache *key_jar;
>  extern struct rb_root key_serial_tree;
>  extern spinlock_t key_serial_lock;
>  extern struct mutex key_construction_mutex;
> +extern struct srcu_struct key_type_srcu;
>  extern wait_queue_head_t request_key_conswq;
>  
>  extern void key_set_index_key(struct keyring_index_key *index_key);
> diff --git a/security/keys/key.c b/security/keys/key.c
> index 3f1f0fc13710..d923ddf457e9 100644
> --- a/security/keys/key.c
> +++ b/security/keys/key.c
> @@ -422,9 +422,10 @@ static void mark_key_instantiated(struct key *key, int reject_error)
>  
>  /*
>   * Instantiate a key and link it into the target keyring atomically.  Must be
> - * called with the target keyring's semaphore writelocked.  The target key's
> - * semaphore need not be locked as instantiation is serialised by
> - * key_construction_mutex.
> + * called with the target keyring's semaphore writelocked.  The caller must
> + * hold key_type_srcu (after checking !KEY_FLAG_DEAD) or key_types_sem for
> + * reading via key_type_lookup(), so the type cannot be retyped to
> + * key_type_dead or its module unloaded while its methods run.
>   */
>  static int __key_instantiate_and_link(struct key *key,
>  				      struct key_preparsed_payload *prep,
> @@ -496,7 +497,9 @@ static int __key_instantiate_and_link(struct key *key,
>   *
>   * If successful, 0 is returned, the authorisation token is revoked and anyone
>   * waiting for the key is woken up.  If the key was already instantiated,
> - * -EBUSY will be returned.
> + * -EBUSY will be returned.  If the key's type has been removed, -EKEYREVOKED
> + * will be returned.  If the key type does not provide an instantiate method,
> + * -EOPNOTSUPP will be returned.
>   */
>  int key_instantiate_and_link(struct key *key,
>  			     const void *data,
> @@ -506,7 +509,28 @@ int key_instantiate_and_link(struct key *key,
>  {
>  	struct key_preparsed_payload prep;
>  	struct assoc_array_edit *edit = NULL;
> -	int ret;
> +	int ret, srcu_idx;
> +
> +	/*
> +	 * A reference on the key does not pin the module that provides its
> +	 * type.  Hold key_type_srcu across every use of key->type
> +	 * (def_datalen, preparse, restrict_link->check, instantiate and
> +	 * free_preparse) and across linking into @keyring.  Pass 1 of
> +	 * key_garbage_collector() sets KEY_FLAG_DEAD and waits for
> +	 * synchronize_srcu(&key_type_srcu) before pass 2 unlinks dead keys
> +	 * and pass 3 retypes them to key_type_dead.
> +	 */
> +	srcu_idx = srcu_read_lock(&key_type_srcu);
> +
> +	if (test_bit(KEY_FLAG_DEAD, &key->flags)) {
> +		ret = -EKEYREVOKED;
> +		goto out;
> +	}
> +
> +	if (!key->type->instantiate) {
> +		ret = -EOPNOTSUPP;
> +		goto out;
> +	}
>  
>  	memset(&prep, 0, sizeof(prep));
>  	prep.orig_description = key->description;
> @@ -517,17 +541,17 @@ int key_instantiate_and_link(struct key *key,
>  	if (key->type->preparse) {
>  		ret = key->type->preparse(&prep);
>  		if (ret < 0)
> -			goto error;
> +			goto out_free_preparse;
>  	}
>  
>  	if (keyring) {
>  		ret = __key_link_lock(keyring, &key->index_key);
>  		if (ret < 0)
> -			goto error;
> +			goto out_free_preparse;
>  
>  		ret = __key_link_begin(keyring, &key->index_key, &edit);
>  		if (ret < 0)
> -			goto error_link_end;
> +			goto out_link_end;
>  
>  		if (keyring->restrict_link && keyring->restrict_link->check) {
>  			struct key_restriction *keyres = keyring->restrict_link;
> @@ -535,19 +559,22 @@ int key_instantiate_and_link(struct key *key,
>  			ret = keyres->check(keyring, key->type, &prep.payload,
>  					    keyres->key);
>  			if (ret < 0)
> -				goto error_link_end;
> +				goto out_link_end;
>  		}
>  	}
>  
>  	ret = __key_instantiate_and_link(key, &prep, keyring, authkey, &edit);
>  
> -error_link_end:
> +out_link_end:
>  	if (keyring)
>  		__key_link_end(keyring, &key->index_key, edit);
>  
> -error:
> +out_free_preparse:
>  	if (key->type->preparse)
>  		key->type->free_preparse(&prep);
> +
> +out:
> +	srcu_read_unlock(&key_type_srcu, srcu_idx);
>  	return ret;
>  }
>  
> @@ -581,7 +608,8 @@ int key_reject_and_link(struct key *key,
>  			struct key *authkey)
>  {
>  	struct assoc_array_edit *edit = NULL;
> -	int ret, awaken, link_ret = 0;
> +	int ret, awaken, link_ret = 0, srcu_idx;
> +	bool dead;
>  
>  	key_check(key);
>  	key_check(keyring);
> @@ -589,22 +617,42 @@ int key_reject_and_link(struct key *key,
>  	awaken = 0;
>  	ret = -EBUSY;
>  
> +	/*
> +	 * Hold key_type_srcu across linking into @keyring and
> +	 * key_set_expiry() (which reads key->type->flags).  If the key is
> +	 * already marked dead, skip linking and expiry but still complete
> +	 * negative instantiation so waiters are woken and @authkey is
> +	 * invalidated.
> +	 */
> +	srcu_idx = srcu_read_lock(&key_type_srcu);
> +	dead = test_bit(KEY_FLAG_DEAD, &key->flags);
> +
>  	if (keyring) {
> -		link_ret = __key_link_lock(keyring, &key->index_key);
> -		if (link_ret == 0) {
> -			/*
> -			 * Check the restriction under the keyring semaphore.
> -			 * keyring_restrict() installs it while holding the
> -			 * semaphore, so testing it beforehand races with a
> -			 * concurrent restriction install.
> -			 */
> -			if (keyring->restrict_link) {
> -				__key_link_end(keyring, &key->index_key, edit);
> -				return -EPERM;
> +		if (dead) {
> +			link_ret = -EKEYREVOKED;
> +		} else {
> +			link_ret = __key_link_lock(keyring, &key->index_key);
> +			if (link_ret == 0) {
> +				/*
> +				 * Check the restriction under the keyring
> +				 * semaphore. keyring_restrict() installs it
> +				 * while holding the semaphore, so testing it
> +				 * beforehand races with a concurrent
> +				 * restriction install.
> +				 */
> +				if (keyring->restrict_link) {
> +					__key_link_end(keyring, &key->index_key,
> +						       edit);
> +					ret = -EPERM;
> +					goto out;
> +				}
> +				link_ret = __key_link_begin(keyring,
> +							    &key->index_key,
> +							    &edit);
> +				if (link_ret < 0)
> +					__key_link_end(keyring, &key->index_key,
> +						       edit);
>  			}
> -			link_ret = __key_link_begin(keyring, &key->index_key, &edit);
> -			if (link_ret < 0)
> -				__key_link_end(keyring, &key->index_key, edit);
>  		}
>  	}
>  
> @@ -616,7 +664,8 @@ int key_reject_and_link(struct key *key,
>  		atomic_inc(&key->user->nikeys);
>  		mark_key_instantiated(key, -error);
>  		notify_key(key, NOTIFY_KEY_INSTANTIATED, -error);
> -		key_set_expiry(key, ktime_get_real_seconds() + timeout);
> +		if (!dead)
> +			key_set_expiry(key, ktime_get_real_seconds() + timeout);
>  
>  		if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags))
>  			awaken = 1;
> @@ -641,7 +690,10 @@ int key_reject_and_link(struct key *key,
>  	if (awaken)
>  		wake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT);
>  
> -	return ret == 0 ? link_ret : ret;
> +	ret = ret == 0 ? link_ret : ret;
> +out:
> +	srcu_read_unlock(&key_type_srcu, srcu_idx);
> +	return ret;
>  }
>  EXPORT_SYMBOL(key_reject_and_link);
>  
> -- 
> 2.47.3
> 
o

LGTM with quick skim. I'll revisit later with time

Br, Jarkko

^ permalink raw reply	[flat|nested] 9+ messages in thread

* [PATCH v4] KEYS: Protect key instantiation and rejection against type removal
  2026-11-25  3:26   ` [PATCH v3] " Guicai Ma
  2026-11-25 17:19     ` Jarkko Sakkinen
@ 2026-11-26  2:39     ` Guicai Ma
  2026-11-26 16:18       ` Jarkko Sakkinen
  1 sibling, 1 reply; 9+ messages in thread
From: Guicai Ma @ 2026-11-26  2:39 UTC (permalink / raw)
  To: David Howells, Jarkko Sakkinen
  Cc: Paul Moore, James Morris, Serge E. Hallyn, keyrings,
	linux-security-module, linux-kernel, Guicai Ma

key_instantiate_and_link() and key_reject_and_link() access key->type
and link keys without synchronizing against unregister_key_type(). If
the type is removed during construction, key_instantiate_and_link() can
call key_type_dead.instantiate, which is NULL, and either function can
link a dead key into the keyring before GC pass 3 retypes it.

key->sem cannot be used here because it inverts lock order with
encrypted_instantiate() and uses a freed lockdep class after a modular
type unloads, while key_types_sem may be held and methods may sleep.
Guard both paths with key_type_srcu and a KEY_FLAG_DEAD check, waiting
with synchronize_srcu(&key_type_srcu) after GC pass 1; for a dead key in
key_reject_and_link(), just wake waiters and invalidate @authkey under
key_construction_mutex, leaving the key uninstantiated.

Fixes: 0c061b5707ab ("KEYS: Correctly destroy key payloads when their keytype is removed")
Cc: stable@vger.kernel.org
Signed-off-by: Guicai Ma <maguicai@kylinos.cn>
---
v4:
- Rebase onto jarkko/master.
- In key_reject_and_link(), handle KEY_FLAG_DEAD under
  key_construction_mutex alone without taking key->sem or changing
  key->state, and document the result in the kerneldoc.

v3:
- Shorten the commit message and focus on why SRCU is used.
- Change Fixes tag to 0c061b5707ab.

v2:
- Switch from key->sem to key_type_srcu and check KEY_FLAG_DEAD in
  key_instantiate_and_link() and key_reject_and_link().

 security/keys/gc.c       |  13 ++++
 security/keys/internal.h |   2 +
 security/keys/key.c      | 160 ++++++++++++++++++++++++++++-----------
 3 files changed, 129 insertions(+), 46 deletions(-)

diff --git a/security/keys/gc.c b/security/keys/gc.c
index eda445f815d4..61cb2b9a7aaf 100644
--- a/security/keys/gc.c
+++ b/security/keys/gc.c
@@ -35,6 +35,8 @@ static unsigned long key_gc_flags;
 #define KEY_GC_REAP_KEYTYPE	1	/* A keytype is being unregistered */
 #define KEY_GC_REAPING_KEYTYPE	2	/* Cleared when keytype reaped */
 
+DEFINE_SRCU(key_type_srcu);
+
 
 /*
  * Any key whose type gets unregistered will be re-typed to this if it can't be
@@ -286,6 +288,17 @@ static void key_garbage_collector(struct work_struct *work)
 		key_schedule_gc(new_timer);
 	}
 
+	if (unlikely((gc_state & KEY_GC_REAPING_DEAD_1) &&
+		     (gc_state & KEY_GC_FOUND_DEAD_KEY))) {
+		/* Wait for any in-flight key_instantiate_and_link() or
+		 * key_reject_and_link() calls that did not observe
+		 * KEY_FLAG_DEAD before pass 2 unlinks dead keys from keyrings
+		 * and pass 3 retypes them to key_type_dead.
+		 */
+		kdebug("gc dead type sync");
+		synchronize_srcu(&key_type_srcu);
+	}
+
 	if (unlikely(gc_state & KEY_GC_REAPING_DEAD_2) ||
 	    !list_empty(&graveyard)) {
 		/* Make sure that all pending keyring payload destructions are
diff --git a/security/keys/internal.h b/security/keys/internal.h
index c452d71cce03..4cf6b8070227 100644
--- a/security/keys/internal.h
+++ b/security/keys/internal.h
@@ -19,6 +19,7 @@
 #include <linux/compat.h>
 #include <linux/mm.h>
 #include <linux/vmalloc.h>
+#include <linux/srcu.h>
 
 struct iovec;
 struct keyring_link;
@@ -92,6 +93,7 @@ extern struct kmem_cache *key_jar;
 extern struct rb_root key_serial_tree;
 extern spinlock_t key_serial_lock;
 extern struct mutex key_construction_mutex;
+extern struct srcu_struct key_type_srcu;
 extern wait_queue_head_t request_key_conswq;
 
 extern void key_set_index_key(struct keyring_index_key *index_key);
diff --git a/security/keys/key.c b/security/keys/key.c
index 5854c2e2c4e6..c08082443418 100644
--- a/security/keys/key.c
+++ b/security/keys/key.c
@@ -422,9 +422,10 @@ static void mark_key_instantiated(struct key *key, int reject_error)
 
 /*
  * Instantiate a key and link it into the target keyring atomically.  Must be
- * called with the target keyring's semaphore writelocked.  The target key's
- * semaphore need not be locked as instantiation is serialised by
- * key_construction_mutex.
+ * called with the target keyring's semaphore writelocked.  The caller must
+ * hold key_type_srcu (after checking !KEY_FLAG_DEAD) or key_types_sem for
+ * reading via key_type_lookup(), so the type cannot be retyped to
+ * key_type_dead or its module unloaded while its methods run.
  */
 static int __key_instantiate_and_link(struct key *key,
 				      struct key_preparsed_payload *prep,
@@ -498,7 +499,9 @@ static int __key_instantiate_and_link(struct key *key,
  *
  * If successful, 0 is returned, the authorisation token is revoked and anyone
  * waiting for the key is woken up.  If the key was already instantiated,
- * -EBUSY will be returned.
+ * -EBUSY will be returned.  If the key's type has been removed, -EKEYREVOKED
+ * will be returned.  If the key type does not provide an instantiate method,
+ * -EOPNOTSUPP will be returned.
  */
 int key_instantiate_and_link(struct key *key,
 			     const void *data,
@@ -508,7 +511,25 @@ int key_instantiate_and_link(struct key *key,
 {
 	struct key_preparsed_payload prep;
 	struct keyring_edit edit = {};
-	int ret;
+	int ret, srcu_idx;
+
+	/*
+	 * Hold key_type_srcu across key->type accesses and linking into
+	 * @keyring.  Pass 1 of key_garbage_collector() sets KEY_FLAG_DEAD
+	 * and runs synchronize_srcu(&key_type_srcu) before pass 2 unlinks
+	 * dead keys and pass 3 retypes them to key_type_dead.
+	 */
+	srcu_idx = srcu_read_lock(&key_type_srcu);
+
+	if (test_bit(KEY_FLAG_DEAD, &key->flags)) {
+		ret = -EKEYREVOKED;
+		goto out;
+	}
+
+	if (!key->type->instantiate) {
+		ret = -EOPNOTSUPP;
+		goto out;
+	}
 
 	memset(&prep, 0, sizeof(prep));
 	prep.orig_description = key->description;
@@ -519,17 +540,17 @@ int key_instantiate_and_link(struct key *key,
 	if (key->type->preparse) {
 		ret = key->type->preparse(&prep);
 		if (ret < 0)
-			goto error;
+			goto out_free_preparse;
 	}
 
 	if (keyring) {
 		ret = __key_link_lock(keyring, &key->index_key);
 		if (ret < 0)
-			goto error;
+			goto out_free_preparse;
 
 		ret = __key_link_begin(keyring, &key->index_key, &edit);
 		if (ret < 0)
-			goto error_link_end;
+			goto out_link_end;
 
 		if (keyring->restrict_link && keyring->restrict_link->check) {
 			struct key_restriction *keyres = keyring->restrict_link;
@@ -537,19 +558,22 @@ int key_instantiate_and_link(struct key *key,
 			ret = keyres->check(keyring, key->type, &prep.payload,
 					    keyres->key);
 			if (ret < 0)
-				goto error_link_end;
+				goto out_link_end;
 		}
 	}
 
 	ret = __key_instantiate_and_link(key, &prep, keyring, authkey, &edit);
 
-error_link_end:
+out_link_end:
 	if (keyring)
 		__key_link_end(keyring, &key->index_key, &edit);
 
-error:
+out_free_preparse:
 	if (key->type->preparse)
 		key->type->free_preparse(&prep);
+
+out:
+	srcu_read_unlock(&key_type_srcu, srcu_idx);
 	return ret;
 }
 
@@ -574,7 +598,10 @@ EXPORT_SYMBOL(key_instantiate_and_link);
  *
  * If successful, 0 is returned, the authorisation token is revoked and anyone
  * waiting for the key is woken up.  If the key was already instantiated,
- * -EBUSY will be returned.
+ * -EBUSY will be returned.  If the key's type has been removed, the key is
+ * left uninstantiated, the authorisation token is revoked, anyone waiting
+ * for the key is woken up, and -EKEYREVOKED is returned if @keyring was
+ * given.
  */
 int key_reject_and_link(struct key *key,
 			unsigned timeout,
@@ -583,7 +610,8 @@ int key_reject_and_link(struct key *key,
 			struct key *authkey)
 {
 	struct keyring_edit edit = {};
-	int ret, awaken, link_ret = 0;
+	int ret, awaken, link_ret = 0, srcu_idx;
+	bool dead;
 
 	key_check(key);
 	key_check(keyring);
@@ -591,51 +619,88 @@ int key_reject_and_link(struct key *key,
 	awaken = 0;
 	ret = -EBUSY;
 
+	/*
+	 * Hold key_type_srcu across linking into @keyring and
+	 * key_set_expiry() (which reads key->type->flags).  If the key is
+	 * already marked dead, skip linking, key->sem, and negative
+	 * instantiation so wait_for_key_construction() wakes up and returns
+	 * -EKEYREVOKED via key_validate().
+	 */
+	srcu_idx = srcu_read_lock(&key_type_srcu);
+	dead = test_bit(KEY_FLAG_DEAD, &key->flags);
+
 	if (keyring) {
-		link_ret = __key_link_lock(keyring, &key->index_key);
-		if (link_ret == 0) {
-			/*
-			 * Check the restriction under the keyring semaphore.
-			 * keyring_restrict() installs it while holding the
-			 * semaphore, so testing it beforehand races with a
-			 * concurrent restriction install.
-			 */
-			if (keyring->restrict_link) {
-				__key_link_end(keyring, &key->index_key, &edit);
-				return -EPERM;
+		if (dead) {
+			link_ret = -EKEYREVOKED;
+		} else {
+			link_ret = __key_link_lock(keyring, &key->index_key);
+			if (link_ret == 0) {
+				/*
+				 * Check the restriction under the keyring
+				 * semaphore. keyring_restrict() installs it
+				 * while holding the semaphore, so testing it
+				 * beforehand races with a concurrent
+				 * restriction install.
+				 */
+				if (keyring->restrict_link) {
+					__key_link_end(keyring, &key->index_key,
+						       &edit);
+					ret = -EPERM;
+					goto out;
+				}
+				link_ret = __key_link_begin(keyring,
+							    &key->index_key,
+							    &edit);
+				if (link_ret < 0)
+					__key_link_end(keyring, &key->index_key,
+						       &edit);
 			}
-			link_ret = __key_link_begin(keyring, &key->index_key, &edit);
-			if (link_ret < 0)
-				__key_link_end(keyring, &key->index_key, &edit);
 		}
 	}
 
 	mutex_lock(&key_construction_mutex);
-	down_write_nested(&key->sem, 2);
 
-	/* can't instantiate twice */
-	if (key->state == KEY_IS_UNINSTANTIATED) {
-		/* mark the key as being negatively instantiated */
-		atomic_inc(&key->user->nikeys);
-		mark_key_instantiated(key, -error);
-		notify_key(key, NOTIFY_KEY_INSTANTIATED, -error);
-		key_set_expiry(key, ktime_get_real_seconds() + timeout);
+	if (dead) {
+		if (key->state == KEY_IS_UNINSTANTIATED) {
+			if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT,
+					       &key->flags))
+				awaken = 1;
+
+			ret = 0;
+
+			/* disable the authorisation key */
+			if (authkey)
+				key_invalidate(authkey);
+		}
+	} else {
+		down_write_nested(&key->sem, 2);
+
+		/* can't instantiate twice */
+		if (key->state == KEY_IS_UNINSTANTIATED) {
+			/* mark the key as being negatively instantiated */
+			atomic_inc(&key->user->nikeys);
+			mark_key_instantiated(key, -error);
+			notify_key(key, NOTIFY_KEY_INSTANTIATED, -error);
+			key_set_expiry(key, ktime_get_real_seconds() + timeout);
 
-		if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags))
-			awaken = 1;
+			if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT,
+					       &key->flags))
+				awaken = 1;
 
-		ret = 0;
+			ret = 0;
 
-		/* and link it into the destination keyring */
-		if (keyring && link_ret == 0)
-			__key_link(keyring, key, &edit);
+			/* and link it into the destination keyring */
+			if (keyring && link_ret == 0)
+				__key_link(keyring, key, &edit);
 
-		/* disable the authorisation key */
-		if (authkey)
-			key_invalidate(authkey);
+			/* disable the authorisation key */
+			if (authkey)
+				key_invalidate(authkey);
+		}
+
+		up_write(&key->sem);
 	}
 
-	up_write(&key->sem);
 	mutex_unlock(&key_construction_mutex);
 
 	if (keyring && link_ret == 0)
@@ -645,7 +710,10 @@ int key_reject_and_link(struct key *key,
 	if (awaken)
 		wake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT);
 
-	return ret == 0 ? link_ret : ret;
+	ret = ret == 0 ? link_ret : ret;
+out:
+	srcu_read_unlock(&key_type_srcu, srcu_idx);
+	return ret;
 }
 EXPORT_SYMBOL(key_reject_and_link);
 
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 9+ messages in thread

* Re: [PATCH v4] KEYS: Protect key instantiation and rejection against type removal
  2026-11-26  2:39     ` [PATCH v4] " Guicai Ma
@ 2026-11-26 16:18       ` Jarkko Sakkinen
  2026-11-27 13:26         ` Jarkko Sakkinen
  0 siblings, 1 reply; 9+ messages in thread
From: Jarkko Sakkinen @ 2026-11-26 16:18 UTC (permalink / raw)
  To: Guicai Ma, Linus Torvalds
  Cc: David Howells, Paul Moore, James Morris, Serge E. Hallyn,
	keyrings, linux-security-module, linux-kernel

On Wed, Nov 25, 2026 at 09:39:20PM -0500, Guicai Ma wrote:
> key_instantiate_and_link() and key_reject_and_link() access key->type
> and link keys without synchronizing against unregister_key_type(). If
> the type is removed during construction, key_instantiate_and_link() can
> call key_type_dead.instantiate, which is NULL, and either function can
> link a dead key into the keyring before GC pass 3 retypes it.
> 
> key->sem cannot be used here because it inverts lock order with
> encrypted_instantiate() and uses a freed lockdep class after a modular
> type unloads, while key_types_sem may be held and methods may sleep.
> Guard both paths with key_type_srcu and a KEY_FLAG_DEAD check, waiting
> with synchronize_srcu(&key_type_srcu) after GC pass 1; for a dead key in
> key_reject_and_link(), just wake waiters and invalidate @authkey under
> key_construction_mutex, leaving the key uninstantiated.
> 
> Fixes: 0c061b5707ab ("KEYS: Correctly destroy key payloads when their keytype is removed")
> Cc: stable@vger.kernel.org
> Signed-off-by: Guicai Ma <maguicai@kylinos.cn>
> ---
> v4:
> - Rebase onto jarkko/master.
> - In key_reject_and_link(), handle KEY_FLAG_DEAD under
>   key_construction_mutex alone without taking key->sem or changing
>   key->state, and document the result in the kerneldoc.
> 
> v3:
> - Shorten the commit message and focus on why SRCU is used.
> - Change Fixes tag to 0c061b5707ab.
> 
> v2:
> - Switch from key->sem to key_type_srcu and check KEY_FLAG_DEAD in
>   key_instantiate_and_link() and key_reject_and_link().
> 
>  security/keys/gc.c       |  13 ++++
>  security/keys/internal.h |   2 +
>  security/keys/key.c      | 160 ++++++++++++++++++++++++++++-----------
>  3 files changed, 129 insertions(+), 46 deletions(-)

It's unfortunate that the fix needs to be this complicated but as we've
looked this through, also with failed alternatives, I still think this
is a feasible fix.

And it's good to now before I even consider moving forward with my
keyring GC overhaul, which ties keys to their key type's LKM, and
removes racy key types altogether.

Linus, I'll give a forewarning on this fix because is not every day
thing to introduce SRCU in stable fixes.


Reviewed-by: Jarkko Sakkinen <jarkko@kernel.org>


> 
> diff --git a/security/keys/gc.c b/security/keys/gc.c
> index eda445f815d4..61cb2b9a7aaf 100644
> --- a/security/keys/gc.c
> +++ b/security/keys/gc.c
> @@ -35,6 +35,8 @@ static unsigned long key_gc_flags;
>  #define KEY_GC_REAP_KEYTYPE	1	/* A keytype is being unregistered */
>  #define KEY_GC_REAPING_KEYTYPE	2	/* Cleared when keytype reaped */
>  
> +DEFINE_SRCU(key_type_srcu);
> +
>  
>  /*
>   * Any key whose type gets unregistered will be re-typed to this if it can't be
> @@ -286,6 +288,17 @@ static void key_garbage_collector(struct work_struct *work)
>  		key_schedule_gc(new_timer);
>  	}
>  
> +	if (unlikely((gc_state & KEY_GC_REAPING_DEAD_1) &&
> +		     (gc_state & KEY_GC_FOUND_DEAD_KEY))) {
> +		/* Wait for any in-flight key_instantiate_and_link() or

nit:

/*
 * ...


https://docs.kernel.org/process/coding-style.html

> +		 * key_reject_and_link() calls that did not observe
> +		 * KEY_FLAG_DEAD before pass 2 unlinks dead keys from keyrings
> +		 * and pass 3 retypes them to key_type_dead.
> +		 */
> +		kdebug("gc dead type sync");
> +		synchronize_srcu(&key_type_srcu);
> +	}
> +
>  	if (unlikely(gc_state & KEY_GC_REAPING_DEAD_2) ||
>  	    !list_empty(&graveyard)) {
>  		/* Make sure that all pending keyring payload destructions are
> diff --git a/security/keys/internal.h b/security/keys/internal.h
> index c452d71cce03..4cf6b8070227 100644
> --- a/security/keys/internal.h
> +++ b/security/keys/internal.h
> @@ -19,6 +19,7 @@
>  #include <linux/compat.h>
>  #include <linux/mm.h>
>  #include <linux/vmalloc.h>
> +#include <linux/srcu.h>
>  
>  struct iovec;
>  struct keyring_link;
> @@ -92,6 +93,7 @@ extern struct kmem_cache *key_jar;
>  extern struct rb_root key_serial_tree;
>  extern spinlock_t key_serial_lock;
>  extern struct mutex key_construction_mutex;
> +extern struct srcu_struct key_type_srcu;
>  extern wait_queue_head_t request_key_conswq;
>  
>  extern void key_set_index_key(struct keyring_index_key *index_key);
> diff --git a/security/keys/key.c b/security/keys/key.c
> index 5854c2e2c4e6..c08082443418 100644
> --- a/security/keys/key.c
> +++ b/security/keys/key.c
> @@ -422,9 +422,10 @@ static void mark_key_instantiated(struct key *key, int reject_error)
>  
>  /*
>   * Instantiate a key and link it into the target keyring atomically.  Must be
> - * called with the target keyring's semaphore writelocked.  The target key's
> - * semaphore need not be locked as instantiation is serialised by
> - * key_construction_mutex.
> + * called with the target keyring's semaphore writelocked.  The caller must
> + * hold key_type_srcu (after checking !KEY_FLAG_DEAD) or key_types_sem for
> + * reading via key_type_lookup(), so the type cannot be retyped to
> + * key_type_dead or its module unloaded while its methods run.
>   */
>  static int __key_instantiate_and_link(struct key *key,
>  				      struct key_preparsed_payload *prep,
> @@ -498,7 +499,9 @@ static int __key_instantiate_and_link(struct key *key,
>   *
>   * If successful, 0 is returned, the authorisation token is revoked and anyone
>   * waiting for the key is woken up.  If the key was already instantiated,
> - * -EBUSY will be returned.
> + * -EBUSY will be returned.  If the key's type has been removed, -EKEYREVOKED
> + * will be returned.  If the key type does not provide an instantiate method,
> + * -EOPNOTSUPP will be returned.
>   */
>  int key_instantiate_and_link(struct key *key,
>  			     const void *data,
> @@ -508,7 +511,25 @@ int key_instantiate_and_link(struct key *key,
>  {
>  	struct key_preparsed_payload prep;
>  	struct keyring_edit edit = {};
> -	int ret;
> +	int ret, srcu_idx;
> +
> +	/*
> +	 * Hold key_type_srcu across key->type accesses and linking into
> +	 * @keyring.  Pass 1 of key_garbage_collector() sets KEY_FLAG_DEAD
> +	 * and runs synchronize_srcu(&key_type_srcu) before pass 2 unlinks
> +	 * dead keys and pass 3 retypes them to key_type_dead.
> +	 */
> +	srcu_idx = srcu_read_lock(&key_type_srcu);
> +
> +	if (test_bit(KEY_FLAG_DEAD, &key->flags)) {
> +		ret = -EKEYREVOKED;
> +		goto out;
> +	}
> +
> +	if (!key->type->instantiate) {
> +		ret = -EOPNOTSUPP;
> +		goto out;
> +	}
>  
>  	memset(&prep, 0, sizeof(prep));
>  	prep.orig_description = key->description;
> @@ -519,17 +540,17 @@ int key_instantiate_and_link(struct key *key,
>  	if (key->type->preparse) {
>  		ret = key->type->preparse(&prep);
>  		if (ret < 0)
> -			goto error;
> +			goto out_free_preparse;
>  	}
>  
>  	if (keyring) {
>  		ret = __key_link_lock(keyring, &key->index_key);
>  		if (ret < 0)
> -			goto error;
> +			goto out_free_preparse;
>  
>  		ret = __key_link_begin(keyring, &key->index_key, &edit);
>  		if (ret < 0)
> -			goto error_link_end;
> +			goto out_link_end;
>  
>  		if (keyring->restrict_link && keyring->restrict_link->check) {
>  			struct key_restriction *keyres = keyring->restrict_link;
> @@ -537,19 +558,22 @@ int key_instantiate_and_link(struct key *key,
>  			ret = keyres->check(keyring, key->type, &prep.payload,
>  					    keyres->key);
>  			if (ret < 0)
> -				goto error_link_end;
> +				goto out_link_end;
>  		}
>  	}
>  
>  	ret = __key_instantiate_and_link(key, &prep, keyring, authkey, &edit);
>  
> -error_link_end:
> +out_link_end:
>  	if (keyring)
>  		__key_link_end(keyring, &key->index_key, &edit);
>  
> -error:
> +out_free_preparse:
>  	if (key->type->preparse)
>  		key->type->free_preparse(&prep);
> +
> +out:
> +	srcu_read_unlock(&key_type_srcu, srcu_idx);
>  	return ret;
>  }
>  
> @@ -574,7 +598,10 @@ EXPORT_SYMBOL(key_instantiate_and_link);
>   *
>   * If successful, 0 is returned, the authorisation token is revoked and anyone
>   * waiting for the key is woken up.  If the key was already instantiated,
> - * -EBUSY will be returned.
> + * -EBUSY will be returned.  If the key's type has been removed, the key is
> + * left uninstantiated, the authorisation token is revoked, anyone waiting
> + * for the key is woken up, and -EKEYREVOKED is returned if @keyring was
> + * given.
>   */
>  int key_reject_and_link(struct key *key,
>  			unsigned timeout,
> @@ -583,7 +610,8 @@ int key_reject_and_link(struct key *key,
>  			struct key *authkey)
>  {
>  	struct keyring_edit edit = {};
> -	int ret, awaken, link_ret = 0;
> +	int ret, awaken, link_ret = 0, srcu_idx;
> +	bool dead;
>  
>  	key_check(key);
>  	key_check(keyring);
> @@ -591,51 +619,88 @@ int key_reject_and_link(struct key *key,
>  	awaken = 0;
>  	ret = -EBUSY;
>  
> +	/*
> +	 * Hold key_type_srcu across linking into @keyring and
> +	 * key_set_expiry() (which reads key->type->flags).  If the key is
> +	 * already marked dead, skip linking, key->sem, and negative
> +	 * instantiation so wait_for_key_construction() wakes up and returns
> +	 * -EKEYREVOKED via key_validate().
> +	 */
> +	srcu_idx = srcu_read_lock(&key_type_srcu);
> +	dead = test_bit(KEY_FLAG_DEAD, &key->flags);
> +
>  	if (keyring) {
> -		link_ret = __key_link_lock(keyring, &key->index_key);
> -		if (link_ret == 0) {
> -			/*
> -			 * Check the restriction under the keyring semaphore.
> -			 * keyring_restrict() installs it while holding the
> -			 * semaphore, so testing it beforehand races with a
> -			 * concurrent restriction install.
> -			 */
> -			if (keyring->restrict_link) {
> -				__key_link_end(keyring, &key->index_key, &edit);
> -				return -EPERM;
> +		if (dead) {
> +			link_ret = -EKEYREVOKED;
> +		} else {
> +			link_ret = __key_link_lock(keyring, &key->index_key);
> +			if (link_ret == 0) {
> +				/*
> +				 * Check the restriction under the keyring
> +				 * semaphore. keyring_restrict() installs it
> +				 * while holding the semaphore, so testing it
> +				 * beforehand races with a concurrent
> +				 * restriction install.
> +				 */
> +				if (keyring->restrict_link) {
> +					__key_link_end(keyring, &key->index_key,
> +						       &edit);
> +					ret = -EPERM;
> +					goto out;
> +				}
> +				link_ret = __key_link_begin(keyring,
> +							    &key->index_key,
> +							    &edit);
> +				if (link_ret < 0)
> +					__key_link_end(keyring, &key->index_key,
> +						       &edit);
>  			}
> -			link_ret = __key_link_begin(keyring, &key->index_key, &edit);
> -			if (link_ret < 0)
> -				__key_link_end(keyring, &key->index_key, &edit);
>  		}
>  	}
>  
>  	mutex_lock(&key_construction_mutex);
> -	down_write_nested(&key->sem, 2);
>  
> -	/* can't instantiate twice */
> -	if (key->state == KEY_IS_UNINSTANTIATED) {
> -		/* mark the key as being negatively instantiated */
> -		atomic_inc(&key->user->nikeys);
> -		mark_key_instantiated(key, -error);
> -		notify_key(key, NOTIFY_KEY_INSTANTIATED, -error);
> -		key_set_expiry(key, ktime_get_real_seconds() + timeout);
> +	if (dead) {
> +		if (key->state == KEY_IS_UNINSTANTIATED) {
> +			if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT,
> +					       &key->flags))
> +				awaken = 1;
> +
> +			ret = 0;
> +
> +			/* disable the authorisation key */
> +			if (authkey)
> +				key_invalidate(authkey);
> +		}
> +	} else {
> +		down_write_nested(&key->sem, 2);
> +
> +		/* can't instantiate twice */
> +		if (key->state == KEY_IS_UNINSTANTIATED) {
> +			/* mark the key as being negatively instantiated */
> +			atomic_inc(&key->user->nikeys);
> +			mark_key_instantiated(key, -error);
> +			notify_key(key, NOTIFY_KEY_INSTANTIATED, -error);
> +			key_set_expiry(key, ktime_get_real_seconds() + timeout);
>  
> -		if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags))
> -			awaken = 1;
> +			if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT,
> +					       &key->flags))
> +				awaken = 1;
>  
> -		ret = 0;
> +			ret = 0;
>  
> -		/* and link it into the destination keyring */
> -		if (keyring && link_ret == 0)
> -			__key_link(keyring, key, &edit);
> +			/* and link it into the destination keyring */
> +			if (keyring && link_ret == 0)
> +				__key_link(keyring, key, &edit);
>  
> -		/* disable the authorisation key */
> -		if (authkey)
> -			key_invalidate(authkey);
> +			/* disable the authorisation key */
> +			if (authkey)
> +				key_invalidate(authkey);
> +		}
> +
> +		up_write(&key->sem);
>  	}
>  
> -	up_write(&key->sem);
>  	mutex_unlock(&key_construction_mutex);
>  
>  	if (keyring && link_ret == 0)
> @@ -645,7 +710,10 @@ int key_reject_and_link(struct key *key,
>  	if (awaken)
>  		wake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT);
>  
> -	return ret == 0 ? link_ret : ret;
> +	ret = ret == 0 ? link_ret : ret;
> +out:
> +	srcu_read_unlock(&key_type_srcu, srcu_idx);
> +	return ret;
>  }
>  EXPORT_SYMBOL(key_reject_and_link);
>  
> -- 
> 2.47.3
> 

Br, Jarkko

^ permalink raw reply	[flat|nested] 9+ messages in thread

* Re: [PATCH v4] KEYS: Protect key instantiation and rejection against type removal
  2026-11-26 16:18       ` Jarkko Sakkinen
@ 2026-11-27 13:26         ` Jarkko Sakkinen
  2026-11-28 10:28           ` Jarkko Sakkinen
  0 siblings, 1 reply; 9+ messages in thread
From: Jarkko Sakkinen @ 2026-11-27 13:26 UTC (permalink / raw)
  To: Guicai Ma, Linus Torvalds
  Cc: David Howells, Paul Moore, James Morris, Serge E. Hallyn,
	keyrings, linux-security-module, linux-kernel

On Thu, Nov 26, 2026 at 06:18:38PM +0200, Jarkko Sakkinen wrote:
> On Wed, Nov 25, 2026 at 09:39:20PM -0500, Guicai Ma wrote:
> > key_instantiate_and_link() and key_reject_and_link() access key->type
> > and link keys without synchronizing against unregister_key_type(). If
> > the type is removed during construction, key_instantiate_and_link() can
> > call key_type_dead.instantiate, which is NULL, and either function can
> > link a dead key into the keyring before GC pass 3 retypes it.
> > 
> > key->sem cannot be used here because it inverts lock order with
> > encrypted_instantiate() and uses a freed lockdep class after a modular
> > type unloads, while key_types_sem may be held and methods may sleep.
> > Guard both paths with key_type_srcu and a KEY_FLAG_DEAD check, waiting
> > with synchronize_srcu(&key_type_srcu) after GC pass 1; for a dead key in
> > key_reject_and_link(), just wake waiters and invalidate @authkey under
> > key_construction_mutex, leaving the key uninstantiated.
> > 
> > Fixes: 0c061b5707ab ("KEYS: Correctly destroy key payloads when their keytype is removed")
> > Cc: stable@vger.kernel.org
> > Signed-off-by: Guicai Ma <maguicai@kylinos.cn>
> > ---
> > v4:
> > - Rebase onto jarkko/master.
> > - In key_reject_and_link(), handle KEY_FLAG_DEAD under
> >   key_construction_mutex alone without taking key->sem or changing
> >   key->state, and document the result in the kerneldoc.
> > 
> > v3:
> > - Shorten the commit message and focus on why SRCU is used.
> > - Change Fixes tag to 0c061b5707ab.
> > 
> > v2:
> > - Switch from key->sem to key_type_srcu and check KEY_FLAG_DEAD in
> >   key_instantiate_and_link() and key_reject_and_link().
> > 
> >  security/keys/gc.c       |  13 ++++
> >  security/keys/internal.h |   2 +
> >  security/keys/key.c      | 160 ++++++++++++++++++++++++++++-----------
> >  3 files changed, 129 insertions(+), 46 deletions(-)
> 
> It's unfortunate that the fix needs to be this complicated but as we've
> looked this through, also with failed alternatives, I still think this
> is a feasible fix.
> 
> And it's good to now before I even consider moving forward with my
> keyring GC overhaul, which ties keys to their key type's LKM, and
> removes racy key types altogether.
> 
> Linus, I'll give a forewarning on this fix because is not every day
> thing to introduce SRCU in stable fixes.
> 
> 
> Reviewed-by: Jarkko Sakkinen <jarkko@kernel.org>

I rebased my series on top of this and yeah, it will be erased by the
last commit:

https://git.kernel.org/pub/scm/linux/kernel/git/jarkko/linux-tpmdd.git/commit/?h=keyring_gc&id=5028b0336d35f14981116926d9ee5e131ff7c7ed

That does not make the fix less important. On contrary, it is good to
have it in place for stable kernels.

Br, JArkko

^ permalink raw reply	[flat|nested] 9+ messages in thread

* Re: [PATCH v4] KEYS: Protect key instantiation and rejection against type removal
  2026-11-27 13:26         ` Jarkko Sakkinen
@ 2026-11-28 10:28           ` Jarkko Sakkinen
  0 siblings, 0 replies; 9+ messages in thread
From: Jarkko Sakkinen @ 2026-11-28 10:28 UTC (permalink / raw)
  To: Guicai Ma, Linus Torvalds
  Cc: David Howells, Paul Moore, James Morris, Serge E. Hallyn,
	keyrings, linux-security-module, linux-kernel

On Fri, Nov 27, 2026 at 03:26:11PM +0200, Jarkko Sakkinen wrote:
> On Thu, Nov 26, 2026 at 06:18:38PM +0200, Jarkko Sakkinen wrote:
> > On Wed, Nov 25, 2026 at 09:39:20PM -0500, Guicai Ma wrote:
> > > key_instantiate_and_link() and key_reject_and_link() access key->type
> > > and link keys without synchronizing against unregister_key_type(). If
> > > the type is removed during construction, key_instantiate_and_link() can
> > > call key_type_dead.instantiate, which is NULL, and either function can
> > > link a dead key into the keyring before GC pass 3 retypes it.
> > > 
> > > key->sem cannot be used here because it inverts lock order with
> > > encrypted_instantiate() and uses a freed lockdep class after a modular
> > > type unloads, while key_types_sem may be held and methods may sleep.
> > > Guard both paths with key_type_srcu and a KEY_FLAG_DEAD check, waiting
> > > with synchronize_srcu(&key_type_srcu) after GC pass 1; for a dead key in
> > > key_reject_and_link(), just wake waiters and invalidate @authkey under
> > > key_construction_mutex, leaving the key uninstantiated.
> > > 
> > > Fixes: 0c061b5707ab ("KEYS: Correctly destroy key payloads when their keytype is removed")
> > > Cc: stable@vger.kernel.org
> > > Signed-off-by: Guicai Ma <maguicai@kylinos.cn>
> > > ---
> > > v4:
> > > - Rebase onto jarkko/master.
> > > - In key_reject_and_link(), handle KEY_FLAG_DEAD under
> > >   key_construction_mutex alone without taking key->sem or changing
> > >   key->state, and document the result in the kerneldoc.
> > > 
> > > v3:
> > > - Shorten the commit message and focus on why SRCU is used.
> > > - Change Fixes tag to 0c061b5707ab.
> > > 
> > > v2:
> > > - Switch from key->sem to key_type_srcu and check KEY_FLAG_DEAD in
> > >   key_instantiate_and_link() and key_reject_and_link().
> > > 
> > >  security/keys/gc.c       |  13 ++++
> > >  security/keys/internal.h |   2 +
> > >  security/keys/key.c      | 160 ++++++++++++++++++++++++++++-----------
> > >  3 files changed, 129 insertions(+), 46 deletions(-)
> > 
> > It's unfortunate that the fix needs to be this complicated but as we've
> > looked this through, also with failed alternatives, I still think this
> > is a feasible fix.
> > 
> > And it's good to now before I even consider moving forward with my
> > keyring GC overhaul, which ties keys to their key type's LKM, and
> > removes racy key types altogether.
> > 
> > Linus, I'll give a forewarning on this fix because is not every day
> > thing to introduce SRCU in stable fixes.
> > 
> > 
> > Reviewed-by: Jarkko Sakkinen <jarkko@kernel.org>
> 
> I rebased my series on top of this and yeah, it will be erased by the
> last commit:
> 
> https://git.kernel.org/pub/scm/linux/kernel/git/jarkko/linux-tpmdd.git/commit/?h=keyring_gc&id=5028b0336d35f14981116926d9ee5e131ff7c7ed
> 
> That does not make the fix less important. On contrary, it is good to
> have it in place for stable kernels.

It's better not to have these changes in v7.5 yet so that there is
more window for fixes.

I.e., only rhashtable changes will land to that release and keyring_gc
with current ETA to  v7.6.

Br, Jarkko

^ permalink raw reply	[flat|nested] 9+ messages in thread

end of thread, other threads:[~2026-11-28 10:28 UTC | newest]

Thread overview: 9+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-11-24  5:33 [PATCH] KEYS: Protect the instantiate method against type removal Guicai Ma
2026-11-24  9:12 ` [PATCH v2] KEYS: Protect key instantiation and rejection " Guicai Ma
2026-11-24 16:27   ` Jarkko Sakkinen
2026-11-25  3:26   ` [PATCH v3] " Guicai Ma
2026-11-25 17:19     ` Jarkko Sakkinen
2026-11-26  2:39     ` [PATCH v4] " Guicai Ma
2026-11-26 16:18       ` Jarkko Sakkinen
2026-11-27 13:26         ` Jarkko Sakkinen
2026-11-28 10:28           ` Jarkko Sakkinen

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox