Skip to content

Instantly share code, notes, and snippets.

@gildas-lormeau
Last active December 1, 2022 21:28
Show Gist options
  • Save gildas-lormeau/3de0d4bbfce1873b0286ef7ce293f2ce to your computer and use it in GitHub Desktop.
Save gildas-lormeau/3de0d4bbfce1873b0286ef7ce293f2ce to your computer and use it in GitHub Desktop.
/*
The MIT License (MIT)
Copyright (c) 2016 Gildas Lormeau (Capsule Code)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
const safeEval = (() => {
const sourceCode = (() => {
const whitelist = ["Array", "ArrayBuffer", "Boolean", "Date", "DataView", "Error", "Float32Array", "Float64Array", "Infinity", "Int8Array", "Int16Array", "Int32Array", "JSON", "Map", "Math", "NaN", "Number", "Object", "Promise", "RegExp", "Set", "String", "Symbol", "Uint8Array", "Uint8ClampedArray", "Uint16Array", "Uint32Array", "WeakMap", "WeakSet", "atob", "btoa", "decodeURI", "decodeURIComponent", "encodeURI", "encodeURIComponent", "escape", "isNaN", "parseFloat", "parseInt", "undefined", "unescape", "eval"];
const scope = getScope(Object.create(null), window);
delete Function.prototype.constructor;
delete Object.getPrototypeOf(async () => { }).constructor;
delete (function * () { }).prototype.constructor.constructor;
return code => {
with (scope) {
return (function () {
"use strict";
return eval(`(0,eval)("eval = undefined"),${code}`);
})();
}
};
function getScope(scope, object) {
Object.getOwnPropertyNames(object)
.filter(name => whitelist.indexOf(name) == -1)
.concat(["getScope", "scope", "whitelist"])
.forEach(name => scope[name] = undefined);
const proto = Object.getPrototypeOf(object);
return proto ? getScope(scope, proto) : scope;
}
}).toString();
return code => {
const sandboxIframe = document.createElement("iframe");
document.body.appendChild(sandboxIframe);
const script = document.createElement("script");
script.textContent = "var safeEval = (" + sourceCode + ")();";
const sandboxWindow = sandboxIframe.contentWindow;
sandboxWindow.document.body.appendChild(script);
const safeEval = sandboxWindow.safeEval;
document.body.removeChild(sandboxIframe);
return safeEval(code);
};
})();
let myFunction;
myFunction = safeEval("() => this");
console.log(myFunction()); // undefined
myFunction = safeEval("() => window");
console.log(myFunction()); // undefined
myFunction = safeEval("() => self");
console.log(myFunction()); // undefined
myFunction = safeEval("() => eval");
console.log(myFunction()); // undefined
myFunction = safeEval("() => (0,eval)");
console.log(myFunction()); // undefined
myFunction = safeEval("() => Object.getPrototypeOf(function() {}).constructor");
console.log(myFunction()); // undefined
myFunction = safeEval("() => Object.getPrototypeOf(async () => {}).constructor");
console.log(myFunction()); // undefined
myFunction = safeEval("() => Object.getPrototypeOf(function * () {}).constructor.constructor");
console.log(myFunction()); // undefined
@ghoullier
Copy link

@gildas-lormeau j'avoue la c'est tendu. J'ai vu que tu avais interdis eval aussi ^

@ghoullier
Copy link

ghoullier commented Oct 28, 2016

safeEval(`
(async () => {
  const fn =  async () => {}
  const getter = new fn.constructor('return this')
  const global = await getter()
  return global.localStorage.clear()
})()
`)

@gildas-lormeau
Copy link
Author

gildas-lormeau commented Oct 28, 2016

Sous Canary version 56.0.2902.0 (64-bit), j'obtiens en retour de l'appel :

Promise
  __proto__: Promise
  [[PromiseStatus]]: "rejected"
  [[PromiseValue]]: TypeError: Cannot read property 'clear' of null at eval (eval at <anonymous> (:10:28), <anonymous>:6:29)

@ghoullier
Copy link

Faire du code sur mobile c'est pas une bonne idée ^^

Voila un meilleur exemple, j'arrive a retourner une promesse qui expose un objet censé etre blackboxé

safeEval(`
(async () => {
  const a =  async () => {}
  const b = new a.constructor('return this')
  const c = await b()
  const d = c.Function('return this')
  return d().setTimeout
})()
`).then(console.log)

@ghoullier
Copy link

La même avec les generateurs

safeEval(`
(() => {
  const g = function * () {}
  const code = "return setTimeout"
  const h = new g.prototype.constructor.constructor(code)()
  const setTimeout = h.next().value
  return setTimeout
})()
`)

@ghoullier
Copy link

ghoullier commented Nov 3, 2016

Le fait que l'iframe soit créée et détruite de manière synchrone fait que l'effet de bord ne se voit pas, mais le contexte d'exécution de la fonction safeEval peut être bypassé par async/wait et les generateurs

@gildas-lormeau
Copy link
Author

gildas-lormeau commented Dec 30, 2016

J'ai mis à jour le gist (cf. https://gist.github.com/gildas-lormeau/3de0d4bbfce1873b0286ef7ce293f2ce#file-safeeval-js-L17-L18). Pour le coup, la défense est toujours la même, faut juste détruire tous ces constructeurs malicieux.

Pour info, j'ai vérifié dans la spec, constructor a la propriété configurable = true, donc on peut la détruire, y'a pas de hack.

Encore merci pour l'aide, je suis conscient de la prise de tête que ça représente ;-)

@viebel
Copy link

viebel commented Mar 16, 2017

Ca a l'air super. Je vais jetter un coup d'oeil plus profond tres bientot.

@viebel
Copy link

viebel commented Mar 17, 2017

Le problème, c'est qu'on ne peut pas définir des variables:

safeEval(x=1+2) cause un erreur:

Uncaught ReferenceError: x is not defined
    at eval (eval at <anonymous> (:11:28), <anonymous>:1:31)
    at <anonymous>:11:28
    at code (<anonymous>:12:19)
    at code (<anonymous>:36:16)
    at <anonymous>:1:1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment