[PATCH] HID: core: avoid signed overflow in multiplier calculation
DORMANTno replies
From: Aldo Ariel Panzardo <hidden>
Date: 2026-09-15 04:12:36
Also in:
lkml, stable
Subsystem:
hid core layer, the rest · Maintainers:
Jiri Kosina, Benjamin Tissoires, Linus Torvalds
A HID descriptor can make both logical range subtractions overflow
signed 32-bit arithmetic. On x86, the resulting INT_MIN / -1
operation can raise a divide exception and crash the kernel.
Promote the operands before subtraction, use the signed 64-bit
division helper, and check the remaining multiply and add operations
for overflow. Fall back to the default multiplier when the descriptor
cannot be represented safely.
Fixes: 5a4abb36f312 ("HID: core: process the Resolution Multiplier")
Cc: stable@vger.kernel.org
Signed-off-by: Aldo Ariel Panzardo <redacted>
---
drivers/hid/hid-core.c | 24 +++++++++++++++++++-----
1 file changed, 19 insertions(+), 5 deletions(-)
diff --git a/drivers/hid/hid-core.c b/drivers/hid/hid-core.c
index cf123347a..92d76b789 100644
--- a/drivers/hid/hid-core.c
+++ b/drivers/hid/hid-core.c@@ -18,6 +18,7 @@ #include <linux/init.h> #include <linux/kernel.h> #include <linux/list.h> +#include <linux/math64.h> #include <linux/mm.h> #include <linux/spinlock.h> #include <linux/unaligned.h>
@@ -1083,7 +1084,11 @@ EXPORT_SYMBOL_GPL(hid_validate_values); static int hid_calculate_multiplier(struct hid_device *hid, struct hid_field *multiplier) { - int m; + s64 logical_range; + s64 physical_range; + s64 quotient; + s64 scaled; + s64 m; __s32 v = *multiplier->value; __s32 lmin = multiplier->logical_minimum; __s32 lmax = multiplier->logical_maximum;
@@ -1097,13 +1102,21 @@ static int hid_calculate_multiplier(struct hid_device *hid, * Resolution Multiplier of zero." * HID Usage Table, v1.12, Section 4.3.1, p31 */ - if (lmax - lmin == 0) + logical_range = (s64)lmax - lmin; + if (!logical_range) return 1; + + physical_range = (s64)pmax - pmin; + quotient = div64_s64((s64)v - lmin, logical_range); /* * Handling the unit exponent is left as an exercise to whoever * finds a device where that exponent is not 0. */ - m = ((v - lmin)/(lmax - lmin) * (pmax - pmin) + pmin); + if (check_mul_overflow(quotient, physical_range, &scaled) || + check_add_overflow(scaled, (s64)pmin, &m)) { + hid_warn(hid, "Resolution Multiplier calculation overflow\n"); + return 1; + } if (unlikely(multiplier->unit_exponent != 0)) { hid_warn(hid, "unsupported Resolution Multiplier unit exponent %d\n",
@@ -1112,11 +1125,12 @@ static int hid_calculate_multiplier(struct hid_device *hid, /* There are no devices with an effective multiplier > 255 */ if (unlikely(m == 0 || m > 255 || m < -255)) { - hid_warn(hid, "unsupported Resolution Multiplier %d\n", m); + hid_warn(hid, "unsupported Resolution Multiplier %lld\n", + (long long)m); m = 1; } - return m; + return (int)m; } static void hid_apply_multiplier_to_field(struct hid_device *hid,
--
2.43.0