From 919db65a6a8c326ab35cd5f9d20d0349d049f7d6 Mon Sep 17 00:00:00 2001 From: Hao Zhang Date: Wed, 15 Jun 2022 14:16:36 +0800 Subject: [PATCH] coresight: core: Fix a possible array overflow in sink_name_store() When there is a "\0" character in the middle of input buffer, the kstrdup would copy a incomplete string to sink_name buffer, so the buffer length would less than the input size, then if we add a null-terminal string to the end(worry index) of sink_name buffer, it could result in the buffer overflow. Because of this, replace the kstrdup with kstrndup. Change-Id: Ieb5a4685f61dedeb16f90e03821b68d610fba4d5 Signed-off-by: Hao Zhang --- drivers/hwtracing/coresight/coresight-core.c | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/drivers/hwtracing/coresight/coresight-core.c b/drivers/hwtracing/coresight/coresight-core.c index 53cd1f5deec7..ca2288e5f730 100644 --- a/drivers/hwtracing/coresight/coresight-core.c +++ b/drivers/hwtracing/coresight/coresight-core.c @@ -1485,7 +1485,8 @@ static ssize_t sink_name_store(struct device *dev, const char *buf, size_t size) { u32 hash; - char *sink_name; + + char sink_name[MAX_SINK_NAME] = ""; struct coresight_device *new_sink, *current_sink; struct coresight_device *csdev = to_coresight_device(dev); @@ -1497,10 +1498,8 @@ static ssize_t sink_name_store(struct device *dev, return size; } - sink_name = kstrdup(buf, GFP_KERNEL); - if (!sink_name) - return -ENOMEM; - sink_name[size-1] = 0; + if (sscanf(buf, "%s", sink_name) != 1) + return -EINVAL; hash = hashlen_hash(hashlen_string(NULL, sink_name)); new_sink = coresight_get_sink_by_id(hash); @@ -1510,13 +1509,11 @@ static ssize_t sink_name_store(struct device *dev, new_sink && current_sink->type != new_sink->type)) { dev_err(&csdev->dev, - "Sink name is invalid or another type sink is enabled.\n"); - kfree(sink_name); + "Sink name [%s] is invalid or another type sink is enabled.\n", sink_name); return -EINVAL; } csdev->def_sink = new_sink; - kfree(sink_name); return size; }