Vulnerability Development mailing list archives

*snprinf vs strncpy (misconception)


From: shok () CANNABIS DATAFORCE NET (Matt Conover)
Date: Wed, 28 Jun 2000 15:59:17 +0400


I just wanted to clear up a misconception I've been seeing:

I've been auditing a lot of source these last few weeks and I keep seeing
the same problem.  The length argument snprintf functions (vsnprintf and
snprintf) should be the total length of the buffer.  It will use length-1
(I usually null the buffer before calling snprintf, as doing sizeof(buf)
will still ensure I have a null at the end.  However, strncpy, will NOT.
This is where the problem is.  The developers use the length parameter to
snprintf and strncpy the same way, and that is the mistake.  With strncpy,
length should be the total buffer length - 1.  It's okay to use the full
buffer (nulls don't *have* to be there), as long as you don't utilize any
further string operatings (i.e., don't use anything that expects a null
terminator).

If further string operatings, such as strcat, printf, etc. occur, bad
things can happen.  It will not necessary crash the program--that will
only happen if it reaches bad memory or overflows enough of the buffer to
corrupt important information before finding a null (there are often nulls
nearby to prevent this from happening).  Instead, these string
operatings will read more data than the buffer is long, and they will
often include garbage at the end, which may cause bugs and unexpected
results, depending on how the data is used.

An example (note vsnprintf behaves the same was as snprintf):
#include <stdio.h>
#include <string.h>

int main()
{
   char buf[8], buf1[8];

   buf[7] = buf1[7] = '\0';
   snprintf(buf, 8, "AAAAAAAA");
   strncpy(buf1, "AAAAAAAA", 8);

   printf("buf with snprintf: %s\n", buf);
   printf("buf with strncpy: %s\n", buf1);

   return 0;
}

Matt (Shok)


Current thread: