Re: [PATCH v4] KEYS: Protect key instantiation and rejection against type removal
From: Jarkko Sakkinen
Date: Fri Nov 27 2026 - 08:26:22 EST
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@xxxxxxxxxxxxxxx
> > Signed-off-by: Guicai Ma <maguicai@xxxxxxxxxx>
> > ---
> > 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@xxxxxxxxxx>
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