Examples of prototype pollution in libraries like Lodash
Impact and risks associated with prototype pollution
Methods to prevent prototype pollution
Tools and practices for detecting vulnerabilities
Prototype pollution is a significant security vulnerability in JavaScript that allows attackers to manipulate an object's prototype chain. This can lead to unexpected behavior and potential security breaches in applications. Understanding this vulnerability is crucial for developers who rely on JavaScript's dynamic nature.
Prototype pollution occurs when an arbitrary payload can overwrite properties or methods on the prototype chain of one or more objects. This often happens when using a merge function, which can recursively merge properties from one object to another. If the payload includes a special property like __proto__, it can alter the prototype of all objects, leading to a widespread impact.
An example can be seen with the Hook library versions 4.1.2 and 4.2.0. A malicious payload containing __proto__ can be used to add properties to the prototype chain, which becomes accessible in unrelated objects. This highlights the risk of recursive merge functions that do not filter out dangerous properties.
The Lodash library, known for its popularity in JavaScript projects, has also been susceptible to prototype pollution. Older versions allowed similar payloads to modify prototype chains, leading to unintended access and property definitions. This underscores the importance of keeping libraries up-to-date with security patches.
Prototype pollution can have severe consequences, including remote code execution (RCE). Since 2018, numerous Common Vulnerabilities and Exposures (CVEs) have been reported related to this issue. High-profile cases, such as those involving Kibana and Parse Server, demonstrate the potential for attackers to execute arbitrary code by exploiting prototype pollution.
To mitigate these risks, developers should adopt several strategies:
Filtering out dangerous properties in merge functions is essential. Libraries like Lodash have implemented fixes to prevent prototype pollution by excluding __proto__ from merge operations. Developers should also ensure that their custom code follows similar practices.
Using defensive programming techniques can safeguard against prototype pollution. One method is creating objects with Object.create(null), which produces objects without a prototype, thus avoiding pollution. This approach ensures that objects are safe from prototype-based attacks.
Data sanitization is another critical step. Validating and sanitizing inputs from external sources can prevent malicious payloads from entering the application. Libraries like Joi offer robust validation mechanisms that developers can leverage to protect their applications.
Developers should also monitor their applications for incoming objects that might carry malicious payloads. Performing regular security audits and using tools like npm audit can help identify known vulnerabilities in dependencies, including those related to prototype pollution.
Understanding how to access and manipulate prototypes in JavaScript is essential for developers. Objects have prototypes, and properties not found on an object can be looked up on its prototype. This process, known as the prototype chain, continues recursively until the property is found or the end of the chain is reached.
Tools like Semgrep can aid in detecting potential vulnerabilities in codebases. While traditional linters may not catch complex issues like prototype pollution, Semgrep offers advanced analysis capabilities that can identify problematic patterns, making it a valuable tool in a developer's arsenal.
Prototype pollution is a critical concern in JavaScript development. By understanding its mechanisms and impacts, developers can implement effective strategies to prevent it. Regular audits, data validation, and using the right tools can significantly reduce the risk of exploitation, ensuring applications remain secure and reliable.
In 2018, a new attack vector against JavaScript codebases has been published: Prototype Pollution. At first glance, it seemed pretty limited in impact: it would basically be a good way to crash some code. However, multiple cases of Remote Code Executions have happened based on this vector. In this talk, we will clarify what are prototype pollutions, their real impact and of to prevent them from happening in your codebase.
This talk has been presented at Node Congress 2023, check out the latest edition of this JavaScript Conference.
Prototype pollution in JavaScript occurs when an arbitrary payload handled by the code can overwrite properties or methods on the prototype chain of one or multiple objects. This usually happens through functions like merging, where properties on the prototype can be unintentionally modified, leading to unexpected behavior or security vulnerabilities.
Prototype pollution can lead to security vulnerabilities such as unauthorized access, remote code execution, and other unintended behaviors within an application. It manipulates the prototype of an object, which all instances of objects inherit methods and properties from, potentially allowing attackers to exploit this for malicious purposes.
To prevent prototype pollution, developers can sanitize and validate incoming data to ensure it does not contain malicious inputs, use Object.create(null) to create objects with no prototype, avoid using vulnerable versions of functions like merge or extend, and employ libraries or tools that filter out prototype properties like __proto__.
Yes, using maps instead of plain JavaScript objects can help prevent prototype pollution because maps do not have a prototype that can be polluted. Maps store keys and values in a form that doesn't interfere with the object's prototype chain.
The __proto__ property in JavaScript is used to assign the prototype of an object. In the context of prototype pollution, malicious payloads can manipulate __proto__ to overwrite properties on an object's prototype chain, leading to potential security risks.
Prototype pollution can significantly impact third-party libraries by altering their behavior if these libraries do not properly guard against modifications to their prototype. This can lead to widespread issues across applications that utilize the affected libraries, compromising application integrity and security.
Real-world consequences of prototype pollution include unauthorized data access, application crashes, and remote code execution. Historical incidents have shown that prototype pollution can lead to significant security breaches, affecting large-scale systems and leading to data loss or corruption.
This Talk discusses prototype production in JavaScript and focuses on the concept of prototype pollution. It explains the impact of prototype pollution and ways to avoid it. The Talk also highlights real-world examples of prototype pollution vulnerabilities in Kibana and MongoDB. It provides recommendations for preventing and mitigating prototype pollution, such as filtering out merge functions and using defensive objects. The Talk concludes with a discussion on tools like Semgrep for static analysis and the importance of sanitization and validation in preventing outside attacks.
We'll talk about prototype production in JavaScript, but before that, let's address something important. The speaker discusses their current situation, being unemployed and working on building a company.
2. Understanding Prototype Pollution
Let's talk about prototype pollution. First, let's learn what prototypes are. We'll also discuss the impact of prototype pollution and avoiding it in JavaScript. JavaScript is prototype-based and somewhat typed. We have the type of operator to check variable types. Objects in JavaScript have prototypes, and when a method or property is not found on an object, it's looked up on the prototype. We'll recursively check the prototype chain until we find the method or property. If it's nowhere in the prototype chain, it's undefined.
3. Understanding Prototype Chain
The prototype chain forms a tree structure. Objects created with different methods may or may not share prototypes. Item three has a prototype, my proto, while item one and item two have the prototype of class one. The prototype of old style class is still in the chain. The method bar is not available on cl.prototype but is available on old style class.prototype.
4. Accessing Object Prototypes
To access the prototype of an object in JavaScript, there are multiple ways. We can use the Object.getPrototypeOf() method, the __proto__ property, or the constructor.prototype property. It's important to note that there is a single instance of the prototype in the heap.
5. Prototype Pollution in JavaScript
Prototype pollution occurs when an arbitrary payload can overwrite properties or methods on the prototype chain of objects. This can happen when using a merge function. A specific example is shown with the Hook library, where a malicious payload is used to modify the prototype chain. The impact of prototype pollution can be severe, with over 200 disclosed vulnerabilities since 2018, including remote code execution in Kibana and the PaaS server.
6. Prototype Pollution in Kibana and Parse Server
KTH University published an interesting paper on prototype pollution in Kibana. The Node.js child processes in Kibana share the parent process environment through a JavaScript object. The Node.option environment variable allows passing command line arguments. The dash e option enables running code passed as a string. Prototype pollution in Kibana allowed writing Node option in the prototype chain. This allowed running arbitrary code on the server and spawning child processes. Dash e is no longer allowed in Node option, but a bypass exists. Kibana has fixed the prototype pollution issue. Parse is a backend project for mobile apps that exposes an API in front of MongoDB.
7. Prototype Pollution in MongoDB
You can request object from MongoDB through a wave API. It's vulnerable to prototype pollution before it was fixed. The library used, bsonjs, allows storing functions in MongoDB. By default, functions are not unserialized. However, if the eval function option for the bson library is true, arbitrary functions can be evaluated. This can lead to running arbitrary code when retrieving objects from the database.
8. Preventing Prototype Pollution
To prevent prototype pollution, filter out merge functions and specifically remove underscore, underscore, proto, underscore, underscore. Lodash has fixed all instances of prototype pollution. When using as-owned property, ensure it exists on the object and not its prototype chain. Building defensive objects using Object.create or Object.createNull can prevent prototype pollution. Sanitization and data validation are crucial for preventing outside attacks. Consider using libraries like joy for data sanitization when building a Node.js web server. Node.js has an option to disable proto, underscore, underscore, proto, underscore, underscore, but be cautious as it may break some code.
9. Mitigating Prototype Pollution
Someone published a paper about class pollution in Python. There is no proof of actual use in the wild for malicious attacks, but it highlights the vulnerability. It's important to check where your objects come from in your codebase, especially for web applications that accept objects from the outside. Be cautious of third-party attacks from NPM modules and inputs from the network. Sanitize and validate the objects that enter your app to prevent injections and ensure they match your expectations. Use tools like Sneak Audit and NPM Audit to check for known vulnerabilities in your codebase.
QnA
Questions and Answers
Are there equivalents to Express or Fastify that prevent prototype pollution? I'm not sure, but it's worth checking the documentation. The -e argument in node options bypass allows passing a JavaScript code string instead of a file. Object.assign may not create polluted prototypes, but further research is needed. Other ways of achieving RCE with prototype pollution depend on the application's string evaluation capabilities. Consider using maps instead of objects to avoid pollution, but ensure there is no intrinsic pollution. It's unclear if merging objects with a native spread operator is safe from pollution. It's important to explore different solutions and not assume vulnerability. ES lint rules detecting these problems may require taint tracking.
Semgrep and Merging Objects
Semgrep is a powerful static analysis code that can find vulnerabilities by running part of your code in a VM. It's open source and designed to check if you're merging based on incoming objects.
This talk discusses the usage of Microfrontends in Remix and introduces the Tiny Frontend library. Kazoo, a used car buying platform, follows a domain-driven design approach and encountered issues with granular slicing. Tiny Frontend aims to solve the slicing problem and promotes type safety and compatibility of shared dependencies. The speaker demonstrates how Tiny Frontend works with server-side rendering and how Remix can consume and update components without redeploying the app. The talk also explores the usage of micro frontends and the future support for Webpack Module Federation in Remix.
RemixConf EU discussed full stack components and their benefits, such as marrying the backend and UI in the same file. The talk demonstrated the implementation of a combo box with search functionality using Remix and the Downshift library. It also highlighted the ease of creating resource routes in Remix and the importance of code organization and maintainability in full stack components. The speaker expressed gratitude towards the audience and discussed the future of Remix, including its acquisition by Shopify and the potential for collaboration with Hydrogen.
Debugging JavaScript is a crucial skill that is often overlooked in the industry. It is important to understand the problem, reproduce the issue, and identify the root cause. Having a variety of debugging tools and techniques, such as console methods and graphical debuggers, is beneficial. Replay is a time-traveling debugger for JavaScript that allows users to record and inspect bugs. It works with Redux, plain React, and even minified code with the help of source maps.
WebAssembly enables optimizing JavaScript performance for different environments by deploying the JavaScript engine as a portable WebAssembly module. By making JavaScript on WebAssembly fast, instances can be created for each request, reducing latency and security risks. Initialization and runtime phases can be improved with tools like Wiser and snapshotting, resulting in faster startup times. Optimizing JavaScript performance in WebAssembly can be achieved through techniques like ahead-of-time compilation and inline caching. WebAssembly usage is growing outside the web, offering benefits like isolation and portability. Build sizes and snapshotting in WebAssembly depend on the application, and more information can be found on the Mozilla Hacks website and Bike Reliance site.
In the last 10 years, Webpack has shaped the way we develop web applications by introducing code splitting, co-locating style sheets and assets with JavaScript modules, and enabling bundling for server-side processing. Webpack's flexibility and large plugin system have also contributed to innovation in the ecosystem. The initial configuration for Webpack can be overwhelming, but it is necessary due to the complexity of modern web applications. In larger scale applications, there are performance problems in Webpack due to issues with garbage collection, leveraging multiple CPUs, and architectural limitations. Fixing problems in Webpack has trade-offs, but a rewrite could optimize architecture and fix performance issues.
There is a need for a standard library of APIs for JavaScript runtimes, as there are currently multiple ways to perform fundamental tasks like base64 encoding. JavaScript runtimes have historically lacked a standard library, causing friction and difficulty for developers. The idea of a small core has both benefits and drawbacks, with some runtimes abusing it to limit innovation. There is a misalignment between Node and web browsers in terms of functionality and API standards. The proposal is to involve browser developers in conversations about API standardization and to create a common standard library for JavaScript runtimes.
During this workshop, participants will review the essential JavaScript patterns that every developer should know. Through hands-on exercises, real-world examples, and interactive discussions, attendees will deepen their understanding of best practices for organizing code, solving common challenges, and designing scalable architectures. By the end of the workshop, participants will gain newfound confidence in their ability to write high-quality JavaScript code that stands the test of time. Points Covered: 1. Introduction to JavaScript Patterns2. Foundational Patterns3. Object Creation Patterns4. Behavioral Patterns5. Architectural Patterns6. Hands-On Exercises and Case Studies How It Will Help Developers: - Gain a deep understanding of JavaScript patterns and their applications in real-world scenarios- Learn best practices for organizing code, solving common challenges, and designing scalable architectures- Enhance problem-solving skills and code readability- Improve collaboration and communication within development teams- Accelerate career growth and opportunities for advancement in the software industry
Dive into the world of AI with our interactive workshop designed specifically for web developers. "Hands-On AI: Integrating LangChain with JavaScript for Web Developers" offers a unique opportunity to bridge the gap between AI and web development. Despite the prominence of Python in AI development, the vast potential of JavaScript remains largely untapped. This workshop aims to change that.Throughout this hands-on session, participants will learn how to leverage LangChain—a tool designed to make large language models more accessible and useful—to build dynamic AI agents directly within JavaScript environments. This approach opens up new possibilities for enhancing web applications with intelligent features, from automated customer support to content generation and beyond.We'll start with the basics of LangChain and AI models, ensuring a solid foundation even for those new to AI. From there, we'll dive into practical exercises that demonstrate how to integrate these technologies into real-world JavaScript projects. Participants will work through examples, facing and overcoming the challenges of making AI work seamlessly on the web.This workshop is more than just a learning experience; it's a chance to be at the forefront of an emerging field. By the end, attendees will not only have gained valuable skills but also created AI-enhanced features they can take back to their projects or workplaces.Whether you're a seasoned web developer curious about AI or looking to expand your skillset into new and exciting areas, "Hands-On AI: Integrating LangChain with JavaScript for Web Developers" is your gateway to the future of web development. Join us to unlock the potential of AI in your web projects, making them smarter, more interactive, and more engaging for users.
Using CodeMirror to Build a JavaScript Editor with Linting and AutoComplete
Top Content
WorkshopFree
2 authors
Using a library might seem easy at first glance, but how do you choose the right library? How do you upgrade an existing one? And how do you wade through the documentation to find what you want? In this workshop, we’ll discuss all these finer points while going through a general example of building a code editor using CodeMirror in React. All while sharing some of the nuances our team learned about using this library and some problems we encountered.
This workshop will teach you the basics of writing useful end-to-end tests using Cypress Test Runner. We will cover writing tests, covering every application feature, structuring tests, intercepting network requests, and setting up the backend data. Anyone who knows JavaScript programming language and has NPM installed would be able to follow along.
Get ready to supercharge your web development skills with React Server Components! In this immersive, 3-hour workshop, we'll unlock the full potential of this revolutionary technology and explore how it's transforming the way developers build lightning-fast, efficient web applications. Join us as we delve into the exciting world of React Server Components, which seamlessly blend server-side rendering with client-side interactivity for unparalleled performance and user experience. You'll gain hands-on experience through practical exercises, real-world examples, and expert guidance on how to harness the power of Server Components in your own projects. Throughout the workshop, we'll cover essential topics, including:- Understanding the differences between Server and Client Components- Implementing Server Components to optimize data fetching and reduce JavaScript bundle size- Integrating Server and Client Components for a seamless user experience- Strategies for effectively passing data between components and managing state- Tips and best practices for maximizing the performance benefits of React Server Components
Passwordless authentication may seem complex, but it is simple to add it to any app using the right tool. We will enhance a full-stack JS application (Node.JS backend + React frontend) to authenticate users with OAuth (social login) and One Time Passwords (email), including:- User authentication - Managing user interactions, returning session / refresh JWTs- Session management and validation - Storing the session for subsequent client requests, validating / refreshing sessions At the end of the workshop, we will also touch on another approach to code authentication using frontend Descope Flows (drag-and-drop workflows), while keeping only session validation in the backend. With this, we will also show how easy it is to enable biometrics and other passwordless authentication methods. Table of contents- A quick intro to core authentication concepts- Coding- Why passwordless matters Prerequisites- IDE for your choice- Node 18 or higher
Comments