Be Careful with _alloca

Be Careful with _alloca

The _alloca function allocates dynamic memory on the stack. The allocated space is freed automatically when the calling function exits, not when the allocation merely passes out of scope. Here's some sample code using _alloca:

void function(char *szData) { PVOID p = _alloca(lstrlen(szData)); // use p }

If an attacker provides a long szData, one longer than the stack size, _alloca will raise an exception, causing the application to halt. This is especially bad if the code is present in a server.

The correct way to cope with such error conditions is to wrap the call to _alloca in an exception handler and to reset the stack on failure:

void function(char *szData) { __try { PVOID p = _alloca(lstrlen(szData)); // use p } __except ((EXCEPTION_STACK_OVERFLOW == GetExceptionCode()) ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { _resetstkoflw(); } }

ATL Conversion Macros

You should be wary also of certain Active Template Library (ATL) string conversion macros because they also call _alloca. The macros include A2W, W2A, CW2CT, and so on. If your code is server code, do not call any of these conversion functions without regard for the data length. This is another example of simply not trusting input.

The version of ATL 7.0 included with Visual Studio .NET 2003 offers support for string conversion macros that offload the data to the heap if the source data is too large. The maximum size allowed is supplied as part of the class instantiation:

#include "atlconv.h"  LPWSTR szwString = CA2WEX<64>(szString);

Note that C# includes the stackalloc construct, which is similar to _alloca. However, stackalloc can be used only when the code is compiled with the /unsafe option and the function is marked unsafe:

public static unsafe void Fibonacci() { int* fib = stackalloc int[100]; int* p = fib; *p++ = *p++ = 1; for (int i=2; i<100; ++i, ++p) *p = p[-1] + p[-2]; for (int i=0; i<10; ++i) Console.WriteLine (fib[i]); }



Writing Secure Code
Writing Secure Code, Second Edition
ISBN: 0735617228
EAN: 2147483647
Year: 2001
Pages: 286

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net