如何在不使用安全黑客的情况下向 SQL 服务器注册 C# CLR 程序集?

How does one Register a C# CLR Assembly with SQL Server without using Security Hacks?

当我尝试通过 SSMS 中的对象资源管理器在 SQL 服务器中注册签名的 C# 程序集时,方法是右键单击 "Assemblies" 节点并选择 "New Assembly",然后我的签名通过 "Browse" 的 DLL,我收到以下错误:

CREATE or ALTER ASSEMBLY for assembly 'My Assembly' with the SAFE or EXTERNAL_ACCESS option failed because the 'clr strict security' option of sp_configure is set to 1. Microsoft recommends that you sign the assembly with a certificate or asymmetric key that has a corresponding login with UNSAFE ASSEMBLY permission. Alternatively, you can trust the assembly using sp_add_trusted_assembly.

尽管我已经尝试通过 "Signing" 项目属性生成的 PFX 文件和 sn.exe 生成的 SNK 文件(通过破解项目文件的 AssemblyOriginatorKeyFile 节点),两者都会导致 "New Assembly" 对话框中的 SQL 服务器仍将 DLL 报告为没有 "Strong Name":

我已经在 .NET 4.8 和 .NET 4.0 中使用 Visual-Studio-2019 生成的 Class 库项目和 Visual-Studio-2010 生成的 SQL 进行了尝试CLR 数据库项目都是为了同一个目的。

我理解错误消息建议使用安全黑客来解决问题(我也尝试过但无济于事),但我正试图避免这些问题,因为数据库服务器面向 public。我该如何正确解决这个问题?

假设 DLL 确实已签名,那么您可能会错过错误消息第一部分中指出的首选方法的第二步,具体而言:

that has a corresponding login with UNSAFE ASSEMBLY permission.

该部分对于正常工作至关重要。 将程序集加载到SQL服务器之前,您需要执行以下操作:

  1. 从 DLL
  2. [master] 数据库中创建一个非对称密钥
  3. 从该非对称密钥创建登录
  4. 授予新登录 UNSAFE ASSEMBLY 实例级权限

然后 您可以将任何程序集加载到任何数据库中,只要它已被同一个强名称密钥/pfx 文件(如果您有您的解决方案中有多个项目)。

Even though I've tried signing the assembly both through ..., both result in the DLL still being reported as not having a "Strong Name" by SQL Server in the "New Assembly" dialog:

正确。这是由于 UI 设计不佳或错误所致。创建新程序集时,"Additional properties:" 字段 而不是 反映 "Path to assembly:" 字段中指示的文件值。这很可能只是所有与程序集相关的东西的 "assembly" 对话框,它对已经加载到 SQL 服务器的程序集工作得很好,但对你试图加载的程序集不起作用。如果意图是查看文件以指示在 "Path to assembly:" 字段中指定的路径中找到的任何内容的当前值,那么这是一个错误(但我怀疑它是前者)。我已在此处向 Microsoft 报告此问题:

SSMS: "Additional properties" in "New Assembly" dialog is misleading as it doesn't describe DLL being imported


有关使用 SQLCLR 的一般信息,请访问 SQLCLR Info