Re: [PATCH] block: add allocation size check in blkdev_pr_read_keys()
From: Deepanshu Kartikey
Date: Fri Dec 12 2025 - 09:47:57 EST
On Fri, Dec 12, 2025 at 11:46 AM Christoph Hellwig <hch@xxxxxxxxxxxxx> wrote:
> Well, bother checks for sure are redundant. But maybe this is also
> a good chance to pick a sane arbitrary limited instead of
> KMALLOC_MAX_SIZE. And if that is above KMALLOC_MAX_SIZE, switch to
> using kvzalloc.
>
Thanks for the feedback.
How about limiting num_keys to 64K (1u << 16)? In practice, PR keys
are used for shared storage coordination and typical deployments have
only a handful of hosts, so this should be more than enough for any
realistic use case.
With a bounded num_keys, the SIZE_MAX check becomes unnecessary, so
I've removed it. Also switched to kvzalloc/kvfree to handle larger
allocations gracefully.
Something like below:
+/* Limit the number of keys to prevent excessive memory allocation */
+#define PR_KEYS_MAX_NUM (1u << 16)
+
static int blkdev_pr_read_keys(struct block_device *bdev, blk_mode_t mode,
struct pr_read_keys __user *arg)
{
...
if (copy_from_user(&read_keys, arg, sizeof(read_keys)))
return -EFAULT;
+ if (read_keys.num_keys > PR_KEYS_MAX_NUM)
+ return -EINVAL;
+
keys_info_len = struct_size(keys_info, keys, read_keys.num_keys);
- if (keys_info_len == SIZE_MAX)
- return -EINVAL;
- keys_info = kzalloc(keys_info_len, GFP_KERNEL);
+ keys_info = kvzalloc(keys_info_len, GFP_KERNEL);
if (!keys_info)
return -ENOMEM;
...
out:
- kfree(keys_info);
+ kvfree(keys_info);
return ret;
}