Re: [PATCH] profiling: fix shift-out-of-bounds in profile_setup

From: Tetsuo Handa
Date: Sun Aug 08 2021 - 07:22:04 EST


On 2021/07/17 4:04, Pavel Skripkin wrote:
> Syzbot reported shift-out-of-bounds bug in profile_init().
> The problem was in incorrect prof_shift. Since prof_shift value comes from
> userspace we need to check this value to avoid too big shift.
>
> Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2")
> Reported-and-tested-by: syzbot+e68c89a9510c159d9684@xxxxxxxxxxxxxxxxxxxxxxxxx
> Suggested-by: Tetsuo Handa <penguin-kernel@xxxxxxxxxxxxxxxxxxx>
> Signed-off-by: Pavel Skripkin <paskripkin@xxxxxxxxx>
> ---
> kernel/profile.c | 9 +++++----
> 1 file changed, 5 insertions(+), 4 deletions(-)
>
> diff --git a/kernel/profile.c b/kernel/profile.c
> index c2ebddb5e974..c905931e3c3b 100644
> --- a/kernel/profile.c
> +++ b/kernel/profile.c
> @@ -42,6 +42,7 @@ struct profile_hit {
>
> static atomic_t *prof_buffer;
> static unsigned long prof_len, prof_shift;
> +#define MAX_PROF_SHIFT (sizeof(prof_shift) * 8)

I came to think that we should directly use BITS_PER_LONG, for
the integer value which is subjected to shift operation is e.g.

(_etext - _stext)

part of

prof_len = (_etext - _stext) >> prof_shift;

in profile_init().

Since "unsigned char" will be sufficient for holding BITS_PER_LONG - 1,
defining MAX_PROF_SHIFT based on size of prof_shift is incorrect.

Also, there is

unsigned int sample_step = 1 << prof_shift;

in read_profile(). This may result in shift-out-of-bounds on BITS_PER_LONG == 64
architecture. Shouldn't this variable changed from "unsigned int" to "unsigned long"
and use 1UL instead of 1 ?