POST data issues - javascript

I have an issue with submitting post data. I have a form which have a couple of text fields in, and when a button is pressed to submit the data, it is run through a custom from validation (JS), then I construct a query string like
title=test&content=some content
which is then submitted to the server. The problem I had is when I have '&' (eg &nbsp) entered into one of the inputs which then breaks up the query string. Eg:
title=test&content=some content &nbsp
How do I get around this?
Thanks in advance,
Harry.

Run encodeURIComponent over each key and value.
var title = "test";
var content = "some content &nbsp ";
var data = encodeURIComponent('title') + /* You don't actually need to encode this as it is a string that only contains safe characters, but you would if you weren't sure about the data */
'=' + encodeURIComponent(title) +
'&' + encodeURIComponent('content') +
'=' + encodeURIComponent(content);

Encode the string..when you want to encode a query string with special characters you need to use encoding. ampersand is encoded like this
title=test&content=some content %26
basically any character in a query string can be replaced by its ASCII Hex equivalent with a % as the prefix
Space = %20
A = %41
B = %42
C = %43
...

You need to encode your query to make it URL-safe. You can refer to the following links on how to do that in JS:
http://xkr.us/articles/javascript/encode-compare/
http://www.webtoolkit.info/javascript-url-decode-encode.html

You said:
...and when a button is pressed to submit the data, it is run through a custom from validation (JS), then I construct a query string...
In the section where you are building the query string you should also run the value of each input through encodeURIComponent() as David Dorward suggested.
As you do - be careful that you only assign the new value to your processed query string and NOT the form element value, otherwise your users will think their input was somehow corrupted and potentially freak out.
[EDIT]
I just re-read your question and realized something important: you're encoding an &nbsp ;character. This is probably a more complicated issue than other posters here have read into. If you want that character, and other &code; type characters to transfer over you'll need to realize that they are codes. Those characters &, n, b, s, p and ; are not themselves the same as " " which is a space character that does not break.
You'll have to add another step of encoding/decoding. You can place this step either before of after the data is sent (or "POSTed").
Before:
(Using this question's answers)
var data = formElement.value;
data = rhtmlspecialchars(data, 0);
Which is intended to replace your "special" characters like with " " so that they are then properly encoded by encodeURIComponent(data)
Or after:
(using standard PHP functions)
<?PHP
$your_field_name = htmlspecialchars_decode(urldecode($_POST['your_field_name']));
?>
This assumes that you escaped the & in your POST with %26
If you replaced it with some function other than encodeURIComponent() you'll have to find a different way to decode it in PHP.

This should solve your problem:
encodeURIComponent(name)+'='+encodeURIComponent(value)+'&'+encodeURIComponent(name2)+'='+encodeURIComponent(value2)
You need to escape each value (and name if you want to be on the safe side) before concatenating them when you're building your query.
The JavaScript global function encodeURIComponent() does the escaping.
The global function escape() (DOM) does this for you in a browser. Although people are saying it is not doing the escaping well for unicode chars. Anyway if you're only concerned about '&' then this would solve your problem.

Related

Replace character with a absolute value

When searching my db all special characters work aside from the "+" - it thinks its a space. Looking on the backend which is python, there is no issues with it receiving special chars which I believe it is the frontend which is Javascript
what i need to do is replace "+" == "%2b". Is there a way for me to use create this so it has this value going forth?
You can use decodeURIComponent('%2b'), or encodeUriComponent('+');
if you decode the response from the server, you get the + sign-
if you want to replace all ocurrence just place the whole string insde the method and it decodes/encodes the whole string.

Javascript How to escape \u in string literal

Strange thing...
I have a string literal that is passed to my source code as a constant token (I cannot prehandle or escape it beforehand).
Example
var username = "MYDOMAIN\tom";
username = username.replace('MYDOMAIN','');
The string somewhere contains a backslash followed by a character.
It's too late to escape the backslash at this point, so I have to escape these special characters individually like
username = username.replace(/\t/ig, 't');
However, that does not work in the following scenario:
var username = "MYDOMAIN\ulrike";
\u seems to introduce a unicode character sequence. \uLRIK cannot be interpreted as a unicode sign so the Javascript engine stops interpreting at this point and my replace(/\u/ig,'u') comes too late.
Has anybody a suggestion or workaround on how to escape such a non-unicode character sequence contained in a given string literal? It seems a similar issue with \b like in "MYDOMAIN\bernd".
I have a string literal that is passed to my source code
Assuming you don't have any < or >, move this to inside an HTML control (instead of inside your script block) or element and use Javacript to read the value. Something like
<div id="myServerData">
MYDOMAIN\tom
</div>
and you retrieve it so
alert(document.getElementById("myServerData").innerText);
IMPORTANT : injecting unescaped content, where the user can control the content (say this is data entered in some other page) is a security risk. This goes for whether you are injecting it in script or HTML
Writing var username = "MYDOMAIN\ulrike"; will throw a syntax error. I think you have this string coming from somewhere.
I would suggest creating some html element and setting it's innerHTML to the received value, and then picking it up.
Have something like:
<div id="demo"></div>
Then do document.getElementById("demo").innerHTML = username;
Then read the value from there as document.getElementById("demo").innerHTML;
This should work I guess.
Important: Please make sure this does not expose the webpage to script injections. If it does, this method is bad, don't use it.

How to encode and decode HTML special characters to get entity name

The character set is mentioned at Special Character Map. I need a Java-script or J-Query encoding code to get entity name.
for e.g. if I pass £ then I should get "&pound ;" or for ¥ it should return "&yen ;".
Even I copy the symbols instead of typing in then also it should work.
I am trying to use following J-Query code but it doesn't seem to work when I copy-paste strings.
function krEncodeEntities() {
var s = $('#input').val();
return $('#lblEncode').text($("<div/>").text(s).html());
}
function krDencodeEntities() {
var s = $('#lblEncode').text();
return $('#lblDecode').text($("<div/>").html(s).text());
}
Can anyone please help me?
JavaScript has no concept of HTML identities. To JS, everything is UCS16 (a forerunner of UTF16).
You have a couple of options.
Option 1
Make a big translation object of characters and their identities.
Option 2
See if some other form of encoding will work for you.
When are you supposed to use escape instead of encodeURI / encodeURIComponent?

JS/XSS: When assigning user-provided strings to variables; is it enough to replace <,>, and string delimiter?

If a server-side script generates the following output:
<script>
var a = 'text1';
var b = 'text2';
var c = 'text3';
</script>
, and the values (in this example "text1", "text2" and "text3") are user supplied (via HTTP GET/POST), is it enough to remove < and > from the input and to replace
'
with
' + "'" + '
in order to be safe from XSS? (This is my main question)
I'm particularly worried about the backslash not being escaped because an attacker could unescape the trailing '. Could that be a potential problem in this context? If the variable assignments were not separated by line breaks, an attacker could supply the values
text1
text2\
;alert(1);//
and end up with working JS code like
<script>
var a = 'text1'; var b = 'text2\'; var c = ';alert(1);//text3';
</script>
But since there are line breaks that shouldn't be a problem either. Am I missing something else?
It would be more secure to JSON encode your data, instead of rolling your own Javascript encoding function. When dealing with web application security, rolling your own is almost always not the answer. A JSON representation would handle the quotes and backslashes and any other special characters.
Most server side languages have a JSON module. Some also have a function specifically for what you're doing such as HttpUtility.JavaScriptStringEncode for the .NET framework.
If you were to roll your own, then it would be better to replace the characters for example like " to \x22, instead of changing single quotes or removing them. Also consider there is a multitude of creative XSS attacks that you'd need to defend against.
The end result, whatever method you use, is your data should remain intact when presented to the user. For example it's no good having O"Neil if someone's name is O'Neil.

How do you define a string in JavaScript that could contain any character?

Even though I'm using a Salesforce variable in my JavaScript, it is not necessary to know Salesforce to answer my question. There's a password field I want to access. I can do this by using the Salesforce variable, {!Account.Password__c}, inside my JavaScript like so:
var p = '{!Account.Password__c}';
I've been using this for a long time, but there are some instances where it doesn't work. The only problem is that the password could contain any character (as a good password should). So if it contains a single quote, then this JavaScript will not run. I could write it with double quotes:
var p = "{!Account.Password__c}";
But it could contain a double quote also. It could also contain forward slashes and/or back slashes.
The password string needs to be able to take any of these:
Idon'tknow
pass"word"
/-\_|)_/-\_/\/\
"'!##
+*co/rn
This is my code:
var u = '{!Account.Email_Address__c}';
var p = escape(encodeURIComponent('{!Account.Password__c}'));
window.open('http://mywebsite.com/?&u=' + u + '&p=' + p,'_blank');
What you're looking for is the JSENCODE function. It will escape quotes, backslashes, and anything else that might mess up your Javascript string.
var p = '{!JSENCODE(Account.Password__c)}';
If your Javascript is inside an HTML tag (eg: in an 'onclick' attribute) then use the JSINHTMLENCODE function, which will html-encode the characters <&> .
These are documented in the Visualforce Functions reference.
Your problem is that of escaping. You can backslash any character in a string - so if you have, say, owowow"'!thisishard as a password, to assign it straight up to a JS var, you would do this:
var p = "owowow\"\'!thisishard";
Which deals with the escaping. You do not need to do this if you have acquired the variable from another source (say, a text element through element.value).
This does not reove a couple of issues:
Passing passwords through GET params is pretty high up on the OWASP guidelines of things not to do. The reason being that they will show up on server logs in addition to being sniffable through conventional means.
Why on earth are you doing this?

Categories

Resources