alerting double encoded character - javascript

I'm trying to alert document.cookie when the dot is double encoded, but it doesn't work.
here's my code:
<script>alert(unescape(document%252Ecookie))</script>
How can i make it work using double encoding on the dot?
Thanks.

No idea what you are trying to do really, but here are some clarifications:
unescape() works on strings. it takes a string and returns another string. document%252Ecookie is not a string, so you cannot use unescape() on it.
To use unescape, put quotes around "document%252Ecookie"
unescape(unescape("document%252Ecookie")) will give you the string "document.cookie" (remember, unescape goes from strings to strings). If you alert this you will have an alert box saying "document.cookie", which is probably not what you are looking for. To get the contents of document.cookie you can use eval(). It takes a string and evaluates the contents of it.
So to do what you want to do you would type:
alert(eval(unescape(unescape("document%252Ecookie"))))
No idea of why you would want to do this, but this is how it can be done. I want to point out that this code is pretty stupid, but hopefully I've made some things more clear to you.

Related

RegEx that works in Javascript won't do so in PHP

I will try to make my question short yet understandable, I have a simple RegEx I use in javascript to check for characters that aren't alphanumeric (AKA Symbols). It would be "/[$-/:-?{-~!"^_`[]]/"
In javascript, doing
if(/[$-/:-?{-~!"^_`\[\]]/.test( string ))
just works, if any of those characters are in the string, it will give true, else, it will give false. I tried to do the same in PHP, the following way
if(preg_match('/[$-/:-?{-~!"^_`\[\]]/', $string ))
other regexes work when done this way, but this particular one simply will give false no matter what when ran in PHP.
Is there any reason to this? Am I doing something wrong? Does PHP comprehend regexes in a different way? What should I change to make it work?
Thanks for your time.
Since php uses PCRE, you will get a pattern error using delimiter / as seen here http://regex101.com/r/3ILGgE/1
So, it should be escaped correctly.
Using / as the delimiter, the string is
'/[$-\/:-?{-~!"^_`\[\]]/'
Using ~ as the delimiter, the string is
'~[$-/:-?{-\~!"^_`\[\]]~'
Also, be aware you have a couple of range's in the class $-/ and :-? and {-~
that will include the characters between the from/to range characters as well
and does not include the range character - itself as it is an operator.

A way to automatically enclosure quotes inside string containing code (RegExp maybe?)

Is there a way to automatically enclosure all quotes inside the string of js-code which contains other strings by itself? I just failed to make a RegExp valuable to identify all the quotes properly. Because in some cases (blocks of code generated by script) there strings of code like:
$(".class1.class2:contains('text')").param(s1+s2+"-"+s3+"_"+i)...
var r=new RegExp("blabla[qwer]\\'\\w+\\d\\'");
//etc.
More complex actually and less readable =)
But anyways is there a way to get rid of constant http/ajax/json requests and make code to work without injection but via eval? It's not intended to be used in outer net so it's safe, dont tell me anything 'bout eval =) The main problem: how to make enclosurement of quotes inside the string...
Edit:
Sorry i just don't know how to say it in English, so by enclosurement i mean insertion of a specific symbol before char which has dual meaning to clarify it's definition for compiler or machine-interpreter.
Example1: ('first_part_of_string enclosured_quote=\' second_part_of_string')
Example2: `<- these symbols don't get interpreted as code-markers because of enclosurement ->`
Sure, here it is with single quotes:
'
$(".class1.class2:contains(\'text\')").param(s1+s2+"-"+s3+"_"+i)...
var r=new RegExp("blabla[qwer]\\\\\'\\\w+\\\d\\\\\'");
'
here it is with double quotes:
"
$(\".class1.class2:contains('text')\").param(s1+s2+\"-\"+s3+\"_\"+i)...
var r=new RegExp(\"blabla[qwer]\\\\'\\\\w+\\\\d\\\\'\");
"
You can use the Mega-String tool to do this automatically
I used the single / double quote option from the Other category..

Escaping quotation marks in PHP for JavaScript function argument

I'm having trouble escaping a quotation mark in PHP.
I have a table of products and each row has an onclick function, with the name of the product as the argument.
The name contains the length which is measured in inches, so the name contains a quotation mark. I wrapped an addslashes() around the string. This adds a backslash before the quotation mark but for some reason it doesn't seem to escape the character!
Here's a snippet of my code:
<?$desc1 = addslashes($row['Desc1']);?>
<tr class='tableRow' onclick='afterProductSelection("<?=$desc1?>")'>
<td><?=$row['Desc1']?></td>
When I inspect element in Google Chrome, the colour of the syntax indicates that this has not been escaped, clicking on it gives me a syntax error.
Probably something simple that I'm missing. Hope you can help!
There are a lot of different cases where you need to escape a string. addslashes() is the wrong answer to pretty much all of them.
The addslashes() function is an obsolete hang-over from PHP's early days; it is not suitable for any escaping. Don't use it. Ever. For anything.
In your particular case, since you're creating Javascript data from PHP, use json_encode().
json_encode() will take a PHP variable (whether it's a string, array, object or whatever) and convert it into a JSON string. A JSON string is basically fully escaped Javascript variable, including the quotes around your strings, etc. This is what you need to do.
The addslashes() function is an obsolete hang-over from PHP's early days; it is not suitable for any escaping. Don't use it. Ever. For anything. -Spudley
I think the function you're looking for is htmlentities()
<?=htmlentities($desc1, ENT_QUOTES)?>
http://ca1.php.net/htmlentities
You are generating a JavaScript string encoded as HTML so you need to encode twice:
Use json_encode() to generate the string
Use htmlspecialchars() to encode as HTML
Use json_encode to output variables from the backend in JavaScript:
<tr onclick='afterProductSelection(<? print json_encode($desc1); ?>)'>
N.B.: For string output there is no need for extra quotes.

JSON String as Javascript function argument

I am trying to define a pure JSON string as an argument in a Javascript function.
Below is the way I want to define it:
Link
Firebug gives me an error alert: unterminated string literal, even when I escape the double-quotes on the JSON string.
How can I solve this?
Thanks.
Use " for your double quotes, then in js_func(), replace them with actual double quote characters (") before evaluating your JSON string. (thanks for the demo Matthew, I updated your fiddle with the example from the question:)
http://jsfiddle.net/brillyfresh/kdwRy/1/
simply defining the link as Link works fine. JSON is valid JavaScript, you don't need to enclose it in ''s.
I also suggest to use an EventListener (element.addEventListener()), this makes the html cleaner and would reduce this problem to nothing.
ryou are either trying to pass the parsed object or pass a string
Object: onclick="js_func(arg_1, arg_2, {'key': 'value'});"
String: on_click="js_func('arg_1', 'arg_2', '{\"key\": \"value\"}'); return false"
All I've got handy to test is firebug interpreter but both worked fine for me.
>>>>'{\"key\": \"value\"}'
"{"key": "value"}"
>>>> {'key': 'value'}
Object {key="value"}
(I don't mean to presume whether arg_1 and arg_2 are strings or variable names, and it doesnt matter. just did the same thing as with the JSON)

Double-Escaped Unicode Javascript Issue

I am having a problem displaying a Javascript string with embedded Unicode character escape sequences (\uXXXX) where the initial "\" character is itself escaped as "\"
What do I need to do to transform the string so that it properly evaluates the escape sequences and produces output with the correct Unicode character?
For example, I am dealing with input such as:
"this is a \u201ctest\u201d";
attempting to decode the "\" using a regex expression, e.g.:
var out = text.replace('/\/g','\');
results in the output text:
"this is a \u201ctest\u201d";
that is, the Unicode escape sequences are displayed as actual escape sequences, not the double quote characters I would like.
As it turns out, it's unescape() we want, but with '%uXXXX' rather than '\uXXXX':
unescape(yourteststringhere.replace(/\/g,'%'))
This is a terrible solution, but you can do this:
var x = "this is a \u201ctest\u201d".replace(/\/g,'\\')
// x is now "this is a \u201ctest\u201d"
eval('x = "' + x + '"')
// x is now "this is a “test”"
It's terrible because:
eval can be dangerous, if you don't know what's in the string
the string quoting in the eval statement will break if you have actual quotation marks in your string
Are you sure '\' is the only character that might get HTML-escaped? Are you sure '\uXXXX' is the only kind of string escape in use?
If not, you'll need a general-purpose HTML-character/entity-reference-decoder and JS-string-literal-decoder. Unfortunately JavaScript has no built-in methods for this and it's quite tedious to do manually with a load of regexps.
It is possible to take advantage of the browser's HTML-decoder by assigning the string to an element's innerHTML property, and then ask JavaScript to decode the string as above:
var el= document.createElement('div');
el.innerHTML= s;
return eval('"'+el.firstChild.data+'"');
However this is an incredibly ugly hack and a security hole if the string comes from a source that isn't 100% trusted.
Where are the strings coming from? It would be nicer if possible to deal with the problem at the server end where you may have more powerful text handling features available. And if you could fix whatever it is that is unnecessarily HTML-escaping your backslashes you could find the problem fixes itself.
I'm not sure if this is it, but the answer might have something to do with eval(), if you can trust your input.
I was thinking along the same lines, but using eval() in everyway I could imagine resulted in the same escaped output; e.g.,
eval(new String("this is a \u201ctest&#amp;92;u201d"));
or even
eval(new String("this is a \u201ctest&#amp;92;u201d".replace('/&amp#92;/g','\')));
all results in the same thing:
"this is a \u201ctest\u201d";
It's as if I need to get the Javascript engine to somehow re-evaluate or re-parse the string, but I don't know what would do it. I thought perhaps eval() or just creating a new string from using the properly escaped input would do it, but now luck.
The fundamental question is - what do I have to do to turn the given string:
"this is a \u201ctest&#amp;92;u201d"
into a string that uses the proper Unicode characters?

Categories

Resources