public inbox for linux-kernel@vger.kernel.org
 help / color / mirror / Atom feed
* Is strncpy really less secure than strscpy ?
@ 2023-10-18 23:22 James Dutton
  2023-10-19  1:49 ` Bagas Sanjaya
  0 siblings, 1 reply; 7+ messages in thread
From: James Dutton @ 2023-10-18 23:22 UTC (permalink / raw)
  To: LKML Mailing List

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.
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.

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;
}


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

Kind Regards

James

^ permalink raw reply	[flat|nested] 7+ messages in thread

end of thread, other threads:[~2023-10-19 17:57 UTC | newest]

Thread overview: 7+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2023-10-18 23:22 Is strncpy really less secure than strscpy ? James Dutton
2023-10-19  1:49 ` Bagas Sanjaya
2023-10-19  2:27   ` Randy Dunlap
2023-10-19  2:56     ` Kees Cook
2023-10-19  3:40       ` Bagas Sanjaya
2023-10-19 17:09       ` Justin Stitt
2023-10-19 18:13     ` James Dutton

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox