Wizer CTF #19: Calculator
Link to challenge: CTF #19
Link to challenge: CTF #19
In this challenge, we're identifying a tricky Code Injection vulnerability.
The code below showcases a simple calculator endpoint. The developer figured this would be safer than just using eval because they read about scopes in JavaScript and noticed that Function() runs in a different scope. Today we prove that it's not safer at all! A requirement of the feature was to allow the consumers of the endpoint to take advantage of the `mathjs` library to enable calculations such as `100 + Math.sqrt(1000)`. To achieve that, the developer provided `require` as an external argument to the scope so that the isolated scope is able to run the following calculation: `100 + argument[0]('mathjs').sqrt(1000)`.
The `require` argument can be misused to import libraries which will provide unauthorized access to data/files and assets.
An attacker could use the `require` argument to import the `fs` library and read the contents of any file including `/etc/passwd`. Dynamically requiring the `fs` library, makes functions like `readFileSync('[path]')` accessible.
Code Injection is an extremely dangerous vulnerability, once an attacker gains access to execute any code and basically any library by controlling user-input, the range of opportunities is broad starting from reading secret keys, through server and infrastructure take over.