From e01e180f6248590348bad5c354c6b4e0cf1a956a Mon Sep 17 00:00:00 2001 From: Marcus Nilsson Date: Mon, 6 May 2024 11:40:00 +0200 Subject: [PATCH] drivers/cmsis_dap: Fix buffer overflow in cmsis_dap_hid_open() Use mbstowcs() to get required length of wide character string and include space for terminating null wide character. Change-Id: I668de6f0acc9b3ec5aca033d870dd9ef354f9077 Signed-off-by: Marcus Nilsson Reviewed-on: https://review.openocd.org/c/openocd/+/8232 Tested-by: jenkins Reviewed-by: Antonio Borneo Reviewed-by: Tomas Vanek --- src/jtag/drivers/cmsis_dap_usb_hid.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/jtag/drivers/cmsis_dap_usb_hid.c b/src/jtag/drivers/cmsis_dap_usb_hid.c index 98ccc3e381..aeec685b9d 100644 --- a/src/jtag/drivers/cmsis_dap_usb_hid.c +++ b/src/jtag/drivers/cmsis_dap_usb_hid.c @@ -121,8 +121,12 @@ static int cmsis_dap_hid_open(struct cmsis_dap *dap, uint16_t vids[], uint16_t p break; if (cur_dev->serial_number) { - size_t len = (strlen(serial) + 1) * sizeof(wchar_t); - wchar_t *wserial = malloc(len); + size_t len = mbstowcs(NULL, serial, 0) + 1; + wchar_t *wserial = malloc(len * sizeof(wchar_t)); + if (!wserial) { + LOG_ERROR("unable to allocate serial number buffer"); + return ERROR_FAIL; + } mbstowcs(wserial, serial, len); if (wcscmp(wserial, cur_dev->serial_number) == 0) {