1

i'm having trouble with security for a website. I've been using php with PDO. So what i want to avoid is if a user inputs code into message box that executes when it is sent. So for example purposes if the user enters the following <?php echo "123"; ?> into my current message box, it'll send a blank box to the recipient. My code is the following;

$insert = $pdo->prepare("INSERT INTO message (sender_id,recipient_id,subject,message,reference_id) VALUES(:userID,:recipientID,:subject,:msg,:ref)");
$insert->bindParam(':userID', $user['user_id'], PDO::PARAM_INT);
$insert->bindParam(':recipientID', $recipientId['user_id'], PDO::PARAM_INT);
$insert->bindParam(':subject', $subject, PDO::PARAM_STR);
$insert->bindParam(':msg', $msg, PDO::PARAM_STR);
$insert->bindParam(':ref', $newRef, PDO::PARAM_INT);
$insert->execute();

I pretty much want anything a user enters into the message box to be converted into a string before POST-ing to the database. So in this case the recipient would receive the message <?php echo "123"; ?> instead of a blank box. Note, i was under the impression that i already sanitize the user input during the variable binding ($insert->bindParam) and that this was sufficient enough that people could not enter code in the message box. But i am told that they can and have drop tables successfully for example in my database as a test.

sw19
  • 25
  • 2
  • The code looks fine afaics and should allow the user to put in whatever they want without you worrying about SQL injection (as long as emulated prepares is turned off). Have you checked the DB to see if the variables are input? What code is outputting? – Jonnix May 20 '15 at 09:49
  • Take a look on this on how PDO can be made vulnerable : http://stackoverflow.com/a/12202218/1218075 – Makesh May 20 '15 at 09:50

2 Answers2

1

It seems that you are conflating SQL injection with XSS. The PDO parameterization is securing your system from SQL injection, but the content could still be used for XSS.

Continue saving data in your database as you are doing now, but when you must echo out the contents, use htmlentities() as so:

foreach ( $row = stmt->fetchRow(PDO::FETCH_ASSOC) ) {
    echo 'Hello ' . htmlentities($row['username']) . '!';
}

The htmlentities() function will properly escape the <>&'" characters to protect against XSS.

dotancohen
  • 30,064
  • 36
  • 138
  • 197
  • also just a query before i start using the htmlentities() function, if I escape the <>&'" characters, won't my echos not work? Or will my echo still work? – sw19 May 20 '15 at 11:39
  • Your echos will work fine. The 'escaping' is done by converting the characters to HTML entities, such as `<` for `<`. It is not simply placing backspaces before them, as is done with escaping quotes in SQL queries for example. – dotancohen May 20 '15 at 11:45
0

it is. once you use bind variables a string sent from a malicious user can't construct some other query you don't intend to.

gilg
  • 73
  • 7