.net - 如何有效地编写 F# 程序集以实现部分信任?

标签 .net f# code-access-security

有人有在部分信任场景中使用 F# 代码的经验吗?例如,使用 [<AllowPartiallyTrustedCallers>] 创建程序集?

我正在开发几个项目,我们需要能够在部分信任的情况下运行,并且我们一直在尝试使用 2 级安全规则 ( http://msdn.microsoft.com/en-us/library/dd233102.aspx )。在实践中,对于我们的独立程序集来说,这很简单 - 只需添加一个属性即可;但有时我们的程序集会引用未注释且假定为“SecurityCritical”的第三方 DLL。这就是它变得“有趣”的地方。

在过去几天的使用中,F# 似乎存在严重问题。 .NET 安全策略期望您使用 [<SecuritySafeCritical>] 注释类型/方法如果他们引用或调用“SecurityCritical”代码,这恰好是 NuGet 上的大部分代码,因为这是它的默认值。现在,在 F# 中,这可以正常工作,直到您开始使用闭包。你不能这样做:

namespace Foo

open System.Security

[<assembly: AllowPartiallyTrustedCallers>]
[<assembly: SecurityRules(SecurityRuleSet.Level2)>]
do()

[<SecurityCritical>]
module C =
    let get () = [ 1 .. 10 ]

[<SecuritySafeCritical>]
module M =

    let foo () =
        seq {
            for i in 1 .. 10 do
                yield!
                    C.get ()
                    |> Seq.filter (fun x -> x % 2 = 0)
        }

此程序集未能通过 SecAnnotate.exe检查是因为 F# 编译器将闭包提升为单独的类型,该类型现在未用 [<SecuritySafeCritical>] 进行注释,默认为透明,但引用了一些关键代码,这是一个错误。

这听起来像是一个小限制,但我花了很多时间修改代码以避免关闭并满足 SecAnnotate 约束。也许 F# 可以将安全属性传播到它创建的闭包类型?我缺少另一种简单的方法吗?

最佳答案

您可以将 SecurityCritical 应用为程序集级属性:

[<assembly: SecurityCritical>]

不过,假设您只是编写一个“普通”F# 程序集(即不执行任何需要特殊安全性的操作(例如 P/Invoke)的程序集),更好的方法是替换:

[<assembly: AllowPartiallyTrustedCallers>]

[<assembly: SecurityTransparent>]

SecurityTransparentAttribute 的 MSDN 页面说:

Specifies that an assembly cannot cause an elevation of privilege.

Transparent assemblies can be accessed from partially trusted code and cannot expose access to any protected resources or functionality. Code in the assembly is not allowed to suppress code access security checks and cannot cause an elevation of privilege.

出于同样的原因,F# 3.0 版本的 FSharp.Core 也使用此属性。

附加信息链接:

关于.net - 如何有效地编写 F# 程序集以实现部分信任?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17616831/

相关文章:

c# - 在面板上显示图像

c# - 为什么 Split from System.String 不接受字符串作为重载?

f# - 在构建服务器上安装 F# 4.1 SDK

f# - 使用 FsUnit 创建测试类时,[<Test>] 不是成员的有效属性。为什么?

security - 安全透明方法 X 尝试访问安全关键方法 Y 失败

c# - 为什么后台垃圾收集有时会暂停我的应用程序,我该如何防止它发生?

c# - C++ 到 .NET : I need help with understanding C++ code to convert it to . NET

git - 如何将代码 checkout 仅限于某个用户/机器组合

网络共享上的 .NET 安全异常

.net - vb.net mdi 子标题栏没有隐藏