【牛腩新闻】——浅入浅出SQL注入

【牛腩新闻】——浅入浅出SQL注入

What

所谓SQL注入,就是通过把SQL命令插入到Web表单提交或输入域名或页面请求的查询字符串,最终达到欺骗服务器执行恶意的SQL命令。

Why

SQL注入的产生原因通常表现在以下几方面:①不当的类型处理;②不安全的数据库配置;③不合理的查询集处理;④不当的错误处理;⑤转义字符处理不合适;⑥多个提交处理不当。

举几个小例子:

1.判断有无注入点

; and 1=1 and 1=2

2.猜表一般的表的名称无非是adminadminuser user pass password 等..

and 0<>(select count(*) from *)

and 0<>(select count(*) from admin)---判断是否存在admin这张表

3.猜帐号数目 如果遇到0<返回正确页面, 1<返回错误页面,说明帐号数目就是1个

and 0<(select count(*) from admin)

and 1<(select count(*) from admin)

4.猜解字段名称 在len() 括号里面加上我们想到的字段名称.

and 1=(select count(*) from admin wherelen(*)>0)--

and 1=(select count(*) from admin where len(用户字段名称name)>0)

and 1=(select count(*) from admin where len(密码字段名称password)>0)

5.猜解各个字段的长度 猜解长度就是把>0变换 直到返回正确页面为止

and 1=(select count(*) from admin wherelen(*)>0)

and 1=(select count(*) from admin wherelen(name)>6) 错误

and 1=(select count(*) from admin wherelen(name)>5) 正确 长度是6

and 1=(select count(*) from admin wherelen(name)=6) 正确

and 1=(select count(*) from admin wherelen(password)>11) 正确

and 1=(select count(*) from admin wherelen(password)>12) 错误 长度是12

and 1=(select count(*) from admin wherelen(password)=12) 正确

防止SQL注入

1.(简单又有效的方法)PreparedStatement

采用预编译语句集,它内置了处理SQL注入的能力,只要使用它的setXXX方法传值即可。

使用好处:

(1).代码的可读性和可维护性.

(2).PreparedStatement尽最大可能提高性能.

(3).最重要的一点是极大地提高了安全性.

原理:

sql注入只对sql语句的准备(编译)过程有破坏作用

而PreparedStatement已经准备好了,执行阶段只是把输入串作为数据处理,

而不再对sql语句进行解析,准备,因此也就避免了sql注入问题.

2.使用正则表达式过滤传入的参数

下面是具体的正则表达式:

检测SQL meta-characters的正则表达式 :

/(\%27)|(\’)|(\-\-)|(\%23)|(#)/ix

修正检测SQL meta-characters的正则表达式 :/((\%3D)|(=))[^\n]*((\%27)|(\’)|(\-\-)|(\%3B)|(:))/i

典型的SQL 注入攻击的正则表达式 :/\w*((\%27)|(\’))((\%6F)|o|(\%4F))((\%72)|r|(\%52))/ix

检测SQL注入,UNION查询关键字的正则表达式:/((\%27)|(\’))union/ix(\%27)|(\’)

检测MS SQL Server SQL注入攻击的正则表达式:

/exec(\s|\+)+(s|x)p\w+/ix

等等…..

3.字符串过滤

比较通用的一个方法:

(||之间的参数可以根据自己程序的需要添加)

public static boolean sql_inj(String str)

{

String inj_str ="'|and|exec|insert|select|delete|update|

count|*|%|chr|mid|master|truncate|char|declare|;|or|-|+|,";

String inj_stra[] =split(inj_str,"|");

for (int i=0 ; i &lt; inj_stra.length ;i++ )

{

if (str.indexOf(inj_stra[i])&gt;=0)

{

return true;

}

}

return false;

}

4.jsp中调用该函数检查是否包函非法字符

防止SQL从URL注入:

5.JSP页面判断代码:

使用javascript在客户端进行不安全字符屏蔽

功能介绍:检查是否含有”‘”,”\\”,”/”

参数说明:要检查的字符串

返回值:0:是1:不是

函数名是

function check(a)

{

return 1;

fibdn = new Array (”‘” ,”\\”,”/”);

i=fibdn.length;

j=a.length;

for (ii=0; ii<i;ii++)

{ for (jj=0; jj<j;jj++)

{ temp1=a.charAt(jj);

temp2=fibdn[ii];

if (tem’;p1==temp2)

{ return 0; }

}

}

return 1;

}

===================================

总的说来,防范一般的SQL注入只要在代码规范上下点功夫就可以了

猜你喜欢

转载自blog.csdn.net/yanwenwennihao/article/details/80030413