JavaScript and JQuery - Encoding HTML - javascript

I have a web page that has a textarea defined on it like so:
<textarea id="myTextArea" rows="6" cols="75"></textarea>
There is a chance that a user may enter single and double quotes in this field. For instance, I have been testing with the following string:
Just testin' using single and double "quotes". I'm hoping the end of this task is comin'.
Additionally, the user may enter HTML code, which I would prefer to prevent. Regardless, I am passing the contents of this textarea onto web service. I must encode the contents of the textarea in JavaScript before I can send it on. Currently, I'm trying the following:
var contents $('<div/>').text($("#myTextArea").val()).html();
alert(contents);
I was expecting contents to display
Just testin' using single and double "quotes". I'm hoping the end of this task is comin'.
Instead, the original string is printed out. Beyond just double-and-single quotes, there are a variety of entities to consider. Because of this, I was assuming there would be a way to encode HTML before passing it on. Can someone please tell me how to do this?
Thank you,

If you're sending to a web service, you'll presumably be URL-encoding these (as part of a POST, for instance, either via form submission of Ajax). That will handle any necessary escaping at your end. The service at the other end is responsible for interpreting the input string correctly. If the service doesn't accept HTML tags, it's the service's job to do the necessary entity encoding (or whatever other kind of encoding it wants).
If the service doesn't take responsibility for this, it's open to errors in the client and attacks by people with nefarious intent. So it's really the other end's problem.

By using:
var contents = $("<div/>").text($("#myTextArea").val()).text();
alert(contents);
You display the textual contents instead of the contents in html.

Related

ExpressJS: How to prevent a user from posting/patching code inside req.body

I'm developing an API with expressJS. This API is a semi-weblog service, and clients can create, update and delete their posts and contents. I have a sec urity concern about implementing its post and patch routes.
If the user injects some JS code and sends it to API to store in Mongodb, could these codes affect our API? How can I prevent users from posting and patching requests with any code inside them?
I have found "xss-clean" middleware to sanitize the user input body, is it enough for this purpose?
Because it is very important to me to ensure that I am using the correct middleware to protect this API, I am asking this question.
If the user injects some JS code and sends it to API to store in Mongodb, could these codes affect our API?
Generally speaking: It won't.
The code come into express as a message body. It gets parsed by your middleware into a data structure where it will appear as a string. You then put that string in an object of structured data that you pass through the Mongodb client API which sends it to the database with any escaping that is needed.
I have found "xss-clean" middleware to sanitize the user input body, is it enough for this purpose?
XSS is an attack in which data injected into an HTML document contains special characters which are treated as special characters in HTML.
e.g.
<h1>{{ your_name }}</h1>
Where your_name is data that contains <script>...</script>.
This is generally dealt with by applying proper escaping to the data (at a very basic level that means replacing < with <).
XSS won't affect your API directly.
If your data is going to be taken out of the Mongodb store and injected into an HTML document, then XSS is a consideration.
xss-clean is a wrapper around xss-filters.
xss-filters looks (I've only glanced at it) like a good module and is designed to be used as an output filter (i.e. run just before you insert data into an HTML document).
xss-clean works as an input filter, which isn't a good approach. It makes your data HTML safe at the expense of making it not useful for any purpose other than HTML. You might want to use the data in an email, or generate a report in Excel format.

Unescapping client data in C# to prevent XSS or other attack

To prevent web application input from XSS or any other attack, we would like to decode all the input coming from the client (browser).
To bypass the standard validation, bad guys encode the data. Example:
<IMG SRC=javascript:alert('XSS')>
That gets translated to
<IMG SRC=javascript:alert('XSS')>
In C#, we can use HttpUtility.HtmlDecode & HttpUtility.UrlDecode to decode the client input. But, it does not cover all the type of encoding. For example, following encoded values are not getting translated using above methods. However, all the browser decode and execute them properly. One can verify them at https://mothereff.in/html-entities as well.
<img src=x onerror="&#0000106&#0000097&#0000118&#0000097&#0000115&#0000099&#0000114&#0000105&#0000112&#0000116&#0000058&#0000097&#0000108&#0000101&#0000114&#0000116&#0000040&#0000039&#0000088&#0000083&#0000083&#0000039&#0000041">
It gets decoded to <img src=x onerror="javascript:alert('XSS')">
There are some more encoded text that does not get decoded using HtmlDecode method. In Java, https://github.com/unbescape/unbescape handles all such varieties.
Do we have a similar library in .Net or how do handle such scenarios?
Generally, you should not allow users to enter code into a text box.
Client side
Judging from the comments on your post, I'd simply add some client-side validation to prevent users from adding any sort of malicious inputs (such as verifying email fields contain emails) and then add the same validation techniques to your server.
Server side
As soon as you read a user's input in a model, you should validate and sanitise it before you do any further processing. Have a generic AntiXSS() class that can remove any malicious characters such as the <> symbols by checking myString.Contains("<") or myString.Contains(">") for example. If it does, remove that character. Validate your types. If you're checking the userEmail field, make sure it conforms to email syntax.
The general idea is that you can pass data to the client, but never trust any of the data that comes back from the client without first sanitising and cleansing everything.
I found the solution. HtmlUtility.HtmlDecode decodes the chars between ampersand '&' and semicolon ';'. However, the browsers do not bother about the suffixed ';'.
In my case, semicolon ';' was missing. I have written simple code to insert a semicolon before calling HtmlDecode method. Now, it's decoding properly as expected.

How to sanitize user input text so that it can be used in Javascript/JSON?

I have a web app in which I allow some large text entry using text fields. This text is saved to a database and then later it is sent back to the user as a field in a JSON response. In the browser, I attempt to simply convert it to an Object using JSON.parse, but this sometimes fails depending on what the user put in the field.
I think that right now, the text has single quotes in it, and those are breaking the browser-side Javascript before I can call JSON.parse on it.
What's the best way to sanitize this data so that, ideally, I can just parse it back to an Object with minimal cleansing after it has been saved?
This isn't a sanitization problem : you can very well put a string with quotes in JSON : the encoding simply escapes them.
Your problem is an encoding one. To build a JSON string in a browser, use JSON.stringify. To do it server side, you should use the tool provided by your (unmentionned) server side language/framework.
The awesome thing with JSON is that you do not need to sanitize anything. No matter what you feed to a JSON encoder - it will always output plain JSON. Obviously that JSON needs to be HTML-encoded in case you plan to use it within a HTML page. Depending on the JS encoder you need to ensure there's no </script> in there (e.g. by replacing / with \/).
You also do not need JSON.parse. JSON is a subset of JavaScript so you can do something like that (PHP-ish for simplicity):
<script>
var obj = <?= json_encode($whatever) ?>;
</script>
If you really want to include JSON as as tring inside JSON consider not doing it. You can just have the object itself there - no need to have a JSON string within your JSON data. But if you have this anyway it should also always work.

Best way to send data to client js from node.js

What is the best way to send some data (in the form of a json object ideally) from a node.js server to the client's javascript. I've thought of a couple options, but none of them seem to be very suitable in my opinion. A second opinion, or some other suggestions is what I'm looking for.
Have the server output some code in a <script> tag to set a global variable.
I've used this before, but I dislike the idea of it, mostly because it has potential for XSS, and I think it's bad practice, even if the data being sent isn't defined by a user.
Set a cookie with the data inside it.
This option is a little better, but since the data is likely to change for every page load (at least in my setup), it doesn't really fit since, in my opinion, cookies aren't supposed to be this volatile.
Have the client javascript make an ajax request to the server on page load to request the json file.
This works as well, but it adds a lot of unneeded overhead. 2 requests per page seems unnecessary.
Background:
I have a site with 2 templates: an index for logged-out users, and the main content template.
My server side is built off node.js, express.js, jade, and less.
I am using history.pushState for all my links and crossroads.js for the client's page routing.
I want to be able to send the loaded template, and a user's id / if they are logged in to the client javascript, so it can handle page changes accordingly. Logged out users can view content pages, just without editing privileges, and clicking on certain links should bring them back to the index template.
The <script> tag method is good. If you're worried about other scripts accessing the data then instead of setting a global variable write a function in your client js code that can accept the data.
So instead of generating:
<script>
data = { foo : "bar" }
</script>
generate something like this:
<script>
setData({ foo : "bar" });
</script>
Obviously I don't think I need to tell you that any data you generate should be serialized by a proper JSON serializer to avoid syntax errors etc.
Just enclose the one-time data in <script> tags with type "text/template" or "application/json" and make sure they have IDs. Access their contents with jQuery or standard DOM methods. For shorter bits of data, you can use data-* attributes on key elements.
Instead of Ajax you could implement websockets with either Socket.io or Now (which implements socket.io. These not only allow you to easily pass data back and forth between client and server, but also allows the client to call functions on the server
One way is to use a hidden paragraph to hold a delimited string.
I like to delimit my strings with characters that have no chance of being embedded in my data elements.
My favorite delimiter is:
char delim = (char) 1; // the SOH character of the ASCII character map
The script tag is not a good choice because there are too many delimiters, and there is a likely chance that one of those delimiters is embedded in one of your data elements.
Using JSON has the same problem: too many delimiters.
A hidden HTML paragraph element gets my vote.
Server Side:
Inside a div with id="hiddenStrings" style="visibility:hidden" place paragraphs holding columns and values
p id="delimitedColumnNames"> #Model._ticket.GetDelimitedColumns() /p
p id="delimitedCoulmnValues"> #Model._ticket.GetDelimitedValues() /p
Client Side:
// The leading character is the delimiter.
var delimiter = document.getElementById("delimitedColumnNames").innerHTML.substr(0,1);
var delimited = document.getElementById("delimitedColumnNames").innerHTML.substr(1);
var ticketCols = delimited.split(delimiter);
var delimiter = document.getElementById("delimitedCoulmnValues").innerHTML.substr(0,1);
var delimited = document.getElementById("delimitedCoulmnValues").innerHTML.substr(1);
var ticketValues = delimited.split(delimiter);

Popping up a window for the user to show some data?

I have a webapp where my users might want to get some data from me in xml format. The flow I was thinking of:
User clicks a button named "export"
I generate a long xml string using javascript.
Pop up a new window and just paste the xml string into it.
I would prefer saving the xml string into a text file for the user, but I don't think this is possible with javascript (security reasons).
Are there any other best practices for doing something like this? I guess this will work fine,
Thanks
You can add a hovering text field to the page and paste the XML into that. To make things more simple for the user, set the focus to the field and select everything (so they only have to press Ctrl+C).
If you can access server-side pages, you can generate the XML string using javascript, make an ajax call to give the server your string, then make the user download the generated file.

Categories

Resources