From d138b1072c07c9c7e800eab0ce9cbe8481c455a3 Mon Sep 17 00:00:00 2001
From: Zhang Wensheng <zhangwensheng5@huawei.com>
Date: Sat, 16 Apr 2022 07:27:58 +0000
Subject: [PATCH] nbd: fix possible overflow on 'first_minor' in nbd_dev_add()

hulk inclusion
category: bugfix, https://gitee.com/openeuler/kernel/issues/I51ABL
bugzilla: 186386
CVE: NA

--------------------------------

When 'index' is a big numbers, it may become negative which forced
to 'int'. then 'index << part_shift' might overflow to a positive
value that is not greater than '0xfffff', then sysfs might complains
about duplicate creation. Because of this, move the 'index' judgment
to the front will fix it and be better.

Fixes: b0d9111a2d53 ("nbd: use an idr to keep track of nbd devices")
Fixes: 940c264984fd ("nbd: fix possible overflow for 'first_minor' in nbd_dev_add()")
Signed-off-by: Zhang Wensheng <zhangwensheng5@huawei.com>
Reviewed-by: Jason Yan <yanaijie@huawei.com>
Signed-off-by: Yongqiang Liu <liuyongqiang13@huawei.com>
---
 drivers/block/nbd.c | 22 +++++++++++++---------
 1 file changed, 13 insertions(+), 9 deletions(-)

diff --git a/drivers/block/nbd.c b/drivers/block/nbd.c
index a35189098581..c2e5ba599418 100644
--- a/drivers/block/nbd.c
+++ b/drivers/block/nbd.c
@@ -1704,14 +1704,6 @@ static int nbd_dev_add(int index)
 	int err = -ENOMEM;
 	int first_minor = index << part_shift;
 
-	/*
-	 * Too big index can cause duplicate creation of sysfs files/links,
-	 * because MKDEV() expect that the max first minor is MINORMASK, or
-	 * index << part_shift can overflow.
-	 */
-	if (first_minor < index || first_minor > MINORMASK)
-		return -EINVAL;
-
 	nbd = kzalloc(sizeof(struct nbd_device), GFP_KERNEL);
 	if (!nbd)
 		goto out;
@@ -1844,8 +1836,20 @@ static int nbd_genl_connect(struct sk_buff *skb, struct genl_info *info)
 	if (!netlink_capable(skb, CAP_SYS_ADMIN))
 		return -EPERM;
 
-	if (info->attrs[NBD_ATTR_INDEX])
+	if (info->attrs[NBD_ATTR_INDEX]) {
 		index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
+
+		/*
+		 * Too big first_minor can cause duplicate creation of
+		 * sysfs files/links, since index << part_shift might
+		 * overflow, or MKDEV() expect that the max bits of
+		 * first_minor is 20.
+		 */
+		if (index < 0 || index > MINORMASK >> part_shift) {
+			printk(KERN_ERR "nbd: illegal input index %d\n", index);
+			return -EINVAL;
+		}
+	}
 	if (!info->attrs[NBD_ATTR_SOCKETS]) {
 		printk(KERN_ERR "nbd: must specify at least one socket\n");
 		return -EINVAL;
-- 
GitLab