jquery - how to escape html to prevent XSS? - javascript

I'm using laravel, when a user sends a text message, it may contain some malicious code. When I use {{}} it will show me the exact text the user has sent. If he has sent
<script>alert("malicious")</script>
it will show exactly the same and it's good, but when I use jquery ajax, I put the fetched data to some variables within some html tags and lastly append all of them to a main tag like so:
data = '';
//loop starts here // some otger codes deleted for cleanness
data += "<h2>"+response.name+"</h2>";
data += "<p>"+response.description+"</p>";
$('#mydata').html(data);
and now the problem is that if I use html() the user malicious code will be executed and if I don't, the result will not be shown as html.
I guess I should do something with $.parseHTML, isn't it?
Thanks

You should use jQuery text() to encode the data.
$('#mydata').text(data);
EDIT: To create the content of #mydata you can use
$('#mydata')
.html("")
.append($("<h2></h2>").text(response.name))
.append($("<p></p>").text(response.description))

you cannot render user data as HTML and escape it into safe way in the same time.
You may assume that some god-level regex could help you to drop just attributes but not tags. Unfortunately there are so many ways to inject JS into markup then you will never be sure.
So you have just few options:
ignore risks at all
escape all the things (either using jQuery's text() or escaping on backend side with htmlspecialchars()
use non-HTML markup that is translated to HTML by simple rules in controlled way

You can also do this to remove tags...
$('#mydata').text(data).replace(/(<([^>]+)>)/ig,"");
read more on this post
Todo List Sanitizing Input jQuery

We had a similar scenario in of the project I worked. We used to get html content from server side which should be appended to DOM using Jquery. Before adding it to Add, we wanted to validate the HTML content we received from Server to safe guard the XSS security issues. Following is the generic method to encode the HTML content,
function htmlEncode(source) {
return $("<div>").text(source).html();
}

Related

Replace HTML code with code from another page

I have got two html files, say page1.html and page2.html. In both files I have an article element. Now, on page1.html I would like to replace the content of the article element with that of page2.html using JavaScript (I don't want to use jQuery).
Currently, my solution is the following: When page1.html is loaded, I use the fetch method to get the content of page2.html's article element. Then, when the user clicks a button, I call
article.innerHTML = newContent;
This does work fine so far, but recently I've read that innerHTML shouldn't be used to prevent XSS attacks. Obviously, I cannot set the property article.textContent since I've got "real" html code in my articles that I want to be interpreted as such. Another solution I could think of is to include the html code in the script file as a string. The downside of this method would be that I would have to change both page2.html and the script file, whenever I want to change the article.
Is there a recommended way to achieve what I want to do? Also, all the examples of XSS attacks I've read about seem to indicate that my specific use of innerHTML doesn't allow XSS attacks (since I fetch the code from a site which I control myself), but I don't just want to be like "I can't think of an XSS attack, so there'll never be one". Any insights about the danger of XSS attacks in this context?
In case you have control over the content of this page2.html i.e. either you have a static or dynamic data which is not generated by the visitors visiting your webpages, then there is won't be any issue of XSS attack. In such cases you can confidently use innerHtml method.
But, in case the content of the page2.html contains the data from visitors (such as comments, posts, etc.) then only there is a chance of XSS attack. XSS attack is nothing but when your user put some JavaScript code for their advantage.
E.g. In case your page2.html contains comments, I can post comment like Hello world! <script> alert("You have been hacked, transfer money to this bank to save your computer") </script>. Or I can attach link to another vulnerable script which steal your user's data like cookie data.
For such use cases, please do not use innerHtml directly. The safe solution is either use textContent or sanitize your visitor's data (like the comment mentioned above) (Ref: https://remarkablemark.org/blog/2019/11/29/javascript-sanitize-html/)
try the following code here you have to call the .text() method in fetch response to get the actual HTML and insert it using Element.innerHTML
fetch('DataPage.html') .then((res) => res.text()) //here you have to change the response into html text .then(res => {document.querySelector("#target").innerHTML = res;})
You can do this with PHP.
<?php echo file_get_contents('./to/file'); ?>
This downloads the files with the thing. You could also do it with include.
<?php include "./to/file"; ?>

DHTMLX with php form connector - How to not strip html on form save

DHTMLX frontend javascript library. I'm using input form tag with rows>1 attribute to edit some html. (On top of that textarea are powerful html editor). Loading is fine, I can see html tags as plain text in input, but after saving to database and reloading - all html tags are stripped. Is there a way to avoid it for some particular forms?
That html edited only by admin, no security risks to allow all html. It should be stored in db as plain html.
I look few existing answers, all about strip html, but I need non-striping, nor escaping.
I found a way for full form, could anybody help to do same for one particular field of form?
<?php
require_once('../dx/connector/form_connector.php');
ConnectorSecurity::$xss = DHX_SECURITY_TRUSTED;
Above will be protected by .htaccess or php basic auth.

Accessing property in my struts action from JavaScript

I am still trying to get my head around how client server comms work with JSP/js and Struts.
I have a Struts property in my action that I can display on my page using
As I understand it this works by looking in my Action for a method called getMyMessage(). So this works ok for me.
I now want to be able to access this value from inside my Javascript so I can dynamically populate a test area when the page loads.
I use
$(document).ready(function( data )
{
$('#contextsTextArea').html(data.myMessage);
});
but this does not work. I know I could assign a var in my JSP that stores the struts property and reference this var in my JS but is there a cleaner way to do this?
JSP runs on the server, JavaScript runs in your browser.
You cannot use a JSP variable like 'myMessage' as a variable in your JavaScript. You can, however, turn it into text on the server so it works as JS when it gets to your browser.
So, try something like this:
$('#contextsTextArea').val('<s:property value="myMessage"/>')
When this JSP is processed on the server the JS code will be left as text while the tag will be turned into the text in your myMessage variable.
Note that you really need to JS escape myMessage otherwise, for example, if the message contains a single quote then the JS will break.
Have a look at your page source to understand what's going on here.
If you are talking about textarea you have to use .val() instead. Like the following.
$('#contextsTextArea').val(data.myMessage);

How to decode JSONP data with jQuery?

I have some data that I'm retrieving using JSONP from a remote server. The content contains HTML and I need to make it so the characters render properly instead of printing the tags out. For example, if something has bold tags, it should just appear bold and not have the strong tags around it.
This needs to be done in JavaScript/jQuery. Just about everything I've found in search results uses some type of server side code.
If you read http://en.wikipedia.org/wiki/JSONP you can understand that you need to wrap you content into a Javascript function such as:
remoteScripts.js:
function getContent(){
return 'YOUR HTML CONTENT';
}
and so in your HTML page you can do via JQuery:
$('YOUR ELEMENT').html(getContent());

on jQuery change... using .html();

OK let's say I have a jQuery function... it's an AJAX Post... well after success I do this
$("#title"+id).html(Z);
and Z is var Z=$("#"+X+" textarea.editAnswer").val();.
However if I type in the textarea something like <script>alert('Test');</script> and then press save... it will save it and the test alert will popup. So... how do I fix this?
This is code injection and should be avoided with HTML encoding.
Either:
return HTML encoded result from the server (after you've saved it) and populate that into your #title element or
use escape() Javascript function to encode it on the client and populate that result into your #title element
Depending on the scenario, you should always use the one that makes it harder for the user to hack. I'd suggest you use server side approach, because users won't be able to override your custom javascript function and address their own twisted agenda...
Your options are escaping the code or using whitelists.
Do you need the html code? Take a look at this question: How to prevent Javascript injection attacks within user-generated HTML
And then these ones:
Script injection - form validation (jquery)
Do you only run htmlspecialchars() on output or is there other functionality you also do?

Categories

Resources