简体   繁体   English

有没有办法以编程方式从 C# 语句(如 SQL 服务器上的 CREATE/ALTER DATABASE)调用而不会产生安全问题?

[英]Is there a way to programmatically call from C# statements like CREATE/ALTER DATABASE on SQL Server without creating security issues?

I have an .NET application which is running the following statement using SqlCommand:我有一个 .NET 应用程序,它使用 SqlCommand 运行以下语句:

DECLARE @SQL VARCHAR(100)
SELECT @SQL = 'CREATE DATABASE ' + @DB
EXEC(@SQL)

The @DB parameter comes from user input, so obviously the application is vulnerable to something like 'X DROP DATABASE Y'. @DB 参数来自用户输入,因此应用程序显然容易受到“X DROP DATABASE Y”之类的攻击。 I'm sure there must be an obvious way I'm missing...我敢肯定一定有一个明显的方式我错过了......

Edit: using a parametrized statement cannot work because you cannot use a parameter in CREATE DATABASE (CREATE DATABASE @DB returns a syntax error).编辑:使用参数化语句不起作用,因为您不能在 CREATE DATABASE 中使用参数(CREATE DATABASE @DB 返回语法错误)。

First, you should never, ever do this from a web app.首先,您永远不应该从 web 应用程序中执行此操作。 Ever.曾经。 Really.真的。 I'm serious.我是认真的。 With the exception of deployment packages, the only time I've needed to execute a CREATE DATABASE is from the query analyzer in SSMS.除了部署包之外,我唯一需要执行CREATE DATABASE的时间是来自 SSMS 中的查询分析器。 Additionally, I'm suspicious of any code that would let a user enter a database name, and then go and create it.此外,我怀疑任何允许用户输入数据库名称,然后 go 并创建它的代码。

Most importantly, what you've posted is not a "parameterized query."最重要的是,您发布的不是“参数化查询”。 It's concatenated SQL, which is the source of SQL injection vulnerabilities.它串联了SQL,这是SQL注入漏洞的来源。 . . If it were a parameterized query (or a stored proc, but I don't think you can do a CREATE DATABASE from a sproc), SQL injection would be a non-issue.如果它是参数化查询(或存储过程,但我认为您不能从存储过程中CREATE DATABASE ),则 SQL 注入将不是问题。

You can either use a real parametrized query ( here is a good tutorial on parametrized queries. ), or sanitize your inputs, but ADO.NET or whatever other db library will reliably handle this for you IF you properly build the command and parameter objects.您可以使用真正的参数化查询( here is a good tutorial on parametrized queries。 ),或者清理您的输入,但是如果您正确构建命令和参数对象,ADO.NET 或任何其他数据库库将为您可靠地处理此问题。

You probably want to specify parameters - paramaterized queries pretty much eliminate SQL injection attacks (as long as you're not concatenating strings in your receiving stored procedures).您可能想要指定参数- 参数化查询几乎可以消除 SQL 注入攻击(只要您没有在接收存储过程中连接字符串)。

Like I said in my comment, I hope there's an exceptionally good reason for creating databases/tables on the fly where creating rows seems to work for most everyone else.就像我在评论中所说的那样,我希望动态创建数据库/表有一个非常好的理由,因为创建行似乎对大多数其他人都有效。

Use a whitelist approach: allow only letters.使用白名单方法:只允许字母。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM