Secure Coding mailing list archives

RE: New Microsoft Security Tool for developers


From: Gene Spafford <spaf () cerias purdue edu>
Date: Sat, 13 Dec 2003 15:47:16 +0000


Many good comments have been made.

But consider:

main()
{
  char fbuf[2];

  noOverflow(fbuf);
}

void noOverflow(char *str)
{
   char buffer[10];
   strncpy(buffer,str,(sizeof(buffer)-1));
   buffer[(sizeof(buffer)-1)]=0;
  /* Avoiding buffer overflow with the above two lines */
}


Several of you pointed out that the subroutine should check that the 
passed-in pointer is non-null.    But remember that it is only a 
pointer -- there is no way to ensure that the buffer pointed to has 
at least 10 entries if it is non-null!


This is one of the biggest problems with C, as has been noted already 
-- strings (and arrays in general) do not have their lengths as 
intrinsic values associated with them.


Thus, the fix I would suggest is that the subroutine have an extra 
argument added -- the length of the buffer:


void noOverflow(char *str, unsigned int bufsize)
{
    if (str == NULL  || bufsize == 0)
        return;
   strncpy(buffer,str, bufsize-1));
   buffer[bufsize-1]=0;
}


Then depend on the compiler to catch argument mismatches.    There 
are other stylistic tweaks that could help (use of "const" for 
instance, or filling the whole buffer) but this is the problem that 
will silently bite you on the butt if you don't program defensively.


--spaf






Current thread: