您的位置:首页 > 数据库

关于sql注入的问题以及如何避免

2013-08-30 14:02 330 查看
一、什么是sql注入呢?
所谓SQL注入,就是通过把SQL命令插入到Web表单递交或输入域名或页面请求的查询字符串,最终达到欺骗服务器执行恶意的SQL命令,比如先前的很多影视网站泄露VIP会员密码大多就是通过WEB表单递交查询字符暴出的,这类表单特别容易受到SQL注入式攻击.当应用程序使用输入内容来构造动态sql语句以访问数据库时,会发生sql注入攻击。如果代码使用存储过程,而这些存储过程作为包含未筛选的用户输入的字符串来传递,也会发生sql注入。
黑客通过SQL注入攻击可以拿到网站数据库的访问权限,之后他们就可以拿到网站数据库中所有的数据,恶意的黑客可以通过SQL注入功能篡改数据库中的数据甚至会把数据库中的数据毁坏掉。做为网络开发者的你对这种黑客行为恨之入骨,当然也有必要了解一下SQL注入这种功能方式的原理并学会如何通过代码来保护自己的网站数据库。
二、sql注入产生原因
 
sql注入攻击是利用是指利用设计上的漏洞,在目标服务器上运行Sql语句以及进行其他方式的攻击,动态生成Sql语句时没有对用户输入的数据进行验证是Sql注入攻击得逞的主要原因。对于java数据库连接JDBC而言,SQL注入攻击只对Statement有效,对PreparedStatement是无效的,这是因为PreparedStatement不允许在不同的插入时间改变查询的逻辑结构。
如验证用户是否存在的SQL语句为:
用户名'and pswd='密码
如果在用户名字段中输入: 'or 1=1或是在密码字段中输入:'or 1=1
将绕过验证,但这种手段只对只对Statement有效,对PreparedStatement无效。相对Statement有以下优点:

1.防注入攻击

2.多次运行速度快

3.防止数据库缓冲区溢出

4.代码的可读性可维护性好
这四点使得PreparedStatement成为访问数据库的语句对象的首选,缺点是灵活性不够好,有些场合还是必须使用Statement。

三、具体处理方法(如下例)
 
String product_id = Request["product_id"];

string sql = "SELECT * FROM products WHERE id = '"+product_id +"'";

SqlCommand command = new SqlCommand(sql, connection);
从第二行可以看出此sql是拼接的字符串,容易造成sql注入,(sql注入是通过把SQL命令插入到Web表单递交或输入域名或页面请求的查询字符串,最终达到欺骗服务器执行恶意的Sql命令);

This can be seen from the second line ofstitching string sql is likely to cause sql injection,
(sql injection is inserted into SQLcommands via the Web form to submit or enter the domain
name or page request query string, andultimately to the server to execute malicious deception
the Sql command);

1.通过参数查询方式

1 can be avoided through the parameterquery

 

String product_id =Request["product_id"]

String sql = "select * from productswhere id = @product_id"

SqlCommand command = newSqlCommand(sql,connection)

command.Parameters.Add("@product_id",SqlDbType.VarChar,30);

command.Parameters["@product_id"].Value=product_id;

 

2.通过传递参数的方式

2 By way of passing parameters

string sql = "SELECT * FROM productsWHERE id = @id";

SqlParameter parameter = new SqlParameter("@id",product_id);

command.Parameters = parameter;

 

3.通过存储过程

3.through stored procedures

create procedure products_info

@product_id varchar(30),

as

select * from products where id =@product_id

go

 

execute products_info

 

4.通过过滤非法字符串

4.Illegal string through the filter

public static string filtRiskChar(stringstr) //过滤非法字符   

{      

 string s = "";  

 s =str.Replace("'", " ");       

 s =s.Replace(";", " ");       

 s =s.Replace("1=1", " ");   

 s =s.Replace("|", " ");       

 s =s.Replace("<", " ");       

 s =s.Replace(">", " ");   

 return s;  

 }

 

 
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐