Hacker News new | ask | show | jobs
by loeg 3324 days ago
Couldn't you trivially harden against single byte overflows by just changing your malloc implementation to add one to the requested allocation size?
1 comments

No doubt. However, if the single byte off the end is reliably accessible, then programs may come to rely on it by accident. If a program is allocating n but using n+1, then a single-byte overflow would access n+2 and the problem repeats. Better to have that single byte off the end be reliably crashy to touch, but not exploitable.

You'd also incur substantial space overhead for small allocations in many cases. I'm not familiar with Linux's implementation, but on the Mac, for example, all allocations are a multiple of 16 bytes. It's common to allocate 16 or 32 bytes for small objects, so padding the allocation by one byte will bump you up to 32 and 48 bytes respectively.

One of the funniest things I've seen in code I saw in PHP core a decade ago; they had a buffer underflow where they would overwrite arr[-1] with some character. Their solution was to save the contents of arr[-1] before the loop, then restore it afterwards.
Sweet Jesus. I could almost understand it if they allocated an extra byte and then used an offset base pointer....
You could do that at the compiler level, and only for types that end in a flexible array member, or only when malloc's argument looks like "sizeof (T) + x". That would generally avoid the space overhead, and in the flexible array member case you could e.g. add a whole int (4 byes) for an int-typed flexible array member. But I am not sure it's a good idea, for the other reason you mentioned.
malloc already hands you more than you ask for in a lot of cases, check out malloc_usable_size.
This is true. But in the case where the malloc heap metadata is under attack, the attacker will usually just allocate exactly the right size to ensure that the off-by-one goes off the end of the chunk, instead of into slack space.