Re: [PATCH] KEYS: Prevent key type removal during key_instantiate_and_link()

From: Guicai Ma

Date: Tue Nov 24 2026 - 18:00:31 EST


On Tue, 24 Nov 2026 19:40:35 +0200, Jarkko Sakkinen wrote:
> @@ -610,11 +628,12 @@ int key_reject_and_link(struct key *key,
> }
> }
>
> - mutex_lock(&key_construction_mutex);
> down_write_nested(&key->sem, 2);
>
> /* can't instantiate twice */
> if (key->state == KEY_IS_UNINSTANTIATED) {
> + mutex_lock(&key_construction_mutex);

Here __key_link_begin() still runs before key->sem is taken and there is
no KEY_FLAG_DEAD check, so the link path is still taken: on 7.4-rc3 with
KASAN and PROVE_LOCKING, KEYCTL_REJECT with a target keyring on a dead
key returns 0 instead of -EKEYREVOKED. If pass 3 retypes the key before
key->sem is taken, __key_link() inserts it with an edit built from the
old type.

Taking key->sem before __key_link_begin() and skipping the link with
link_ret = -EKEYREVOKED when KEY_FLAG_DEAD is set avoids that, and still
lets the negative instantiation finish so request_key() waiters wake up.

In key_instantiate_and_link():
> + down_write_nested(&key->sem, 2);
> +
> + if (test_bit(KEY_FLAG_DEAD, &key->flags)) {
> + ret = -EKEYREVOKED;
> + goto out_unlock;
> + }

After a modular type is unloaded, key->sem still carries the module's
lock_class_key, which lockdep_free_key_range() dropped. In the post-rmmod
instantiate test up_write() here warns "trying to release lock
(&type->lock_class) ... no more locks to release". Module pinning would
remove this; it still matters for stable backports.

The 200-round instantiate/reject race and encrypted-key instantiation
pass.

Thanks,
Guicai