Escaping output safely for both html and input fields

13,932

Solution 1

I'm sorry but I cannot reproduce the behaviour you describe. I've always used htmlspecialchars() (which does essentially the same task as htmlentities()) and it's never lead to any sort of double-encoding. The page source shows déjà vu in both places (of course! that's the point!) but the rendered page shows the appropriate values and that's what sent back to the server.

Can you post a full self-contained code snippet that exhibits such behaviour?

Update: some testing code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>

<?php

$default_value = 'déjà vu <script> ¿foo?';

if( !isset($_GET['foo']) ){
    $_GET['foo'] = $default_value;
}

?>

<form action="" method="get">
    <p><?php echo htmlentities($_GET['foo']); ?></p>
    <input type="text" name="foo" value="<?php echo htmlentities($_GET['foo']); ?>">
    <input type="submit" value="Submit">
</form>

</body>
</html>

Answer to updated question

The htmlentities() function, as its name suggests, is used when generating HTML output. That's why it's of little use in your second example: JavaScript is not HTML. It's a language of its own with its own syntax.

Now, the problem you want to fix is how to generate output that follows these two rules:

  1. It's a valid string in JavaScript.
  2. It can be embedded safely in an HTML document.

The closest PHP function for #1 I'm aware of is json_encode(). Since JSON syntax is a subset of JavaScript, if you feed it with a PHP string it will output a JavaScript string.

As about #2, once the browser enters a JavaScript block it expects a </script> tag to leave it. The json_encode() function takes care of this and escapes it properly (<\/script>).

My revised test code:

<?php

$default_value = 'déjà vu </script> ¿foo?';

if( !isset($_GET['foo']) ){
    $_GET['foo'] = $default_value;
}

?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript"><!--
$(function(){
    $("input[type=text]").val(<?php echo json_encode(utf8_encode($_GET['foo'])); ?>);
});
//--></script>
</head>
<body>


<form action="" method="get">
    <p><?php echo htmlentities($_GET['foo']); ?></p>
    <input type="text" name="foo" value="(to be replaced)">
    <input type="submit" value="Submit">
</form>

</body>
</html>

Note: utf8_encode() converts from ISO-8859-1 to UTF-8 and it isn't required if your data is already in UTF-8 (recommended).

Solution 2

If you just need to reverse the encode then you can use html_entity_decode - http://www.php.net/manual/en/function.html-entity-decode.php.

Another possibility to is only run htmlentities at the time the content will be displayed as part of a web page. Otherwise, keep the unencoded text, as submitted or loaded from your datastore.

Share:
13,932
Tesserex
Author by

Tesserex

I enjoy writing games to improve my coding skills.

Updated on June 04, 2022

Comments

  • Tesserex
    Tesserex almost 2 years

    In my web app, users can input text data. This data can be shown to other users, and the original author can also go back and edit their data. I'm looking for the correct way to safely escape this data.

    I'm only sql sanitizing on the way in, so everything is stored as it reads. Let's say I have "déjà vu" in the database. Or, to be more extreme, a <script> tag. It is possible that this may be valid, and not even maliciously intended, input.

    I'm using htmlentities() on the way out to make sure everything is escaped. The problem is that html and input fields treat things differently. I want to make sure it's safe in HTML, but that the author when editing the text, sees exactly what they typed in the input fields. I'm also using jQuery to fill form fields with the data dynamically.

    If I do this:

     <p><?=htmlentities("déjà vu");?></p>
     <input type=text value="<?=htmlentities("déjà vu");?>">
    

    The page source puts d&eacute;j&agrave; vu in both places (I had to backtick that or you would see "déjà vu"!) The problem is that the output in the <p> is correct, but the input just shows the escaped text. If the user resubmits their form, they double escape and ruin their input.

    I know I still have to sanitize text that goes into the field, otherwise you can end the value quote and do bad things. The only solution I found is this. Again, I'm using jQuery.

    var temp = $("<div></div>").html("<?=htmlentities("déjà vu");?>");
    $("input").val(temp.html());
    

    This works, as it causes the div to read the escaped text as encoded characters, and then the jquery copies those encoded characters to the input tag, properly preserved.

    So my question: is this still safe, or is there a security hole somewhere? And more importantly, is this the only / correct way to do this? Am I missing something about how html and character encoding works that make this a trivial issue to solve?

    EDIT

    This is actually wrong, I oversimplified my example to the point of it not working. The problem is actually because I'm using jQuery's val() to insert the text into the field.

    <input>
    <script>$("input").val("<?=htmlentities("déjà vu");?>");</script>
    

    The reason for this is that the form is dynamic - the user can add or remove fields at will and so they are generated after page load.

    So it seems that jQuery is escaping the data to go into the input, but it's not quite good enough - if I don't do anything myself, a user can still put in a </script> tag, killing my code and inserting malicious code. But there's another argument to be made here. Since only the original author can see the text in an input box anyway, should I even bother? Basically the only people they could execute an XSS attack against is themselves.