Home > Net >  Prevent XSS attacks but still display single quotes for instance
Prevent XSS attacks but still display single quotes for instance

Time:03-26

I want to secure some inputs.

For instance, a free textarea where the user could write some sentences in it.

On the server side, I HTML & javascript encode:

_htmlEncoder.Encode(_javascriptEncoder.Encode(input))

But I struggle to make it painless for the user. For instance, If I enter the following french text:

C'est une phrase importante pour moi.

After the encoding, I will get:

C\u0026#x27;est une phrase importante pour moi.

The single quote is encoded. Obviously, I could decode it before but that would make it vulnerable to XSS attacks.

I must have missed something obvious. What options do I have?

CodePudding user response:

This happens if you encode too much.

You need to use exactly the amount of encoding needed, not more, but not less either. For example, if your input is not used verbatim in JavaScript, there's not point in JavaScript-encoding it. There is no makeMyStringSecure(...) method that will magically prevent XSS. You need to understand where and how every single string is used and encode it exactly as required in that particular case.

[Followup-question from the comments:] So in this case, I use the input in 2 different places: normal UI [and] in an email. Which means that I should encode just before using it, and not at the database level? (for XSS I mean, for sql injection, of course I will)

Exactly! The database should contain the raw, unencoded value, and you encode it on demand based on your needs: JSON encoding if you send it via JSON, XML encoding if you send it via XML, HTML encoding for web pages, Quoted-Printable for an e-mail, etc...

Ideally, the encoding is done by (UI) library code, not by the business logic. Everything that needs to be done manually is prone to errors. Likewise, there should be no need to SQL encode your strings: Use parameterized queries, and the library takes care of it!

  • Related