Class Pollution in Ruby: A Deep Dive into Exploiting Recursive Merges
A Ruby application recursively merges user-supplied JSON into an object's attributes, letting an attacker set instance variables and singleton methods on that object. This allowed privilege escalation by overriding the to_s method and code execution by injecting into the protected_methods list that is later evaluated.
blog.doyensec.com
Published on blog.doyensec.com
In this post, we are going to explore a rarely discussed class of vulnerabilities in Ruby, known as class pollution. This concept is inspired by the idea of prototype pollution in JavaScript, where recursive merges are exploited to poison the prototype of objects, leading to unexpected behaviors.
The full write-up lives on its author's site
It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.
Not written yet. The AI write-up for this write-up has not been written yet. The Original tab links to the source.
How it worked
Root cause
Likely the recursive merge blindly sets instance variables and singleton accessors from attacker-controlled keys, so method names such as to_s or protected_methods can be overwritten.
Impact
An attacker could escalate a regular user to admin and could execute arbitrary code through the health check, though the text notes the changes are limited to the specific object instance.
What the attacker needed
Ability to submit JSON to the merge; application uses recursive merge on objects
The fix
Developers should carefully consider how data merges are handled to mitigate class pollution risk.
How it was found
- Send JSON to the application that is parsed and passed to the recursive merge.
- Include a key such as to_s with the value Admin so the object's method is replaced.
- Call the authorize method, which compares to_s to Admin and grants access.
- Alternatively include a protected_methods key with code, then trigger health_check to run it.
Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.
Not written yet. The AI write-up for this write-up has not been written yet. The Original tab links to the source.
Ruby objects can have their own private set of values and methods, separate from the class they belong to. If a program copies data from a user into those values without checking the names, the user can add or replace methods on that object. Here that let a normal user pretend to be an admin, and even run their own code.
What is Prototype pollution?
Input changes JavaScript's shared object prototype, altering behaviour across the application, sometimes to XSS or code execution.