Ajax.Request to external site: XSS or not? - javascript

I thought the below was not working because I was attempting XSS, but I tried performing a local port redirect to confirm, and it still wouldn't work. Can someone let me know if this is XSS or not, and if not, why it's not working?
<html>
<div id="output"></div>
<script src="prototype.js" type="text/javascript"></script>
<script type="text/javascript">
function test()
{
this.url = "http://www.google.com"
}
test.prototype.run = function()
{
var request = new Ajax.Request(this.url,
{
method: "get",
onSuccess: this.success.bind(this),
onFailure: function(response) { alert("failure"); }
});
};
test.prototype.success = function(response)
{
var debug = "this.url = " + this.url + ",<br>"
+ " response.status = " + response.status + ",<br>"
+ " response.statusText = " + response.statusText + ",<br>"
+ " response.readyState = " + response.readyState + ",<br>"
+ " response.responseText = " + response.responseText + ",<br>"
+ " response.responseXML = " + response.responseXML + ",<br>"
+ " response.responseJSON = " + response.responseJSON + ",<br>"
+ " response.headerJSON = " + response.headerJSON + ",<br>"
+ " response.request = " + response.request + ",<br>"
+ " response.transport = " + response.transport + ",<br>"
+ " response.transport.readyState = " + response.transport.readyState + ",<br>"
+ " response.transport.responseText = " + response.transport.responseText + ",<br>";
document.getElementById("output").update(debug);
};
new test().run();
</script>
</html>

it's not XSS (which is a way to attack the client side of web applications), but it is simply the same origin policy being in effect here. You can't simply request data with an Ajax request from a domain other than your own (your own meaning the one your web application was loaded from).
Learn more about it here: http://en.wikipedia.org/wiki/Same_origin_policy

Related

execute a script in javascript using selenium. how to return the output of that script?

I am trying to execute a script in javascript using selenium(not sure whether it is possible to run that way or not). I don't know how to return the output of that script. Please provide me with some leads to store the output of the below script.
final JavascriptExecutor js = (JavascriptExecutor) driver;
String ans =(String) (js.executeScript("var myHeaders = new Headers();\n" +
"myHeaders.append('client-id', 'LPDP');\n" +
"myHeaders.append('a2z-csrf-token', 'NON_SDF');\n" +
"myHeaders.append('x-amz-rid', 'M6507NCWPW2FVPSSRMVM');\n" +
"let inputEntities = new Map();\n" +
"inputEntities.set(\"Commons$customerId\", \"\\\"A2ZLDCQRXMMNLG\\\"\")\n" +
"inputEntities.set(\"Commons$marketPlaceId\", \"\\\"A2XZLSVIQ0F4JT\\\"\")\n" +
"inputEntities.set(\"Commons$sessionId\", \"\\\"asdb3412\\\"\")\n" +
"inputEntities.set(\"Commons$ubId\", \"\\\"abc\\\"\")\n" +
"inputEntities.set(\"Rewards$APPA$Commons$eventId\", \"\\\"prsrohitest-1\\\"\")\n" +
"inputEntities.set(\"Rewards$APPA$Commons$clientId\", \"\\\"HFC\\\"\")\n" +
"inputEntities.set(\"Rewards$APPA$Commons$useCaseName\", \"\\\"lineItemPromotionPaymentMethodEvent\\\"\")\n" +
"inputEntities.set(\"Rewards$APPA$Commons$eventTimeStamp\",\"\\\"2022-04-20T21:21:57.934Z\\\"\" )\n" +
"inputEntities.set(\"Rewards$APPA$Commons$category\", \"\\\"HFC\\\"\")\n" +
"inputEntities.set(\"Rewards$APPA$Commons$subCategory\", \"\\\"PREPAID_RECHARGE\\\"\")\n" +
"inputEntities.set(\"Rewards$APPA$Commons$requestType\", \"\\\"HFCBP\\\"\")\n" +
"inputEntities.set(\"Rewards$APPA$Commons$partition\", \"\\\"useCaseName,category,subCategory\\\"\")\n" +
"inputEntities.set(\"Rewards$APPA$Commons$benefitsToBeEvaluated\", \"[\\\"GCCashback\\\",\\\"Coupon\\\",\\\"Membership\\\",\\\"ScratchCard\\\"]\")\n" +
"\n" +
"let entitiesToBeResolved = [\"Rewards$APPA$GetAllPromotions$applicablePromotionDetailList\"]\n" +
"\n" +
"const executeInput = {\n" +
"\"inputEntities\": Object.fromEntries(inputEntities),\n" +
"\"entitiesToBeResolved\": entitiesToBeResolved,\n" +
"};\n" +
"\n" +
"fetch(\"https://dummy url\", {\n" +
" method: 'POST',\n" +
" headers: myHeaders,\n" +
" body: JSON.stringify(executeInput),\n" +
"})\n" +
" .then(response => response.text())\n" +
" .then(result => console.log(result))\n" +
" .catch(error => console.log('error', error));\n" +
"\n"));

How to get variable value from Javascript using Selenium with Python

Using Selenium, the following is the code I am running on Python to get my geo-coordinates via use of the navigator web api:
coordinates = driver.execute_script(
" return () => { " +
" var savedCoordinates; " +
" " +
" navigator.geolocation.getCurrentPosition( " +
" (pos) => savedCoordinates = pos.coords, " +
" error, " +
" options); " +
" " +
" let options = { " +
" enableHighAccuracy: true, " +
" timeout: 5000, " +
" maximumAge: 0 " +
" }; " +
" " +
" function error(err) { " +
" console.warn(`ERROR(${err.code}): ${err.message}`); " +
" }; " +
" " +
" return savedCoordinates; " +
" } " )
print(coordinates)
Expected output: {latitude: XXX.XXX, longitude XX.XXXX}
Actual output: {}
Can someone help me figure out how I can get my geo-coordinates using this method?
It should work without return () => { }
coordinates = driver.execute_script(
" var savedCoordinates; " +
" " +
" navigator.geolocation.getCurrentPosition( " +
" (pos) => savedCoordinates = pos.coords, " +
" error, " +
" options); " +
" " +
" let options = { " +
" enableHighAccuracy: true, " +
" timeout: 5000, " +
" maximumAge: 0 " +
" }; " +
" " +
" function error(err) { " +
" console.warn(`ERROR(${err.code}): ${err.message}`); " +
" }; " +
" " +
" return savedCoordinates; " )
print(coordinates)
As for me this () => {} only defines function but it doesn't run it - so it returns this function, not result from function. You may need () to run it
return (() => {...code...})()

Ajax Request problem, returns undefined 2 out of 3 times

This might be a silly question, but I'm working on a homework project. Most of it is already working, but when I try to write some html with jquery inside an ajax request, two out of three return undefined.
$.ajax({
url: "myurl",
type: "Get",
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa(user + ":" + userpass));
},
dataType: "json",
}).
done(function (data) {
$('#uebersicht').children(".item").remove();
for (var i = 0; i < data.length; i++) {
$('#uebersicht').append("<p class='item' onclick='deleteitem(" + data[i].id + ")'>" +
data[i].datum + ", " + data[i].Stunden + " Stunden - " + data[i].Anmerkungen + "</p>");
}
});
I tried searching around, but I wasn't very lucky. Probably my searching is just off, but if someone could point me in the right direction I would be very glad.
Any help is appreciated. Thank you in advance.
You'll need to Parse the string data to json after it is received.
.done(function (data) {
var data = JSON.parse(data); // Parse it here
$('#uebersicht').children(".item").remove();
for (var i = 0; i < data.length; i++) {
$('#uebersicht').append("<p class='item' onclick='deleteitem(" + data[i].id + ")'>" +
data[i].datum + ", " + data[i].Stunden + " Stunden - " + data[i].Anmerkungen + "</p>");
}
});
});
// Or you could use the `$.each()` function to loop through the data:
.done(function (data) {
$('#uebersicht').children(".item").remove();
$.each(data, function(item, element){
$('#uebersicht').append("<p class='item' onclick='deleteitem(" + element.id + ")'>" +
element.datum + ", " + element.Stunden + " Stunden - " + element.Anmerkungen + "</p>");
})
});

Android Lollipop WebView does not show <iframe> content

I receive from the server xhtml code which I want to show in Android app like ebook reader. For this the Monocle library was chosen.
Next I prepare webview with follow code:
contentView.addJavascriptInterface(new LectureJSInterface(), "Android");
contentView.getSettings().setAllowFileAccess(true);
contentView.getSettings().setJavaScriptEnabled(true);
contentView.setBackgroundColor(0xFFECECEC);
contentView.setWebChromeClient(new WebChromeClient());
contentView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
Global.dismissProgressDialog();
}
});
After this I download the xhtml code from the server and add to it JS code for working with Monocle:
private String prepareCode(String code) {
if ((code == null) || code.equals("")) return "";
String newCode = code.substring(code.indexOf("<html"), code.indexOf("<head>")+6);
newCode = newCode.concat(
"<script src=\"file:///android_asset/monocore.js\"></script>\n" +
"<link rel=\"stylesheet\" type=\"text/css\" href=\"file:///android_asset/monocore.css\" />\n" +
"<style>\n" +
" #reader {\n" +
" width: 100%;\n" +
" height: 100%;\n" +
" border: 0px solid #000;\n" +
" }\n" +
"</style>\n" +
"<script>\n" +
"\n" +
" var isNightMode = false;\n" +
" var isFirstLoading = false;\n" +
" var startPageNumber = 1;\n" +
"\n" +
" function setSettingsForFirstLoading(fontSize, pageNumber, nightMode) {\n" +
" Android.printLogInfo('setSettingsForFirstLoading()');\n" +
" isFirstLoading = true;\n" +
" isNightMode = nightMode;\n" +
" startPageNumber = pageNumber;\n" +
" window.changeFontSize(fontSize);\n" +
" }\n" +
"\n" +
" function changeFontSize(fontSize) {\n" +
" Android.printLogInfo('changeFontSize()');\n" +
" window.reader.formatting.setFontScale(fontSize);\n" +
" }\n" +
"\n" +
" function nightModeOn() {\n" +
" Android.printLogInfo('nightModeOn()');\n" +
" isNightMode = true;\n" +
" var i = 0;\n" +
" var frame;\n" +
" while (frame = window.reader.dom.find('component', i++)) {\n" +
" frame.contentDocument.body.style.backgroundColor = '#1F1F1F';\n" +
" frame.contentDocument.body.style.color = '#ECECEC';\n" +
" }\n" +
" }\n" +
"\n" +
" function nightModeOff() {\n" +
" Android.printLogInfo('nightModeOff()');\n" +
" isNightMode = false;\n" +
" var i = 0;\n" +
" var frame;\n" +
" while (frame = window.reader.dom.find('component', i++)) {\n" +
" frame.contentDocument.body.style.backgroundColor = '#ECECEC';\n" +
" frame.contentDocument.body.style.color = '#1F1F1F';\n" +
" }\n" +
" }\n" +
"\n" +
" function turnPage(pageNumber) {\n" +
" Android.printLogInfo('turnPage(' + pageNumber + ')');\n" +
" window.reader.moveTo({ page: pageNumber });\n" +
" }\n" +
"\n" +
" function savePercents() {\n" +
" Android.printLogInfo('savePercents()');\n" +
" Android.savePercents(window.reader.getPlace().percentAtTopOfPage());\n" +
" }\n" +
"\n" +
" function moveToPercents(percent) {\n" +
" Android.printLogInfo('moveToPercents(' + percent + ')');\n" +
" turnPage(window.reader.getPlace().pageAtPercentageThrough(percent));\n" +
" }\n" +
"\n" +
" function listenFor(evtName) {\n" +
" Monocle.Events.listen('reader', evtName, report);\n" +
" }\n" +
"\n" +
" function report(evt) {\n" +
" switch (evt.type) {\n" +
" case 'monocle:loaded':\n" +
" Android.calculateSeekBar(window.reader.getPlace().properties.component.lastPageNumber());\n" +
" break;\n" +
"\n" +
" case 'monocle:turn':\n" +
" Android.updatePagesCounter(window.reader.getPlace().pageNumber());\n" +
" break;\n" +
"\n" +
" case 'monocle:recalculated':\n" +
" if (isNightMode) nightModeOn();\n" +
" if (isFirstLoading) { isFirstLoading = false; turnPage(startPageNumber); }\n" +
" Android.calculateSeekBar(window.reader.getPlace().properties.component.lastPageNumber());\n" +
" Android.updatePagesCounter(window.reader.getPlace().pageNumber());\n" +
" break;\n" +
" }\n" +
" }\n" +
"\n" +
" function init() {\n" +
" var options = {\n" +
" flipper: Monocle.Flippers.Slider\n" +
" }\n" +
"\n" +
" listenFor('monocle:turn');\n" +
" listenFor('monocle:loaded');\n" +
" listenFor('monocle:recalculated');\n" +
"\n" +
" window.reader = Monocle.Reader('reader', null, options);\n" +
" }\n" +
"\n" +
" Monocle.Events.listen(window, 'load', init);\n" +
"</script>\n");
newCode = newCode.concat(code.substring(code.indexOf("<head>") + 6, code.indexOf("<body>") + 6));
newCode = newCode.concat("<div id=\"reader\">");
newCode = newCode.concat(code.substring(code.indexOf("<body>") + 6, code.indexOf("</body>")));
newCode = newCode.concat("</div>");
newCode = newCode.concat(code.substring(code.indexOf("</body>")));
return newCode;
}
After finishing this task the WebView loads it:
contentView.loadDataWithBaseURL(baseUrl, prepareCode(code), "text/html", "UTF-8", null);
What I have as results? I tested this app on six devices with Android 4.x and 5.x. On Android 4.x the entire content is shown correctly, but on Android 5.x I see a blank page. I should notice that the xhtml code was loaded because I can call JS-functions and get its results via JS Interface.
Are there any ideas about ways to fixing this bug?
Thanks in advance!
You can try uninstalling the webview system update.
or
Try monocle 2.3.1
or
https://github.com/joseph/Monocle/issues/259

Function in JavaScript that outputs concat url to YUI Chart Library Output

Trying to properly write a function in JavaScript that outputs a concat'd url to Chart Library Output (for chart re-rendering)... based on selected options in dropdown list.
Problem: I am not getting the chart to re-render with the concatenated url (which should be sent each time an option is selected in the dropdown).
JavaScript code in head:
function httpGet(theUrl)
{
var xmlHttp = null;
xmlHttp = new XMLHttpRequest(); // instantiate request
xmlHttp.open( "GET", theUrl, false ); // open url
xmlHttp.send( null ); // sending nothing
return xmlHttp.responseText; // return url's data as text
};
function selectFabric(){
var urlString = "http://localhost:8083/tbl/sparqlmotion?id=LiabilityChart&arg1=";
var fabrics = document.getElementById('fabrics');
var selectedFabric = fabrics.options[fabrics.selectedIndex];
var linkAddTogether = [urlString + selectedFabric.value];
var linkResult = linkAddTogether[0];
var result = httpGet(linkResult);
if (selectedFabric.value != "nothing"){
return linkResult; // update begins // document.write(linkAddTogether)
};
};
function revive (key, value) {
if (value.datatype == "http://www.w3.org/2001/XMLSchema#double" || // if datatype is this
value.datatype == "http://www.w3.org/2001/XMLSchema#integer" || // or, this
value.datatype == "http://www.w3.org/2001/XMLSchema#float") // or, this
{
return (parseInt(value.value)) // if '#double', '#integer', or '#schema', then: 'vars' label + convert the datatype's float value to integer
}
else if (value.type == 'literal')
{
return (value.value) // if datatype's value is a literal: 'vars' label + return as a string
}
else if (value.datatype == 'http://www.w3.org/2001/XMLSchema#date')
{
return value.value // if "XMLSchema#date's" value is a literal: 'vars' label + return as a string
}
else
{
return value // if datatype is anything else: 'vars' label + return value as a string
}
};
var scriptHead = ["YUI().use('charts',function(Y){var myDataValues=\n\n["];
var scriptTail = ["\n];\n\nvar styleDef={series:{Stock:{line:{color:'#EEB647'},marker:{fill:{color:'#eee',alpha:0,wmode:'transparent'},border:{color:'#222',alpha:0,wmode:'transparent'},over:{fill:{color:'#eee'},border:{color:'#000'},width:9,height:9}}},Liability:{line:{color:'#171944'},marker:{fill:{color:'#eee',alpha:0,wmode:'transparent'},border:{color:'#222',alpha:0,wmode:'transparent'},over:{fill:{color:'#eee'},border:{color:'#000'},width:9,height:9}}},Shipment:{line:{color:'#ff0000',alpha:0,wmode:'transparent'},marker:{fill:{color:'#eee',alpha:0,wmode:'transparent'},border:{color:'#ff0000',alpha:0,wmode:'transparent'},over:{fill:{color:'#ff0000',alpha:0,wmode:'transparent'},border:{color:'#000',alpha:0,wmode:'transparent'},width:16,height:16}}},Production:{line:{color:'#FFD700',alpha:0,wmode:'transparent'},marker:{fill:{color:'#eee',alpha:0,wmode:'transparent'},border:{color:'#FFD700',alpha:0,wmode:'transparent'},over:{fill:{color:'#FFD700',alpha:0,wmode:'transparent'},border:{color:'#000',alpha:0,wmode:'transparent'},width:16,height:16}}},Order:{line:{color:'#006400',alpha:0,wmode:'transparent'},marker:{fill:{color:'#eee',alpha:0,wmode:'transparent'},border:{color:'#006400',alpha:0,wmode:'transparent'},over:{fill:{color:'#006400',alpha:0,wmode:'transparent'},border:{color:'#000',alpha:0,wmode:'transparent'},width:16,height:16}}}}};var myAxes={dateRange:{keys:['date'],position:'bottom',type:'category',title:'Date Range',styles:{majorTicks:{display:'none'},label:{rotation:-45,margin:{top:5}},title:{fontSize:'90%'}}}};var mychart=new Y.Chart({dataProvider:myDataValues,interactionType:'planar',render:'#mychart',categoryKey:'Date',styles:styleDef,categoryType:'time',horizontalGridlines:{styles:{line:{color:'#fff'}}},verticalGridlines:{styles:{line:{color:'#fff'}}}})});\n\n"];
var simpleHead = [scriptHead];
var simpleTail = [scriptTail];
var oldData = JSON.parse(result, revive);
HTML code for form (in body):
form style="width:200px; color:#333; padding-right:5px; padding-bottom:2px; padding-left:55px; margin-top:0px; clear:none;" name="properties" id="properties">
select style="width:160px; color:#333; clear:none; display:block;" name="fabrics" id="fabrics" onChange="selectFabric()">
option value="nothing">Select Fabric END option
option value="KOD23-4074-LV">KOD23-4074-LV END option
option value="SGOD2-2858-LV">SGOD2-2858-LV END option
option value="W-897-LV">W-897-LV END option
option value="FF-4084-LV">FF-4084-LV END option
END select
END form
JavaScript code for chart (write script in body to render YUI chart plug-in):
document.write('\x3Cscript type="text/javascript" id="source">');
document.write(simpleHead[0] + '\n{Date: "' + oldData.results.bindings[0].date + '", Liability: ' + oldData.results.bindings[0].liability + ", Stock: " + oldData.results.bindings[0].stock + ", " + oldData.results.bindings[0].event + ": " + oldData.results.bindings[0].current + "}," + "\n\n");
document.write('\n{Date: "' + oldData.results.bindings[1].date + '", Liability: ' + oldData.results.bindings[1].liability + ", Stock: " + oldData.results.bindings[1].stock + ", " + oldData.results.bindings[1].event + ": " + oldData.results.bindings[1].current + "}," + "\n\n");
document.write('\n{Date: "' + oldData.results.bindings[2].date + '", Liability: ' + oldData.results.bindings[2].liability + ", Stock: " + oldData.results.bindings[2].stock + ", " + oldData.results.bindings[2].event + ": " + oldData.results.bindings[2].current + "}," + "\n\n");
document.write('\n{Date: "' + oldData.results.bindings[3].date + '", Liability: ' + oldData.results.bindings[3].liability + ", Stock: " + oldData.results.bindings[3].stock + ", " + oldData.results.bindings[3].event + ": " + oldData.results.bindings[3].current + "}," + "\n\n");
document.write('\n{Date: "' + oldData.results.bindings[4].date + '", Liability: ' + oldData.results.bindings[4].liability + ", Stock: " + oldData.results.bindings[4].stock + ", " + oldData.results.bindings[4].event + ": " + oldData.results.bindings[4].current + "}," + "\n\n");
document.write('\n{Date: "' + oldData.results.bindings[5].date + '", Liability: ' + oldData.results.bindings[5].liability + ", Stock: " + oldData.results.bindings[5].stock + ", " + oldData.results.bindings[5].event + ": " + oldData.results.bindings[5].current + "}," + "\n\n");
document.write('\n{Date: "' + oldData.results.bindings[6].date + '", Liability: ' + oldData.results.bindings[6].liability + ", Stock: " + oldData.results.bindings[6].stock + ", " + oldData.results.bindings[6].event + ": " + oldData.results.bindings[6].current + "}" + simpleTail[0] + "\n\n");
document.write('\x3C/script>');

Categories