MrCode
MrCode

Reputation: 64526

Is addslashes() safe to prevent XSS in a HTML attribute?

I'm having to work on an old web app that a previous developer left. It is using addslashes() to prevent XSS on a HTTML attribute.

Here is an example:

<?php
  // all $_POST vars are put through addslashes()

  echo "<input type='hidden' value='" . $_POST['id'] . "' />";
?>

Is this vulnerable to XSS? Is there any way javascript can run in a value attribute like it can in an src attribute for example, src='javascript:alert(99)'. Or can the value attribute be broken out of and then script tags can be inserted?

Edit: Thanks to Quentin, I believe it is vulnerable.

Upvotes: 5

Views: 3346

Answers (2)

Quentin
Quentin

Reputation: 943211

Is addslashes() safe to prevent XSS in a HTML attribute?

It is highly ineffective.

Is this vulnerable to XSS?

Yes.

Is there any way javascript can run in a value attribute like it can in an src attribute for example, src='javascript:alert(99)'.

No

Or can the value attribute be broken out of and then script tags can be inserted?

The data just has to include a " and the attribute is broken out of.

Use htmlspecialchars when you want to insert an arbitrary string into an attribute value.

Upvotes: 9

Phil
Phil

Reputation: 164739

addslashes() is not appropriate for this task. Use htmlspecialchars() or htmlentities() instead, eg

<input type="hidden"
       value="<?php echo htmlspecialchars($_POST['id'], ENT_QUOTES, 'UTF-8') ?>">

Upvotes: 3

Related Questions