escaping a JS reserved word (already double encapsulated) - javascript

I have a JS function which is generated by some PHP, the function call is below:
onClick=openPopup('".$row['imgname']."','".$row['adtitle']."','".$row['adviews']."')
Now this works unless the value of $row['adtitle'] contains a JS keyword. The one that brought the bug in my code to my attention was the word 'THIS'. Would there be a way to escape these values, I can't figure it out as I have already used a lot of encapsulation in this call.
Thanks in advance.
EDIT:
openPopup('efc86f7223790e91f423ef1b73278435.jpg','THIS IS A TEST ADVERT 12345678','2')
This call does not work.
openPopup('eada91a6c1197d2f2320e59f45d8ca6b.jpg','is a test','2')
however this one does work..
only thing I could figure was the THIS as when looking at the source, the text following THIS is highlighed differently.
Edit 2 : Here is my function:
function openPopup(imgname,adtitle,adviews) {
document.getElementById('popup').style.display = 'block';
document.getElementById('delimg').src = 'imgstore/' + imgname;
document.getElementById('delAdTitle').innerHTML = adtitle;
document.getElementById('delAdViews').innerHTML = adviews;
document.getElementById('confirm').onclick = function() {
location.href = '?delete=1&id=' + imgname;
}
}

Maybe it’s just a question of proper formatting:
$onclick = 'openPopup('.json_encode($row['imgname']).','.json_encode($row['adtitle']).','.json_encode($row['adviews']).')';
echo 'onClick="'.htmlspecialchars($onclick).'"';
Note that we’re abusing json_encode here to quote the JavaScript string literals. Although we shouldn’t as strictly speaking JSON strings are not a subset of JavaScript strings.

Related

Syntax error in scripting HTML using javascript

I have the following javascript code that attempts to insert HTML code dynamically. I have an error the syntax but I do not know how to correct it. Please can someone advise?
loadNextContainer.innerHTML = '<span class="sr_43" id="srloadnext_2" onclick="srt.loadNextMatchRecords(\''+numDownloadSoFar+'\', \''+maxDownloadLimit+'\', \''+folderName+'\', \''+jsonHashTags+'\', \''+fromDate+'\', \''+toDate+'\', \''+lastScanId+'\')">LoadNext</span>';
ERROR MESSAGE:
Uncaught SyntaxError: Invalid or unexpected token
I believe the error revovles around the function variables. In particular the JSON variable. I cannot change the use of double quotation marks for each element in the JSON. So that has to stay in any solution.
You could try it using backticks like this.
loadNextContainer.innerHTML = `<span class="sr_43" id="srloadnext_2" onclick="srt.loadNextMatchRecords('`+numDownloadSoFar+`', '`+maxDownloadLimit+`', '`+folderName+`', '`+jsonHashTags+`', '`+fromDate+`', '`+toDate+`', '`+lastScanId+`')">LoadNext</span>';
Or just escape the double-quotes instead of the single quotes. The way you're doing it, you're unintentionally opening up the string when you try to escape it.
loadNextContainer.innerHTML = "<span class=\"sr_43\" id=\"srloadnext_2\" onclick=\"srt.loadNextMatchRecords('"+numDownloadSoFar+"', '"+maxDownloadLimit+"', '"+folderName+"', '"+jsonHashTags+"', '"+fromDate+"', '"+toDate+"', '"+lastScanId+"')\">LoadNext</span>";
Judging from your image of your variables, none of the template literal solutions are going to help you, because at least one of your parameters is an array.
Yes, it would be possible, with enough effort, to convert that array into a string representation that would work with innerHTML. But it's going to be very difficult. You'd end up needing to use JSON.stringify to get the string version of your array at least.
An easier solution is actually going to be to create the element and then add the onclick operator through pure javascript, like this:
var s = document.createElement('span');
s.className = 'sr_43';
s.id = 'srloadnext_2';
s.innerText = 'LoadNext';
loadNextContainer.appendChild(s);
s.onclick = function(e) {
srt.loadNextMatchRecords(numDownloadSoFar, maxDownloadLimit, folderName, jsonHashTags, fromDate, toDate, lastScanId);
};
Try it with template literals:
loadNextContainer.innerHTML = `<span class="sr_43" id="srloadnext_2" onclick="srt.loadNextMatchRecords(\'${numDownloadSoFar}\', \'${maxDownloadLimit}\', \'${folderName}\', \'${jsonHashTags}\', \'${fromDate}\', \'${toDate}\', \'${lastScanId}\')">LoadNext</span>`;
Edit:
As others already mentioned. Sorry.

Escaping javascript entities in js?

I want to escape javascript entities on client side. For example :-
If my input string is tes"t result should be tes\"t
Is there any inbuilt function provided by jquery for this ?
This is a really crazy, almost stupid shot in the dark on my part, but...
If you're using a server-side language like PHP to output variables' contents into JavaScript, you should use json_encode as this handles ALL escaping for you, regardless of the type of variable.
On the other hand, if you're (I really hope you're not) doing something like this:
var input = "test"t";
And trying to escape that properly while in JavaScript... that's not going to work. It's a syntax error. You need to escape your literals manually.
Kevin van Zonneveld provide a JavaScript equivalent of PHP’s addslashes here :
http://phpjs.org/functions/addslashes/
function addslashes(str) {
// example 1: addslashes("kevin's birthday");
// returns 1: "kevin\\'s birthday"
return (str + '')
.replace(/[\\"']/g, '\\$&')
.replace(/\u0000/g, '\\0');
}
Based on this function, I guess you might want to add this function to prototype of the String like this.
if (!String.prototype.addslashes) {
String.prototype.addslashes = function () {
return this.replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
};
}
var str = 'tes"t';
alert(str.addslashes()); // shows 'tes\"t'
DEMO: http://jsfiddle.net/naokiota/6F6aN/6/
Hope this helps.

Detect if string contains javascript tags using jQuery/JavaScript

I am trying to create a very simplistic XSS detection system for a system I am currently developing. The system as it stands, allows users to submit posts with javascript embedded within the message. Here is what I currently have:-
var checkFor = "<script>";
alert(checkFor.indexOf("<script>") !== -1);
This doesn't really work that well at all. I need to write code that incorporates an array which contains the terms I am searching for [e.g - "<script>","</script>","alert("]
Any suggestions as to how this could be achieved using JavaScript/jQuery.
Thanks for checking this out. Many thanks :)
Replacing characters is a very fragile way to avoid XSS. (There are dozens of ways to get < in without typing the character -- like < Instead, HTML-encode your data. I use these functions:
var encode = function (data) {
var result = data;
if (data) {
result = $("<div />").html(data).text();
}
};
var decode = function (data) {
var result = data;
if (data) {
result = $("<div />").text(data).html();
}
};
As Explosion Pills said, if you're looking for cross–site exploits, you're probably best to either find one that's already been written or someone who can write one for you.
Anyway, to answer the question, regular expressions are not appropriate for parsing markup. If you have an HTML parser (client side is easy, server a little more difficult) you could insert the text as the innerHTML of an new element, then see if there are any child elements:
function mightBeMarkup(s) {
var d = document.createElement('div');
d.innerHTML = s;
return !!(d.getElementsByTagName('*').length);
}
Of course there still might be markup in the text, just that it's invalid so doesn't create elements. But combined with some other text, it might be valid markup.
The most effective way to prevent xss attacks is by replacing all <, > and & characters with
<, >, and &.
There is a javascript library from OWASP. I haven't worked with it yet so can't tell you anything about the quality. Here is the link: https://www.owasp.org/index.php/ESAPI_JavaScript_Readme

Replace all strings "<" and ">" in a variable with "<" and ">"

I am currently trying to code an input form where you can type and format a text for later use as XML entries. In order to make the HTML code XML-readable, I have to replace the code brackets with the corresponding symbol codes, i.e. < with < and > with >.
The formatted text gets transferred as HTML code with the variable inputtext, so we have for example the text
The <b>Genji</b> and the <b>Heike</b> waged a long and bloody war.
which needs to get converted into
The <b>Genji</b> and the <b>Heike</b> waged a long and bloody war.
I tried it with the .replace() function:
inputxml = inputxml.replace("<", "<");
inputxml = inputxml.replace(">", ">");
But this would just replace the first occurrence of the brackets. I'm pretty sure I need some sort of loop for this; I also tried using the each() function from jQuery (a friend recommended I looked at the jQuery package), but I'm still new to coding in general and I have troubles getting this to work.
How would you code a loop which would replace the code brackets within a variable as described above?
Additional information
You are, of course, right in the assumption that this is part of something larger. I am a graduate student in Japanese studies and currently, I am trying to visualize information about Japenese history in a more accessible way. For this, I am using the Simile Timeline API developed by MIT grad students. You can see a working test of a timeline on my homepage.
The Simile Timeline uses an API based on AJAX and Javascript. If you don't want to install the AJAX engine on your own server, you can implement the timeline API from the MIT. The data for the timeline is usually provided either by one or several XML files or JSON files. In my case, I use XML files; you can have a look at the XML structure in this example.
Within the timeline, there are so-called "events" on which you can click in order to reveal additional information within an info bubble popup. The text within those info bubbles originates from the XML source file. Now, if you want to do some HTML formatting within the info bubbles, you cannot use code bracket because those will just be displayed as plain text. It works if you use the symbol codes instead of the plain brackets, however.
The content for the timeline will be written by people absolutely and totally not accustomed to codified markup, i.e. historians, art historians, sociologists, among them several persons of age 50 and older. I have tried to explain to them how they have to format the XML file if they want to create a timeline, but they occasionally slip up and get frustrated when the timeline doesn't load because they forgot to close a bracket or to include an apostrophe.
In order to make it easier, I have tried making an easy-to-use input form where you can enter all the information and format the text WYSIWYG style and then have it converted into XML code which you just have to copy and paste into the XML source file. Most of it works, though I am still struggling with the conversion of the text markup in the main text field.
The conversion of the code brackets into symbol code is the last thing I needed to get working in order to have a working input form.
look here:
http://www.bradino.com/javascript/string-replace/
just use this regex to replace all:
str = str.replace(/\</g,"<") //for <
str = str.replace(/\>/g,">") //for >
To store an arbitrary string in XML, use the native XML capabilities of the browser. It will be a hell of a lot simpler that way, plus you will never have to think about the edge cases again (for example attribute values that contain quotes or pointy brackets).
A tip to think of when working with XML: Do never ever ever build XML from strings by concatenation if there is any way to avoid it. You will get yourself into trouble that way. There are APIs to handle XML, use them.
Going from your code, I would suggest the following:
$(function() {
$("#addbutton").click(function() {
var eventXml = XmlCreate("<event/>");
var $event = $(eventXml);
$event.attr("title", $("#titlefield").val());
$event.attr("start", [$("#bmonth").val(), $("#bday").val(), $("#byear").val()].join(" "));
if (parseInt($("#eyear").val()) > 0) {
$event.attr("end", [$("#emonth").val(), $("#eday").val(), $("#eyear").val()].join(" "));
$event.attr("isDuration", "true");
} else {
$event.attr("isDuration", "false");
}
$event.text( tinyMCE.activeEditor.getContent() );
$("#outputtext").val( XmlSerialize(eventXml) );
});
});
// helper function to create an XML DOM Document
function XmlCreate(xmlString) {
var x;
if (typeof DOMParser === "function") {
var p = new DOMParser();
x = p.parseFromString(xmlString,"text/xml");
} else {
x = new ActiveXObject("Microsoft.XMLDOM");
x.async = false;
x.loadXML(xmlString);
}
return x.documentElement;
}
// helper function to turn an XML DOM Document into a string
function XmlSerialize(xml) {
var s;
if (typeof XMLSerializer === "function") {
var x = new XMLSerializer();
s = x.serializeToString(xml);
} else {
s = xml.xml;
}
return s
}
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace
You might use a regular expression with the "g" (global match) flag.
var entities = {'<': '<', '>': '>'};
'<inputtext><anotherinputext>'.replace(
/[<>]/g, function (s) {
return entities[s];
}
);
You could also surround your XML entries with the following:
<![CDATA[...]]>
See example:
<xml>
<tag><![CDATA[The <b>Genji</b> and the <b>Heike</b> waged a long and bloody war.]]></tag>
</xml>
Wikipedia Article:
http://en.wikipedia.org/wiki/CDATA
What you really need, as mentioned in comments, is to XML-encode the string. If you absolutely want to do this is Javascript, have a look at the PHP.js function htmlentities.
I created a simple JS function to replace Greater Than and Less Than characters
Here is an example dirty string: < noreply#email.com >
Here is an example cleaned string: [ noreply#email.com ]
function RemoveGLthanChar(notes) {
var regex = /<[^>](.*?)>/g;
var strBlocks = notes.match(regex);
strBlocks.forEach(function (dirtyBlock) {
let cleanBlock = dirtyBlock.replace("<", "[").replace(">", "]");
notes = notes.replace(dirtyBlock, cleanBlock);
});
return notes;
}
Call it using
$('#form1').submit(function (e) {
e.preventDefault();
var dirtyBlock = $("#comments").val();
var cleanedBlock = RemoveGLthanChar(dirtyBlock);
$("#comments").val(cleanedBlock);
this.submit();
});

Javascript problem

I'm a noob in Javascript but here is my problem:
I'm cleaning up some PHP-files. Some of them contain Javascript functions which I want to transfer to a separate xxx.js file.
Most of them are working fine again but one causes me trouble. I think because of the punctuation (the ' and ").
Here's the script as it shows up IN the PHP-file:
function preview(){
dd=window.open('','prv','height=600,width=500,resizable=1,scrollbars=1')
document.addnews.mod.value='preview';document.addnews.target='prv'
document.addnews.submit();dd.focus()
setTimeout(\"document.addnews.mod.value='addnews';document.addnews.target='_self'\",500)
}
When copying this to the xxx.js file it won't work.
Anybody knows how it should look in a real .js-file?
Thanks in advance!
Cleaned a bit:
function preview() {
var dd = window.open('', 'prv', 'height=600,width=500,resizable=1,scrollbars=1');
document.addnews.mod.value = 'preview';
document.addnews.target='prv';
document.addnews.submit();
dd.focus();
setTimeout(function() {
document.addnews.mod.value = 'addnews';
document.addnews.target = '_self';
}, 500);
}
Remove the backslashes in front of the double quotes.
setTimeout("document.addnews.mod.value='addnews';document.addnews.target='_self'",500)
It looks like this function was originally in a double-quoted string, so all double-quotes inside are escaped. Good for you for moving them out of PHP :)

Categories

Resources