损坏状态异常处理的可靠性
我目前正在研究 C# / .NET 的可靠性功能和异常处理,
尤其是 HandleProcessCorruptedStateExceptions
属性和 CER 以及准备ConstrainedRegions
。
现在我正在阅读 SecureString
类的参考源代码,因为这是一个即使在特殊情况下也要保持数据加密的安全性非常关键的地方,并发现类似这样的地方:
[HandleProcessCorruptedStateExceptions]
//...
RuntimeHelpers.PrepareConstrainedRegions();
try
{
Unprotect();
// ...
}
catch(Exception)
{
Protect();
throw;
}
finally
{
Protect();
// ...
}
catch
块的原因是什么? finally
块不足以重新保护数据吗?
或者这些损坏的状态异常是否只会影响 catch
并随后终止应用程序?
I'm currently looking into reliability features and exception handling of C# / .NET
These are especially the HandleProcessCorruptedStateExceptions
attribute and CER s with PrepareConstrainedRegions
.
Now I was reading the reference source code of the SecureString
class, as this is a place where it is highly security critical to keep data encrypted even in exceptional situations, and found places similar like this:
[HandleProcessCorruptedStateExceptions]
//...
RuntimeHelpers.PrepareConstrainedRegions();
try
{
Unprotect();
// ...
}
catch(Exception)
{
Protect();
throw;
}
finally
{
Protect();
// ...
}
What is the reason for the catch
block? Isn't the finally
block sufficient to re-protect data?
Or could those corrupted state exceptions only affect catch
and terminate the application afterwards?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于异常过滤功能(C# 不提供,但 Visual Basic 和其他提供)中的安全漏洞,catch 块中需要重复代码。它允许恶意用户在捕获异常之后、执行finally 块之前在您的try-catch-finally 块中执行其代码。
威胁如下所示:您的库的 Visual Basic 用户在 Unprotect() 之后导致异常(甚至由于内存不足而导致 OutOfMemoryException),CLR 找不到 catch 块,然后 CLR 执行用户的异常过滤器代码,该代码窃取 Unprotect() 编辑的数据,然后 CLR 才会在finally 块中执行Protect()。
因此,将安全清理代码放在 catch 和finally 块中,通常的清理仅保留在finally 中。
Code duplication in catch block is needed because of security breach in exception filtering feature (not provided by C#, but Visual Basic and others offer it). It allows malicious user to execute their code in your try-catch-finally block, after exception is caught and before finally block is executed.
Threat looks like this: Visual Basic user of your library causes exception after Unprotect() (even OutOfMemoryException by running out of memory), CLR finds no catch block, then CLR executes user's exception filter code, this code steals Unprotect()-ed data, and only then CLR executes Protect() in finally block.
So, put security cleanup code in both catch and finally blocks, usual cleanup stays in finally only.
除了少数情况外,
Finally
块几乎总是被调用。请参阅C#“finally”块是否始终执行?< /a> 了解更多。
所以是的,protect 总是在
Finally
中调用。Finally
blocks are almost always called, except in a few cases. SeeDoes the C# "finally" block ALWAYS execute? for more.
So yes, the protect is always called in the
Finally
.