【发布时间】:2019-08-19 08:07:01
【问题描述】:
我正在尝试按照https://sqlquantumleap.com/2017/08/09/sqlclr-vs-sql-server-2017-part-2-clr-strict-security-solution-1/ 中描述的过程在 SQL Server 2017 数据库中部署 CLR 程序集。基本上,出于测试目的,我只是包含了一个带有几个基于正则表达式的函数的程序集:
public class TextUdf
{
[SqlFunction(Name = "RegexIsMatch", IsDeterministic = true, IsPrecise = true)]
public static SqlBoolean RegexIsMatch(SqlString text, SqlString pattern,
SqlInt32 options)
{
if (text.IsNull) return SqlBoolean.Null;
if (pattern.IsNull) pattern = "";
return Regex.IsMatch((string)text,
(string)pattern,
options.IsNull? RegexOptions.None : (RegexOptions)options.Value,
new TimeSpan(0, 0, 10))
? SqlBoolean.True
: SqlBoolean.False;
}
[SqlFunction(Name = "RegexReplace", IsDeterministic = true, IsPrecise = true)]
public static SqlString RegexReplace(SqlString text, SqlString pattern,
SqlString replacement, SqlInt32 options)
{
if (text.IsNull || pattern.IsNull) return text;
return Regex.Replace((string)text, (string)pattern,
(string)replacement,
options.IsNull ? RegexOptions.None : (RegexOptions)options.Value);
}
}
我在https://github.com/Myrmex/sqlclr 创建了一个完整的复制解决方案。我可以按照那里描述的整个过程(自述文件)直到我必须将 PFX 证书分配给要部署的 CLR 程序集。此时,我收到此错误:
MSB3325: Cannot import the following key file: pfx. The key file may be password protected. To correct this, try to import the certificate again or manually install the certificate to the Strong Name CSP with the following key container name: ...
按照错误信息的指导,我发现可以通过使用sn安装PFX来解决这个问题,这样我就可以在提示时手动输入密码(见Cannot import the keyfile 'blah.pfx' - error 'The keyfile may be password protected')。
完成此操作后,我可以使用 UDF 函数编译我的 CLR 程序集。现在,当我尝试通过CREATE ASSEMBLY [SqlServerUdf] FROM 0x...binary stuff... 将其安装到测试数据库(为此目的创建的只是一个空数据库)中时,我收到此错误:
CREATE or ALTER ASSEMBLY for assembly 'SqlServerUdf' 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.
这违背了我必须遵循的漫长过程的目的,以便让 SQL Server 接受我的 CLR 而不会降低严格的安全性。
显然我遗漏了一些东西,但我不确定这个棘手程序的许多细节,所以这将是一个很难猜测的事情。谁能建议我们该过程有什么问题,以便我们可以快速而肮脏地一步一步地参考如何在 SQL Server 中插入 CLR 程序集?这个简单的任务似乎在最新版本中变得非常困难......
【问题讨论】:
-
您是否在 SQL Server 中创建了证书并使用它进行了登录?参考:sqlshack.com/…(见选项 4)这帮助我解决了一个类似的问题(不过,我使用的是选项 3,所以我不能说这是一个多么好的解决方案)。
-
@Natfis:只是为了确认一下,您可以编译/签署
SqlServerUdf程序集吗?并且,您在尝试部署之前执行了 PreDeploy.sql 脚本,或者至少在SqlServerUdf项目中注册了 PreDeploy.sql 脚本?我相信我知道问题出在哪里,并将把其余的细节放在答案中。 -
@JasonWhitish SQLShack 页面还不错,但无助于创建自包含的部署脚本,也无助于将解决方案集成到完全与 Visual Studio 和/或自动化CI 过程。我的帖子中列出的选项——Asymmetric Key / snk 或Certificate-only——需要更多步骤,但会实现完全自动化:-D。
标签: c# sql-server sqlclr