defensive programming

BBC NEWS | Technology | ‘Critical’ flaw found in Windows

Microsoft has issued a warning about a critical security flaw that affects most versions of its Windows software.
[ . . . ]
The flaw, found by eEye Security, would allow a specially crafted MIDI instruction to swamp the cache, or buffer, in DirectX and allow a hidden program within it to run on the target machine.

Such buffer overflow bugs are quite a common way for malicious programs to infect a machine.

Microsoft has issued an alert about the flaw and a patch to close the loophole. It said that currently there were no known exploits of the bug.

The instruction could get into a computer by being put on a webpage.

It can also be put into an e-mail message that uses web formatting.

Secure C Programming

Buffer Overflows
A buffer overflow is what happens when programs try to store more data in a variable than it has been allocated space for. For example, suppose you have a variable called name that’s defined as an array of 10 characters. There is room for 9 characters, plus the terminating null. By default, C does no bounds checking at run-time, so it is very easy for the user of a badly written program to over flow a buffer. Consider this code fragment:

char name [10];
printf ("Enter your name: ");
fflush (stdout);
gets (name);


If the user of this program enters a name that’s less than 10 characters, all is well. But if they enter a longer string, the stack will get stomped on and data corruption can occur, causing a core dump, or worse, giving the user shell prompt. If the program is running as root, this would be disastrous.

So what can you do to avoid these buffer overflow problems? One answer is to provide really big buffers that “no one will ever overflow”. This is a bad idea because it hasn’t fixed the problem; it merely makes it harder to accidentally overflow the buffer. But it won’t stop a malicious user from deliberately overflowing the buffer. To do that, you need to use functions that let you specify a maximum number of characters to copy. If you change the line that reads

gets (name);
to
fgets (name, 10, stdin);

it doesn’t matter how many characters the user types in response to the prompt, as only the first 9 characters will be copied into the variable name. (With this example, you also have to remove the n character from the end of the name, as fgets() doesn’t remove it.)

This is, literally, what you learn in a 1st quarter programming class, especially if you learn C or C++. Given no bounds-checking or other safety harnesses, it’s up to the programmer to verify with test cases that his code can’t be misused or exploited by either a naive or cunning end-user, person or process. A Google search for “profiling+tools+buffer+overflow+bounds+checking” turns up some research and tools on this topic.

The fact this bug is in Windows Server 2003 suggests those much-discussed code reviews aren’t being taken all the seriously.