[PATCH] posix-timers: Prevent overflow for clock_nanosleep

From: Yu Liao
Date: Sat Oct 29 2022 - 05:00:22 EST


UBSAN complains about signed-integer-overflow:
[ 127.044171] ================================================================================
[ 127.045183] UBSAN: signed-integer-overflow in ./include/linux/ktime.h:43:14
[ 127.046043] -9223372037 * 1000000000 cannot be represented in type 'long long int'
[ 127.046991] CPU: 5 PID: 218 Comm: a.out Not tainted 5.10.135 #20
[ 127.047443] Hardware name: linux,dummy-virt (DT)
[ 127.048290] Call trace:
[ 127.049600] dump_backtrace+0x0/0x258
[ 127.050183] show_stack+0x18/0x68
[ 127.050507] dump_stack+0xd8/0x134
[ 127.050765] ubsan_epilogue+0x10/0x58
[ 127.051038] handle_overflow+0xdc/0x108
[ 127.051315] __ubsan_handle_mul_overflow+0x14/0x20
[ 127.051660] posix_cpu_timer_set+0x2f8/0x370
[ 127.052295] do_cpu_nanosleep+0xc8/0x1e8
[ 127.052659] posix_cpu_nsleep_restart+0x48/0x70
[ 127.053025] __arm64_sys_restart_syscall+0x1c/0x28
[ 127.053353] el0_svc_common.constprop.4+0x68/0x188
[ 127.053684] do_el0_svc+0x24/0x90
[ 127.053926] el0_svc+0x20/0x30
[ 127.054163] el0_sync_handler+0x90/0xb8
[ 127.054424] el0_sync+0x160/0x180
[ 127.054914] ================================================================================

This can be reproduced by the following code with UBSAN enabled:

#include <unistd.h>
#include <syscall.h>
#include <sys/time.h>

int main(int argc, char* argv[]) {
struct timespec ts = {
.tv_sec = 9223372036854775807,
.tv_nsec = 0
};
syscall(__NR_clock_nanosleep, 2, 0, &ts, NULL);
}

Compile and execute the following sequence, it makes syscall
clock_nanosleep restart.

./a.out &
kill -STOP [pid]
kill -CONT [pid]

This happens because parameter 'exp' of cpu_timer_setexpires consists of
two parts: user input from clock_nanosleep() and cpu_clock_sample return
value, both of which are s64 types, so 'exp' may be greater than S64_MAX.
When cpu_timer_setexpires stores 'exp' in cpu_timer, it convert u64 to
ktime_t resulting in expires of cpu_timer may be negative.

Fix it by limiting the maximum value of 'exp'.

Cc: <stable@xxxxxxxxxxxxxxx>
Signed-off-by: Yu Liao <liaoyu15@xxxxxxxxxx>
---
include/linux/posix-timers.h | 3 +++
1 file changed, 3 insertions(+)

diff --git a/include/linux/posix-timers.h b/include/linux/posix-timers.h
index 2c6e99ca48af..54ef0aedea3e 100644
--- a/include/linux/posix-timers.h
+++ b/include/linux/posix-timers.h
@@ -103,6 +103,9 @@ static inline u64 cpu_timer_getexpires(struct cpu_timer *ctmr)

static inline void cpu_timer_setexpires(struct cpu_timer *ctmr, u64 exp)
{
+ if (unlikely(exp > KTIME_MAX))
+ exp = KTIME_MAX;
+
ctmr->node.expires = exp;
}

--
2.25.1