0

Think bobby drop tables, now consider the following:

$dbh = new PDO("mysql:host=...;dbname=mysql", ...);


$dbh->query("use newdatabase");

This seems super insecure. Why would I ever want this? Because I have built my own database connection tool and the last part is allowing you to specify which database to use. My connection tool returns a \PDO object at the end of the day regardless of which type of database server you connect to: pgsql, mysql or sqlite.

The issue with this is that if I create a setDatabase(string $database) then you could be malicious. Is the appropriate way to do it through the connection string and then connect? Or is there a safe way where I could connect, then set the database?

TheWebs
  • 12,470
  • 30
  • 107
  • 211

2 Answers2

2

I believe this is safe. As long as no user input is fed to setDatabase(). If user input does need to get passed to setDatabase() you could use some form of whitelist of available databases.

Put simply: it's safe since there's no user input and no opportunity for injection.

Enstage
  • 2,106
  • 13
  • 20
  • Accept there would be: $databaseName. The way I designed his, which might be wrong, is that you can connect with out setting a database for the connection string, connect and then later set said database name. Hence me asking if this is wrong and what's the right way is. – TheWebs May 17 '17 at 04:23
  • No, that's perfectly fine. – Enstage May 17 '17 at 04:24
  • You also mentioned white listing the database names, well you technically couldn't, because the user could do a sql create script and call their database what ever they want, so maybe create database blog and then it would be setDatabase('blog') thisnis why I was curious if this would be a security issue. – TheWebs May 17 '17 at 04:26
  • If you let the user set the database dynamicly however, you atleast need a kind of blacklist to limit access to databases that is either reserved for the server itself, and if there are certain admin settings or otherwise important content you dont want the user to mess with directly – Troels M. B. Jensen May 17 '17 at 07:02
-2

Whatever the query is and whether you're using prepared statements, you can secure your script from SQL injection following these two steps:

1. Always escape user input

<?php
    $user_input = htmlspecialchars($user_input, ENT_QUOTES | ENT_HTML5, "UTF-8", false);

Escaping it like this will protect you from SQL Injection and XSS atacks.

2. Always wrap values with quotes

SELECT * FROM `table` WHERE `value` = "some value here";

If you are using WHERE and comparing integers you are not obligated to wrap the value with quotes, but in that case someone and easily do SQL Injection, and htmlspecialchars can't protect you then.

b0ne
  • 653
  • 3
  • 10