Make sure user doesn't put in malicious html in code - javascript

I'm using a textarea to get input from the user and display it on the screen. How can I make sure that if they put in something like
<h1>YAY, I hacked in</h1>
I only display it as it is, and it doesn't display as an <h1>. There must be a function for this. Help? :D

As I commented, if you're about to send that data to a server, you should use one of the various XML Parsers available and strip + validate the input.
If you however, need to purely validate on the client, I suggest you use document.implementation.createHTMLDocument, which creates an fully fledged DOM Object on the stack. You can then operate in there and return your validated data.
Example:
function validate( input ) {
var doc = document.implementation.createHTMLDocument( "validate" );
doc.body.innerHTML = input;
return [].map.call( doc.body.querySelectorAll( '*' ), function( node ) {
return node.textContent;
}).join('') || doc.body.textContent;
}
call it like
validate( "<script>EVIL!</script>" );

You need to address this on the server side. If you filter with JavaScript at form submission time, the user can subvert your filter by creating their own page, using telnet, by disabling JavaScript, using the Chrome/FF/IE console, etc. And if you filter at display time, you haven't mitigated anything, you've only moved the breakin-point around on the page.
In PHP, for instance, if you wish to just dump the raw characters out with none of the user's formatting, you can use:
print htmlentities($user_submitted_data, ENT_NOQUOTES, 'utf-8');
In .NET:
someControl.innerHTML = Server.HtmlEncode(userSubmittedData);
If you're trying to sanitize the content client-side for immediate/preview display, this should be sufficient:
out.innerHTML = user_data.replace(/</g, "<").replace(/>/g, ">");

Related

How to put fully string content in js

so i have this block of sql query code here for sending user description to db in node js.
const sqlAddDescription = (desc, id) => {return `UPDATE \`Memcon\`.\`users_list\` SET \`description\` = '${desc}' WHERE (\`id\` = '${id}')`}
it's working completely fine, in the client user inputs a text and the db process goes on with no problem.
BUT if the user sends an input with backticks or quotes or even brackets, the process gonna fail because their text head on goes to ${desc} and it replaces it, so it creates an error.
How can i tell js to fully stringify the text, no matter the inputs.
(i also tried JSON.stringify but that serves a different purpose )

Prevent XSS attacks with string replace method in JavaScript

I am writing an application where the user can add messages, they are saved in the firebase, and displayed on the page. I am using the following method to protect html injection:
function testHtml(str){
return str.replace(/</g, '<').replace(/>/g, '>');
}
And I output the text as follows:
$("#save").click(function(){
let text = $("#text").val(); //user input
text = testHtml(text);
$("#resultDiv").append(text);
});
I want to know if this method is safe? Are there any workarounds? If so, which ones? I use this filtering method when displaying messages. Many thanks for considering my request.

Send a user to a certain URL depending on his text field input

Basically I want the ff. done:
User inputs a text in my text field. If his text matches a text in my "list," he is sent to a certain URL once he hits the submit button.
I found a similar code on this site but his is just one specific text value. [ Get input text field from HTML into JavaScript and go to URL ]
I want mine to determine the user's text input from a list I provide. My list will have a lot of texts/urls and it will continue to grow, so manually inputting values into the script won't work for me.. I want to be able to edit the list (possibly in an admin panel or something?) instead of the js code.
Example:
input text: aaaa, go to URL1
input text: mmne, go to URL2
input text: lhfj, go to URL3
input text: tigf, go to URL4
input text: gred, go to URL5
Can anyone help me with this please? Thanks!
Hope this helps you
var Something =$("#TextBoxID").val();
if(Something == "aaaa")
{
window.location.href = 'URL1'; //Will take you to URL1
}
......
......
if you want to configure the list on an admin console you need to have some kind of server side technology like php (or node.js if you want to keep using javascript). You need to think of where this data will be stored. A possibility would be fetching the list of text/url pairs using ajax (e.g. with jQuery) and storing the data in some database or in your case also a plain text file probably would suffice. The functionality you are looking for is not possible with plain HTML and JavaScript on cient side.
Use a function like this, if you store your URLs on the client side (HTML/JS page):
function determineAndGoToURL(text) {
var url = "#";
switch(text) {
case "aaaa":
url="www.google.com";
break;
case "bbbb":
url = "www.bing.com";
break;
default:
url = "www.yahoo.com";
break;
}
window.location.href = "http://" + url;
}
If you have an updated list of URLs on the server side, get them from server-side to client side, and iterate over them with a for statement.
I'd suggest, you'd get them from the server as JSON, and use JSON.parse(text) to create an object out of them, and then iterate.

Create a textfile from the input of an html-form with the browser (client-side)

I have an html site with a form in it and I want the user to be able to create a text/xml file depending on the input. But I wan't to avoid setting up a webserver only for this task.
Is there a good way, to do that, e.g. with Javascript? I think you can't create files with Javascript, but maybe create a data url and pass the text, so the user can save it to file?
Or is there another way to achieve this simple task without a webserver?
Solved it, somehow. I create a data url data:text/xml;charset=utf-8, followed by the XML.
function createXML() {
var XML = 'data:text/xml;charset=utf-8,<MainNode>';
var elements = document.getElementsByTagName('input'),i;
for (i in elements) {
if (elements[i].checked == true) {
XML += elements[i].value;
}
}
XML += '</MainNode>';
window.open(XML);
}
So the url looks like data:text/xml;charset=utf-8,<MainNode><SubNode>...</SubNode>...</MainNode>
Unfortunately this doesn't work for me on Chromium(Chrome) and on Firefox. It just displays the XML instead of showing a save dialog. But I think that's because of my settings and at least you can save it as a XML-file manually.
I haven't tried this but it should work.
After getting form data, system will call page A.
page A will have javascript that gets query strings and builds the page accordingly.
After finishing page build, user can save current page with following statement in javascript
document.execCommand('SaveAs',true,'file.html');

Using jQuery on a string containing HTML

I'm trying to make a field similar to the facebook share box where you can enter a url and it gives you data about the page, title, pictures, etc. I have set up a server side service to get the html from the page as a string and am trying to just get the page title. I tried this:
function getLinkData(link) {
link = '/Home/GetStringFromURL?url=' + link;
$.ajax({
url: link,
success: function (data) {
$('#result').html($(data).find('title').html());
$('#result').fadeIn('slow');
}
});
}
which doesn't work, however the following does:
$(data).appendTo('#result')
var title = $('#result').find('title').html();
$('#result').html(title);
$('#result').fadeIn('slow');
but I don't want to write all the HTML to the page as in some case it redirects and does all sorts of nasty things. Any ideas?
Thanks
Ben
Try using filter rather than find:
$('#result').html($(data).filter('title').html());
To do this with jQuery, .filter is what you need (as lonesomeday pointed out):
$("#result").text($(data).filter("title").text());
However do not insert the HTML of the foreign document into your page. This will leave your site open to XSS attacks.
As has been pointed out, this depends on the browser's innerHTML implementation, so it does not work consistently.
Even better is to do all the relevant HTML processing on the server. Sending only the relevant information to your JS will make the client code vastly simpler and faster. You can whitelist safe/desired tags/attributes without ever worrying about dangerous ish getting sent to your users. Processing the HTML on the server will not slow down your site. Your language already has excellent HTML parsers, why not use them?.
When you place an entire HTML document into a jQuery object, all but the content of the <body> gets stripped away.
If all you need is the content of the <title>, you could try a simple regex:
var title = /<title>([^<]+)<\/title>/.exec(dat)[ 1 ];
alert(title);
Or using .split():
var title = dat.split( '<title>' )[1].split( '</title>' )[0];
alert(title);
The alternative is to look for the title yourself. Fortunately, unlike most parse your own html questions, finding the title is very easy because it doesn;t allow any nested elements. Look in the string for something like <title>(.*)</title> and you should be set.
(yes yes yes I know never use regex on html, but this is an exceptionally simple case)

Categories