Re: [PATCH v6 02/12] fs/exec: make __get_task_comm always get a nul terminated string

From: Kees Cook
Date: Mon Oct 25 2021 - 17:09:03 EST


On Mon, Oct 25, 2021 at 08:33:05AM +0000, Yafang Shao wrote:
> If the dest buffer size is smaller than sizeof(tsk->comm), the buffer
> will be without null ternimator, that may cause problem. We can make sure
> the buffer size not smaller than comm at the callsite to avoid that
> problem, but there may be callsite that we can't easily change.
>
> Using strscpy_pad() instead of strncpy() in __get_task_comm() can make
> the string always nul ternimated.
>
> Suggested-by: Kees Cook <keescook@xxxxxxxxxxxx>
> Suggested-by: Steven Rostedt <rostedt@xxxxxxxxxxx>
> Signed-off-by: Yafang Shao <laoar.shao@xxxxxxxxx>
> Cc: Mathieu Desnoyers <mathieu.desnoyers@xxxxxxxxxxxx>
> Cc: Arnaldo Carvalho de Melo <arnaldo.melo@xxxxxxxxx>
> Cc: Andrii Nakryiko <andrii.nakryiko@xxxxxxxxx>
> Cc: Peter Zijlstra <peterz@xxxxxxxxxxxxx>
> Cc: Steven Rostedt <rostedt@xxxxxxxxxxx>
> Cc: Al Viro <viro@xxxxxxxxxxxxxxxxxx>
> Cc: Kees Cook <keescook@xxxxxxxxxxxx>
> Cc: Petr Mladek <pmladek@xxxxxxxx>
> ---
> fs/exec.c | 3 ++-
> 1 file changed, 2 insertions(+), 1 deletion(-)
>
> diff --git a/fs/exec.c b/fs/exec.c
> index 404156b5b314..bf2a7a91eeea 100644
> --- a/fs/exec.c
> +++ b/fs/exec.c
> @@ -1209,7 +1209,8 @@ static int unshare_sighand(struct task_struct *me)
> char *__get_task_comm(char *buf, size_t buf_size, struct task_struct *tsk)
> {
> task_lock(tsk);
> - strncpy(buf, tsk->comm, buf_size);
> + /* The copied value is always null terminated */

This may could say "always NUL terminated and zero-padded"

> + strscpy_pad(buf, tsk->comm, buf_size);
> task_unlock(tsk);
> return buf;
> }
> --
> 2.17.1
>

But for the replacement with strscpy_pad(), yes please:

Reviewed-by: Kees Cook <keescook@xxxxxxxxxxxx>


--
Kees Cook