Simulate JS execution to read heap memory

603 views Asked by At

I have a problem where I need to see if a particular JavaScript source code takes a lot of heap space. Ideally I would like to have access to heap memory usage and data type of objects in the heap. The trouble is that it seems I'll have to execute the code to have access to heap mem allocation information.

The code, however, are malicious (heap spray attacks) so I would like to avoid full execution. Is there a way for me to simulate the execution instead? I've read that I can use sbrk or API hook (MSFT Detours) to get memory usage for a particular process (usually the JS interpreter/engine), but it looks like these use cases actually executed the code.

EDIT: I would need to access heap memory as part of a pipeline for multiple JS files so it would be ideal having memory info via a command or through an API.

2

There are 2 answers

3
AdelmoMezzi On

If you use Chrome you can use the Perfomance tab of Developer Tools. Just press record refresh the page or apply JS script: enter image description here

If you want to see JS memory you can also use Task Manager. enter image description here -> More Tools -> Task Manager enter image description here

2
jmrk On

What does it mean to "simulate execution"?

Generally speaking: JavaScript engines are made to execute JavaScript. For real.

For analyzing malicious code, you'll probably want to look into sandboxing/isolating it as much as possible. In theory, executing it normally in a browser should be enough -- in practice though, security bugs do sometimes exist in browsers, and malicious code will attempt to exploit those, so for this particular purpose that probably won't be enough.

One approach is to add a whole other layer of sandboxing. Find yourself a JavaScript-on-JavaScript interpreter. Or pick a non-JIT-compiling JavaScript engine, and compile it to WebAssembly, and run that from your app. You can then inspect the memory of the WebAssembly instance running the malicious code; this memory is exposed as an ArrayBuffer to your JavaScript app. (I don't have a particular recommendation for such a JS engine, but I'm sure they exist.) It might be a bit of effort to get such a setup going (not sure; haven't tried), but it'd give you perfect isolation from evil code.