Avoiding Buffer Overruns
Collapse the table of content
Expand the table of content

Avoiding Buffer Overruns

A buffer overrun is one of the most common sources of security risk. A buffer overrun is essentially caused by treating unchecked, external input as trustworthy data. The act of copying this data, using operations such as CopyMemory, strcat, strcpy, or wcscpy, can create unanticipated results, which allows for system corruption. In the best of cases, your application will abort with a core dump, segmentation fault, or access violation. In the worst of cases, an attacker can exploit the buffer overrun by introducing and executing other malicious code in your process. Copying unchecked, input data into a stack-based buffer is the most common cause of exploitable faults.

Buffer overruns can occur in a variety of ways. The following list provides a brief introduction to a few types of buffer overrun situations and offers some ideas and resources to help you avoid creating new risks and mitigate existing ones:

Static buffer overruns

A static buffer overrun occurs when a buffer, which has been declared on the stack, is written to with more data than it was allocated to hold. The less apparent versions of this error occur when unverified user input data is copied directly to a static variable, causing potential stack corruption.

Heap overruns

Heap overruns, like static buffer overruns, can lead to memory and stack corruption. Because heap overruns occur in heap memory rather than on the stack, some people consider them to be less able to cause serious problems; nevertheless, heap overruns require real programming care and are just as able to allow system risks as static buffer overruns.

Array indexing errors

Array indexing errors also are a source of memory overruns. Careful bounds checking and index management will help prevent this type of memory overrun.

Preventing buffer overruns is primarily about writing good code. Always validate all your inputs and fail gracefully when necessary. For more information about writing secure code, see the following resources:

  • Maguire, Steve [1993], Writing Solid Code, ISBN 1-55615-551-4, Microsoft Press, Redmond, Washington.
  • Howard, Michael and LeBlanc, David [2003], Writing Secure Code, 2d ed., ISBN 0-7356-1722-8, Microsoft Press, Redmond, Washington.
Note  These resources may not be available in some languages and countries.

Safe string handling is a long-standing issue that continues to be addressed both by following good programming practices and often by using and retrofitting existing systems with secure, string-handling functions. An example of such a set of functions for the Windows shell starts with StringCbCat.



Community Additions

© 2016 Microsoft