[PATCH v2] i2c: i801: Fix kernel stack buffer overflow in i801_block_transaction_byte_by_byte

w15303746062@163.com posted 1 patch 1 week, 6 days ago
drivers/i2c/busses/i2c-i801.c | 9 +++++++++
1 file changed, 9 insertions(+)
[PATCH v2] i2c: i801: Fix kernel stack buffer overflow in i801_block_transaction_byte_by_byte
Posted by w15303746062@163.com 1 week, 6 days ago
From: Mingyu Wang <25181214217@stu.xidian.edu.cn>

A kernel stack buffer overflow exists in the
i801_block_transaction_byte_by_byte() function due to a missing bounds
check on the user-provided block length.

When userspace executes an ioctl(I2C_SMBUS) with the
I2C_SMBUS_I2C_BLOCK_DATA command, the user data is copied into a local
stack variable `union i2c_smbus_data temp` (which is approximately 34
bytes) in i2cdev_ioctl_smbus(). This data is then passed unmodified
through i2c_smbus_xfer() and i801_access() directly into
i801_block_transaction_byte_by_byte().

The length of the transaction is blindly extracted from
`data->block[0]`. If a malicious user provides a maliciously large
length (e.g., 255), the subsequent `for (i = 1; i <= len; i++)` loop
will drive `ioread8()` to continuously read from the hardware and
write out-of-bounds into the `data->block` array. This completely
overwrites the 34-byte `temp` stack variable in i2cdev_ioctl_smbus(),
clobbering the kernel stack's return address and leading to control
flow hijacking (e.g., jumping to NX-protected pages).

Fix this by strictly validating that the length does not exceed
I2C_SMBUS_BLOCK_MAX before entering the read/write loop, while
exempting the special SMBUS_LEN_SENTINEL value used by the driver.

Signed-off-by: Mingyu Wang <25181214217@stu.xidian.edu.cn>
---
Changes in v2:
 - Added an exemption for SMBUS_LEN_SENTINEL to prevent breaking
   legitimate SMBus Block Read transactions where the length is
   initially unknown.
 - Removed duplicated paragraph in the commit message.

 drivers/i2c/busses/i2c-i801.c | 9 +++++++++
 1 file changed, 9 insertions(+)

diff --git a/drivers/i2c/busses/i2c-i801.c b/drivers/i2c/busses/i2c-i801.c
index 32a3cef02c7b..4dd3ae5f49af 100644
--- a/drivers/i2c/busses/i2c-i801.c
+++ b/drivers/i2c/busses/i2c-i801.c
@@ -684,6 +684,15 @@ static int i801_block_transaction_byte_by_byte(struct i801_priv *priv,
 
 	len = data->block[0];
 
+	/*
+	 * Prevent kernel stack buffer overflow.
+	 * The user-provided length must not exceed the maximum SMBus block size.
+	 * We must allow SMBUS_LEN_SENTINEL, which is used by the driver to
+	 * indicate an unknown length for SMBus Block Read.
+	 */
+	if (len < 1 || (len > I2C_SMBUS_BLOCK_MAX && len != SMBUS_LEN_SENTINEL))
+		return -EINVAL;
+
 	if (read_write == I2C_SMBUS_WRITE) {
 		iowrite8(len, SMBHSTDAT0(priv));
 		iowrite8(data->block[1], SMBBLKDAT(priv));
-- 
2.34.1