[PATCH v2] nvme: fix memleak in nvme_ctrl_dhchap_secret_store()

Zhang Qilong zhangqilong3 at huawei.com
Mon Nov 21 20:49:29 PST 2022


If dhchap_secret is not consistent with options or
nvme_auth_generate_key() fails, we should free the
memory of dhchap_secret to avoid memleak.

We fix it by changing the check strcmp to strncmp
directly against buf and moving allocating inside
to the clause.

Fixes: f50fff73d620 ("nvme: implement In-Band authentication")
Signed-off-by: Zhang Qilong <zhangqilong3 at huawei.com>
---
v2:
- changing checking function and allocating location.
---
 drivers/nvme/host/core.c | 15 ++++++++-------
 1 file changed, 8 insertions(+), 7 deletions(-)

diff --git a/drivers/nvme/host/core.c b/drivers/nvme/host/core.c
index da55ce45ac70..bfec2a63d0d8 100644
--- a/drivers/nvme/host/core.c
+++ b/drivers/nvme/host/core.c
@@ -3730,7 +3730,6 @@ static ssize_t nvme_ctrl_dhchap_secret_store(struct device *dev,
 {
 	struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
 	struct nvmf_ctrl_options *opts = ctrl->opts;
-	char *dhchap_secret;
 
 	if (!ctrl->opts->dhchap_secret)
 		return -EINVAL;
@@ -3739,17 +3738,19 @@ static ssize_t nvme_ctrl_dhchap_secret_store(struct device *dev,
 	if (memcmp(buf, "DHHC-1:", 7))
 		return -EINVAL;
 
-	dhchap_secret = kzalloc(count + 1, GFP_KERNEL);
-	if (!dhchap_secret)
-		return -ENOMEM;
-	memcpy(dhchap_secret, buf, count);
 	nvme_auth_stop(ctrl);
-	if (strcmp(dhchap_secret, opts->dhchap_secret)) {
+	if (strncmp(buf, opts->dhchap_secret, count)) {
 		int ret;
+		char *dhchap_secret;
 
+		dhchap_secret = kmemdup(buf);
+		if (!dhchap_secret)
+			return -ENOMEM;
 		ret = nvme_auth_generate_key(dhchap_secret, &ctrl->host_key);
-		if (ret)
+		if (ret) {
+			kfree(dhchap_secret);
 			return ret;
+		}
 		kfree(opts->dhchap_secret);
 		opts->dhchap_secret = dhchap_secret;
 		/* Key has changed; re-authentication with new key */
-- 
2.25.1




More information about the Linux-nvme mailing list