Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - is it safe to check the 6 first characters of a query to be sure it is a SELECT?

Tags:

sql

php

mysql

A coworker of mine has written something really awful. Our boss wanted to be able to write any SELECT queries from the Back Office of our website, then get the result in CSV format.

Those queries will be executed by our PRODUCTION MySQL cluster. This back-office feature should reject any non-SELECT queries.

So he comes up with a really naive solution for that. This is the PHP code:

function checkQuery()
{
        $sQuery = trim($_POST['query']);
        if (empty($sQuery))
                return false;
        $sCmd = substr($sQuery, 0, 6);
        if (strtolower($sCmd) != 'select')
                return errorDiv('Only SELECT queries are authorized');
        return $sQuery;
}

For people not knowing PHP, this code removes white space from the begining and the end of an SQL query string, then get the 6 first characters, transforms them to lowercase characters, and if it doesn't match (erf... loosely match) 'select', the query is rejected.

It looks awful and disgusting to me. I tried to convince him to create at least another MySQL user, with limited privileges, but he is too lazy to do that.

However I cannot prove him that some kind of hacks are possible.

He uses mysql_query() to run the query string, and this driver rejects multiple queries at once. I can't find any real exploit, but I think there are at least 50% of chance that something bad can happen.

Maybe some NUL char, or some obscur utf-8 chars can do the trick?

like image 773
cronvel Avatar asked May 07 '14 13:05

cronvel


People also ask

How do I SELECT the first letter of a word in MySQL?

To fetch the first alphabet from the strings, use LEFT(). This method allows you to return characters from the left of the string.

Which of the following statements about MySQL is true?

1 Answer. Correct option is (b) The USE command is used to activate a database.

Does MySQL allow special characters?

Alternatively, MySQL also has special character escape sequences as shown below: \0 - An ASCII NUL (0x00) character. \' - A single quote ( ' ) character. \" - A double quote ( " ) character.


1 Answers

The correct approach to this feature (if you can't convince him it is a bad idea) is to run the queries as a limited MySQL user. Grant that user only the SELECT permission. You can also limit the table set if desired.

like image 196
Dark Falcon Avatar answered Sep 22 '22 10:09

Dark Falcon