oss-sec mailing list archives
Re: Off-by-one question
From: Simon McVittie <smcv () debian org>
Date: Sat, 22 Nov 2014 09:41:13 +0000
On 22/11/14 06:28, Joshua Roers wrote:
I'm just wondering, is it possible to use strncpy to overwrite memory addresses?
It is possible to use anything that writes through a pointer to overwrite memory addresses, if you use it incorrectly.
char buf[4]; strncpy(buf, "Four", sizeof(buf));
buf = { 'F', 'o', 'u', 'r' } There is no write overflow into the next thing on the stack after buf, unless I'm missing something important, because "The strncpy() function shall copy not more than n bytes" (strncpy(3posix), derived from POSIX.1-2001). However, buf is not 0-terminated yet, so printf("%s\n", buf) at this point would output arbitrary memory contents from buf until the next 0 byte - a read overflow.
buf[sizeof(buf)-1] = '\0';
buf = { 'F', 'o', 'u', '\0' }
printf("%s\n", buf);
outputs "Fou" with no read or write overflow
will strncpy write beyond the memory of 'buf', and set it to NUL?
"If there is no null byte in the first n bytes of the array pointed to by s2, the result is not null-terminated." -strncpy(3posix) again
From my understanding from http://cwe.mitre.org/data/definitions/193.html, it would.
I think the statement "the strncpy will add a null terminator to each character array" in Example 2 is incorrect, unless there is an implementation of strncpy() on some platform with behaviour other than what POSIX says (I haven't checked the original specification of strncpy(), which is ISO C). However, "if the character arrays are output to the user through the printf method the memory addresses at the overflow location may be output to the user" is correct. In Example 3, unlike Example 2, I think there is really a memory write vulnerability: "The code does not account for the null character that is added by the second strncat function call". strncat() is not like strncpy(): it can write at most n+1 bytes. The devil is in the details with this stuff. Prefer to use your favourite runtime library's automatically-sized-string-buffer class instead of ISO C string manipulation where possible. S
Current thread:
- Off-by-one question Joshua Roers (Nov 21)
- Re: Off-by-one question Simon McVittie (Nov 22)
- Re: Off-by-one question Stuart Gathman (Nov 22)
- Re: Off-by-one question Joshua Rogers (Nov 22)