[PATCH v2] KEYS: do not let an unmatched key decide the search result

From: Guixiong Wei

Date: Sun Nov 08 2026 - 22:31:07 EST


With the dns_resolver key type available, put a key named "foo" in a
fresh session keyring, revoke it, and search for "bar":

keyctl new_session >/dev/null
A=$(printf '127.0.0.1\0' | keyctl padd dns_resolver foo @s)
keyctl revoke "$A"
keyctl search @s dns_resolver bar

Results:

keyctl_search: Key has been revoked

The search returns -EKEYREVOKED even though there is no key named "bar".
It should return -ENOKEY.

A dns_resolver search walks the keys in the keyring and uses
dns_resolver_cmp() to compare their descriptions with the requested
name. When keyring_search_iterator() sees the revoked "foo" key, it
records -EKEYREVOKED in ctx->result and skips the key before comparing
its description. The search continues, but without a match it returns
the error recorded for "foo".

Call the match callback before checking for invalidated, revoked or
expired keys. A nonmatching key then leaves ctx->result alone.

Fixes: b2a4df200d57 ("KEYS: Expand the capacity of a keyring")
Reported-by: Jarkko Sakkinen <jarkko@xxxxxxxxxx>
Closes: https://lore.kernel.org/lkml/avDG8G-Jl1YsmfCs@xxxxxxxxxx/
Signed-off-by: Guixiong Wei <weiguixiong@xxxxxxxxxxxxx>
---

Changes in v2:
- Explain the wrong errno using Jarkko's original reproducer and output.
- Clarify that the search continues after skipping the revoked key.
- Add Reported-by and Closes tags. Keep the code diff unchanged.

v1: https://lore.kernel.org/lkml/20261108131413.12012-2-weiguixiong@xxxxxxxxxxxxx/

security/keys/keyring.c | 12 ++++++------
1 file changed, 6 insertions(+), 6 deletions(-)

diff --git a/security/keys/keyring.c b/security/keys/keyring.c
index 7143f3079d200..39645b8f9b30c 100644
--- a/security/keys/keyring.c
+++ b/security/keys/keyring.c
@@ -598,6 +598,12 @@ static int keyring_search_iterator(const void *object, void *iterator_data)
return 0;
}

+ /* A key the caller did not ask for must not decide the result. */
+ if (!ctx->match_data.cmp(key, &ctx->match_data)) {
+ kleave(" = 0 [!match]");
+ return 0;
+ }
+
/* skip invalidated, revoked and expired keys */
if (ctx->flags & KEYRING_SEARCH_DO_STATE_CHECK) {
time64_t expiry = READ_ONCE(key->expiry);
@@ -617,12 +623,6 @@ static int keyring_search_iterator(const void *object, void *iterator_data)
}
}

- /* keys that don't match */
- if (!ctx->match_data.cmp(key, &ctx->match_data)) {
- kleave(" = 0 [!match]");
- return 0;
- }
-
/* key must have search permissions */
if (!(ctx->flags & KEYRING_SEARCH_NO_CHECK_PERM) &&
key_task_permission(make_key_ref(key, ctx->possessed),
--
2.55.0