0

I have a problem with restricting malicious content in a field which can accept any input from the user.

I have to encode that field and save it in the database - see examples:

1st example

<space> is saved as &lt;space&gt;

2nd example (malicious text)

"><svg/onload=prompt(1)> is saved as &quot;&gt;&lt;svg/onload=prompt(1)&gt;

Now in reports I have to decode that into actual text, but the second text is malicious script now. What should I do?

Is there any other way to stop malicious text on both client and server side?

9
  • 1
    " I have to decode that into actual text,"...Do you? Why? Leave it encoded, problem solved. That was the whole point of encoding it in the first place. If you're just going to decode it again when you display it, you've defeated the entire purpose of adding this protection. Putting malicious HTML into a database isn't, in itself, a problem - databases don't care about HTML or script. It's only a problem when you come to re-display it again in a HTML document. Encoding it for storage, only to decode it again when retrieving it means you achieve nothing useful. Commented Jul 4, 2018 at 9:52
  • I agree with @ADyson . Save the text as it’s received and encode it before you serve it on the client site. Commented Jul 4, 2018 at 9:56
  • @crellee Glad you agree. One point though - it's going to be more efficient computation-wise to encode it once when it's received and stored, rather than having to repeatedly encode it every time it's displayed. Commented Jul 4, 2018 at 9:57
  • .. and you should always encode user input before you send it to other clients to prevent cross site scripting Commented Jul 4, 2018 at 9:58
  • 1
    Yes that will be it. In what kind of format you save the text is your decision. Like @ADyson said you will save some work for each request if you encode it before you store it in the database. But it’s still a matter of taste - I prefer to save the data as it is (unless I encrypt or hashes) so the data is easier to read and easier to access. So therefore for each request I will need to encode the text. But to answer your question; If you serve the text in HTML you MUST encode it first. Commented Jul 4, 2018 at 12:40

0

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.