OMG, why a note from nemozny at gmail dot com is still here? HOW MANY INJECTIONS it made possible?
Removing quotes from PDO::qiuote IS A DISASTER! Do not use that stupid substr() solution - it will actually open your query to injection.
PDO::quote
(PHP 5 >= 5.1.0, PECL pdo >= 0.2.1)
PDO::quote — Protège une chaîne pour l'utiliser dans une requête SQL PDO
Description
$string
[, int $parameter_type = PDO::PARAM_STR
] )PDO::quote() place des guillemets simples autour d'une chaîne d'entrée, si nécessaire et protège les caractères spéciaux présents dans la chaîne d'entrée, en utilisant le style de protection approprié au pilote courant.
Si vous utilisez cette fonction pour construire des requêtes SQL, vous êtes vivement invités à utiliser PDO::prepare() pour préparer les requêtes SQL avec des paramètres liés au lieu d'utiliser PDO::quote() pour interpréter les entrées utilisateur dans la requête SQL. Les requêtes préparées avec des paramètres liés sont non seulement plus portables, plus souples et plus sécuritaires, mais bien plus rapides à exécuter que d'interpréter les requêtes, étant donné que les côtés client et serveur peuvent mettre en cache une version compilée de la requête.
Tous les pilotes PDO n'implémentent pas cette méthode (comme PDO_ODBC). Utilisez les requêtes préparées à la place.
Securité : le jeu de caractères par défaut
Le jeu de caractères doit être défini soit au niveau du serveur, soit lors de la connexion à la base de données (suivant le driver utilisé) pour qu'il affecte la méthode PDO::quote(). Voir la documentation spécifique au driver pour plus d'informations.
Liste de paramètres
-
string -
La chaîne à protéger.
-
parameter_type -
Le type de données pour les drivers qui ont des styles particuliers de protection.
Valeurs de retour
Retourne une chaîne protégée, qui est théoriquement sûre à utiliser
dans une requête SQL. Retourne FALSE si le pilote ne supporte pas
ce type de protections.
Exemples
Exemple #1 Protection d'une chaîne normale
<?php
$conn = new PDO('sqlite:/home/lynn/music.sql3');
/* Chaîne simple */
$string = 'Nice';
print "Chaîne non échappée : $string\n";
print "Chaîne échappée : " . $conn->quote($string) . "\n";
?>
L'exemple ci-dessus va afficher :
Chaîne non échappée : Nice Chaîne échappée: 'Nice'
Exemple #2 Protection d'une chaîne dangereuse
<?php
$conn = new PDO('sqlite:/home/lynn/music.sql3');
/* Chaîne dangereuse */
$string = 'Chaîne \' particulière';
print "Chaîne non échappée : $string\n";
print "Chaîne échappée :" . $conn->quote($string) . "\n";
?>
L'exemple ci-dessus va afficher :
Chaîne non échappée : Chaîne ' particulière Chaîne échappée : 'Chaîne '' particulière'
Exemple #3 Protection d'une chaîne complexe
<?php
$conn = new PDO('sqlite:/home/lynn/music.sql3');
/* Chaîne complexe */
$string = "Co'mpl''exe \"ch'\"aîne";
print "Chaîne non protégée : $string\n";
print "Chaîne protégée : " . $conn->quote($string) . "\n";
?>
L'exemple ci-dessus va afficher :
Chaîne non échappée: Co'mpl''exe "ch'"aîne Chaîne échappée: 'Co''mpl''''exe "ch''"aîne'
Voir aussi
- PDO::prepare() - Prépare une requête à l'exécution et retourne un objet
- PDOStatement::execute() - Exécute une requête préparée
While rewriting some application to PDO, remember that PDO->quote is adding the quotes around the whole value! Compared to mysql_real_escape_string which is quoting only the dangerous characters.
<?php
$value = "hello's world";
echo mysql_real_escape_string($value);
// hello''s world
echo $dbh->quote($value);
// 'hello''s world'
// This second quoting will break your old SQL statements which includes the quotes already. Workaround is to remove first and last character
echo substr($dbh->quote($value), 1, -1);
// hello''s world
?>
Note that this function just does what the documentation says: It escapes special characters in strings.
It does NOT - however - detect a "NULL" value. If the value you try to quote is "NULL" it will return the same value as when you process an empty string (-> ''), not the text "NULL".
One have to understand that string formatting has nothing to do with identifiers.
And thus string formatting should NEVER ever be used to format an identifier ( table of field name).
To quote an identifier, you have to format it as identifier, not as string.
To do so you have to
- Enclose identifier in backticks.
- Escape backticks inside by doubling them.
So, the code would be:
<?php
function quoteIdent($field) {
return "`".str_replace("`","``",$field)."`";
}
?>
this will make your identifier properly formatted and thus invulnerable to injection.
However, there is another possible attack vector - using dynamical identifiers in the query may give an outsider control over fields the aren't allowed to:
Say, a field user_role in the users table and a dynamically built INSERT query based on a $_POST array may allow a privilege escalation with easily forged $_POST array.
Or a select query which let a user to choose fields to display may reveal some sensitive information to attacker.
To prevent this kind of attack yet keep queries dynamic, one ought to use WHITELISTING approach.
Every dynamical identifier have to be checked against a hardcoded whitelist like this:
<?php
$allowed = array("name","price","qty");
$key = array_search($_GET['field'], $allowed));
if ($key == false) {
throw new Exception('Wrong field name');
}
$field = $db->quoteIdent($allowed[$key]);
$query = "SELECT $field FROM t"; //value is safe
?>
(Personally I wouldn't use a query like this, but that's just an example of using a dynamical identifier in the query).
And similar approach have to be used when filtering dynamical arrays for insert and update:
<?php
function filterArray($input,$allowed)
{
foreach(array_keys($input) as $key )
{
if ( !in_array($key,$allowed) )
{
unset($input[$key]);
}
}
return $input;
}
//used like this
$allowed = array('title','url','body','rating','term','type');
$data = $db->filterArray($_POST,$allowed);
// $data now contains allowed fields only
// and can be used to create INSERT or UPDATE query dynamically
?>
For those of you who do want to have null returned as NULL, it is fairly easy to add.
<?php
class Real_PDO extends PDO {
public function quote($value, $parameter_type = PDO::PARAM_STR ) {
if( is_null($value) ) {
return "NULL";
}
return parent::quote($value, $parameter_type);
}
}
?>
then all you have to do is change your creation of the PDO object to this new class, and you shouldn't have to change any other function calls. The nice thing about this method is that you can override any PDO function or add your own. IMO, PDO should natively handle this, as there is a difference in databases between NULL and an empty string(''), the quoting of numeric values is another issue altogether.
