Re: [PATCH mm] maccess: fix strncpy_from_user_nofault empty string handling
From: Andrii Nakryiko
Date: Thu Apr 17 2025 - 17:07:29 EST
On Thu, Apr 17, 2025 at 1:40 PM Andrew Morton <akpm@xxxxxxxxxxxxxxxxxxxx> wrote:
>
> On Thu, 17 Apr 2025 16:28:08 +0100 Mykyta Yatsenko <mykyta.yatsenko5@xxxxxxxxx> wrote:
>
> > strncpy_from_user_nofault should return the length of the copied string
> > including the trailing NUL, but if the argument unsafe_addr points to
> > an empty string ({'\0'}), the return value is 0.
> >
> > This happens as strncpy_from_user copies terminal symbol into dst
> > and returns 0 (as expected), but strncpy_from_user_nofault does not
> > modify ret as it is not equal to count and not greater than 0, so 0 is
> > returned, which contradicts the contract.
>
> Looks right, I think.
>
> But why do strncpy_from_user() and strncpy_from_user_nofault() have
> different interfaces?
>
> /**
> * strncpy_from_user: - Copy a NUL terminated string from userspace.
> * ...
> * On success, returns the length of the string (not including the trailing
> * NUL).
>
> /**
> * strncpy_from_user_nofault: - Copy a NUL terminated string from unsafe user
> * address.
> * ...
> * On success, returns the length of the string INCLUDING the trailing NUL.
>
> This is surprising and I'm wondering what led us to do this?
Agreed, this is very surprising and error-prone. strncpy_from_user()
semantics is a bit better, IMO, in that it allows to "detect" empty
string even if buffer size is 1 byte. And there isn't a lot of places
where we use strncpy_from_user_nofault (only 6, it seems). Maybe we
should just change the semantics of strncpy_from_user_nofault?