我正在编写此代码以保护我的服务器免受SQL注入。目标是在匹配的任何内容之前插入[BloCKiT]。请不要使用空格分割单词,因为它不适用于这种情况。例如“s = 290'; DECLARE%”。这会导致错误。
请参阅代码中的评论,谢谢。
以下代码是用c#编写的。
string MyOutPut = "";
string PatternAnywhereFromWord = "declare|exec|insert|update|delete|varchar|cast";//search any within the word CASE-INSENTIVE. This is the regular expression
string AttachmeMe = "[BloCKiT]";//Insert this string into the statement
//find patterns case-insensitive anywhere within the statement and attach the AttachmeMe variable in front of the matched position
string InputStatment = "delete s=290';DECLARE%20@S%20NVARCHAR(4000) ;insert into update all xdelete * from database exec";
//some logic here. I plan to write some loop but i think i would perform pretty slow
MyOutPut = "YOUR LOGIC HERE";
//The result should be [BloCKiT]delete s=290';[BloCKiT]DECLARE%20@S%20NVARCHAR(4000) ;[BloCKiT]insert into [BloCKiT]update all x[BloCKiT]delete * from database [BloCKiT]exec
答案 0 :(得分:7)
drop database master; --oops
相反,请使用SQL parameters将任何用户输入安全。
答案 1 :(得分:1)
Microsoft提供了有关如何避免SQL注入攻击的指南页面。您永远不必手动解析sql字符串,也不必手动生成sql字符串。因为这容易出错并使您的解决方案变得僵硬且难以维护。
答案 2 :(得分:0)
这将完成您要做的事情:
MyOutPut = Regex.Replace(InputStatment,
"(?<tok>" + PatternAnywhereFromWord + ")",
AttachmeMe + "${tok}");
然而,正如Dan Abramov所说,这实际上不是防止SQL注入攻击的有效方法。此外,它很可能会丢弃各种完全合法的输入;并且它对引号和分号没有任何作用,这通常是SQL注入时所担心的主要内容。