存储过程替换Ntext类型字段中被SQL注入式攻击后的注入代码
ASP.net后台代码
protected void Button1_Click(object sender, EventArgs e)
{
string aaaa = this.TextBox3.Text.Trim(); //字段名
string bbbb = this.TextBox1.Text.Trim(); //需要替换的字符
string cccc = this.TextBox2.Text.Trim(); //替换后的字符
if (this.TextBox2.Text == "") //如果没有输入用于替换的字符,则赋予空值
{
cccc = null;
}
//在 T-SQL 中,两个单引号表示一个单引号(''表示为')
//Update [数据表名] SET [字段名] = REPLACE([字段名],'老字符串','新字符串')
//string sqlStr = "Update 表名 set nkey = REPLACE(nkey,',','>') where nkey like '%,%'";
if (aaaa == "字段名") //如果字段名是 字段名 ,因为字段名是Ntext数据类型
{
string ConnectionString = 链接数据库的链接字符串;
SqlConnection conn = new SqlConnection(ConnectionString);
conn.Open();
//设定SqlCommand的属性
SqlCommand cmd = new SqlCommand("存储过程名", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@SourceStr", SqlDbType.VarChar, 1000).Value = this.TextBox1.Text.Trim(); //需要替换的字符
cmd.Parameters.Add("@ReplaceStr", SqlDbType.VarChar, 1000).Value = this.TextBox2.Text.Trim(); //替换后的字符
cmd.CommandTimeout=600; //等待时间
cmd.ExecuteNonQuery(); //执行SqlCommand命令
}
else //不是 Ntext 类型
{
string sqlStr = "Update 表名 set " + aaaa + "= REPLACE(" + aaaa + ",'" + bbbb + "'," + "'" + cccc + "')";
string connstring = 链接数据库的链接字符串;
using (SqlConnection con = new SqlConnection(connstring))
{
con.Open();
SqlHelper.CreateSqlTable(connstring, sqlStr);
Response.Write("
"); //2"'
}
}
}
存储过程的内容
ALTER PROCEDURE [dbo].[newUsersProc_Replace]
@SourceStr Varchar(1000),
@ReplaceStr Varchar(1000)
AS
BEGIN
--定义替换的字符串
declare @s_str varchar(8000),@r_str varchar(8000)
select @s_str=@SourceStr --要替换的字符串
,@r_str=@ReplaceStr --替换成的字符串
--替换处理
declare @id int,@ptr varbinary(16)
declare @start int,@s nvarchar(4000),@len int
declare @s_str1 nvarchar(4000),@s_len int,@i int,@step int
select @s_str1=reverse(@s_str),@s_len=len(@s_str)
,@step=case when len(@r_str)>len(@s_str)
then 4000/len(@r_str)*len(@s_str)
else 4000 end
declare tb cursor local for
select articleID,start=charindex(@s_str,[字段名])-1
from 表名
where charindex(@s_str,字段名)>0
--这里可以定义要处理的记录的条件
open tb
fetch tb into @id,@start
while @@fetch_status=0
begin
select @ptr=textptr([字段名])
,@s=substring([字段名],@start+1,@step)
from [表名]
where articleID=@id
while len(@s)>=@s_len
begin
select @len=len(@s),@i=charindex(@s_str1,reverse(@s))
if @i>0
begin
select @i=case when @i>=@s_len then @s_len else @i end
,@s=replace(@s,@s_str,@r_str)
updatetext [表名].[字段名] @ptr @start @len @s
end
else
set @i=@s_len
select @start=@start+len(@s)-@i+1
,@s=substring([字段名],@start+1,@step)
from [表名]
where articleID=@id
end
fetch tb into @id,@start
end
close tb
deallocate tb
end