在 C# 中可以利用缓冲区溢出漏洞吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9343665/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Are buffer overflow exploits possible in C#?
提问by poke
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?
假设 C# 程序仅使用托管 .NET 代码,该程序中是否可能存在缓冲区溢出安全漏洞?如果是这样,这种脆弱性怎么可能?
采纳答案by CodesInChaos
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.
是的,但它们更难生产。如果您使用某些不安全的结构,您只能得到缓冲区溢出,而不是使用“正常”的 C# 代码。当您的代码以较低的信任度运行时,内存损坏代码根本不可能发生。
A few possibilities for buffer overflows:
缓冲区溢出的几种可能性:
- Using the
unsafekeyword, 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
Marshalclass - (Mono only) You can disable array range checking (safety vs. performance trade-off)
- 使用
unsafe允许指针的关键字。不安全的代码就像 c 或 c++ 中基于指针的代码一样容易出错。 - 使用不安全的API,比如从方法
Marshal类 - (仅限单声道)您可以禁用数组范围检查(安全与性能权衡)
There are also a few other ways to corrupt memory apart from buffer overflows.
除了缓冲区溢出之外,还有一些其他方法可以破坏内存。
StructLayoutKind.Explicit- Wrong native interop signatures
StructLayoutKind.Explicit- 错误的本机互操作签名
(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)
(运行时本身是用 C++ 编写的,因此运行时中的错误也会损坏内存或溢出缓冲区,但我认为这超出了本问题的范围)
回答by seand
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.
从绝对意义上讲,是的,由于 .NET 运行时中的错误,缓冲区漏洞利用是可能的。然而,.NET 可以防止大多数最终用户代码(“不安全”使用除外)出现此类问题,因此在现实生活中风险较小。
In real life, most problems like this will occur from native calls (COM dlls etc) invoked from managed code.
在现实生活中,大多数像这样的问题都会发生在从托管代码调用的本机调用(COM dll 等)中。
回答by Lasse Espeholt
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.
您不能使用数组进行传统的缓冲区溢出。它会在访问数组之前进行边界检查,除非它 (CLR) 可以保证它是安全的。

