1 From 1576034634512ab27c2c2fefccd454a66ef4b9c1 Mon Sep 17 00:00:00 2001
2 From: Sasha Levin <sashal@kernel.org>
3 Date: Tue, 1 Sep 2020 17:30:13 +0800
4 Subject: time: Prevent undefined behaviour in timespec64_to_ns()
6 From: Zeng Tao <prime.zeng@hisilicon.com>
8 [ Upstream commit cb47755725da7b90fecbb2aa82ac3b24a7adb89b ]
12 Undefined behaviour in ./include/linux/time64.h:127:27
13 signed integer overflow:
14 17179869187 * 1000000000 cannot be represented in type 'long long int'
16 timespec64_to_ns include/linux/time64.h:127 [inline]
17 set_cpu_itimer+0x65c/0x880 kernel/time/itimer.c:180
18 do_setitimer+0x8e/0x740 kernel/time/itimer.c:245
19 __x64_sys_setitimer+0x14c/0x2c0 kernel/time/itimer.c:336
20 do_syscall_64+0xa1/0x540 arch/x86/entry/common.c:295
22 Commit bd40a175769d ("y2038: itimer: change implementation to timespec64")
23 replaced the original conversion which handled time clamping correctly with
24 timespec64_to_ns() which has no overflow protection.
26 Fix it in timespec64_to_ns() as this is not necessarily limited to the
29 [ tglx: Added comment and adjusted the fixes tag ]
31 Fixes: 361a3bf00582 ("time64: Add time64.h header and define struct timespec64")
32 Signed-off-by: Zeng Tao <prime.zeng@hisilicon.com>
33 Signed-off-by: Thomas Gleixner <tglx@linutronix.de>
34 Reviewed-by: Arnd Bergmann <arnd@arndb.de>
35 Cc: stable@vger.kernel.org
36 Link: https://lore.kernel.org/r/1598952616-6416-1-git-send-email-prime.zeng@hisilicon.com
37 Signed-off-by: Sasha Levin <sashal@kernel.org>
39 include/linux/time64.h | 4 ++++
40 kernel/time/itimer.c | 4 ----
41 2 files changed, 4 insertions(+), 4 deletions(-)
43 diff --git a/include/linux/time64.h b/include/linux/time64.h
44 index 19125489ae948..5eab3f2635186 100644
45 --- a/include/linux/time64.h
46 +++ b/include/linux/time64.h
47 @@ -132,6 +132,10 @@ static inline bool timespec64_valid_settod(const struct timespec64 *ts)
49 static inline s64 timespec64_to_ns(const struct timespec64 *ts)
51 + /* Prevent multiplication overflow */
52 + if ((unsigned long long)ts->tv_sec >= KTIME_SEC_MAX)
55 return ((s64) ts->tv_sec * NSEC_PER_SEC) + ts->tv_nsec;
58 diff --git a/kernel/time/itimer.c b/kernel/time/itimer.c
59 index 77f1e5635cc18..62dc9757118c6 100644
60 --- a/kernel/time/itimer.c
61 +++ b/kernel/time/itimer.c
62 @@ -147,10 +147,6 @@ static void set_cpu_itimer(struct task_struct *tsk, unsigned int clock_id,
63 u64 oval, nval, ointerval, ninterval;
64 struct cpu_itimer *it = &tsk->signal->it[clock_id];
67 - * Use the to_ktime conversion because that clamps the maximum
68 - * value to KTIME_MAX and avoid multiplication overflows.
70 nval = ktime_to_ns(timeval_to_ktime(value->it_value));
71 ninterval = ktime_to_ns(timeval_to_ktime(value->it_interval));