1

I want to have a text area to post stuff to the database with BBCode. So, I downloaded a JavaScript code (to write in the specific BBCode when the image is clicked) but it didn't transform the text.

There are images of letters above the text area like B, I and U. When I click one of them, maybe B, the JavaScript inserts [b][/b] to the text area. But when I submit the text with some other text in the bold BBcode, it doesn't make the text bold.

So, I thought this would work:

str_replace('[', '<', $_POST['text']);    
str_replace(']', '>', $_POST['text']);

It worked but I can't add htmlentities() now which I've been using to prevent XSS. So, what other options do I have to stop XSS?

1
  • is this a security question? I'm not seeing security implications here.
    – schroeder
    Jun 19, 2016 at 9:40

1 Answer 1

4

Parsing BBCode in a safe way that does not open the doors to XSS hell is a tricky task, and there have been many failed attempts. As you yourself note, the way you currently do it is vulnerable to XSS - all you need to do is post [script src="evil.js"]. Just using htmlentities() will not solve this for you, it is much more complex. This blog illustrates the problem neatly.

So I would not recommend you to try to implement your own BBCode interpreter. Instead I would look at existing libraries, either in PHP or client side in JavaScript and evaluate their security record. Some places to start:

To add an extra layer of security you can run the generated HTML through a HTML sanitizer designed to "sandbox" HTML and keep any unwanted tags or attributes out (like script or onerror) in case the BBCode library should fail you. Some examples:

Do note that I have not evaluated the security of these libraries. Perhaps there are better alternatives - these are just provided here as examples. Whatever library you pick, you will need to look at its track record and decide for yourself if you trust it or not. And as usual, make sure to keep the libraries updated.

As SilverlightFox says in comments, as third layer of defense (for browsers that support it) you can set a content security policy that disallows inline scripts.

2
  • 2
    Also implementation of a content security policy if possible will mitigate any bypasses discovered within those HTML sanitizers. Jun 19, 2016 at 10:25
  • @SilverlightFox Good point! I will add that to my answer since it can not be said to many times.
    – Anders
    Jun 19, 2016 at 10:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .