Re: [PATCH 2/2] random: spread out jitter callback to different CPUs
From: Sultan Alsawaf
Date: Thu Oct 06 2022 - 12:39:59 EST
On Thu, Oct 06, 2022 at 02:41:11PM +0200, Sebastian Andrzej Siewior wrote:
> On 2022-10-06 06:26:04 [-0600], Jason A. Donenfeld wrote:
> > e) del_timer_sync() on line 5 is called, and its `base->running_timer !=
> > timer` check is false, because of step (c).
> If `base->running_timer != timer` then the timer ('s callback) is not
> currently active/ running. Therefore it can be removed from the timer
> bucket (in case it is pending in the future).
> If `base->running_timer == timer` then the timer ('s callback) is
> currently active. del_timer_sync() will loop in cpu_relax() until the
> callback finished. And then try again.
> > f) `stack.timer` gets freed / goes out of scope.
> > g) The callback scheduled from step (b) runs, and we have a UaF.
> > That's, anyway, what I understand Sultan to have pointed out to me. In
> > looking at this closely, though, to write this email, I noticed that
> > add_timer_on() does set TIMER_MIGRATING, which lock_timer_base() spins
> > on. So actually, maybe this scenario should be accounted for? Sultan, do
> > you care to comment here?
> During TIMER_MIGRATING the del_timer_sync() caller will spin until the
> condition is over. So it can remove the timer from the right bucket and
> check if it is active vs the right bucket.
My concern stems from the design of add_timer_on(). Specifically, add_timer_on()
expects the timer to not already be pending or running.
Because of this, add_timer_on() doesn't check `base->running_timer` and doesn't
wait for the timer to finish running, because it expects the timer to be
completely idle. Giving add_timer_on() a timer which is already running is a
bug, as made clear by the `BUG_ON(timer_pending(timer) || !timer->function);`.
But since a timer is marked as not-pending prior to when it runs, add_timer_on()
can't detect if the timer is actively running; the above BUG_ON() won't be
tripped. So the UaF scenario I forsee is that doing this:
// timer is actively running on CPU0, timer is no longer pending
add_timer_on(timer, 1); // changes timer base, won't wait for timer to stop
del_timer_sync(timer); // only checks CPU1 timer base for the running timer
may result in the del_timer_sync() not waiting for the timer function to finish
running on CPU0 from the `add_timer_on(timer, 0);`, since add_timer_on() won't
wait for the timer function to finish running before changing the timer base.
And since Jason's timer is declared on the stack, his timer callback function
would dereference `stack.timer` after it's been freed.