I want example of why replacing ' with '' and for parameters of a query is dangerous

Asked

Viewed 63 times

0

I see many posts on this subject, but I do not see any example that has fit for this my case.

function sanitize($value)
{
    $val = str_replace("'", "''", $value);
    $val = str_replace("\\", "\\\\", $val);

    return $val;
}

The query would be mysqli_query($conn,"insert into tabela (Nome) values ('".sanitize($ipt)."')") Whereas even int will enter this procedure above and considering that all querys will be written EXACTLY this way, with parameters marked with '(single quotes), which input would be able to break the security and cause an Injection?

  • 1

    If there is an error or not I can not say, but I would guess that maybe exists. The best alternative would be to use the mysqli_real_escape_string($ipt). You can use prepared statements (that is, use the mysqli_prepare () and then the mysqli_bind_param()) this solution may be more difficult to apply, requiring more changes. I believe this will be better than trying to "reinvent" the wheel.

1 answer

2

In your example the insertion is actually escaping the characters in order to avoid Injection. Ok.

The big problem is just the way you’re gonna do it:

whereas even int will enter into this procedure above and whereas all querys will be written EXACTLY of this way [...]

How will you ensure this with extreme certainty? If you forget the sanitize in a single query, how will you figure it out? Just one place and your site will be vulnerable.

If something has a chance to go wrong, it WILL go wrong... So why give chance to bad luck?

If the language offers ways to prevent such problems natively, what is the problem of using this solution?

We have the Prepared statments in the mysqli, in the PDO, where the Sanitize of the query is made assertively and transparently that it is incoherent not to use them if you know of its existence.

Code maintenance is also easier. See an example:

$connection = new PDO('mysql:dbname=test;host=127.0.0.1', 'db', 'pass');

$stment = $connection->prepare('INSERT INTO user VALUES (:id, :name, :idade);');
$stment->bindParam(':id', $id, PDO::PARAM_INT);
$stment->bindParam(':name', $name, PDO::PARAM_STR, 25);
$stment->bindParam(':idade', $idade, PDO::PARAM_INT);

$id = 1;
$name = 'Joao';
$idade = 18;

$stment->execute();

The code above is no clearer than the code below?

$connection = new PDO('mysql:dbname=test;host=127.0.0.1', 'db', 'pass');

$id = 1;
$name = 'Joao';
$idade = 18;

$connection->query("INSERT INTO user VALUES ('" . sanitize($id) . "', '" . sanitize($name) "','" . sanitize($idade) . "');");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.