Search code examples
javascriptnode.jsregexvirtual-machinenode-vm2

Prevent infinite loop when using NodeVM with code injection rather than threads


Lately am building an API with Node.js that receives untrusted code to run it using vm2. The issue is I want to run async functions, so I need to use NodeVM which does not support timeout for infinite loop, the solutions that I found all about using child process then kill it if it's not working.

But I am receiving the code as a string and I want to prevent having an infinite loop in it, so I thought of using regex to inject the while/for loop with a timeout condition or something so throw an exception whenever infinite loop happened.

Is that possible?


Solution

  • The perfect solution that worked for me is to use AST. so I learned more about it so I can inject the string with anything anywhere I want.

    Then I followed these steps:

    1- convert string code to AST using Esprima parser.

    2- Inject the Infinite loop code protection, which is:

    // Before any loop
    let myvar = Date.now();
    // Inside the loop
    if (Date.now() - myvar > 1000) { break;}
    

    use break or throw an error, notice that you need a unique variable name generator every time you catch a loop.

    3- Convert it back to a string using escodegen.