Javascript used in URL - javascript

Looking through analytics, I saw that someone visited my cart page and added the following to the URL:
cart?wvstest=javascript:domxssExecutionSink(1,%2522%253Cbr%253E()locxss%2522)
What would this do, and should I be considered of any security issues?

It's an attempt at injecting JavaScript by penetration tool Acunetix. The specfic attack is DOM based XSS (as shown by the function named domxssExecutionSink). If you were to echo the query parameter wvstest directly to the page, their JavaScript would have been executed.
Read more about XSS atacks (and how to mitigate them) at OWASP

It will pass the data to your server.
What happens next depends on your server side code.
If you were to read wvstest as a query string and then inject it (without proper sanitisation) into an HTML document, you would have an XSS security hole.

Related

Why does Medium's API prepend while(1) to the JSONP response? [duplicate]

Why does Google prepend while(1); to their (private) JSON responses?
For example, here's a response while turning a calendar on and off in Google Calendar:
while (1);
[
['u', [
['smsSentFlag', 'false'],
['hideInvitations', 'false'],
['remindOnRespondedEventsOnly', 'true'],
['hideInvitations_remindOnRespondedEventsOnly', 'false_true'],
['Calendar ID stripped for privacy', 'false'],
['smsVerifiedFlag', 'true']
]]
]
I would assume this is to prevent people from doing an eval() on it, but all you'd really have to do is replace the while and then you'd be set. I would assume the eval prevention is to make sure people write safe JSON parsing code.
I've seen this used in a couple of other places, too, but a lot more so with Google (Mail, Calendar, Contacts, etc.) Strangely enough, Google Docs starts with &&&START&&& instead, and Google Contacts seems to start with while(1); &&&START&&&.
What's going on here?
It prevents JSON hijacking, a major JSON security issue that is formally fixed in all major browsers since 2011 with ECMAScript 5.
Contrived example: say Google has a URL like mail.google.com/json?action=inbox which returns the first 50 messages of your inbox in JSON format. Evil websites on other domains can't make AJAX requests to get this data due to the same-origin policy, but they can include the URL via a <script> tag. The URL is visited with your cookies, and by overriding the global array constructor or accessor methods they can have a method called whenever an object (array or hash) attribute is set, allowing them to read the JSON content.
The while(1); or &&&BLAH&&& prevents this: an AJAX request at mail.google.com will have full access to the text content, and can strip it away. But a <script> tag insertion blindly executes the JavaScript without any processing, resulting in either an infinite loop or a syntax error.
This does not address the issue of cross-site request forgery.
It prevents disclosure of the response through JSON hijacking.
In theory, the content of HTTP responses is protected by the Same Origin Policy: pages from one domain cannot get any pieces of information from pages on the other domain (unless explicitly allowed).
An attacker can request pages on other domains on your behalf, e.g. by using a <script src=...> or <img> tag, but it can't get any information about the result (headers, contents).
Thus, if you visit an attacker's page, it couldn't read your email from gmail.com.
Except that when using a script tag to request JSON content, the JSON is executed as JavaScript in an attacker's controlled environment. If the attacker can replace the Array or Object constructor or some other method used during object construction, anything in the JSON would pass through the attacker's code, and be disclosed.
Note that this happens when the JSON is executed as JavaScript, not when it's parsed.
There are multiple countermeasures:
Making sure the JSON never executes
By placing a while(1); statement before the JSON data, Google ensures that the JSON data is never executed as JavaScript.
Only a legitimate page could actually get the whole content, strip the while(1);, and parse the remainder as JSON.
Things like for(;;); have been seen on Facebook for instance, with the same results.
Making sure the JSON is not valid JavaScript
Similarly, adding invalid tokens before the JSON, like &&&START&&&, makes sure that it is never executed.
Always return JSON with an Object on the outside
This is OWASP recommended way to protect from JSON hijacking and is the less intrusive one.
Similarly to the previous counter-measures, it makes sure that the JSON is never executed as JavaScript.
A valid JSON object, when not enclosed by anything, is not valid in JavaScript, since the { } gets interpreted as a code block:
eval('{"foo":"bar"}')
// SyntaxError: Unexpected token :
This is however valid JSON:
JSON.parse('{"foo":"bar"}')
// Object {foo: "bar"}
So, make sure you always return an Object at the top level of the response and make sure that the JSON is not valid JavaScript, while still being valid JSON.
As noted by #hvd in the comments, the empty object {} is valid JavaScript, and knowing the object is empty may itself be valuable information.
Comparison of the above methods
The OWASP way is less intrusive, as it needs no client library changes, and transfers valid JSON. It is unsure whether past or future browser bugs could defeat this, however. As noted by #oriadam, it is unclear whether data could be leaked in a parse error through an error handling or not (e.g. window.onerror).
Google's way requires a client library in order for it to support automatic de-serialization and can be considered to be safer with regard to browser bugs.
Both methods require server-side changes in order to avoid developers accidentally sending vulnerable JSON.
This is to ensure some other site can't do nasty tricks to try to steal your data. For example, by replacing the array constructor, then including this JSON URL via a <script> tag, a malicious third-party site could steal the data from the JSON response. By putting a while(1); at the start, the script will hang instead.
A same-site request using XHR and a separate JSON parser, on the other hand, can easily ignore the while(1); prefix.
That would be to make it difficult for a third-party to insert the JSON response into an HTML document with the <script> tag. Remember that the <script> tag is exempt from the Same Origin Policy.
Note: as of 2019, many of the old vulnerabilities that lead to the preventative measures discussed in this question are no longer an issue in modern browsers. I'll leave the answer below as a historical curiosity, but really the whole topic has changed radically since 2010 (!!) when this was asked.
It prevents it from being used as the target of a simple <script> tag. (Well, it doesn't prevent it, but it makes it unpleasant.) That way bad guys can't just put that script tag in their own site and rely on an active session to make it possible to fetch your content.
edit — note the comment (and other answers). The issue has to do with subverted built-in facilities, specifically the Object and Array constructors. Those can be altered such that otherwise innocuous JSON, when parsed, could trigger attacker code.
Since the <script> tag is exempted from the Same Origin Policy which is a security necessity in the web world, while(1) when added to the JSON response prevents misuse of it in the <script> tag.
As this is a High traffic post I hope to provide here an answer slightly more undetermined to the original question and thus provide further background on a JSON Hijacking attack and its consequences
JSON Hijacking as the name suggests is an attack similar to Cross-Site Request Forgery where an attacker can access cross-domain sensitive JSON data from applications that return sensitive data as array literals to GET requests. An example of a JSON call returning an array literal is shown below:
[{"id":"1001","ccnum":"4111111111111111","balance":"2345.15"},
{"id":"1002","ccnum":"5555555555554444","balance":"10345.00"},
{"id":"1003","ccnum":"5105105105105100","balance":"6250.50"}]
This attack can be achieved in 3 major steps:
Step 1: Get an authenticated user to visit a malicious page.
Step 2: The malicious page will try and access sensitive data from the application that the user is logged into. This can be done by embedding a script tag in an HTML page since the same-origin policy does not apply to script tags.
<script src="http://<jsonsite>/json_server.php"></script>
The browser will make a GET request to json_server.php and any authentication cookies of the user will be sent along with the request.
Step 3: At this point, while the malicious site has executed the script it does not have access to any sensitive data. Getting access to the data can be achieved by using an object prototype setter. In the code below an object prototypes property is being bound to the defined function when an attempt is being made to set the "ccnum" property.
Object.prototype.__defineSetter__('ccnum',function(obj){
secrets =secrets.concat(" ", obj);
});
At this point, the malicious site has successfully hijacked the sensitive financial data (ccnum) returned byjson_server.php
JSON
It should be noted that not all browsers support this method; the proof of concept was done on Firefox 3.x.This method has now been deprecated and replaced by the useObject.defineProperty There is also a variation of this attack that should work on all browsers where full-named JavaScript (e.g. pi=3.14159) is returned instead of a JSON array.
There are several ways in which JSON Hijacking can be prevented:
Since SCRIPT tags can only generate HTTP GET requests, they only return JSON objects to POST
requests.
Prevent the web browser from interpreting the JSON object as valid JavaScript code.
Implement Cross-Site Request Forgery protection by requiring that a predefined random value be required for all JSON requests.
so as you can see While(1) comes under the last option. In the most simple terms, while(1) is an infinite loop that will run till a break statement is issued explicitly. And thus what would be described as a lock for the key to be applied (google break statement). Therefore a JSON hijacking, in which the Hacker has no key will be consistently dismissed. Alas, If you read the JSON block with a parser, the while(1) loop is ignored.
So in conclusion, the while(1) loop can more easily be visualized as a simple break statement cypher that google can use to control the flow of data.
However, the keyword in that statement is the word 'simple'. The usage of authenticated infinite loops has been thankfully removed from basic practice in the years since 2010 due to its absolute decimation of CPU usage when isolated (and the fact the internet has moved away from forcing through crude 'quick-fixes'). Today instead the codebase has embedded preventative measures, and the system is not crucial or effective anymore. (part of this is the move away from JSON Hijacking to more fruitful data farming techniques that I won't go into at present)
After authentication is in place, JSON hijacking protection can take a
variety of forms. Google appends while(1) into their JSON data, so
that if any malicious script evaluates it, the malicious script enters
an infinite loop.
Reference: Web Security Testing Cookbook: Systematic Techniques to Find Problems Fast

Why does this JSON response have code for an infinite loop? [duplicate]

Why does Google prepend while(1); to their (private) JSON responses?
For example, here's a response while turning a calendar on and off in Google Calendar:
while (1);
[
['u', [
['smsSentFlag', 'false'],
['hideInvitations', 'false'],
['remindOnRespondedEventsOnly', 'true'],
['hideInvitations_remindOnRespondedEventsOnly', 'false_true'],
['Calendar ID stripped for privacy', 'false'],
['smsVerifiedFlag', 'true']
]]
]
I would assume this is to prevent people from doing an eval() on it, but all you'd really have to do is replace the while and then you'd be set. I would assume the eval prevention is to make sure people write safe JSON parsing code.
I've seen this used in a couple of other places, too, but a lot more so with Google (Mail, Calendar, Contacts, etc.) Strangely enough, Google Docs starts with &&&START&&& instead, and Google Contacts seems to start with while(1); &&&START&&&.
What's going on here?
It prevents JSON hijacking, a major JSON security issue that is formally fixed in all major browsers since 2011 with ECMAScript 5.
Contrived example: say Google has a URL like mail.google.com/json?action=inbox which returns the first 50 messages of your inbox in JSON format. Evil websites on other domains can't make AJAX requests to get this data due to the same-origin policy, but they can include the URL via a <script> tag. The URL is visited with your cookies, and by overriding the global array constructor or accessor methods they can have a method called whenever an object (array or hash) attribute is set, allowing them to read the JSON content.
The while(1); or &&&BLAH&&& prevents this: an AJAX request at mail.google.com will have full access to the text content, and can strip it away. But a <script> tag insertion blindly executes the JavaScript without any processing, resulting in either an infinite loop or a syntax error.
This does not address the issue of cross-site request forgery.
It prevents disclosure of the response through JSON hijacking.
In theory, the content of HTTP responses is protected by the Same Origin Policy: pages from one domain cannot get any pieces of information from pages on the other domain (unless explicitly allowed).
An attacker can request pages on other domains on your behalf, e.g. by using a <script src=...> or <img> tag, but it can't get any information about the result (headers, contents).
Thus, if you visit an attacker's page, it couldn't read your email from gmail.com.
Except that when using a script tag to request JSON content, the JSON is executed as JavaScript in an attacker's controlled environment. If the attacker can replace the Array or Object constructor or some other method used during object construction, anything in the JSON would pass through the attacker's code, and be disclosed.
Note that this happens when the JSON is executed as JavaScript, not when it's parsed.
There are multiple countermeasures:
Making sure the JSON never executes
By placing a while(1); statement before the JSON data, Google ensures that the JSON data is never executed as JavaScript.
Only a legitimate page could actually get the whole content, strip the while(1);, and parse the remainder as JSON.
Things like for(;;); have been seen on Facebook for instance, with the same results.
Making sure the JSON is not valid JavaScript
Similarly, adding invalid tokens before the JSON, like &&&START&&&, makes sure that it is never executed.
Always return JSON with an Object on the outside
This is OWASP recommended way to protect from JSON hijacking and is the less intrusive one.
Similarly to the previous counter-measures, it makes sure that the JSON is never executed as JavaScript.
A valid JSON object, when not enclosed by anything, is not valid in JavaScript, since the { } gets interpreted as a code block:
eval('{"foo":"bar"}')
// SyntaxError: Unexpected token :
This is however valid JSON:
JSON.parse('{"foo":"bar"}')
// Object {foo: "bar"}
So, make sure you always return an Object at the top level of the response and make sure that the JSON is not valid JavaScript, while still being valid JSON.
As noted by #hvd in the comments, the empty object {} is valid JavaScript, and knowing the object is empty may itself be valuable information.
Comparison of the above methods
The OWASP way is less intrusive, as it needs no client library changes, and transfers valid JSON. It is unsure whether past or future browser bugs could defeat this, however. As noted by #oriadam, it is unclear whether data could be leaked in a parse error through an error handling or not (e.g. window.onerror).
Google's way requires a client library in order for it to support automatic de-serialization and can be considered to be safer with regard to browser bugs.
Both methods require server-side changes in order to avoid developers accidentally sending vulnerable JSON.
This is to ensure some other site can't do nasty tricks to try to steal your data. For example, by replacing the array constructor, then including this JSON URL via a <script> tag, a malicious third-party site could steal the data from the JSON response. By putting a while(1); at the start, the script will hang instead.
A same-site request using XHR and a separate JSON parser, on the other hand, can easily ignore the while(1); prefix.
That would be to make it difficult for a third-party to insert the JSON response into an HTML document with the <script> tag. Remember that the <script> tag is exempt from the Same Origin Policy.
Note: as of 2019, many of the old vulnerabilities that lead to the preventative measures discussed in this question are no longer an issue in modern browsers. I'll leave the answer below as a historical curiosity, but really the whole topic has changed radically since 2010 (!!) when this was asked.
It prevents it from being used as the target of a simple <script> tag. (Well, it doesn't prevent it, but it makes it unpleasant.) That way bad guys can't just put that script tag in their own site and rely on an active session to make it possible to fetch your content.
edit — note the comment (and other answers). The issue has to do with subverted built-in facilities, specifically the Object and Array constructors. Those can be altered such that otherwise innocuous JSON, when parsed, could trigger attacker code.
Since the <script> tag is exempted from the Same Origin Policy which is a security necessity in the web world, while(1) when added to the JSON response prevents misuse of it in the <script> tag.
As this is a High traffic post I hope to provide here an answer slightly more undetermined to the original question and thus provide further background on a JSON Hijacking attack and its consequences
JSON Hijacking as the name suggests is an attack similar to Cross-Site Request Forgery where an attacker can access cross-domain sensitive JSON data from applications that return sensitive data as array literals to GET requests. An example of a JSON call returning an array literal is shown below:
[{"id":"1001","ccnum":"4111111111111111","balance":"2345.15"},
{"id":"1002","ccnum":"5555555555554444","balance":"10345.00"},
{"id":"1003","ccnum":"5105105105105100","balance":"6250.50"}]
This attack can be achieved in 3 major steps:
Step 1: Get an authenticated user to visit a malicious page.
Step 2: The malicious page will try and access sensitive data from the application that the user is logged into. This can be done by embedding a script tag in an HTML page since the same-origin policy does not apply to script tags.
<script src="http://<jsonsite>/json_server.php"></script>
The browser will make a GET request to json_server.php and any authentication cookies of the user will be sent along with the request.
Step 3: At this point, while the malicious site has executed the script it does not have access to any sensitive data. Getting access to the data can be achieved by using an object prototype setter. In the code below an object prototypes property is being bound to the defined function when an attempt is being made to set the "ccnum" property.
Object.prototype.__defineSetter__('ccnum',function(obj){
secrets =secrets.concat(" ", obj);
});
At this point, the malicious site has successfully hijacked the sensitive financial data (ccnum) returned byjson_server.php
JSON
It should be noted that not all browsers support this method; the proof of concept was done on Firefox 3.x.This method has now been deprecated and replaced by the useObject.defineProperty There is also a variation of this attack that should work on all browsers where full-named JavaScript (e.g. pi=3.14159) is returned instead of a JSON array.
There are several ways in which JSON Hijacking can be prevented:
Since SCRIPT tags can only generate HTTP GET requests, they only return JSON objects to POST
requests.
Prevent the web browser from interpreting the JSON object as valid JavaScript code.
Implement Cross-Site Request Forgery protection by requiring that a predefined random value be required for all JSON requests.
so as you can see While(1) comes under the last option. In the most simple terms, while(1) is an infinite loop that will run till a break statement is issued explicitly. And thus what would be described as a lock for the key to be applied (google break statement). Therefore a JSON hijacking, in which the Hacker has no key will be consistently dismissed. Alas, If you read the JSON block with a parser, the while(1) loop is ignored.
So in conclusion, the while(1) loop can more easily be visualized as a simple break statement cypher that google can use to control the flow of data.
However, the keyword in that statement is the word 'simple'. The usage of authenticated infinite loops has been thankfully removed from basic practice in the years since 2010 due to its absolute decimation of CPU usage when isolated (and the fact the internet has moved away from forcing through crude 'quick-fixes'). Today instead the codebase has embedded preventative measures, and the system is not crucial or effective anymore. (part of this is the move away from JSON Hijacking to more fruitful data farming techniques that I won't go into at present)
After authentication is in place, JSON hijacking protection can take a
variety of forms. Google appends while(1) into their JSON data, so
that if any malicious script evaluates it, the malicious script enters
an infinite loop.
Reference: Web Security Testing Cookbook: Systematic Techniques to Find Problems Fast

Is it secure to use window.location.href directly without validation

Is it secure to use window.location.href without any validation?
For example:
<script>
var value = window.location.href;
alert(value);
</script>
From the above example, is it vulnerable to Cross-site scripting (XSS) attack?
If it is, then how? How the attacker can modify the value of window.location.href to the malicious content?
Edit (Second Situation)
This is the url : www.example.com?url=www.attack.com
Just assume taht I have a getQueryString() function that will return value without validation.
<script>
var value = getQueryString('url');
window.location.href = value;
</script>
Same question, is it vulnerable to Cross-site scripting (XSS) attack?
If it is, then how? How can an attacker just make use of "window.location.href = value" to perform XSS?
Using location.href can be understood to include two things:
Using the value of location.href by passing it around in your code, manipulating it and using it to guide the logic in your code.
Assigning someting to location.href, causing the browser to navigate to different URLs.
The first one, using the value, can be considered safe. The value of location.href is nothing more than a string. Of course it's part of user input, so you don't want to pass it to an eval statement, but that's true for all other forms of user input as well. In fact, the value of location.href is always a valid URL, so certain assumptions can be made of its content. In that sense you could argue it's more safe than most forms of user input. As long as you don't make any wrong assumptions.
The second one is something you should be careful with. Assigning unvalidated values to it can lead to open redirects that can be used for phishing and what's more, XSS issues arising from the use of javascript: and vbscript: URIs.
Edit: As requested, here's a more in-depth explanation of the problems with assiging to location.href:
Say you have an attacker controlled variable foo. The source of it can be anything really, but a query string parameter is a good example. When you assign the value of foo to location.href, what happens? Well, the browser does its best to interpret the value as a URI and then redirects the user to the resulting address. In most cases, this will trigger a page load; e.g. if value is "https://www.google.com/", Google's front page will be loaded. Allowing that to happen without user interaction is known as an open redirect and is considered a security vulnerability!
There are, however, types of URIs that won't trigger a page load. A common example of such a URI would be one that contains nothing but a fragment identifier, e.g. #quux. Assigning that to location.href would cause the page to scroll to the element with the ID "quux" and do nothing else. Fragment URIs are safe as long as you don't do anything stupid with the values of the fragments themselves.
Then to the interesting part: javascript: and vbscript: URIs. These are the ones that will bite you. The JavaScript and VBScript URI schemes are non-standard URI schemes that can be used to execute code in the context of the currently open web page. Sounds bad, doesn't it? Well, it should. Consider our attacker-controlled variable foo: all an attacker has to do to launch an attack against your users is inject a script URI into the variable. When you assign it to location.href, it's basically the same as calling eval on the script.
JavaScript URIs work in all modern browsers, while VBScript is IE-only, and requires the page to be rendered in quirks mode.
Finally, there's one more interesting URI scheme to consider: the data URI. Data URIs are file literals: entire files encoded as URIs. They can be used to encode any files, including HTML documents. And those documents, like any others, can contain scripts.
Most browsers treat each data URI as its own unique origin. That means the scripts in an HTML document wrapped in a data URI can not access any data on other pages. Except in Firefox.
Firefox treats data URIs a bit differently from all other browsers. In it, data URIs inherit the origin of whatever document is opening it. That means any scripts can access the data contained in the referring document. And that's XSS for you.
A XSS is not possible under #1
The worst case I can think of is someone using that for Social Engineering (lets say your domain is really popular like Ebay or Amazon), what an attacker could do is craft a message saying something like "Amazon/Ebay free stuff for you, just go to http://haxor.site" using the URL and sending it to someone.
But still I don't find it dangerous, because of the URL encoding the message would look pretty messy.
EDIT:
This only answer #1, since when I answered this question there wasn't a "#2"
var value = getQueryString('url');
window.location.href = encodeURI(value);
I think this is the easiest way

Why does Google prepend while(1); to their JSON responses?

Why does Google prepend while(1); to their (private) JSON responses?
For example, here's a response while turning a calendar on and off in Google Calendar:
while (1);
[
['u', [
['smsSentFlag', 'false'],
['hideInvitations', 'false'],
['remindOnRespondedEventsOnly', 'true'],
['hideInvitations_remindOnRespondedEventsOnly', 'false_true'],
['Calendar ID stripped for privacy', 'false'],
['smsVerifiedFlag', 'true']
]]
]
I would assume this is to prevent people from doing an eval() on it, but all you'd really have to do is replace the while and then you'd be set. I would assume the eval prevention is to make sure people write safe JSON parsing code.
I've seen this used in a couple of other places, too, but a lot more so with Google (Mail, Calendar, Contacts, etc.) Strangely enough, Google Docs starts with &&&START&&& instead, and Google Contacts seems to start with while(1); &&&START&&&.
What's going on here?
It prevents JSON hijacking, a major JSON security issue that is formally fixed in all major browsers since 2011 with ECMAScript 5.
Contrived example: say Google has a URL like mail.google.com/json?action=inbox which returns the first 50 messages of your inbox in JSON format. Evil websites on other domains can't make AJAX requests to get this data due to the same-origin policy, but they can include the URL via a <script> tag. The URL is visited with your cookies, and by overriding the global array constructor or accessor methods they can have a method called whenever an object (array or hash) attribute is set, allowing them to read the JSON content.
The while(1); or &&&BLAH&&& prevents this: an AJAX request at mail.google.com will have full access to the text content, and can strip it away. But a <script> tag insertion blindly executes the JavaScript without any processing, resulting in either an infinite loop or a syntax error.
This does not address the issue of cross-site request forgery.
It prevents disclosure of the response through JSON hijacking.
In theory, the content of HTTP responses is protected by the Same Origin Policy: pages from one domain cannot get any pieces of information from pages on the other domain (unless explicitly allowed).
An attacker can request pages on other domains on your behalf, e.g. by using a <script src=...> or <img> tag, but it can't get any information about the result (headers, contents).
Thus, if you visit an attacker's page, it couldn't read your email from gmail.com.
Except that when using a script tag to request JSON content, the JSON is executed as JavaScript in an attacker's controlled environment. If the attacker can replace the Array or Object constructor or some other method used during object construction, anything in the JSON would pass through the attacker's code, and be disclosed.
Note that this happens when the JSON is executed as JavaScript, not when it's parsed.
There are multiple countermeasures:
Making sure the JSON never executes
By placing a while(1); statement before the JSON data, Google ensures that the JSON data is never executed as JavaScript.
Only a legitimate page could actually get the whole content, strip the while(1);, and parse the remainder as JSON.
Things like for(;;); have been seen on Facebook for instance, with the same results.
Making sure the JSON is not valid JavaScript
Similarly, adding invalid tokens before the JSON, like &&&START&&&, makes sure that it is never executed.
Always return JSON with an Object on the outside
This is OWASP recommended way to protect from JSON hijacking and is the less intrusive one.
Similarly to the previous counter-measures, it makes sure that the JSON is never executed as JavaScript.
A valid JSON object, when not enclosed by anything, is not valid in JavaScript, since the { } gets interpreted as a code block:
eval('{"foo":"bar"}')
// SyntaxError: Unexpected token :
This is however valid JSON:
JSON.parse('{"foo":"bar"}')
// Object {foo: "bar"}
So, make sure you always return an Object at the top level of the response and make sure that the JSON is not valid JavaScript, while still being valid JSON.
As noted by #hvd in the comments, the empty object {} is valid JavaScript, and knowing the object is empty may itself be valuable information.
Comparison of the above methods
The OWASP way is less intrusive, as it needs no client library changes, and transfers valid JSON. It is unsure whether past or future browser bugs could defeat this, however. As noted by #oriadam, it is unclear whether data could be leaked in a parse error through an error handling or not (e.g. window.onerror).
Google's way requires a client library in order for it to support automatic de-serialization and can be considered to be safer with regard to browser bugs.
Both methods require server-side changes in order to avoid developers accidentally sending vulnerable JSON.
This is to ensure some other site can't do nasty tricks to try to steal your data. For example, by replacing the array constructor, then including this JSON URL via a <script> tag, a malicious third-party site could steal the data from the JSON response. By putting a while(1); at the start, the script will hang instead.
A same-site request using XHR and a separate JSON parser, on the other hand, can easily ignore the while(1); prefix.
That would be to make it difficult for a third-party to insert the JSON response into an HTML document with the <script> tag. Remember that the <script> tag is exempt from the Same Origin Policy.
Note: as of 2019, many of the old vulnerabilities that lead to the preventative measures discussed in this question are no longer an issue in modern browsers. I'll leave the answer below as a historical curiosity, but really the whole topic has changed radically since 2010 (!!) when this was asked.
It prevents it from being used as the target of a simple <script> tag. (Well, it doesn't prevent it, but it makes it unpleasant.) That way bad guys can't just put that script tag in their own site and rely on an active session to make it possible to fetch your content.
edit — note the comment (and other answers). The issue has to do with subverted built-in facilities, specifically the Object and Array constructors. Those can be altered such that otherwise innocuous JSON, when parsed, could trigger attacker code.
Since the <script> tag is exempted from the Same Origin Policy which is a security necessity in the web world, while(1) when added to the JSON response prevents misuse of it in the <script> tag.
As this is a High traffic post I hope to provide here an answer slightly more undetermined to the original question and thus provide further background on a JSON Hijacking attack and its consequences
JSON Hijacking as the name suggests is an attack similar to Cross-Site Request Forgery where an attacker can access cross-domain sensitive JSON data from applications that return sensitive data as array literals to GET requests. An example of a JSON call returning an array literal is shown below:
[{"id":"1001","ccnum":"4111111111111111","balance":"2345.15"},
{"id":"1002","ccnum":"5555555555554444","balance":"10345.00"},
{"id":"1003","ccnum":"5105105105105100","balance":"6250.50"}]
This attack can be achieved in 3 major steps:
Step 1: Get an authenticated user to visit a malicious page.
Step 2: The malicious page will try and access sensitive data from the application that the user is logged into. This can be done by embedding a script tag in an HTML page since the same-origin policy does not apply to script tags.
<script src="http://<jsonsite>/json_server.php"></script>
The browser will make a GET request to json_server.php and any authentication cookies of the user will be sent along with the request.
Step 3: At this point, while the malicious site has executed the script it does not have access to any sensitive data. Getting access to the data can be achieved by using an object prototype setter. In the code below an object prototypes property is being bound to the defined function when an attempt is being made to set the "ccnum" property.
Object.prototype.__defineSetter__('ccnum',function(obj){
secrets =secrets.concat(" ", obj);
});
At this point, the malicious site has successfully hijacked the sensitive financial data (ccnum) returned byjson_server.php
JSON
It should be noted that not all browsers support this method; the proof of concept was done on Firefox 3.x.This method has now been deprecated and replaced by the useObject.defineProperty There is also a variation of this attack that should work on all browsers where full-named JavaScript (e.g. pi=3.14159) is returned instead of a JSON array.
There are several ways in which JSON Hijacking can be prevented:
Since SCRIPT tags can only generate HTTP GET requests, they only return JSON objects to POST
requests.
Prevent the web browser from interpreting the JSON object as valid JavaScript code.
Implement Cross-Site Request Forgery protection by requiring that a predefined random value be required for all JSON requests.
so as you can see While(1) comes under the last option. In the most simple terms, while(1) is an infinite loop that will run till a break statement is issued explicitly. And thus what would be described as a lock for the key to be applied (google break statement). Therefore a JSON hijacking, in which the Hacker has no key will be consistently dismissed. Alas, If you read the JSON block with a parser, the while(1) loop is ignored.
So in conclusion, the while(1) loop can more easily be visualized as a simple break statement cypher that google can use to control the flow of data.
However, the keyword in that statement is the word 'simple'. The usage of authenticated infinite loops has been thankfully removed from basic practice in the years since 2010 due to its absolute decimation of CPU usage when isolated (and the fact the internet has moved away from forcing through crude 'quick-fixes'). Today instead the codebase has embedded preventative measures, and the system is not crucial or effective anymore. (part of this is the move away from JSON Hijacking to more fruitful data farming techniques that I won't go into at present)
After authentication is in place, JSON hijacking protection can take a
variety of forms. Google appends while(1) into their JSON data, so
that if any malicious script evaluates it, the malicious script enters
an infinite loop.
Reference: Web Security Testing Cookbook: Systematic Techniques to Find Problems Fast

Why have "while(1);" in XmlHttpRequest response? [duplicate]

Why does Google prepend while(1); to their (private) JSON responses?
For example, here's a response while turning a calendar on and off in Google Calendar:
while (1);
[
['u', [
['smsSentFlag', 'false'],
['hideInvitations', 'false'],
['remindOnRespondedEventsOnly', 'true'],
['hideInvitations_remindOnRespondedEventsOnly', 'false_true'],
['Calendar ID stripped for privacy', 'false'],
['smsVerifiedFlag', 'true']
]]
]
I would assume this is to prevent people from doing an eval() on it, but all you'd really have to do is replace the while and then you'd be set. I would assume the eval prevention is to make sure people write safe JSON parsing code.
I've seen this used in a couple of other places, too, but a lot more so with Google (Mail, Calendar, Contacts, etc.) Strangely enough, Google Docs starts with &&&START&&& instead, and Google Contacts seems to start with while(1); &&&START&&&.
What's going on here?
It prevents JSON hijacking, a major JSON security issue that is formally fixed in all major browsers since 2011 with ECMAScript 5.
Contrived example: say Google has a URL like mail.google.com/json?action=inbox which returns the first 50 messages of your inbox in JSON format. Evil websites on other domains can't make AJAX requests to get this data due to the same-origin policy, but they can include the URL via a <script> tag. The URL is visited with your cookies, and by overriding the global array constructor or accessor methods they can have a method called whenever an object (array or hash) attribute is set, allowing them to read the JSON content.
The while(1); or &&&BLAH&&& prevents this: an AJAX request at mail.google.com will have full access to the text content, and can strip it away. But a <script> tag insertion blindly executes the JavaScript without any processing, resulting in either an infinite loop or a syntax error.
This does not address the issue of cross-site request forgery.
It prevents disclosure of the response through JSON hijacking.
In theory, the content of HTTP responses is protected by the Same Origin Policy: pages from one domain cannot get any pieces of information from pages on the other domain (unless explicitly allowed).
An attacker can request pages on other domains on your behalf, e.g. by using a <script src=...> or <img> tag, but it can't get any information about the result (headers, contents).
Thus, if you visit an attacker's page, it couldn't read your email from gmail.com.
Except that when using a script tag to request JSON content, the JSON is executed as JavaScript in an attacker's controlled environment. If the attacker can replace the Array or Object constructor or some other method used during object construction, anything in the JSON would pass through the attacker's code, and be disclosed.
Note that this happens when the JSON is executed as JavaScript, not when it's parsed.
There are multiple countermeasures:
Making sure the JSON never executes
By placing a while(1); statement before the JSON data, Google ensures that the JSON data is never executed as JavaScript.
Only a legitimate page could actually get the whole content, strip the while(1);, and parse the remainder as JSON.
Things like for(;;); have been seen on Facebook for instance, with the same results.
Making sure the JSON is not valid JavaScript
Similarly, adding invalid tokens before the JSON, like &&&START&&&, makes sure that it is never executed.
Always return JSON with an Object on the outside
This is OWASP recommended way to protect from JSON hijacking and is the less intrusive one.
Similarly to the previous counter-measures, it makes sure that the JSON is never executed as JavaScript.
A valid JSON object, when not enclosed by anything, is not valid in JavaScript, since the { } gets interpreted as a code block:
eval('{"foo":"bar"}')
// SyntaxError: Unexpected token :
This is however valid JSON:
JSON.parse('{"foo":"bar"}')
// Object {foo: "bar"}
So, make sure you always return an Object at the top level of the response and make sure that the JSON is not valid JavaScript, while still being valid JSON.
As noted by #hvd in the comments, the empty object {} is valid JavaScript, and knowing the object is empty may itself be valuable information.
Comparison of the above methods
The OWASP way is less intrusive, as it needs no client library changes, and transfers valid JSON. It is unsure whether past or future browser bugs could defeat this, however. As noted by #oriadam, it is unclear whether data could be leaked in a parse error through an error handling or not (e.g. window.onerror).
Google's way requires a client library in order for it to support automatic de-serialization and can be considered to be safer with regard to browser bugs.
Both methods require server-side changes in order to avoid developers accidentally sending vulnerable JSON.
This is to ensure some other site can't do nasty tricks to try to steal your data. For example, by replacing the array constructor, then including this JSON URL via a <script> tag, a malicious third-party site could steal the data from the JSON response. By putting a while(1); at the start, the script will hang instead.
A same-site request using XHR and a separate JSON parser, on the other hand, can easily ignore the while(1); prefix.
That would be to make it difficult for a third-party to insert the JSON response into an HTML document with the <script> tag. Remember that the <script> tag is exempt from the Same Origin Policy.
Note: as of 2019, many of the old vulnerabilities that lead to the preventative measures discussed in this question are no longer an issue in modern browsers. I'll leave the answer below as a historical curiosity, but really the whole topic has changed radically since 2010 (!!) when this was asked.
It prevents it from being used as the target of a simple <script> tag. (Well, it doesn't prevent it, but it makes it unpleasant.) That way bad guys can't just put that script tag in their own site and rely on an active session to make it possible to fetch your content.
edit — note the comment (and other answers). The issue has to do with subverted built-in facilities, specifically the Object and Array constructors. Those can be altered such that otherwise innocuous JSON, when parsed, could trigger attacker code.
Since the <script> tag is exempted from the Same Origin Policy which is a security necessity in the web world, while(1) when added to the JSON response prevents misuse of it in the <script> tag.
As this is a High traffic post I hope to provide here an answer slightly more undetermined to the original question and thus provide further background on a JSON Hijacking attack and its consequences
JSON Hijacking as the name suggests is an attack similar to Cross-Site Request Forgery where an attacker can access cross-domain sensitive JSON data from applications that return sensitive data as array literals to GET requests. An example of a JSON call returning an array literal is shown below:
[{"id":"1001","ccnum":"4111111111111111","balance":"2345.15"},
{"id":"1002","ccnum":"5555555555554444","balance":"10345.00"},
{"id":"1003","ccnum":"5105105105105100","balance":"6250.50"}]
This attack can be achieved in 3 major steps:
Step 1: Get an authenticated user to visit a malicious page.
Step 2: The malicious page will try and access sensitive data from the application that the user is logged into. This can be done by embedding a script tag in an HTML page since the same-origin policy does not apply to script tags.
<script src="http://<jsonsite>/json_server.php"></script>
The browser will make a GET request to json_server.php and any authentication cookies of the user will be sent along with the request.
Step 3: At this point, while the malicious site has executed the script it does not have access to any sensitive data. Getting access to the data can be achieved by using an object prototype setter. In the code below an object prototypes property is being bound to the defined function when an attempt is being made to set the "ccnum" property.
Object.prototype.__defineSetter__('ccnum',function(obj){
secrets =secrets.concat(" ", obj);
});
At this point, the malicious site has successfully hijacked the sensitive financial data (ccnum) returned byjson_server.php
JSON
It should be noted that not all browsers support this method; the proof of concept was done on Firefox 3.x.This method has now been deprecated and replaced by the useObject.defineProperty There is also a variation of this attack that should work on all browsers where full-named JavaScript (e.g. pi=3.14159) is returned instead of a JSON array.
There are several ways in which JSON Hijacking can be prevented:
Since SCRIPT tags can only generate HTTP GET requests, they only return JSON objects to POST
requests.
Prevent the web browser from interpreting the JSON object as valid JavaScript code.
Implement Cross-Site Request Forgery protection by requiring that a predefined random value be required for all JSON requests.
so as you can see While(1) comes under the last option. In the most simple terms, while(1) is an infinite loop that will run till a break statement is issued explicitly. And thus what would be described as a lock for the key to be applied (google break statement). Therefore a JSON hijacking, in which the Hacker has no key will be consistently dismissed. Alas, If you read the JSON block with a parser, the while(1) loop is ignored.
So in conclusion, the while(1) loop can more easily be visualized as a simple break statement cypher that google can use to control the flow of data.
However, the keyword in that statement is the word 'simple'. The usage of authenticated infinite loops has been thankfully removed from basic practice in the years since 2010 due to its absolute decimation of CPU usage when isolated (and the fact the internet has moved away from forcing through crude 'quick-fixes'). Today instead the codebase has embedded preventative measures, and the system is not crucial or effective anymore. (part of this is the move away from JSON Hijacking to more fruitful data farming techniques that I won't go into at present)
After authentication is in place, JSON hijacking protection can take a
variety of forms. Google appends while(1) into their JSON data, so
that if any malicious script evaluates it, the malicious script enters
an infinite loop.
Reference: Web Security Testing Cookbook: Systematic Techniques to Find Problems Fast

Categories

Resources