lkml.org 
[lkml]   [2023]   [Oct]   [18]   [last100]   RSS Feed
Views: [wrap][no wrap]   [headers]  [forward] 
 
Messages in this thread
/
Date
From
SubjectRe: Is strncpy really less secure than strscpy ?
[Disclaimer: I have little to no knowledge of C, so things may be wrong.
Please correct me if it is the case. Also Cc: recent people who work on
strscpy() conversion.]

On Thu, Oct 19, 2023 at 12:22:33AM +0100, James Dutton wrote:
> Is strncpy really less secure than strscpy ?
>
> If one uses strncpy and thus put a limit on the buffer size during the
> copy, it is safe. There are no writes outside of the buffer.
> If one uses strscpy and thus put a limit on the buffer size during the
> copy, it is safe. There are no writes outside of the buffer.

Well, assuming that the string is NUL-terminated, the end result should
be the same.

> But, one can fit more characters in strncpy than strscpy because
> strscpy enforces the final \0 on the end.
> One could argue that strncpy is better because it might save the space
> of one char at the end of a string array.
> There are cases where strncpy might be unsafe. For example copying
> between arrays of different sizes, and that is a case where strscpy
> might be safer, but strncpy can be made safe if one ensures that the
> size used in strncpy is the smallest of the two different array sizes.

Code example on both cases?

>
> If one blindly replaces strncpy with strscpy across all uses, one
> could unintentionally be truncating the results and introduce new
> bugs.
>
> The real insecurity surely comes when one tries to use the string.
> For example:
>
> #include <stdio.h>
> #include <string.h>
>
> int main() {
> char a[10] = "HelloThere";
> char b[10];
> char c[10] = "Overflow";
> strncpy(b, a, 10);
> /* This overflows and so in unsafe */
> printf("a is %s\n", a);
> /* This overflows and so in unsafe */
> printf("b is %s\n", b);
> /* This is safe */
> printf("b is %.*s\n", 10, a);
> /* This is safe */
> printf("b is %.*s\n", 4, a);
> return 0;
> }

What if printf("a is %.*s\n", a);?

>
>
> So, why isn't the printk format specifier "%.*s" used more instead of
> "%s" in the kernel?

Since basically strings are pointers.

Thanks.

--
An old man doll... just what I always wanted! - Clara
[unhandled content-type:application/pgp-signature]
\
 
 \ /
  Last update: 2023-10-19 03:50    [W:0.055 / U:1.424 seconds]
©2003-2020 Jasper Spaans|hosted at Digital Ocean and TransIP|Read the blog|Advertise on this site