您的位置:首页 > 数据库

Servelt学习:SQL注入漏洞及其避免方法

2012-03-23 19:49 267 查看
SQL注入漏洞是指执行查询语句时在正常的查询语句之后加入 or 1='1'
例如将语句select * FROM [Students].[dbo].[User] where name='admin' and passwd='123'改写为

select * FROM [Students].[dbo].[User] where name='admin' and passwd='123' or 1='1'时便可以查询出数据表中全部内容(甚至name与passwd值可以随意乱填)

正常情况时得到正确的查询结果:



用户名或密码错误则无法获得查询结果



而在正常的查询语句之后加入or 1='1'却可以得到整个表的查询结果



黑客有可能利用SQL漏洞对网站进行攻击。其可以在用户名称栏中随意输入字符,密码栏中输入XXX' or 1='1便可以进入网站。

例如:


(数据库中无该用户)


(由于SQL漏洞,页面成功跳转)

解决方法:

不要用户名和密码同时进行验证,而是通过用户名去查询数据库,返回一个密码。然后用该密码与用户输入密码进行比较,如果相同则用户合法,否则为非法用户。

将查询语句:

ps=ct.prepareStatement("select top 1 * from [Students].[dbo].[User] where name='"+u+"'and passwd='"+p+"'");
rs=ps.executeQuery();
if(rs.next())
{

//跳转到welcome
res.sendRedirect("Wel?user="+u+"&pass="+p);
//HttpSession hs=req.getSession(true);
//hs.setAttribute("uname",u);
}else
{
res.sendRedirect("login");//写需要跳转的servlet的那个url
}


改为:

ps=ct.prepareStatement("select top 1 passwd from [Students].[dbo].[User] where name='"+u+"'");
rs=ps.executeQuery();
if(rs.next())
{
String dbPasswd=rs.getString(1);
System.out.println(dbPasswd);
if(dbPasswd.equals(p))

{
System.out.println(dbPasswd);
res.sendRedirect("Wel?user="+u+"&pass="+p);
HttpSession hs=req.getSession(true);
hs.setAttribute("uname",u);
}

}else//说明用户名不存在
{
res.sendRedirect("login");//写需要跳转的servlet的那个url
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: