From C# reference for stackalloc:
the use of stackalloc automatically enables buffer overrun detection features in the common language runtime (CLR). If a buffer overrun is detected, the process is terminated as quickly as possible to minimize the chance that malicious code is executed.
Specifically, what kind of protection mechanism is implemented for .NET?
And will it also detect buffer underruns?
Against which known attacks is the protection weaker?
For a context, for example for MS C++ compiler the information is available here:
Windows ISV Software Security Defenses:
The Stack Buffer Overrun Detection capability was introduced to the C/C++ compiler in Visual Studio .NET 2002 and has been updated in subsequent versions. /GS is a compiler switch that instructs the compiler to add startup code, and function epilog and prolog code, to generate and check a random number that is placed in a function's stack.
Note that Visual C++ 2005 (and later) also reorders data on the stack to make it harder to predictably corrupt that data. Examples include:
• Moving buffers to higher memory than non-buffers. This step can help protect function pointers that reside on the stack.
• Moving pointer and buffer arguments to lower memory at run time to mitigate various buffer overrun attacks.
Yes, the .NET jitter generates the kind of stack canary checking that also exists in native code generated by the Microsoft C/C++ compiler with the /GS compiler option. The basic scheme is to store a random 32-bit value at the top of the stack, written at method entry. At method exit it checks if the value is still there. A change in the value is a very high predictor for a stack buffer overflow, the kind that malware uses to take control of a program.
Some code to play with:
Running this code triggers the Windows Error Reporting dialog, even with the debugger attached. You can see the crash reason in the Output window:
The exception code is defined in the ntstatus.h SDK header file:
You can see the code that does this with Debug + Windows + Disassembly. The essential parts of Kaboom:
The actual canary value changes every time the code is jitted.