note 98360 modified in function.htmlspecialchars-decode by danbrown

From: Date: Thu, 10 Jun 2010 17:12:41 +0000
Subject: note 98360 modified in function.htmlspecialchars-decode by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-170030@lists.php.net to get a copy of this message
Keep in mind that you should never trust user input - particularly for "mixed-bag" input containing a combination of plain text and markup or scripting code. Why? Well, consider someone sending '&amp;<script>alert('XSS');</script>' to your PHP script: <?php $var = "&amp;<script>alert('XSS');</script>"; $var = (htmlspecialchars_decode($var) == $var) ? htmlspecialchars($var) : $var; echo $var; ?> Since '&amp;' decodes into '&', (htmlspecialchars_decode($var) == $var) will be -false-, thus returning $var without that it's escaped. In consequence, the script-tags are untouched, and you've just opened yourself to XSS. There is, unfortunately, no reliable way to determine whether HTML is escaped or not that does not come with this caveat that I know of. Rather than try and catch the case 'I've already encoded this', you are better off avoiding double-escaping by simply escaping the HTML as close to the actual output as you can muster, e.g. in the view in an MVC development structure. --was-- [@Editors: If you are rejecting this comment, could you please let me know? I really figure it helps to have this in the comments. If you disagree, just tell me, I'll stop trying to put it there. :( I'd just like to know why you keep removing it.] If you're enticed by benharold at mac dot com's html escaping trick, keep in mind he said: "Now, if your dealing with text that is a mixed bag (has HTML entities and non-HTML entities) you're on your own." That means you should never trust user input with that particular ternary construct. Why? Well, consider someone sending '&amp;<script>alert('XSS');</script>' to your PHP script: <?php $var = "&amp;<script>alert('XSS');</script>"; $var = (htmlspecialchars_decode($var) == $var) ? htmlspecialchars($var) : $var; echo $var; ?> Since '&amp;' decodes into '&', (htmlspecialchars_decode($var) == $var) will be -false-, thus returning $var without that it's escaped. In consequence, the script-tags are untouched, and you've just opened yourself to XSS. There is, unfortunately, no reliable way to determine whether HTML is escaped or not that does not come with this caveat that I know of. Rather than try and catch the case 'I've already encoded this', you are better off avoiding double-escaping by simply escaping the HTML as close to the actual output as you can muster, e.g. in the view in an MVC development structure. http://php.net/manual/en/function.htmlspecialchars-decode.php

« previous php.notes (#170030) next »