有没有一种方法可以从 C# 语句(例如 SQL Server 上的 CREATE/ALTER DATABASE)进行编程调用,而不会产生安全问题?
我有一个 .NET 应用程序,它使用 SqlCommand 运行以下语句:
DECLARE @SQL VARCHAR(100)
SELECT @SQL = 'CREATE DATABASE ' + @DB
EXEC(@SQL)
@DB 参数来自用户输入,因此显然该应用程序容易受到“X DROP DATABASE Y”之类的攻击。我确信我错过了一个明显的方法...
编辑:使用参数化语句无法工作,因为您无法在 CREATE DATABASE 中使用参数(CREATE DATABASE @DB 返回语法错误)。
I have an .NET application which is running the following statement using 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'. 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).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,您应该永远、永远通过网络应用程序执行此操作。曾经。真的。我是认真的。除了部署包之外,我唯一需要执行
CREATE DATABASE
的时间是通过 SSMS 中的查询分析器。此外,我对任何允许用户输入数据库名称然后创建它的代码表示怀疑。最重要的是,您发布的内容不是“参数化查询”。它是串联的SQL,这是SQL注入漏洞的根源。。如果它是一个参数化查询(或一个存储过程,但我不认为你可以从存储过程中执行
CREATE DATABASE
),那么SQL注入将不是问题。您可以使用真正的参数化查询(这里有一个关于参数化查询的很好的教程。< /a>),或者清理您的输入,但如果您正确构建命令和参数对象,ADO.NET 或任何其他数据库库将可靠地为您处理此问题。
First, you should never, ever do this from a web app. 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. Additionally, I'm suspicious of any code that would let a user enter a database name, and then go and create it.Most importantly, what you've posted is not a "parameterized query." It's concatenated SQL, which is the source of SQL injection vulnerabilities.. 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.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.
您可能想要指定参数 - 参数化查询几乎消除了 SQL 注入攻击(只要您没有在接收存储过程中连接字符串)。
就像我在评论中所说的那样,我希望有一个非常好的理由来动态创建数据库/表,其中创建行似乎对大多数其他人都适用。
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).
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.