Re: Are bad developer libraries the problem with M$ software?

From: Andrew Dalgleish (secprog@andrewdalgleish.dyndns.org)
Date: 11/19/02

  • Next message: Luciano Miguel Ferreira Rocha: "Re: Are bad developer libraries the problem with M$ software?"
    Date: Wed, 20 Nov 2002 09:57:57 +1100
    From: Andrew Dalgleish <secprog@andrewdalgleish.dyndns.org>
    To: secprog@securityfocus.com
    
    

    On Mon, Nov 18, 2002 at 09:25:46PM -0600, Frank Knobbe wrote:
    > On Mon, 2002-11-18 at 17:10, Andrew Griffiths wrote:
    >
    > > Another thing to use is consistency, for example,
    > >
    > > char dst[50];
    > > strncpy(dst, user_supplied_data, sizeof(dst));
    > > strncat(dst, sizeof(dst) - strlen(dst) -1, moreuserdata);
    > >
    > > This could be exploitable if user_supplied_data is 50 or more bytes long.
    > >
    > > In specific,
    > >
    > > 50 - 50 - 1 == -1
    >
    > If sizeof(dst) is 50, then a 0 terminated string is is 49 chars long
    > (len(dst) is 49). That means we've got 50-49-1 = 0 which is correct as
    > there is no room left in dst.
    >
    > Of course in your example you allow dst to overflow in the strncpy.
    > Using
    > strncpy(dst, user_supplied_data, sizeof(dst)-1);
    > would have prevented that if my math is correct.

    No, it would not. strncpy does NOT append the trailing 0 if the
    length of the source is greater than or equal to the count.

    Using sizeof(dst)-1 will leave the last byte in the buffer unchanged.
    If dst is on the stack there is no guarantee the string is terminated.
    To be sure, you would *also* need to add
    dst[sizeof(dst)-1] = 0;

    C'mon people, this really is beginner stuff.
    Please RTFM before you post well-meaning advice.

    You might also like to look at the bsd-style strlcpy/strlcat functions.