1

I am creating a website in php. One of the features is that users can edit their own pages by entering custom html code. Right now, you can enter code into a textarea and have it displayed in a div. In the future I plan on adding more helpful tools to the user.

My question is how to protect my site from malicious code. I know Facebook has an option to put custom HTML in a page tab so it can be done safely. Currently, the html is being displayed by a php script that echos it onto a page so users can enter javascript in <script> tags as well. I don't know the full limits of javascript and html but I know that custom javascript embedded into the website has the potential to screw things up.

Here are my ideas so far:

  • Remove all javascript from user code

    • Pros: Easy
    • Cons: Users can't do anything interesting with javascript
  • Limit the javascript to only execute inside the display div

    • Pros: Safe custom javascript
    • Cons: May be impossible/very difficult

If anyone has ideas about how to do this or how Facebook did this, I would love to know! Thanks in advance.

2
  • If they're allowing Javascript, they almost certain are putting it in an iframe so that it won't have any access to the main page. Commented Jun 28, 2014 at 5:40
  • I would put it in an iFrame but I want the html to have no css constraints from being inside an iframe. Commented Jun 28, 2014 at 5:56

1 Answer 1

2

If you are using php, an excellent solution is to use HTMLPurifier. It has many options to filter out bad stuff, and as a side effect, guarantees well formed html output.

Sign up to request clarification or add additional context in comments.

1 Comment

@Harrison: You should use it in combination with a Content Security Policy just in case any vulnerabilities in HTMLPurifier are found in future: security.stackexchange.com/a/61134/8340

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.