Biting into the forbidden fruit. Lessons from trusting JavaScript crypto
Krzysztof Kotowicz (Google)
BruCON 0x06 · Day 2
Overview
In this insightful talk from BruCON 2014, Krzysztof Kotowicz, a web security researcher at Google, delves into the contentious world of JavaScript cryptography. The presentation, titled "Biting into the forbidden fruit. Lessons from trusting JavaScript crypto," challenges the long-held skepticism surrounding client-side cryptographic implementations. Kotowicz dissects numerous real-world vulnerabilities found in popular JavaScript crypto libraries and applications, providing a nuanced perspective that compares JavaScript's challenges to those faced by traditional, native cryptographic implementations.

Key moments
- 0:00 Introduction and initial thoughts on JavaScript crypto
- 2:00 Arguments against client-side JavaScript cryptography
- 14:00 Cryptocat proto magic property DoS
- 18:00 AES 1616 Snowman Attack: key recovery
- 32:00 XSS issues in browser crypto extensions
- 40:00 Timing side channels in JavaScript crypto
- 47:00 JS engine vulnerabilities and browser as OS
- 58:00 Recommendations for safer JavaScript crypto
Biting into the forbidden fruit. Lessons from trusting JavaScript crypto
Speakers: Krzysztof Kotowicz, Web Security Researcher, Google
Conference: BruCON
YouTube: https://www.youtube.com/watch?v=MYW84YkNG9Y
Overview
In this insightful talk from BruCON 2014, Krzysztof Kotowicz, a web security researcher at Google, delves into the contentious world of JavaScript cryptography. The presentation, titled "Biting into the forbidden fruit. Lessons from trusting JavaScript crypto," challenges the long-held skepticism surrounding client-side cryptographic implementations. Kotowicz dissects numerous real-world vulnerabilities found in popular JavaScript crypto libraries and applications, providing a nuanced perspective that compares JavaScript's challenges to those faced by traditional, native cryptographic implementations.
The core of Kotowicz's argument is that while JavaScript presents unique pitfalls due to its dynamic nature and the browser's execution environment, many of the fundamental security issues encountered in client-side crypto are not exclusive to the language itself. He demonstrates how vulnerabilities stemming from language quirks, poor randomness, timing side channels, and memory safety issues have direct parallels in battle-tested C or Java libraries. The talk emphasizes that the web platform, acting as the de facto operating system for JavaScript applications, introduces an expansive and often overlooked attack surface.
This presentation is crucial for anyone involved in developing or assessing the security of web applications that handle sensitive data. It moves beyond dogmatic rejection of JavaScript crypto, offering a pragmatic analysis of its strengths, weaknesses, and the defensive strategies necessary to mitigate risks. By illuminating the shared challenges across different programming paradigms, Kotowicz advocates for a more informed and less biased approach to evaluating the security posture of cryptographic solutions, regardless of their implementation language.
Background
▶ Watch: Introduction and initial thoughts on JavaScript crypto (0:00)
The landscape of JavaScript cryptography has historically been met with significant apprehension within the security community. Krzysztof Kotowicz begins by highlighting two seminal blog posts that encapsulate this "classical view": Thomas Ptacek's "JavaScript Cryptography Considered Harmful" and Nate Lawson's "Final Post on JavaScript." These articles articulated several core arguments against the viability of JavaScript for cryptographic operations.
Firstly, a primary contention was that client-side cryptography is not needed in the browser. The argument posits that if the goal is to prevent the server from accessing plaintext, it's futile because the server itself delivers the JavaScript code, making it capable of backdooring the application. Furthermore, any application requiring cryptographic integrity implicitly trusts the server anyway. Since a secure channel (HTTPS) is already necessary to protect the JavaScript code from tampering during transit, why not simply rely on server-side cryptography?
Secondly, JavaScript crypto was deemed dangerous, primarily due to the pervasive threat of Cross-Site Scripting (XSS). An XSS vulnerability allows an attacker to execute arbitrary code within the same origin as the cryptographic application. This immediately compromises any security guarantees, enabling an attacker to exfiltrate keys, plaintext, or manipulate cryptographic operations.
Finally, implementing crypto in JavaScript was considered hard. JavaScript, with its dynamic, weakly typed nature, unconventional inheritance model, and forgiving parser, was seen as an unsuitable language for the precision required in cryptographic implementations. Moreover, the available libraries at the time were often of "mediocrity." The prevailing sentiment was that JavaScript cryptography was "necessarily doomed to fail."
However, Kotowicz notes a significant shift by 2014. Despite these strong arguments, JavaScript crypto had seen widespread adoption. Libraries implementing various cryptographic primitives (symmetric, asymmetric, TLS, OpenPGP) had emerged, and numerous applications were built upon them. He specifically mentions Cryptocat (a multi-party encrypted chat), Mailvelope (OpenPGP in the browser, particularly for Gmail), and OpenPGP.js (a core library used by Mailvelope). Faced with this reality, Kotowicz embarked on a mission to re-evaluate the classical arguments by taking a "deeper look at the code" of these real-world applications and libraries, identify vulnerabilities, uncover their root causes, and crucially, compare the findings to issues in "native crypto" implementations like OpenSSL or GnuTLS, written in statically compiled languages.
Key Findings
▶ Watch: Cryptocat __proto__ magic property DoS (14:00)
Kotowicz's investigation into real-world JavaScript cryptographic applications and libraries revealed a series of vulnerabilities and peculiar behaviors. He categorized the root causes into two distinct groups: language issues specific to JavaScript and web platform issues inherent to how web applications operate.
His central finding challenges the notion that JavaScript is uniquely ill-suited for cryptography. While JavaScript's quirks can indeed introduce subtle flaws, Kotowicz demonstrates that many of these issues have direct, often more severe, parallels in "native" cryptographic libraries written in languages like C or Java. This suggests that the problem isn't solely the choice of JavaScript, but rather the complexity of secure cryptographic implementation itself, exacerbated by the dynamic nature of the web.
Key discoveries include:
- Subtle Language Flaws: JavaScript's weak typing, peculiar number handling (e.g., floating-point arithmetic for all numbers, unexpected bit-shifting results), and "magic properties" like
__proto__can lead to critical vulnerabilities, such as denial-of-service or information leakage, as seen in Cryptocat. - Critical Vulnerabilities from Silent Errors and Unicode Handling: The combination of JavaScript's silent
undefinedreturn for out-of-bounds array access and its native Unicode string support (wherecharCodeAtcan return values > 255) led to a devastating key recovery attack, dubbed the "16/16 Snowman Attack," against an AES encryption library. - Pervasiveness of Web Platform Threats: XSS remains a paramount threat, capable of completely undermining cryptographic guarantees by allowing key exfiltration or manipulation. Poor randomness, often relying on
Math.random(), is another common flaw, as demonstrated by Cryptocat's easily brute-forceable "random" strings. - The Insidious Nature of Timing Side Channels: JavaScript's execution environment allows for precise timing measurements, making remote timing attacks practical. Vulnerabilities in RSA padding decoding, similar to the Bleichenbacher attack, were identified in OpenPGP.js due to non-constant-time operations.
- Browser as the New OS: The browser itself, with its complex attack surface (network stack, HTML parser, JavaScript engine), becomes the equivalent of an operating system for JavaScript crypto. Vulnerabilities in the browser engine (e.g., V8 out-of-bounds reads/writes) can lead to arbitrary code execution, effectively compromising any client-side crypto.
- Shared Vulnerability Patterns: Kotowicz meticulously draws parallels between JavaScript issues and native crypto vulnerabilities:
__proto__issues to Python's magic methods, the "16/16 Snowman Attack" to C'sgoto fail;SSL bug,Math.random()issues to the Debian OpenSSL fiasco, and timing attacks to Java Secure Sockets Extensions vulnerabilities. Even memory corruption, thought impossible in "memory-safe" JavaScript, can occur through exploits in the underlying JS engine, akin to Heartbleed.
In conclusion, Kotowicz found that while JavaScript's unique characteristics demand careful consideration, the more formidable challenges lie in the inherent complexities of cryptographic design and the vast, untrusted attack surface provided by the web platform. He asserts that "the web platform issues are much harder to solve" than the specific language quirks, and ultimately, "malware will always win."
Technical Deep Dive
▶ Watch: XSS issues in browser crypto extensions (32:00)
Krzysztof Kotowicz meticulously dissects vulnerabilities by categorizing them into two primary groups: language issues and web platform issues.
Language Issues: The Quirks of JavaScript
Kotowicz highlights JavaScript's dynamic, weakly typed nature, its unusual inheritance model, implicit global object, and forgiving parser as potential sources of cryptographic insecurity. He offers several examples of how these characteristics can introduce subtle, yet critical, flaws.
- Weak Typing and Type Coercion:
parseInt("0xF", 10)yieldsNaN, butparseInt("0xF", 16)yields15, which is expected but demonstrates how radix affects parsing.Math.min()can returnInfinity, andMath.max()can return-Infinity, leading toMath.min() > Math.max().nullis anobjectbut not aninstanceof Object.- A critical example:
a + 1 == acan be true for numbers likeInfinity,-Infinity, and1 * 10^16(the smallest number with this property in some JS engines), demonstrating unexpected arithmetic behaviors due to floating-point representation. - Bit Shifting: All numbers in JavaScript are floating-point. Bitwise operations coerce them to 32-bit integers, leading to non-intuitive results. For instance,
1 << 31is a large negative number, but1 << 32wraps around to1.(1 << 31) << 1results in0due to operator precedence. The unsigned right shift operator (>>>) also adds complexity.
- Magic Properties (
__proto__):
- Kotowicz describes a Denial-of-Service (DoS) vulnerability in Cryptocat, a multi-party chat application. Cryptocat used an object to store public keys, checking
if (publicKeys[senderID])to determine if a key exchange was needed. - The
__proto__property is always present in any JavaScript object and, when evaluated as a boolean, istrue(as an empty object). - An attacker joining a chat with the username
__proto__would causepublicKeys.__proto__to evaluate totrue. This prevented the application from generating a shared secret for this "user." - Later, when an encrypted message arrived from
__proto__,sharedSecrets.__proto__also evaluated totrue, butsharedSecrets.__proto__(an empty object) lacked expected properties likehmacormsg, leading to an error and breaking the chat for everyone. - Kotowicz notes this isn't unique to JavaScript, citing similar "magic properties" in Python.
- Silent Errors and Unicode: The 16/16 Snowman Attack:
- JavaScript's behavior of returning
undefinedfor out-of-bounds array access andString.charCodeAt()returning values greater than 255 for Unicode characters formed the basis of a significant attack discovered by Daniel A. J. Bernstein against a JavaScript AES encryption library. - AES is a block cipher operating on 16-byte blocks. A key step is the
subBytefunction, which performs a lookup in a 256-value S-box table using the byte as an index. - Vulnerability: If the plaintext block contained Unicode characters that, when converted to a number, exceeded 255, the
subBytefunction would attempt to accesssbox[value > 255]. Due to JavaScript's silent error handling for out-of-bounds array access, this would returnundefinedfor each such byte. - Propagation: After
subByte, the AESstatewould become 16undefinedvalues. The subsequentmixColumnsstep, which involves XOR operations, would then encounterundefined XOR undefined XOR 0x00. In JavaScript, this bizarrely evaluates to0. - Key Recovery: The attacker encrypts 16 Unicode characters. The first round corrupts the state to 16
0bytes. During decryption, the final round'sinverseSubBytefunction receives 160bytes, causing it to consistently returninvSbox[0], which is0x52. The finaladdRoundKeystep XORs these 160x52bytes with the actual AES key. By observing the output, the attacker recovers the AES key XORed with0x52repeated 16 times, effectively revealing the secret key. - Comparison to Native Crypto: Kotowicz draws a parallel to the infamous Apple
goto fail;vulnerability in C, where a missedifstatement led to certificate validation bypass due to C's lack of exceptions and reliance on integer return codes for errors. He argues that while JavaScript's quirks are tricky, they are not fundamentally unique. Defensive practices like ECMAScript 5 strict mode, type-enforcing compilers (like Closure Compiler), unit tests, and code reviews can mitigate these language-specific issues.
Web Platform Issues: The Browser as an OS
Kotowicz argues that the execution environment of JavaScript (the browser) introduces a broader and often more challenging set of security concerns.
- Cross-Site Scripting (XSS):
- XSS is considered the equivalent of Remote Code Execution (RCE) for cryptographic JavaScript. An XSS vulnerability allows an attacker to replace the random number generator, exfiltrate private keys, or substitute the intended recipient's public key with the attacker's own.
- Mailvelope Example: In Mailvelope (an OpenPGP extension for Gmail), an XSS payload encrypted to the victim's public key could be inserted into the email body. Upon decryption, the payload would execute, demonstrating the vulnerability of in-line DOM rendering.
- Cryptocat Example: Cryptocat suffered from an XSS vulnerability in its username field. By bypassing client-side validation and using an XSS payload as a username, an attacker could "pawn everyone else" in the chat. For Firefox add-ons, this was particularly severe, potentially granting direct access to the file system.
- Comparison to Native Crypto: Kotowicz compares this to a buffer overflow in GnuTLS (a C TLS implementation), which could lead to memory corruption and arbitrary code execution, highlighting that the end result (compromised cryptographic operations) is the same.
- Poor Randomness:
- Many JavaScript applications mistakenly rely on
Math.random(), which is not cryptographically secure. Its state can often be recovered, allowing prediction of future "random" numbers. - Modern browsers offer cryptographically safe PRNGs like
crypto.getRandomValues()(Web Crypto API) and Node.js hascrypto.randomBytes(). - Cryptocat Example 1: Cryptocat used
Math.random()forsIDandrIDvalues, which were explicitly stated in the protocol specification as "security critical" and requiring unpredictability. - Cryptocat Example 2 (Decryptocat Exploit): Cryptocat's
cryptocatRandomStringfunction was advertised to generate "64 random bytes" for key generation (implying high entropy). However, its implementation generated 64 numeric characters (0-9). This provided only approximately 3 bits of entropy per character, making the "random" string easily brute-forceable, severely weakening key strength. - Comparison to Native Crypto: The infamous Debian OpenSSL fiasco is presented as a parallel. Debian maintainers, in an attempt to fix Valgrind warnings, removed lines of code that fed entropy from uninitialized memory. This left the RNG solely dependent on the process ID (32 bits), resulting in only 2^32 possible keys for two years.
- Timing Side Channels:
- Cryptographic operations, particularly padding validation, should execute in constant time to prevent attackers from inferring information based on execution duration.
- In a browser, timing differences are highly measurable because the attacker's code (e.g., in another tab) executes on the same CPU, sometimes even in the same thread, allowing for precise measurements.
- OpenPGP.js Example: The
pkcs1decodefunction, used for RSA padding decoding, contained explicitifstatements and earlyreturn -1branches. This non-constant-time behavior made the RSA encryption vulnerable to a Bleichenbacher attack, allowing plaintext decryption. - Comparison to Native Crypto: The Java Secure Sockets Extensions (JSSE) also had a similar RSA padding timing vulnerability. Kotowicz stresses that writing constant-time code is "really tricky" even in compiled languages, as compilers often optimize code for speed, inadvertently introducing branches where none were intended. He shows a Go crypto library example for
bytes.Equalthat uses bitwise operations to avoid branching and ensure constant time.
- Direct Memory Access (Heartbleed Equivalent):
- JavaScript is often considered a "memory safe" language, theoretically immune to buffer overflows or out-of-bounds accesses common in C.
- V8 Engine Vulnerability (Jihad): However, the underlying JavaScript engines (e.g., Chrome's V8) are written in C++. Kotowicz describes a vulnerability (disclosed by "Jihad" in Chrome 33's V8) where an attacker could create an
ArrayBufferand then use a custom getter to overwrite itsbyteLengthproperty to a huge number. This allowed for arbitrary out-of-bounds reads and writes into the JavaScript heap, leading to arbitrary code execution. - Comparison to Native Crypto: This is directly compared to Heartbleed, a memory corruption bug in OpenSSL that allowed attackers to read arbitrary memory, potentially exfiltrating private keys. The outcome is similar: a memory safety bug in the underlying platform compromises cryptographic secrets.
- The Browser as the Operating System:
- Kotowicz argues that for JavaScript crypto, the browser effectively becomes the operating system. Just as malware on an OS compromises cryptographic security, vulnerabilities in the browser itself (its network stack, HTML parser, or JavaScript engine) can undermine any cryptographic guarantees.
- The problem is that the browser is a "giant drive-by downloads playground." Users visit hundreds or thousands of URLs daily, each potentially exploiting a browser vulnerability. The Same-Origin Policy (SOP) provides only a "thin layer" of isolation, and roughly half of users worldwide lack OS-level process sandboxing for their browsers.
- This situation makes trusting client-side JavaScript crypto in a general browser tab extremely difficult, as any exploit in any visited page can compromise the entire browser process.
Demo / Proof of Concept
▶ Watch: Timing side channels in JavaScript crypto (40:00)
While Krzysztof Kotowicz's talk was rich with detailed explanations of vulnerabilities and attack methodologies, it primarily focused on the conceptual breakdown of these flaws rather than live demonstrations. He meticulously described the mechanics of the "__proto__" denial-of-service in Cryptocat, the "16/16 Snowman Attack" against a JavaScript AES library, and XSS vulnerabilities in Mailvelope and Cryptocat. For instance, in discussing the Python magic property, he stated, "I demonstrated how to kill an application," implying a conceptual walkthrough of the attack rather than an on-stage live exploit. The objective was to illustrate the root causes and impact of these vulnerabilities through code examples and detailed logical flow, effectively serving as a "proof of concept" through in-depth analysis of existing codebases and their observed failure modes.
Defensive Implications
▶ Watch: Recommendations for safer JavaScript crypto (58:00)
Krzysztof Kotowicz offers clear, actionable recommendations for developers and defenders seeking to implement or secure JavaScript cryptography, acknowledging the inherent challenges.
- Isolate the Execution Environment:
- Never implement JavaScript crypto directly in a general website context. The browser tab is too hostile and exposed.
- Prefer isolated environments:
- Server-side Node.js: For applications where crypto operations can be offloaded to a more controlled server environment.
- Browser Extensions: Packaging cryptographic applications as browser extensions (e.g., Chrome extensions) provides significantly more isolation. They run in a privileged zone, often in a separate OS-level process (e.g., Chrome's process isolation), reducing the attack surface from other websites. While not perfect (XSS is still possible, and process isolation isn't always guaranteed), it's a substantial improvement over plain web pages.
- Embrace Standard Development Practices:
- Unit Tests and Continuous Integration: Essential for catching regressions and subtle bugs.
- Code Reviews: Crucial for identifying logical flaws, insecure patterns, and non-constant-time operations.
- Strict Language Enforcement:
- Use ECMAScript 5 strict mode (
'use strict') to catch common coding errors and make JavaScript less forgiving. - Utilize type-enforcing compilers (e.g., Closure Compiler) or languages that compile to JavaScript (e.g., TypeScript) to introduce static type checking and reduce type-related issues. These tools can enforce property declarations and provide "Java-ish goodness" to JavaScript projects.
- Mitigate Web Platform Specific Threats:
- Content Security Policy (CSP): Implement strict CSPs to mitigate XSS vulnerabilities by restricting script sources, inline scripts, and other potentially malicious content.
- Cryptographically Secure Randomness: Always use
window.crypto.getRandomValues()for browser-based crypto orcrypto.randomBytes()in Node.js. Never rely onMath.random()for security-critical operations. - Constant-Time Operations: Strive to write cryptographic code that executes in constant time, especially for padding validation and comparisons, to prevent timing side channels. Acknowledge that this is extremely difficult, often requiring low-level bitwise operations and careful consideration of compiler optimizations.
- Request Throttling: Implement rate limiting or request throttling on the server side to mitigate timing side channel exploitation, as these attacks often require a large number of precise measurements.
- Understand the Browser's Role as an OS:
- Recognize that the browser, with its vast and complex codebase (HTML parser, network stack, JavaScript engine), is part of the attack surface. Any vulnerability in the browser itself can compromise client-side crypto.
- While not directly solvable by application developers, this awareness underscores the importance of isolation and the inherent risks of trusting client-side execution in an environment constantly exposed to untrusted code.
In essence, Kotowicz advises treating JavaScript crypto development with the same rigor, if not more, as native crypto. The language's quirks can be tamed with modern tools and practices, but the pervasive threats of the web platform necessitate a fundamental shift towards isolated execution environments and a deep understanding of the browser's security model.
Key Takeaways
- JavaScript Cryptography Has Matured but Remains Challenging: While initial skepticism was valid, JavaScript crypto libraries and applications have significantly improved. However, they continue to face complex security challenges stemming from both the language itself and its execution environment.
- Issues Are Not Unique to JavaScript: Many vulnerabilities often attributed solely to JavaScript (e.g., weak typing, poor randomness, timing attacks, memory safety) have direct parallels in "native" cryptographic implementations written in languages like C or Java. The problem is often the inherent difficulty of secure crypto, not just the language.
- Web Platform Issues Are the Hardest to Solve: Threats like Cross-Site Scripting (XSS), pervasive browser vulnerabilities (acting as the "operating system" for JS crypto), and the precise timing capabilities of the browser environment pose more significant and harder-to-mitigate risks than the specific quirks of the JavaScript language.
- Isolation is Paramount: For security-critical JavaScript cryptography, never run it directly in a general web page. Instead, leverage isolated environments such as server-side Node.js applications or browser extensions, which offer a reduced attack surface and enhanced security guarantees.
- Rigorous Development Practices are Essential: Adopting strict development methodologies—including unit testing, continuous integration, thorough code reviews, and using tools like ECMAScript 5 strict mode and type-enforcing compilers—is crucial for mitigating language-specific pitfalls and ensuring the robustness of cryptographic implementations.
- Awareness of the Entire Attack Surface is Key: Developers must understand that the entire browser stack (JavaScript engine, HTML parser, network stack) constitutes a potential attack surface. Ultimately, any cryptographic operation running on a compromised "OS" (be it a browser with an exploit or a machine with malware) will fail.
About the Speaker(s)
Krzysztof Kotowicz is a distinguished web security researcher currently working at Google. His expertise spans various facets of web security, having previously conducted extensive research on HTML5 security features and browser extensions. Before joining Google, Kotowicz was associated with Cure53, where he collaborated with notable researchers like Mario Heiderich. His work, including the research presented in this talk, often involves deep dives into complex web technologies and their security implications, with a recent focus on the challenging domain of client-side cryptography.