2

I have created a comment system where people comment on a topic. The comment is stored in a SQL database. Now, to avoid malicious links, or JS/HTML/PHP code to be inserted into the comment which could be executed.. How do I prevent this? Suppose the comment is a JS code.. Like

<script> document.DoSomething()</script>

How would I prevent this? Thanks.

Vishal Suthar
  • 17,013
  • 3
  • 59
  • 105
  • You could take in the the input of the field and run it through a script that strips the ` – pattmorter Jan 17 '14 at 06:22
  • possible duplicate of [What are the common defenses against XSS?](http://stackoverflow.com/questions/3129899/what-are-the-common-defenses-against-xss) – Quentin Jan 17 '14 at 07:04

2 Answers2

0

You need to scrub and/or encode user input that you're displaying.

Here is an example of how server emitting contents encodes it (this is Microsoft .NET)

<script><%=Html.Encode(serverSide.DoSomething())%></script>

Scrubbing is a popular topic. Most times it's better to use something that is ready, as the variations of such attacks are so many, that starting from scrach is usually not going to give you the coverage you'd get from existing libs. Look at this one for example: https://code.google.com/p/google-caja/

G. Stoynev
  • 7,389
  • 6
  • 38
  • 49
  • Actually, I used htmlspecialchars to filter it and now the code is just put as it is. AnyHREF tags don't work nor php or JS tags. Is it foolproof? – Rajat Pawar Jan 17 '14 at 07:05
0

Match the comment with a regex like so:

comment.match(/<script>.+</script>/)

If there is a match, then don't allow it.

Aashray
  • 2,753
  • 16
  • 22