I have a javascript file script.js, which has the following code
var winLoc = String(this.window.location);
var pos = winLoc.indexOf("lang=");
var spacer = '?';
if(pos >0) {
var curLang = winLoc.substring(pos+5,pos+7);
winLoc = winLoc.replace('lang=' + curLang, 'lang='+newLang);
} else {
if(winLoc.indexOf("?") > 0) {
spacer = '&';
}
winLoc = winLoc + spacer + 'lang=' + newLang;
}
this.window.location = winLoc; //cross site scripting issue//
I have to add this java code for the variable winLoc
winLoc = ESAPI.encoder().encodeForHTML(winLoc);
and this encoder() method is in ESAPI jar which I need to add as well
I am using it to avoid XSS Cross-Site Scripting Reflected.
Help me out in adding this java code to the JS file or any alternative you have in mind?
Well, I dont know what are you intending to get done, but generally, you cant execute Java code inside JavaScript.
Javascript is client side, meaning its interpreted by users browser, while Java is compiled into bytecode and executed by JVM on server side.
However, you can run JSP in a element, but it has to return valid JS.
https://www.javatpoint.com/jsp-expression-tag
You’ll have to use a JavaScript based tool in stead. Look at something like DOMPurify or jquery encoder.
For the specific context you are asking, HTML escaping looks wrong. You probably use encodeURIComponent instead.
Related
I have been going through so many forums & wikipedia's since few days for trying to understand about XSS attacks alomost I have spent 2-3 days but still not get better idea as suggesting multiple solutions by experts & I want know how the hackers can inject malicious code on victims browser ? and my application have been use to run on some App Scanner standard testing tool so its caught so many XSS issues. I want put here one of XSS issue of my application so can please some one help me out to understand the what exactly I have to do for this issue. Still I have been trying a lot to get better understand about XSS issues. This is my code snippet
function getParameter(param) {
var val = "";
var qs = window.location.search;
var start = qs.indexOf(param);
if (start != -1) {
start += param.length + 1;
var end = qs.indexOf("&", start);
if (end == -1) {
end = qs.length
}
val = qs.substring(start,end);
}
return val;
}
var formName = getParameter("formName");
var myValue = ''+thisDay+'</td>';
document.getElementById('calendarA').innerHTML = myValue;
And these statements are
var qs = window.location.search;
val = qs.substring(start,end);
var formName = getParameter("formName");
var myValue = ''+thisDay+'</td>';
document.getElementById('calendarA').innerHTML = myValue;
cought by App scanner testing tool as possible code for XSS(Cross Site Scripting) issues but I am not sure how it is cause to XSS & how I can fix this issue now. Can anybody please provide insights on how this vulnerability can be fixed?
var myValue = ''+thisDay+'</td>';
This line doesn't have any escaping, it expects '(... \''+formName+'\' );...' to be a string. But it can become some other thing:
formName = "'); alert('I\'m free to do anything here'); (''+"
document.getElementById('calendarA').innerHTML = myValue;
Let's place such fragment into myValue:
... <img src=void onerror="alert('hacked')" /> ...
You can check it works:
document.querySelector('button').addEventListener('click', function () {
document.querySelector('output').innerHTML = document.querySelector('textarea').value;
})
<textarea>... <img src=void onerror="alert('hacked')" /> ...</textarea>
<button>Go</button>
<output></output>
You should never trust any data passed by url string. Any site can place any link to you site. Some user clicks it, goes to your site, parameters are executed in context of your site, and attacker can do anything he wants to.
Nothing in the code you've shown us is vulnerable.
You are reading user input, so there is the potential to introduce a vulnerability there. That is probably what the tool you are using is detecting.
If your code is vulnerable, then it will be because of whatever you do with the value of formName next (in the code you haven't shown us).
This is a possible DOM based XSS issue.
If you are using the value of formName like document.getElementById("demo").innerHTML=formName or somehow your DOM elements are being created/modified using the formName you are vulnerable,
as i can create a custom url like http://urwebsite.html?formName=<script>document.cookie_will_be_transfered_to_my_server_here</script> and ask a logged in person to click it(simple social engineering) .Now i have that person's session id, using which i can do what ever i want.
As a resolution, all the input data from the user has to be html encoded.
I am trying to write a HTML page that asks users a series of questions. The answers to these questions are evaluated by my JavaScript code and used to determine which additional JavaScript file the user needs to access. My code then adds the additional JavaScript file to the head tag of my HTML page. I don't want to merge the code into a single JavaScript file because these additional files are large enough to be a nightmare if they're together, and I don't want to add them all to the head when the page first loads because I will have too many variable conflicts. I'm reluctant to redirect to a new webpage for each dictionary because this will make a lot of redundant coding. I'm not using any libraries.
I begin with the following HTML code:
<head>
<link rel="stylesheet" type="text/css" href="main.css">
<script src="firstSheet.js" type="text/JavaScript"></script>
</head>
//Lots of HTML.
<div id="mainUserMenu">
</div>
And I have the following JavaScript function:
function thirdLevelQuestions(secondLevelAnswer) {
//Code here to calculate the variables. This part works.
activeDictionary = firstKey + secondKey + '.js';
//Changing the HTML header to load the correct dictionary.
document.head.innerHTML = '<link rel="stylesheet" type="text/css" href="main.css"><script src="' + activeDictionary + '" type="text/JavaScript"></script><script src="firstSheet.js" type="text/JavaScript"></script>';
//for loop to generate the next level of buttons.
for (var i = 0; i < availableOptions.length; i++) {
document.getElementById('mainUserMenu').innerHTML += '<button onclick="fourthLevelQuestions(' + i + ')">' + availableOptions[i] + '</button>';
}
}
This creates the buttons that I want, and when I inspect the head element I can see both JavaScript files there. When I click on any of the buttons at this level they should call a function in the second file. Instead Chrome tells me "Uncaught ReferenceError: fourthLevelQuestions is not defined" (html:1). If I paste the code back into firstSheet.js the function works, so I assume the problem is that my HTML document is not actually accessing the activeDictionary file. Is there a way to do this?
What Can be done
You are trying to load Javascript on Demand. This has been a well thought out problem lately and most of the native solutions didn't work well across bowser implementations. Check a study here with different solutions and background of the problem explained well.
For the case of large web applications the solution was to use some javascript library that helped with modularising code and loading them on demand using some script loaders. The focus is on modularizing code and not in just script loading. Check some libraries here. There are heavier ones which includes architectures like MVC with them.
If you use AJAX implementation of jQuery with the correct dataType jQuery will help you evaluate the scripts, they are famous for handling browser differences. You can as well take a look at the exclusive getScript() which is indeed a shorthand for AJAX with dataType script. Keep in mind that loading script with native AJAX does not guarantee evaluation of the javascript included, jQuery is doing the evaluation internally during the processing stage.
What is wrong
What you have done above might work in most modern browsers (not sure), but there is an essential flaw in your code. You are adding the script tags to your head using innerHTML which inserts those lines to your HTML. Even if your browser loads the script it takes a network delay time and we call it asynchronous loading, you cannot use the script right away. Then what do you do? Use the script when its ready or loaded. Surprisingly you have an event for that, just use it. Can be something like:
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';
script.onreadystatechange= function () {
if (this.readyState == 'complete') helper();
}
script.onload= helper;
script.src= 'helper.js';
head.appendChild(script);
Check this article for help with implementation without using external libraries
From the variable name activeDictionary If I guess that you are loading some data sets as opposed to javascript programs, you should try looking into JSON and loading and using them dynamically.
If this Question/Answer satisfies your needs, you should delete your question to avoid duplicate entries in SO.
The best way to achieve this would be with jQuery:
$(document).ready(function() {
$('#button').click(function() {
var html = "<script src='newfile.js' type='text/javascript'></script>";
var oldhtml = "<script src='firstSheet.js' type='text/javascript'></script>";
if ($(this).attr('src') == 'firstSheet.js') {
$('script[src="firstSheet.js"]').replace(html);
return;
}
$('script[src="newfile.js"]').replace(oldhtml);
});
});
I would suggest you create the elements how they should be and then append them. Also, if you are dynamically adding the firstSheet.js you shouldn't include it in your .html file.
function thirdLevelQuestions(secondLevelAnswer) {
var mainUserMenu = document.getElementById('mainUserMenu');
activeDictionary = firstKey + secondKey + '.js';
var css = document.createElement('link');
css.rel = 'stylesheet';
css.type = 'text/css';
css.href = 'main.css';
var script1 = document.createElement('script');
script1.type = 'text/javascript';
script1.src = 'firstSheet.js';
var script2 = document.createElement('script');
script2.type = 'text/javascript';
script2.src = activeDictionary;
document.head.appendChild(css);
document.head.appendChild(script1);
document.head.appendChild(script2);
for (var i = 0; i < availableOptions.length; i++) {
var btn = document.createElement('button');
btn.onclick = 'fourthLevelQuestions(' + i + ')';
var val = document.createTextNode(availableOptions[i]);
btn.appendChild(val);
mainUserMenu.appendChild(btn);
}
}
I'm writing a C++ Project template in VS 2010 using the Custom Wizard technique.
In the default.js, the file which holds the behind JavaScript code, I want to take the current generated project, and locate it in an existing VS solution, in a specific "apps" subfolder.
I have a C# working code which does the above, but I have to rewrite it in JavaScript.
My C# code is:
Projects ps = solution.Projects;
var item = ps.GetEnumerator();
while (item.MoveNext())
{
var project = item.Current as Project;
string name = project.Name;
if (name == "apps")
{
SolutionFolder folder = (SolutionFolder)project.Object;
p = folder.AddFromFile(newProjDir + "\\" + projName + ".vcxproj");
}
}
In JavaScript, I wrote:
var ps = Solution.Projects;
But now I don't succeed to iterate over the projects, as I did in c#.
When I'm trying to write in the JS file:
var item = ps.GetEnumerator();
I'm getting the run time error:
Object doesn't support this property or method
Do you know about any way to iterate over the Projects collection? Is there a JS function which behaves like GetEnumerator()?
As you of course know, JS is a client side language.
You cannot get information from the server (like Solution.Projects).
But you can write a web service and use it from the your web page to get the information.
I found my way:
for (var i = 1; i <= solution.Projects.Count; i++)
{
if(Solution.Projects.Item(i).Name == "apps")
{
appsFolder = Solution.Projects.Item(i);
project = appsFolder.Object.AddFromFile(newProjectPath + "\\" + strProjectName + "\\" + strProjectName + ".vcxproj");
break;
}
}
Thanks you all for trying help :)
I have a important piece of code that modifies my requests written Javascript, but i want to add an external jar and use it from the scripts, any suggestions? It's defined a sort of import function or something like that?
In order to use your own jars in Setup Script in SOAPUI with javascript language you must do the next steps:
With SOAPUI closed, copy your jars to SOAPUI_HOME/bin/ext.
Start SOPAUI
On the project properties select Javascript for Script Language property.
Then in the Setup Script you have to reference the full package for your java classes like (I put a sample where I decode a base64 string):
java.lang.System.out.println("-----------");
java.lang.System.out.println("SAMPLE INIT");
java.lang.System.out.println("-----------\n");
var obj = new org.apache.commons.codec.binary.Base64();
var stringb64 = new java.lang.String("dGVzdA==")
var dataDecoded = obj.decodeBase64(stringb64.getBytes());
java.lang.System.out.println("RESULT " + new java.lang.String(dataDecoded) + "\n");
java.lang.System.out.println("-----------");
java.lang.System.out.println("SAMPLE END");
java.lang.System.out.println("-----------");
If you run soapui from .bat you can see the system out on the cmd:
I'm working on some code that needs to parse numerous files that contain fragments of HTML. It seems that jQuery would be very useful for this, but when I try to load jQuery into something like WScript or CScript, it throws an error because of jQuery's many references to the window object.
What practical way is there to use jQuery in code that runs without a browser?
Update: In response to the comments, I have successfully written JavaScript code to read the contents of files using new ActiveXObject('Scripting.FileSystemObject');. I know that ActiveX is evil, but this is just an internal project to get some data out of some files that contain HTML fragments and into a proper database.
Another Update: My code so far looks about like this:
var fileIo, here;
fileIo = new ActiveXObject('Scripting.FileSystemObject');
here = unescape(fileIo.GetParentFolderName(WScript.ScriptFullName) + "\\");
(function() {
var files, thisFile, thisFileName, thisFileText;
for (files = new Enumerator(fileIo.GetFolder(here).files); !files.atEnd(); files.moveNext()) {
thisFileName = files.item().Name;
thisFile = fileIo.OpenTextFile(here + thisFileName);
thisFileText = thisFile.ReadAll();
// I want to do something like this:
s = $(thisFileText).find('input#txtFoo').val();
}
})();
Update: I posted this question on the jQuery forums as well: http://forum.jquery.com/topic/how-to-use-jquery-without-a-browser#14737000003719577
Following along with your code, you could create an instance of IE using Windows Script Host, load your html file in to the instance, append jQuery dynamically to the loaded page, then script from that.
This works in IE8 with XP, but I'm aware of some security issues in Windows 7/IE9. IF you run into problems you could try lowering your security settings.
var fileIo, here, ie;
fileIo = new ActiveXObject('Scripting.FileSystemObject');
here = unescape(fileIo.GetParentFolderName(WScript.ScriptFullName) + "\\");
ie = new ActiveXObject("InternetExplorer.Application");
ie.visible = true
function loadDoc(src) {
var head, script;
ie.Navigate(src);
while(ie.busy){
WScript.sleep(100);
}
head = ie.document.getElementsByTagName("head")[0];
script = ie.document.createElement('script');
script.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js";
head.appendChild(script);
return ie.document.parentWindow;
}
(function() {
var files, thisFile, win;
for (files = new Enumerator(fileIo.GetFolder(here).files); !files.atEnd(); files.moveNext()) {
thisFile = files.item();
if(fileIo.GetExtensionName(thisFile)=="htm") {
win = loadDoc(thisFile);
// your jQuery reference = win.$
WScript.echo(thisFile + ": " + win.$('input#txtFoo').val());
}
}
})();
This is pretty easy to do in Node.js with the cheerio package. You can read in arbitrary HTML from whatever source you want, parse it with cheerio and then access the parsed elements using jQuery style selectors.