用于检测 SQL 注入的正则表达式
是否有正则表达式可以检测字符串中的 SQL? 有没有人有他们以前使用过的东西的样本可以分享?
Is there a Regular Expression that can detect SQL in a string? Does anyone have a sample of something that they have used before to share?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不要这样做。 你几乎肯定会失败。 请改用
PreparedStatement
(或其等效项)。Don't do it. You're practically guaranteed to fail. Use
PreparedStatement
(or its equivalent) instead.使用存储过程或准备好的语句。 您将如何检测到这样的事情?
顺便说一句,不要运行这个:
这意味着:
Use stored procedures or prepared statements. How will you detect something like this?
BTW do NOT run this:
Which translates to:
避免出现问题,并将存储过程与准备好的语句或参数化查询一起使用。 无论如何,存储过程都是很好的实践,因为它们就像数据库的接口,因此您可以更改幕后(存储过程内)发生的事情,但签名保持不变。 准备好的语句有助于处理注入保护。
Save yourself problems and use stored procedures with prepared statements or parameterized queries. Stored procedures are good practice anyway, as they act like an interface to the database, so you can change what happens behind the scenes (inside the stored proc) but the signature remains the same. The prepared statements help take care of injection protection.
我没有正则表达式,但我的理解是最重要的是检测单引号。 所有的注入攻击都是从那里开始的。 他们可能也有 -- 来注释掉字符串后面的其他 SQL。
I don't have a regex but my understanding is that the most important thing is to detect the single quote. All the injection attacks start from there. They probably have the -- in there too to comment out and other SQL that might be after the string.
如前所述,最好使用准备好的语句。 您可能会争论强制由存储过程执行关键查询来强制使用准备调用。
无论如何,这里有一个简单的 grep 来检测 where 子句中的经典 n=n 整数; 它会跳过标记许多惰性查询构造函数使用的 1=1 AND,但会将其标记为 OR
当然可以改进以检测小数和字符串比较,但它是一种快速检测机制,与其他 grep 一样如ORD(MID(等。
在查询日志上使用它,例如mysql的通用日志
希望它有用
As said, it is better to use prepared statements. You could argue forcing key queries to be executed by a stored procedure to force the use of preparing the call.
Anyway, here is a simple grep to detect classic n=n integer in where clauses; it skips flagging the 1=1 used by many lazy query constructors for the AND, but will flag it for the OR
It could of course be improved to detect decimal and string comparisons, but it was a quick detection mechanism, along with other greps such as ORD(MID(, etc.
Use it on a query log, such as mysql's general log
Hope its useful