且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

正则表达式禁止所有常见形式的sql注入

更新时间:2023-02-22 15:07:03



用于检测SQL元字符的正则表达式:


 /( (\%3D)|(=))[^ \\\
] *((\%27)|(\')|(\-\-)|(\%3B)|(; ))/ i


说明:
此签名首先查找=符号或其十六进制等效值(%3D) )。然后它允许零个或多个非换行符,然后检查单引号,双破折号或分号。


典型的SQL注入尝试当然围绕使用单引号来操纵原始查询,以便它始终产生真值。讨论此攻击的大多数示例都使用字符串 1'或'1'='1 。但是,通过提供诸如 1'or2> 1 - 之类的值,可以容易地避免检测到该字符串。因此,唯一不变的部分是初始字母数字值,后跟单引号,然后是单词'或'。在此之后出现的布尔逻辑可能会变化到一般模式非常复杂或不涵盖所有变体的程度。因此,通过使用下面的2.3节中的下一个正则表达式,可以在很大程度上准确地检测到这些攻击。

典型SQL注入攻击的正则表达式

 / \w *(( \%27)|(\'))((\%6F)| o |(\%4F))((\%72)| r |(\%52))/ ix 


说明:
\w * - 零个或多个字母数字或下划线字符> (\%27)| \' - 无处不在的单引号或其十六进制等值
(\%6F)| o |(\%4F) )((\%72)| r |(\%52) - 单词'或',其大小写和小写等价的各种组合。


使用'union'SQL查询在针对各种数据库的SQL注入攻击中也很常见。如果只检测单引号或其他SQL元字符的早期正则表达式会导致过多的误报,那么可以进一步修改查询以专门检查单引号和关键字'union'。这也可以进一步扩展到其他SQL键诸如"选择","插入","更新","删除"等字样。
希望有所帮助。



Hi,

I want to disallow some common forms of sql injection using regular expression
I don't know how tp frame it up
May i know please does anybody have this or used this before.If so , please show me a sample........or share the expression

Hi,

regex for detection of SQL meta-characters:

/((\%3D)|(=))[^\n]*((\%27)|(\')|(\-\-)|(\%3B)|(;))/i 

Explanation:
This signature first looks out for the = sign or its hex equivalent (%3D). It then allows for zero or more non-newline characters, and then it checks for the single-quote, the double-dash or the semi-colon.

A typical SQL injection attempt of course revolves around the use of the single quote to manipulate the original query so that it always results in a true value. Most of the examples that discuss this attack use the string 1'or'1'='1. However, detection of this string can be easily evaded by supplying a value such as 1'or2>1--. Thus the only part that is constant in this is the initial alphanumeric value, followed by a single-quote, and then followed by the word 'or'. The Boolean logic that comes after this may be varied to an extent where a generic pattern is either very complex or does not cover all the variants. Thus these attacks can be detected to a fair degree of accuracy by using the next regular expression, in section 2.3 below.



Regex for typical SQL Injection attack

/\w*((\%27)|(\'))((\%6F)|o|(\%4F))((\%72)|r|(\%52))/ix 

Explanation:
\w* - zero or more alphanumeric or underscore characters
(\%27)|\' - the ubiquitous single-quote or its hex equivalent
(\%6F)|o|(\%4F))((\%72)|r|(\%52) - the word 'or' with various combinations of its upper and lower case hex equivalents.

The use of the 'union' SQL query is also common in SQL Injection attacks against a variety of databases. If the earlier regular expression that just detects the single-quote or other SQL meta characters results in too many false positives, you could further modify the query to specifically check for the single-quote and the keyword 'union'. This can also be further extended to other SQL keywords such as 'select', 'insert', 'update', 'delete', etc.

Hope it helps.