The Microsoft .NET Framework provides the developer with a number of advanced features such as P/Invoke and unsafe code blocks. This article will take a look at unsafe code blocks and some of the security issues that should be looked for when reviewing or writing such code.
The Spider Woman movie
First off, what is the unsafe keyword and how can it be used? Glad you asked, unsafe allows for the use of pointers in .NET code. This includes pointers to managed objects such as arrays and strings. To use the unsafe keyword the assembly or executable must be compiled with a special flag allowing for unsafe code blocks. The resulting assembly/executable will not be verifiable by the CLR.
Modification of Immutable Types
With power comes the temptation to modify immutable types such as strings. Resist this urge as the CLR does a number of internal optimizations for known immutable types like strings. Modification of these immutable types can and will cause instability in the CLR, and have interesting ramifications. For example, some versions of the CLR keep only a single copy of strings. So if I created three strings, all with the value “Hello World”, I would really only have three references to the same string. This is okay since the string object is immutable. However, if I take a pointer to the string and change its contents I will end up changing the contents of all three strings!!
Managed Pointers and Pinning
The .NET memory manager can move values and object instances around in memory as needed. So, if we are going to get a pointer to such a memory region we need to tell the memory manager not to move that memory on us. Enter object pinning. Pinning tells the CLR not to move something until it is unpinned. A typical bug in unsafe code is when a managed pointer is held on to and used after it’s reference has been unpinned. This is a hard bug to detect as the program may run fine most of time and the crashes that occur may not be obviously linked to the unsafe code.
In the C# managed language, pinning typically occurs using the “fixed” block. This makes it easier to spot issues. I recommend avoiding other methods of pinning variables as they can be harder to review.
Buffer Overflows and other Pointer Issues
With the unsafe keyword and pointer math come all the standard security issues those C/C++ developers need to worry about. There is a real possibility of causing buffer overflows that result in exploitable conditions in .NET applications. Buffer manipulation should be reviewed just like C/C++ for possible overflows.
And so ends part 1 of this article. Please feel free to comment on this post with questions and comments.
Posted in Security