Re: [PATCH 3/5] exec: Remove recursion from search_binary_handler

From: Linus Torvalds
Date: Sat May 09 2020 - 16:25:02 EST


On Sat, May 9, 2020 at 12:45 PM Eric W. Biederman <ebiederm@xxxxxxxxxxxx> wrote:
>
> Instead of recursing in search_binary_handler have the methods that
> would recurse return a positive value, and simply loop in exec_binprm.
>
> This is a trivial change as all of the methods that would recurse do
> so as effectively the last thing they do. Making this a trivial code
> change.

Looks good.

I'd suggest doing that loop slightly differently:

> - ret = search_binary_handler(bprm);
> + do {
> + depth++;
> + ret = search_binary_handler(bprm);
> + /* This allows 4 levels of binfmt rewrites before failing hard. */
> + if ((ret > 0) && (depth > 5))
> + ret = -ELOOP;
> + } while (ret > 0);
> if (ret >= 0) {

That's really an odd way to write this.

So honestly, if "ret < 0", then we can just return directly.

So I think would make much more sense to do this loop something like

for (depth = 0; depth < 5; depth++) {
int ret;

ret = search_binary_handler(bprm);
if (ret < 0)
return ret;

/* Continue searching for the next binary handler? */
if (ret > 0)
continue;

/* Success! */
audit_bprm(bprm);
trace_sched_process_exec(current, old_pid, bprm);
ptrace_event(PTRACE_EVENT_EXEC, old_vpid);
proc_exec_connector(current);
return 0;
}
return -ELOOP;

(if I read the logic of exec_binprm() right - I might have missed something).

Linus