Re: [PATCH] KEYS: Prevent key type removal during key_instantiate_and_link()
From: Jarkko Sakkinen
Date: Tue Nov 24 2026 - 18:24:28 EST
On Tue, Nov 24, 2026 at 06:00:16PM -0500, Guicai Ma wrote:
> 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.
I'm with you on backports part of course, and apparently you are right
what you're saying. Thanks for pointing this out.
Addin SCRU just feels a bit heavy measure but the concurrency case is
also somewhat nasty. But in the end of the day it's only +10 LOC and
I understand why it works, and I also under why this does not :-)
It was not that much more complicated. Can you put the commit message
more brief and exactly put emphasis on SCRU part?
>
> Thanks,
> Guicai
Br, Jarkko