12

有人在部分信任场景中使用 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# 可以将安全属性传播到它创建的闭包类型?还有另一种我想念的简单方法吗?

4

1 回答 1

6

You can apply SecurityCritical as an assembly-level attribute:

[<assembly: SecurityCritical>]

A better approach though, assuming you're just writing a "plain" F# assembly -- i.e., one that isn't doing anything which requires special security (e.g., P/Invoke) -- would be to replace:

[<assembly: AllowPartiallyTrustedCallers>]

with

[<assembly: SecurityTransparent>]

The MSDN page for SecurityTransparentAttribute says:

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.

The F# 3.0 version of FSharp.Core also uses this attribute for the same reason.

Links to additional information:

于 2013-07-12T14:45:12.440 回答