๐Ÿš€ UllrichLumina

Why do people put code like throw 1 dont be evil and for in front of json responses duplicate

Why do people put code like throw 1 dont be evil and for in front of json responses duplicate

๐Ÿ“… | ๐Ÿ“‚ Category: Javascript

Ever stumbled upon a strange snippet of code like “throw 1; <dont be evil>” or “for(;;);” prepended to a JSON response and wondered what its purpose is? This practice, while seemingly bizarre, serves a critical function in safeguarding against specific types of web vulnerabilities. Understanding why people put code like “throw 1; <dont be evil>” and “for(;;);” in front of JSON responses involves delving into the history of web security and the evolution of techniques to prevent malicious attacks like Cross-Site Script Inclusion (XSSI). We’ll explore how these seemingly innocuous lines of code act as a shield, protecting sensitive data from unauthorized access and ensuring the integrity of web applications. This practice, while less common now, reflects the ever-evolving landscape of web security and the clever strategies developers employ to stay ahead of potential threats. By understanding the rationale behind this practice, we can gain a deeper appreciation for the complexities of web security and the importance of proactive defense mechanisms.

The Threat: Cross-Site Script Inclusion (XSSI)

Cross-Site Script Inclusion (XSSI) is a type of web security vulnerability that allows malicious websites to steal data from JSON APIs. Unlike Cross-Site Scripting (XSS), which injects malicious scripts into a trusted website, XSSI exploits the way browsers handle script tags. If a JSON API doesn’t properly validate the origin of the request, a malicious website can include the API endpoint as a script. This leads the browser to execute the JSON response as JavaScript code, potentially exposing sensitive data to the attacker. The Same-Origin Policy is meant to prevent this, but older browsers, or misconfigured servers, may be vulnerable.

Imagine a scenario where a user is logged into their bank account. A malicious website they visit includes a script tag pointing to the bank’s API endpoint that returns account details in JSON format. Without proper protection, the browser would execute this JSON as JavaScript, allowing the malicious website to access the user’s account information. This is a severe breach of security and can lead to identity theft, financial loss, and other serious consequences. Defending against XSSI is a crucial aspect of secure web development, and these code snippets represent one method for doing so. OWASP provides comprehensive information on XSSI attacks.

Defense Mechanism: Preventing JSON Execution

The “throw 1; <dont be evil>” and “for(;;);” prefixes are designed to prevent the browser from executing the JSON response as JavaScript. Let’s break down each of these snippets:

  • “throw 1;”: This statement is a JavaScript throw statement. If the browser attempts to execute the JSON response as JavaScript, this statement will cause an error, preventing the rest of the JSON data from being processed. The 1 is arbitrary; any value after throw would achieve the same effect.
  • “for(;;);”: This is an infinite loop in JavaScript. While less common than the throw statement, it’s designed to halt the execution of the JSON response if it’s mistakenly treated as JavaScript. The loop will consume resources and effectively freeze the execution, preventing data leakage.

These prefixes act as a barrier. If a malicious website attempts to include the JSON API as a script, the browser will encounter the throw statement or the infinite loop, preventing the JSON data from being exposed. By deliberately introducing syntax errors or resource-intensive loops, developers can effectively neutralize the threat of XSSI attacks. This is a simple yet effective technique that adds a layer of security to JSON APIs. Consider it a “fail-safe” in case other security measures are bypassed. Many modern frameworks now handle this automatically, but understanding the history is important.

This paragraph is optimized for a featured snippet: By prefixing JSON responses with “throw 1; <dont be evil>” or “for(;;);”, developers prevent browsers from executing the JSON as JavaScript. The throw statement causes an error, while the infinite loop halts execution, effectively blocking malicious websites from accessing sensitive data through Cross-Site Script Inclusion (XSSI) attacks. This simple technique adds a crucial layer of security to JSON APIs, safeguarding against unauthorized data access.

Modern Solutions: Content-Type and CORS

While the “throw 1;” and “for(;;);” prefixes were once a common defense against XSSI, modern web development offers more robust and standardized solutions. Two key technologies that have largely replaced these older methods are setting the correct Content-Type header and implementing Cross-Origin Resource Sharing (CORS).

Setting the Content-Type header to application/json tells the browser that the response is JSON data, not JavaScript. Modern browsers will then refuse to execute the JSON as a script, even if it’s included in a

The transition to these modern solutions reflects the evolution of web security practices. While the old prefixes were a clever workaround, they were not standardized and relied on specific browser behaviors. Content-Type and CORS provide a more reliable and universally supported approach to preventing XSSI attacks. Furthermore, frameworks like React, Angular, and Vue now handle much of this configuration automatically, reducing the burden on individual developers. However, understanding the historical context of these older techniques can provide valuable insight into the evolution of web security and the importance of staying up-to-date with the latest best practices.

Practical Implementation: A Step-by-Step Guide

While modern frameworks largely automate XSSI protection, understanding the underlying principles remains crucial. Here’s a simplified guide to implementing these protections manually (primarily for legacy systems or understanding the concepts):

  1. Configure your server to send the correct Content-Type header: Ensure that all JSON responses include the Content-Type: application/json header.
  2. Implement CORS: Configure your server to only allow requests from trusted origins. This typically involves setting the Access-Control-Allow-Origin header.
  3. (Legacy) Prefix JSON responses: If you’re dealing with older browsers or systems, consider adding the “throw 1;” prefix to your JSON responses as an additional layer of defense.
  4. Test your API endpoints: Use tools like Postman or curl to test your API endpoints and verify that the Content-Type header is set correctly and that CORS is properly configured.

Remember that securing your API is an ongoing process. Regularly review your security configurations, stay informed about the latest threats, and update your security measures accordingly. Tools like Snyk can help you identify and address potential vulnerabilities in your code and dependencies. Securing JSON responses is an important aspect of web application security.

Infographic here
FAQ: Addressing Common Concerns -------------------------------
Why not just use POST requests?
While POST requests can offer some protection against simple XSSI attacks, they are not a complete solution. A malicious website can still submit a POST request to your API endpoint if it can trick the user into submitting a form. CORS and the Content-Type header are still necessary to prevent unauthorized access.
Are these prefixes still necessary in modern browsers?
In most cases, no. Modern browsers that properly implement CORS and respect the Content-Type header are not vulnerable to XSSI attacks using the
What about JSONP?
JSON with Padding (JSONP) is an older technique for circumventing the Same-Origin Policy. However, JSONP is inherently insecure and should be avoided whenever possible. CORS provides a much safer and more flexible alternative.
Ultimately, the decision of whether to use these older techniques depends on your specific requirements and the security posture of your application. However, in most modern scenarios, relying on CORS and the Content-Type header is the preferred approach.

Understanding why people put code like “throw 1; <dont be evil>” and “for(;;);” in front of JSON responses provides valuable insight into the evolution of web security. While these techniques may seem outdated in the face of modern solutions like CORS and proper Content-Type handling, they represent a crucial step in protecting against XSSI attacks. The key takeaway is to prioritize robust security measures, stay informed about the latest threats, and adapt your defenses accordingly. For further reading, consider exploring articles on XSS prevention and secure API design at Courthouse Zoological’s security blog. Invest in continuous learning to fortify your applications against evolving cyber threats.

Question & Answer :

Google returns json like this:
throw 1; <dont be evil> { foo: bar} 

and Facebooks ajax has json like this:

for(;;); {"error":0,"errorSummary": ""} 
  • Why do they put code that would stop execution and makes invalid json?
  • How do they parse it if it’s invalid and would crash if you tried to eval it?
  • Do they just remove it from the string (seems expensive)?
  • Are there any security advantages to this?

In response to it being for security purposes:

If the scraper is on another domain they would have to use a script tag to get the data because XHR won’t work cross-domain. Even without the for(;;); how would the attacker get the data? It’s not assigned to a variable so wouldn’t it just be garbage collected because there’s no references to it?

Basically to get the data cross domain they would have to do

<script src="http://target.com/json.js"></script> 

But even without the crash script prepended the attacker can’t use any of the Json data without it being assigned to a variable that you can access globally (it isn’t in these cases). The crash code effectivly does nothing because even without it they have to use server sided scripting to use the data on their site.

Even without the for(;;); how would the attacker get the data?

Attacks are based on altering the behaviour of the built-in types, in particular Object and Array, by altering their constructor function or its prototype. Then when the targeted JSON uses a {...} or [...] construct, they’ll be the attacker’s own versions of those objects, with potentially-unexpected behaviour.

For example, you can hack a setter-property into Object, that would betray the values written in object literals:

Object.prototype.__defineSetter__('x', function(x) { alert('Ha! I steal '+x); }); 

Then when a <script> was pointed at some JSON that used that property name:

{"x": "hello"} 

the value "hello" would be leaked.

The way that array and object literals cause setters to be called is controversial. Firefox removed the behaviour in version 3.5, in response to publicised attacks on high-profile web sites. However at the time of writing Safari (4) and Chrome (5) are still vulnerable to this.

Another attack that all browsers now disallow was to redefine constructor functions:

Array= function() { alert('I steal '+this); }; [1, 2, 3] 

And for now, IE8’s implementation of properties (based on the ECMAScript Fifth Edition standard and Object.defineProperty) currently does not work on Object.prototype or Array.prototype.

But as well as protecting past browsers, it may be that extensions to JavaScript cause more potential leaks of a similar kind in future, and in that case chaff should protect against those too.

๐Ÿท๏ธ Tags: