Q: check_unsafe_exec() races (Was: [PATCH 2/4] fix setuid sometimes doesn't)

Oleg Nesterov
2009-03-29T00:59:40Z

> -void check_unsafe_exec(struct linux_binprm *bprm, struct files_struct *files)
> +void check_unsafe_exec(struct linux_binprm *bprm)
> {
> struct task_struct *p = current, *t;
> unsigned long flags;
> - unsigned n_fs, n_files, n_sighand;
> + unsigned n_fs, n_sighand;
>
> bprm->unsafe = tracehook_unsafe_exec(p);
>
> n_fs = 1;
> - n_files = 1;
> n_sighand = 1;
> lock_task_sighand(p, &flags);
> for (t = next_thread(p); t != p; t = next_thread(t)) {
> if (t->fs == p->fs)
> n_fs++;
> - if (t->files == files)
> - n_files++;
> n_sighand++;
> }
>
> if (atomic_read(&p->fs->count) > n_fs ||
> - atomic_read(&p->files->count) > n_files ||
> atomic_read(&p->sighand->count) > n_sighand)
> bprm->unsafe |= LSM_UNSAFE_SHARE;

Can't find the patch which introduced check_unsafe_exec(), so
I am asking here.

How it is supposed to work?

Let's suppose we have two threads T1 and T2. T1 exits, and calls
exit_fs().

exit_fs:

tsk->fs = NULL;
// WINDOW
put_fs_struct(fs);

Now, if T2 does exec() and check_unsafe_exec() happens in the WINDOW
above, we set LSM_UNSAFE_SHARE.

Or we can race with sub-thread doing clone(CLONE_FS|CLONE_THREAD),
the new thread is not visible in ->thread_group, buy copy_fs()
can already increment fs->count.

Another question. Why do we check sighand->count? We always unshare
->sighand on exec, see de_thread().

Minor, but why lock_task_sighand() ? This helper is "__must_check".
If it can't fail (yes, it can't fail here), spin_lock_irq(siglock)
is enough. (and given that ->siglock can't help anyway to calculate
n_fs, we could use rcu_read_lock() instead).

(as for these patches, I think they are correct).

Oleg.