[PATCH AUTOSEL 6.8 2/6] cdrom: rearrange last_media_change check to avoid unintentional overflow

From: Sasha Levin
Date: Wed Jun 05 2024 - 08:21:37 EST


From: Justin Stitt <justinstitt@xxxxxxxxxx>

[ Upstream commit efb905aeb44b0e99c0e6b07865b1885ae0471ebf ]

When running syzkaller with the newly reintroduced signed integer wrap
sanitizer we encounter this splat:

[ 366.015950] UBSAN: signed-integer-overflow in ../drivers/cdrom/cdrom.c:2361:33
[ 366.021089] -9223372036854775808 - 346321 cannot be represented in type '__s64' (aka 'long long')
[ 366.025894] program syz-executor.4 is using a deprecated SCSI ioctl, please convert it to SG_IO
[ 366.027502] CPU: 5 PID: 28472 Comm: syz-executor.7 Not tainted 6.8.0-rc2-00035-gb3ef86b5a957 #1
[ 366.027512] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.16.3-debian-1.16.3-2 04/01/2014
[ 366.027518] Call Trace:
[ 366.027523] <TASK>
[ 366.027533] dump_stack_lvl+0x93/0xd0
[ 366.027899] handle_overflow+0x171/0x1b0
[ 366.038787] ata1.00: invalid multi_count 32 ignored
[ 366.043924] cdrom_ioctl+0x2c3f/0x2d10
[ 366.063932] ? __pm_runtime_resume+0xe6/0x130
[ 366.071923] sr_block_ioctl+0x15d/0x1d0
[ 366.074624] ? __pfx_sr_block_ioctl+0x10/0x10
[ 366.077642] blkdev_ioctl+0x419/0x500
[ 366.080231] ? __pfx_blkdev_ioctl+0x10/0x10
...

Historically, the signed integer overflow sanitizer did not work in the
kernel due to its interaction with `-fwrapv` but this has since been
changed [1] in the newest version of Clang. It was re-enabled in the
kernel with Commit 557f8c582a9ba8ab ("ubsan: Reintroduce signed overflow
sanitizer").

Let's rearrange the check to not perform any arithmetic, thus not
tripping the sanitizer.

Link: https://github.com/llvm/llvm-project/pull/82432 [1]
Closes: https://github.com/KSPP/linux/issues/354
Cc: linux-hardening@xxxxxxxxxxxxxxx
Signed-off-by: Justin Stitt <justinstitt@xxxxxxxxxx>
Link: https://lore.kernel.org/lkml/20240507-b4-sio-ata1-v1-1-810ffac6080a@xxxxxxxxxx
Reviewed-by: Phillip Potter <phil@xxxxxxxxxxxxxxxx>
Link: https://lore.kernel.org/lkml/ZjqU0fbzHrlnad8D@equinox
Signed-off-by: Phillip Potter <phil@xxxxxxxxxxxxxxxx>
Link: https://lore.kernel.org/r/20240507222520.1445-2-phil@xxxxxxxxxxxxxxxx
Signed-off-by: Jens Axboe <axboe@xxxxxxxxx>
Signed-off-by: Sasha Levin <sashal@xxxxxxxxxx>
---
drivers/cdrom/cdrom.c | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/drivers/cdrom/cdrom.c b/drivers/cdrom/cdrom.c
index a5e07270e0d41..20c90ebb3a3f6 100644
--- a/drivers/cdrom/cdrom.c
+++ b/drivers/cdrom/cdrom.c
@@ -2358,7 +2358,7 @@ static int cdrom_ioctl_timed_media_change(struct cdrom_device_info *cdi,
return -EFAULT;

tmp_info.media_flags = 0;
- if (tmp_info.last_media_change - cdi->last_media_change_ms < 0)
+ if (cdi->last_media_change_ms > tmp_info.last_media_change)
tmp_info.media_flags |= MEDIA_CHANGED_FLAG;

tmp_info.last_media_change = cdi->last_media_change_ms;
--
2.43.0