Re: [PATCH] ntp: safeguard against time_constant overflow case

From: John Stultz
Date: Tue May 07 2024 - 02:02:37 EST


On Mon, May 6, 2024 at 3:01 PM Justin Stitt <justinstitt@xxxxxxxxxx> wrote:
>
> Nonetheless, let's slightly rework the logic surrounding time_constant
> and how it is incremented such that we avoid unintentional wrap-around
> (even though it is extremely unlikely to be hit in non-fuzzing scenarios).
>
> [1]: https://github.com/llvm/llvm-project/pull/82432
>
> Signed-off-by: Justin Stitt <justinstitt@xxxxxxxxxx>
> ---
> kernel/time/ntp.c | 11 +++++++----
> 1 file changed, 7 insertions(+), 4 deletions(-)
>
> diff --git a/kernel/time/ntp.c b/kernel/time/ntp.c
> index 406dccb79c2b..a9f039601968 100644
> --- a/kernel/time/ntp.c
> +++ b/kernel/time/ntp.c
> @@ -65,6 +65,9 @@ static s64 time_offset;
> /* pll time constant: */
> static long time_constant = 2;
>
> +/* pll time constant increment: */
> +static long time_constant_inc = 4;
> +

I'd probably use a `#define TIME_CONSTANT_INC 4` for this.

> /* maximum error (usecs): */
> static long time_maxerror = NTP_PHASE_LIMIT;
>
> @@ -734,10 +737,10 @@ static inline void process_adjtimex_modes(const struct __kernel_timex *txc,
>
> if (txc->modes & ADJ_TIMECONST) {
> time_constant = txc->constant;
> - if (!(time_status & STA_NANO))
> - time_constant += 4;
> - time_constant = min(time_constant, (long)MAXTC);
> - time_constant = max(time_constant, 0l);
> + if (!(time_status & STA_NANO) &&
> + unlikely(LONG_MAX - time_constant_inc >= time_constant))
> + time_constant += time_constant_inc;
> + time_constant = clamp_t(long, time_constant, 0, MAXTC);
> }

Overall, this looks fine. Though the time_status conditional is now a
little unwieldy.

I wonder if some sort of a helper like:
time_constant = safe_add(time_constant, TIME_CONSTANT_INC, LONG_MAX);

Might make this a little easier to read?

thanks
-john