21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Avoid using vsprintf( ) and sprintf( ). Use vsnprintf( ) and snprintf( ) or<br />

vasprintf( ) and asprintf( ) instead. Alternatively, use a secure string library such as<br />

SafeStr (see Recipe 3.4).<br />

The functions vsprintf( ) and sprintf( ) assume that the buffer into which they<br />

write their output is large enough to hold it all. This is never a safe assumption<br />

to make and frequently leads to buffer overflow vulnerabilities. (See Recipe 3.3.)<br />

The functions vasprintf( ) and asprintf( ) dynamically allocate a buffer to hold<br />

the formatted output that is exactly the required size. There are two problems<br />

with these functions, however. The first is that they’re not portable. Most modern<br />

BSD derivatives (Darwin, FreeBSD, NetBSD, and OpenBSD) have them, as<br />

does Linux. Unfortunately, older Unix systems and Windows do not. The other<br />

problem is that they’re slower because they need to make two passes over the<br />

format string, one to calculate the required buffer size, and the other to actually<br />

produce output in the allocated buffer.<br />

The functions vsnprintf( ) and snprintf( ) are just as fast as vsprintf( ) and<br />

sprintf( ), but like vasprintf( ) and asprintf( ), they are not yet portable. They<br />

are defined in the C99 standard for C, and they typically enjoy the same availability<br />

as vasprintf( ) and asprintf( ). They both require an additional argument<br />

that specifies the length of the output buffer, and they will never write<br />

more data into the buffer than will fit, including the NULL terminating character.<br />

See Also<br />

• FormatGuard from Immunix: http://www.immunix.org/formatguard.html<br />

• Recipes 3.3, 13.4<br />

3.3 Preventing Buffer Overflows<br />

<strong>Problem</strong><br />

C and C++ do not perform array bounds checking, which turns out to be a securitycritical<br />

issue, particularly in handling strings. The risks increase even more dramatically<br />

when user-controlled data is on the program stack (i.e., is a local variable).<br />

Solution<br />

There are many solutions to this problem, but none are satisfying in every situation.<br />

You may want to rely on operational protections such as StackGuard from Immunix,<br />

use a library for safe string handling, or even use a different programming language.<br />

78 | Chapter 3: Input Validation<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!