Thursday, 10 January 2013

Null Terminated String Copy

Research into a heap buffer overflow error in Windows XP version of NetApi32.dll reveals that the code is using a null terminated string copy.  The patched version of the same dll shows that the copy code has been replaced by a better function that checks the size of the destination buffer.

There are a number of different ways that a programmer can use to copy some text from one place in memory to another place in memory.  One of these is called a null terminated String copy.  The function works by copying the text characters until it reaches a zero termination character at which point the function returns back to the caller.

The problem comes when the destination memory area has been allocated a fixed size but the data being copied is larger than this size.  It means that the memory that is situated after the allocated memory area can become corrupted with the data that is larger than the area.

So if the memory area is 5 characters long but the supplied data is 10 characters long.  The first 5 characters will be placed into the normal allocated memory block and the remaining 5 characters will end up overwriting other blocks of memory used within the program.

Virus writers look for this type of programming bug as it means that if the data to copied is supplied by an external source, such as from keyboard or file, then it means that it might be possible to work out the relevant values to use to gain control of the computer. 

In the picture above for example, what would happen if the section "Memory for other objects" contained a function pointer or return address from sub function? The answer is that It could be overwritten with a different address supplied as part of the Data - causing the processor to jump somewhere else in memory.

Defensive programming should always be used with external input to validate that it is in the correct format and expected size.

No comments:

Post a Comment