HTML comments can be notoriously tricky from an XSS standpoint, and the standard recommendation seems to be to never put untrusted user data in them. But shouldn't it be possible to strip out a few characters and make it safe?

My theory is that the following should be enough:

If I strip them out, am I safe? Implemented in PHP you get:

function echo_html_comment($content) {
    // Warning! This code is untested and therefore unsafe. Do not use!
    $content = str_replace(['<', '>', '[', ']', '`'], '', $content);
    echo "<!-- $content -->";

I consider character encoding exploits outside the scope of the question. You can also assume that comments will only be put between HTML tags, not inside attributes or in other strange places.

You could easily make the argument that the risk is not worth it for something as pointless as a HTML comment, and I might agree. But what I am interested in here is if the above filter is actually breakable?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.