English
 电子信箱
 加入收藏

  威盾防火墙 >> 新闻中心 >> 威盾新闻 >> 防止SQL注入

 

防止SQL注入

威盾防火墙 2015-01-06

 

一个恐怖的例子:

注入式攻击的详细解释SQL下面我们将以一个简单的用户登陆为例,结合代码详细解释一下SQL注入式攻击,与及他的防范措施。对于一个简单的用户登陆可能的代码如下:
try
{
 string strUserName = this.txtUserName.Text;
 string strPwd = this.txtPwd.Text;
 string strSql = "select * from userinfo where UserName='" + strUserName + "' and Password='" + strPwd + "'";
 SqlConnection objDbConn = new SqlConnection("数据库连接字符串");
 SqlDataAdapter objAdapter = new SqlDataAdapter(strSql,objDbConn);
 DataSet objDataSet = null;
 objAdapter.Fill(objDataSet);//TODO 对获取的数据进行判断。
}
catch (System.Exception e)
{
 this.lblMsg.Text = e.Message;
 this.lblMsg.Visible = true;
}
  在上面这段代码中,如果用户的输入是正常的用户名和密码的话,那么执行都会比较正常,但是,假如输入用户名的时候,输入的是“johny’--”的话,在 SQLServer里面执行的语句将会是“select * from userinfo where UserName=’johny’--‘ and Password=’密码’”,只要数据库中存在johny这个用户的话,那么不管密码是什么,语句都能够执行成功,并且能够顺利通过登陆。还 有更加厉害的,我们知道SQLServer里面有一些系统的存储过程,能够执行操作系统的很多命令,比如xp_cmdshell,假如上面用户登陆的时 候,用户名部分输入的是“johny’ exec xp_cmdshell ‘format d:/s’--”,大家想想一下后果是什么?有恶意的用户,只要把’format d:/s’这个命令稍加改造就能够做很多不合法的事情。

 

.NET防SQL注入方法


1,利用SqlCommand传参数的方法:

string strSQL="SELECT * FROM [user] WHERE user_id=@id";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = strSQL;
cmd.Parameters.Add("@id",SqlDbType.VarChar,20).Value=Request["id"].ToString();

  

2,过滤禁止运行法:

/// <summary>
/// 过滤SQL语句,防止注入
/// </summary>
/// <param name="strSql"></param>
/// <returns>0 - 没有注入, 1 - 有注入 </returns>
public int filterSql(string sSql)
{
    int srcLen, decLen = 0;
    sSql = sSql.ToLower().Trim();
    srcLen = sSql.Length;
    sSql = sSql.Replace("exec", "");
    sSql = sSql.Replace("delete", "");
    sSql = sSql.Replace("master", "");
    sSql = sSql.Replace("truncate", "");
    sSql = sSql.Replace("declare", "");
    sSql = sSql.Replace("create", "");
    sSql = sSql.Replace("xp_", "no");
    decLen = sSql.Length;
    if (srcLen == decLen) return 0; else return 1;        
}

3,存储过程


js版的防范SQL注入式攻击代码:

 

<script language="javascript">
<!--
var url = location.search;
var re=/^\?(.*)(select%20|insert%20|delete%20from%20|count\(|drop%20table|update%20truncate%20|asc\(|mid\(|char\(|xp_cmdshell|exec%20master|net%20localgroup%20administrators|\"|:|net%20user|\|%20or%20)(.*)$/gi;
var e = re.test(url);
if(e) {
    alert("地址中含有非法字符~");
    location.href="error.asp";
}
//-->
<script>

 

  

 


总结:在编写代码前一定要细心考虑每种存在的安全性隐患。


相关内容: 最新内容:
解析阻止或减轻SQL注入攻击实用招数[2015-01-05]
网站SQL注入防御实战演示经典版![2015-01-05]
“SQL注入”的前世今生和防御思路[2015-01-05]
T-SQL篇如何防止SQL注入的解决方法[2015-01-05]
新手入门:防范SQL注入攻击的新办法[2015-01-05]
SQL Server网站防注入终极解决方案[2015-01-05]
Apache 防盗链(Apache Anti-Leech)技术的简单实现[2015-01-06]
如何打造一款可靠的WAF(Web应用防火墙)[2015-01-06]
php xss过滤[2015-01-06]
Wp博客被挂马怎么办[2015-01-06]
Php最不安全,Nginx比Apache安全[2015-01-06]
后台post注入爆密码[2015-01-06]