Javascript ghosts

This posts follows the one about breaking the call stack. It’s just a proof of concept to further cover the tracks of execution in the browser.

It’s possible to cut off relation of executed code with the script that brought it into execution environment! This may sound abstract. Put in another way, you can hide the script source from the debugger. It’s pretty simple to do:

const head = document.querySelector('head')
const evilScript = document.createElement('script')
evilScript.text = `
  const malicious = () => { throw new Error() }

This nifty piece of code creates a script, sets it’s ‘code’, adds it to the head of the document an immediately removes it from the DOM. The code inside the added script will run malicious code for which the origin will seem to be javascript virtual machine(VM) and not originating script tag or external script(if used).

What happens here is that script’s code is pushed to the browser’s memory and starts executing. In the meantime the DOM reference to the script is removed. This seems to unlink the code that will be executed from it’s origin, at least in the debugger’s eyes:

VM84:2 Uncaught Error
    at malicious (<anonymous>:2:35)
    at <anonymous>:3:3
    at <anonymous>:7:6

Following the stack trace leads to anonymous virtual machine script.