Home > php教程 > php手册 > body text

有效防止SQL注入漏洞详细说明

WBOY
Release: 2016-06-13 10:11:46
Original
1687 people have browsed it

1.如果动态构造的sql语句中包含参数,请必须对参数做如下操作
a.将'(单引号)替换成''(两个单引号)
b.将--(注释符)替换掉
c.将参数加入语句时,一定要在前后各加上引号,如:'select * from table where id='''+@id+''''这样的加法
2.如果动态构造的sql语句中包含表参数,请勿必给表加上[](中括号),如:'select * from ['+@tab+']'这样的做法

3..避免动态sql语句:尤其是从ie客户端获取查询、修改、删除条件的字段最容易被注入,例如上述从客户端获取personid,为了开发方便,直接把从客户端获取的persongid作为sql语句的条件,却没有对personid作必要的检查,所以在开发时执行sql语句时最好使用preparedstatement类。

 

4.  验证数据:在客户端ie使用网页特效验证用户输入数据的合法性作用其实不是很大,一定要在获取客户端数据之后,对数据进行严格的验证,开发人员不要假想用户只会输入合法的数据。确保在应用程序中检查分号、引号、括号、sql关键字等。可以使用正则表达式来进行复杂的模式匹配,运用它可以达到良好的效果。


×××网站地址薄查看程序需要传递一个personid,personid可以通过url参数传递,由于地址本查看程序直接获取personid,没有做任何数据合法性验证,而且personid是字符串变量,获取personid的代码如下:

if (getparameter(req,"personid")!=null){

personid=getparameter(req,"personid").trim();

}else{

personid="";

}

该程序中组合成的动态sql语句如下:

personsql="select * from 表名 where userid="+long.tostring(userid)+" and addrcontactid="+personid;

 

由于程序没有检查personid是否是整数,所以攻击者随便给personid赋一个值,即可继续运行后续的程序逻辑,如果攻击者输入如下网址:

http://www.----------------------?personid=6414 or 2=2

组合成的sql语句如下:

select * from 表名where userid=1433620 and addrcontactid=6414 or 2=2

防范方法

  sql注入漏洞可谓是“千里之堤,溃于蚁穴”,这种漏洞在网上极为普遍,通常是由于程序员对注入不了解,或者程序过滤不严格,或者某个参数忘记检查导致。在这里,我给大家一个函数,代替asp教程中的request函数,可以对一切的sql注入say no,函数如下:

function saferequest(paraname,paratype)
 '--- 传入参数 ---
 'paraname:参数名称-字符型
 'paratype:参数类型-数字型(1表示以上参数是数字,0表示以上参数为字符)

 dim paravalue
 paravalue=request(paraname)
 if paratype=1 then
  if not isnumeric(paravalue) then
   response.write "参数" & paraname & "必须为数字型!"
   response.end
  end if
 else
  paravalue=replace(paravalue,"'","''")
 end if
 saferequest=paravalue
end function

上面函数应用

对于int型的参数,如文章的id等,可以先判断是不是整数。

id =trim(request("id"))
if id"" then
  if not isnumeric(id) then
    response.write"请提供数字型参数"
    response.end
  end if
  id = clng(id)
else
  response.write"请输入参数id"
  response.end
end if

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!