KEYS: return full count in keyring_read() if buffer is too small

Commit e645016abc ("KEYS: fix writing past end of user-supplied buffer
in keyring_read()") made keyring_read() stop corrupting userspace memory
when the user-supplied buffer is too small.  However it also made the
return value in that case be the short buffer size rather than the size
required, yet keyctl_read() is actually documented to return the size
required.  Therefore, switch it over to the documented behavior.

Note that for now we continue to have it fill the short buffer, since it
did that before (pre-v3.13) and dump_key_tree_aux() in keyutils arguably
relies on it.

Fixes: e645016abc ("KEYS: fix writing past end of user-supplied buffer in keyring_read()")
Reported-by: Ben Hutchings <ben@decadent.org.uk>
Cc: <stable@vger.kernel.org> # v3.13+
Signed-off-by: Eric Biggers <ebiggers@google.com>
Signed-off-by: David Howells <dhowells@redhat.com>
Reviewed-by: James Morris <james.l.morris@oracle.com>
Signed-off-by: James Morris <james.l.morris@oracle.com>
This commit is contained in:
Eric Biggers 2017-11-02 00:47:03 +00:00 committed by James Morris
parent 3a99df9a3d
commit 3239b6f29b

View File

@ -459,34 +459,33 @@ static long keyring_read(const struct key *keyring,
char __user *buffer, size_t buflen) char __user *buffer, size_t buflen)
{ {
struct keyring_read_iterator_context ctx; struct keyring_read_iterator_context ctx;
unsigned long nr_keys; long ret;
int ret;
kenter("{%d},,%zu", key_serial(keyring), buflen); kenter("{%d},,%zu", key_serial(keyring), buflen);
if (buflen & (sizeof(key_serial_t) - 1)) if (buflen & (sizeof(key_serial_t) - 1))
return -EINVAL; return -EINVAL;
nr_keys = keyring->keys.nr_leaves_on_tree; /* Copy as many key IDs as fit into the buffer */
if (nr_keys == 0) if (buffer && buflen) {
return 0; ctx.buffer = (key_serial_t __user *)buffer;
ctx.buflen = buflen;
/* Calculate how much data we could return */ ctx.count = 0;
if (!buffer || !buflen) ret = assoc_array_iterate(&keyring->keys,
return nr_keys * sizeof(key_serial_t); keyring_read_iterator, &ctx);
if (ret < 0) {
/* Copy the IDs of the subscribed keys into the buffer */ kleave(" = %ld [iterate]", ret);
ctx.buffer = (key_serial_t __user *)buffer; return ret;
ctx.buflen = buflen; }
ctx.count = 0;
ret = assoc_array_iterate(&keyring->keys, keyring_read_iterator, &ctx);
if (ret < 0) {
kleave(" = %d [iterate]", ret);
return ret;
} }
kleave(" = %zu [ok]", ctx.count); /* Return the size of the buffer needed */
return ctx.count; ret = keyring->keys.nr_leaves_on_tree * sizeof(key_serial_t);
if (ret <= buflen)
kleave("= %ld [ok]", ret);
else
kleave("= %ld [buffer too small]", ret);
return ret;
} }
/* /*