[PATCH v4] block: add capacity validation in bdev_add_partition()

From: Min Li
Date: Sun Jun 18 2023 - 21:18:15 EST


In the function bdev_add_partition(),there is no check that the start
and end sectors exceed the size of the disk before calling add_partition.
When we call the block's ioctl interface directly to add a partition,
and the capacity of the disk is set to 0 by driver,the command will
continue to execute.

Signed-off-by: Min Li <min15.li@xxxxxxxxxxx>
Reviewed-by: Christoph Hellwig <hch@xxxxxx>

---
Changes from v1:

- Check for overflows of the start + length value
- Place the capacity check at the beginning of the function.

Changes from v2:

- Place the assignment on the first line and merge the two lines into one

Changes from v3:

- Modify the singed name
---
block/partitions/core.c | 11 +++++++++++
1 file changed, 11 insertions(+)

diff --git a/block/partitions/core.c b/block/partitions/core.c
index 49e0496ff23c..b511f88bf558 100644
--- a/block/partitions/core.c
+++ b/block/partitions/core.c
@@ -436,10 +436,21 @@ static bool partition_overlaps(struct gendisk *disk, sector_t start,
int bdev_add_partition(struct gendisk *disk, int partno, sector_t start,
sector_t length)
{
+ sector_t capacity = get_capacity(disk), end;
struct block_device *part;
int ret;

mutex_lock(&disk->open_mutex);
+ if (check_add_overflow(start, length, &end)) {
+ ret = -EINVAL;
+ goto out;
+ }
+
+ if (start >= capacity || end > capacity) {
+ ret = -EINVAL;
+ goto out;
+ }
+
if (!disk_live(disk)) {
ret = -ENXIO;
goto out;
--
2.34.1