MySQL Injection Damages

what sql injection can do to harm you

Potentially, sure. If you can inject a DROP TABLE table; into the SQL statement that is executed, you could just as easily inject an UPDATE statement that modified whatever rows of whatever tables you'd like. You can also frequently add or modify a SELECT statement to show you information that you're interested in. For example, if you have a query like

select name
from people
where person_id = '$person'

you could inject something like

anything` union all select table_name from information_schema.tables

to produce a statement like

select name
from people
where person_id = 'anything'
union all
select table_name
from information_schema.tables

to show you all the tables. You can do the same sort of thing to get a list of columns in the tables and then start running queries to see what data is in the various tables.

How can I prevent SQL injection in PHP?

The correct way to avoid SQL injection attacks, no matter which database you use, is to separate the data from SQL, so that data stays data and will never be interpreted as commands by the SQL parser. It is possible to create an SQL statement with correctly formatted data parts, but if you don't fully understand the details, you should always use prepared statements and parameterized queries. These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL.

You basically have two options to achieve this:

  1. Using PDO (for any supported database driver):

    $stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');
    $stmt->execute([ 'name' => $name ]);

    foreach ($stmt as $row) {
    // Do something with $row
    }
  2. Using MySQLi (for MySQL):

Since PHP 8.2+ we can make use of execute_query() which prepares, binds parameters, and executes SQL statement in one method:

$result = $dbConnection->execute_query('SELECT * FROM employees WHERE name = ?', [$name]);

while ($row = $result->fetch_assoc()) {
// Do something with $row
}

Up to PHP8.1:

$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
$stmt->bind_param('s', $name); // 's' specifies the variable type => 'string'
$stmt->execute();

$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Do something with $row
}

If you're connecting to a database other than MySQL, there is a driver-specific second option that you can refer to (for example, pg_prepare() and pg_execute() for PostgreSQL). PDO is the universal option.



Correctly setting up the connection

PDO

Note that when using PDO to access a MySQL database real prepared statements are not used by default. To fix this you have to disable the emulation of prepared statements. An example of creating a connection using PDO is:

$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8mb4', 'user', 'password');

$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

In the above example, the error mode isn't strictly necessary, but it is advised to add it. This way PDO will inform you of all MySQL errors by means of throwing the PDOException.

What is mandatory, however, is the first setAttribute() line, which tells PDO to disable emulated prepared statements and use real prepared statements. This makes sure the statement and the values aren't parsed by PHP before sending it to the MySQL server (giving a possible attacker no chance to inject malicious SQL).

Although you can set the charset in the options of the constructor, it's important to note that 'older' versions of PHP (before 5.3.6) silently ignored the charset parameter in the DSN.

Mysqli

For mysqli we have to follow the same routine:

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // error reporting
$dbConnection = new mysqli('127.0.0.1', 'username', 'password', 'test');
$dbConnection->set_charset('utf8mb4'); // charset


Explanation

The SQL statement you pass to prepare is parsed and compiled by the database server. By specifying parameters (either a ? or a named parameter like :name in the example above) you tell the database engine where you want to filter on. Then when you call execute, the prepared statement is combined with the parameter values you specify.

The important thing here is that the parameter values are combined with the compiled statement, not an SQL string. SQL injection works by tricking the script into including malicious strings when it creates SQL to send to the database. So by sending the actual SQL separately from the parameters, you limit the risk of ending up with something you didn't intend.

Any parameters you send when using a prepared statement will just be treated as strings (although the database engine may do some optimization so parameters may end up as numbers too, of course). In the example above, if the $name variable contains 'Sarah'; DELETE FROM employees the result would simply be a search for the string "'Sarah'; DELETE FROM employees", and you will not end up with an empty table.

Another benefit of using prepared statements is that if you execute the same statement many times in the same session it will only be parsed and compiled once, giving you some speed gains.

Oh, and since you asked about how to do it for an insert, here's an example (using PDO):

$preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)');

$preparedStatement->execute([ 'column' => $unsafeValue ]);


Can prepared statements be used for dynamic queries?

While you can still use prepared statements for the query parameters, the structure of the dynamic query itself cannot be parametrized and certain query features cannot be parametrized.

For these specific scenarios, the best thing to do is use a whitelist filter that restricts the possible values.

// Value whitelist
// $dir can only be 'DESC', otherwise it will be 'ASC'
if (empty($dir) || $dir !== 'DESC') {
$dir = 'ASC';
}

Can I use SQL injection to alter server db?

It depends on the privileges granted to the database account, the database user that the web server uses to connect to the database, and the nature of the SQL Injection vulnerability.

If the vulnerability is open enough to allow you to extract all data from all tables, it's likely that the website is vulnerable to creation and alteration of procedures, as well INSERT/UPDATE/DELETE operations on tables. (That same inattention and lack of care that goes into creating websites that are vulnerable to SQL Injection, that's often the same kind of inattention that's dedicated to determining database privileges... (I'll just use "root", or I'll use a database account that has all privileges on all objects...)

It's entirely possible, and relatively easy, to create a website that is vulnerable to this kind of injection.

(And StackOverflow questions and answers are rife with examples of the kind of code you would need to make a website vulnerable in this way. SQL Injection vulnerabilities are just the tip of the iceberg... if a website is insecure in this way, it's almost a given that there are other vulnerabilities. (SQL Injection just happens to be a very easy vulnerability to exploit.)

And these insecure patterns that developers become accustomed to...

(after all, this website I'm developing "is only for development/education/my use/et al.", "so security isn't a concern", or "i'll address the security vulnerabilities after I get all of it developed, debugged, tested" yada, yada, yada

... those patterns for writing insecure code becomes firmly entrenched.

SQL Injection and the LIMIT clause

The LIMIT clause is vulnerable to SQL injection, even when it follows an ORDER BY, as Maurycy Prodeus demonstrated earlier this year:

mysql> SELECT field FROM user WHERE id >0 ORDER BY id LIMIT 1,1
procedure analyse(extractvalue(rand(),concat(0x3a,version())),1);
ERROR 1105 (HY000): XPATH syntax error: ':5.5.41-0ubuntu0.14.04.1'

Voilà! The above solution is based on handy known technique of so-called error based injection. If, therefore, our vulnerable web application discloses the errors of the database engine (this is a real chance, such bad practices are common), we solve the problem. What if our target doesn’t display errors? Are we still able to exploit it successfully?

It turns out that we can combine the above method with another well-known technique – time based injection. In this case, our solution will be as follows:

SELECT field FROM table WHERE id > 0 ORDER BY id LIMIT 1,1
PROCEDURE analyse((select extractvalue(rand(),
concat(0x3a,(IF(MID(version(),1,1) LIKE 5, BENCHMARK(5000000,SHA1(1)),1))))),1)

It works. What is interesting that using SLEEP is not possible in this case. That’s why there must be a BENCHMARK instead.

Stop ongoing MySQL injection

You could set the database into read-only mode, if your application can handle it - and I stress the IF.

Still, that leaves the wide field of information-disclosure vulnerability (e.g. if you encrypted passwords instead of hashing them with a strong hash algorithm + salt, birthday dates (credit card fraud), email addresses - spammers lov'em).

The only way to really prevent the leak from being exploited is to take the database offline IMMEDIATELY, fix the bugs, and then put it back online as fast as possible.

An intermediate solution would be to backup the database (after setting it read-only), and then update all confidential information with bogus information on the online version.

e.g.

UPDATE T_Users SET e_mail = 'undisclosed@undisclosed.com', birthdate = '19000101'

SQL Injection Trap - what does this mean

The attacker is trying to inject a UNION SELECT that is wrapped in a MySQL’s variant of C style comments, which allow a conditional exclusion of the contents.

In this case the comment would not be considered a comment if the MySQL version is greater or equal to 3.0.0. In that case a UNION SELECT with strings in hexadecimal notation (i. e., 0x31303235343830303536) equivalent to '1025480056' gets appended to the existing statement. Any remaining code in the same line is ignored by injecting the line-end comment -- .



Related Topics



Leave a reply



Submit