Assuming that a C# program uses only managed .NET code, is it possible to have a buffer overflow security vulnerability within that program? If so, how would such vulnerability be possible?
问题:
回答1:
Yes, but they are much harder to produce. You can only get buffer overflows if you use certain unsafe constructs, and not with "normal" C# code. Memory corrupting code shouldn't be possible at all, when your code is running with lowered trust.
A few possibilities for buffer overflows:
- Using the
unsafe
keyword, which allows pointers. Unsafe code is just as easy to get wrong, as pointer based code in c or c++. - Using unsafe APIs, such as the methods from the
Marshal
class - (Mono only) You can disable array range checking (safety vs. performance trade-off)
There are also a few other ways to corrupt memory apart from buffer overflows.
StructLayoutKind.Explicit
- Wrong native interop signatures
(The runtime itself is written in C++, so a bug in the runtime can also corrupt memory or overflow a buffer, but I consider that out of scope for this question)
回答2:
Yes, in unsafe environments:
unsafe void bufferOverflow(string s)
{
char* ptr = stackalloc char[10];
foreach (var c in s)
{
*ptr++ = c; // Bufferoverflow if s.Length > 10
}
}
"Allow unsafe code" has to be checked for this to compile.
You can't a traditional buffer-overflow with an array. It will do bounds-checking before accessing an array unless it (CLR) can guarantee it is safe.
回答3:
Only if you use the unsafe
keyword.
回答4:
In an absolute sense, yes a buffer exploit is possible due to bugs in the .NET runtime. However .NET prevents most end user code (except 'unsafe' usage) from these sorts of problems so in real life it's less risky.
In real life, most problems like this will occur from native calls (COM dlls etc) invoked from managed code.