Reputation: 13356
I've been using MS's AntiXSS library for a while now. Recently I decided to change the textareas in my site to be plain textareas (used to be WYSIWYG), and run a conversion on the newlines to br's.
Problem is, MS's AntiXSS library doesn't support this... it strips out the br's. I don't want to let the user's entry go directly into my DB unchecked. Without using the MS AntiXSS library, what's a reliable way to prevent XSS while allowing HTML input, including br's (in C#)?
Upvotes: 0
Views: 2047
Reputation: 13356
To resolve this, I decided to store the raw HTML as-is, performing a replace on Environment.Newlines
to <br />
before storing it.
Then on the flip side, when showing it to visitors I use the MS AntiXSS code to clean it up. Not 100% the ideal way I'd like to do it, but gets the job done.
I do a bit of caching here to make sure it's not running through AntiXSS on every request too.
Upvotes: 0
Reputation: 13138
You can disable your AntiXSS for this field and store directly the input from the user in your database. That way, you'll be able to render this text on any output and not only HTML.
Now, when you want to display this text on an HTML page using ASP MVC Razor, you can use something like this :
@Html.Encode(Model.MyMultilineTextField).Replace(@"\n", "<br />")
Html.Encode will encode the text so Html tags are not interpreted and the XSS is not possible. You may add an extension method on Html that does the transformation (whith replace) for you. You may also handle \r.
Upvotes: 1
Reputation: 7421
Is it possible to get a copy of the AntiXSS' output? If so, run your input through the AntiXSS and then make the
replacement afterword and store the data yourself.
Upvotes: 0