在ASP.net中如何预防SQL注入式攻击

时间:2022-09-15 08:16:49

摘 要:分析sql注入攻击,提出防范SQL注入式攻击的方法。

关键词:SQL注入攻击;

中图分类号:TP文献标识码:A文章编号:1672-3198(2008)10-0354-01

SQL注入式攻击是指利用程序设计上的漏洞,在目标服务器上运行SQL命令以及其他命令的攻击,动态生成SQL命令时没有对用户输入的数据进行验证,是SQL注入攻击得逞的主要原因。

例如,如果用户的查询语句是select count(*) from tab_userwhere name=' " & user & " 'and password = ' " & pwd & " ' ,那么,如果name字段的值为1'or'1'='1 ,则查询语句将会变成:

Select count(*) from tab_user where name='1' or '1' = '1' and password = ' " & pwd & " '。

以上输入经系统核对无误运行后,注入者将通过验证,进入程序管理界面,从而获得软件的管理权限,对系统安全造成一定程度的威胁。由此可见,防范SQL注入式攻击对于系统安全有着至关重要的作用。

防范SQL注入式攻击的方法之一是,对用户输入的信息进行检查。特别是一些特别字符,比如单引号、双引号、分号、逗号、冒号和连接号等。对这些字符进行转换或者过滤,可有效防止攻击的发生。

在代码中使用如下子程序可有效过滤特殊字符及字符串:

///inputString为用户输入需过滤的字符串

Public string ConvertSql(string inputString)

{

inputString = inputString.Trim();

inputString = inputString.Replace("' ", " " ");

inputString = inputString.Replace(";―― ", " ");

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

inputString = inputString.Replace("or", " ");

inputString = inputString.省略中并非最有效的防范手段,最佳方法是通过SqlCommand.Parameters属性的参数传值方法实现防范,这样一来可以通过参数将非法字符过滤掉。代码如下:

Public int checkLogin(string namevalue,string pwdvalue)

{

SqlConnection conn = new SqlConnection(ConfigurationManager. AppSettings["connstr"]);

///从web.config中读出connstr对应的键值;

SqlCommand cmd= new SqlCommand("select count(*) from tab_user where name=@name_param and password=@pwd_param " ,conn);

///动态创建SQL语句,其中声明两个参数name_param和pwd_param;

cmd.Parameters.Add(new SqlParameter("@name_param",SqlDbType.NVarChar,20));

///动态创建参数name_param;

cmd.Parameters["name_param"].Value=namevalue;

///对参数name_param进行赋值;

cmd.Parameters.Add(new SqlParameter("@pwd_param",SqlDbType.NVarChar,20));

///动态创建参数pwd_param;

cmd.Parameters[“pwd_param”].Value=pwdvalue;

///对参数pwd_param进行赋值;

cmd.Connection.Open();

///打开数据链接;

int I = ( int ) cmd.ExecuteScalar();

///运行SQL语句,并提取返回值;

cmd.Connection.Close();

///关闭数据连接;

return I;

///返回结果;

上一篇:引力发散悖论研究 下一篇:基于Web Services的PDM系统的研究与实现