From 4ff67140b8e1655c2295b4bce981b3d2f16596c6 Mon Sep 17 00:00:00 2001 From: jean-emmanuel Date: Sun, 7 Apr 2019 18:03:51 +0200 Subject: [PATCH] jsparser: prevent access to the host window --- package.json | 2 +- src/client/app/widgets/utils.js | 51 ++++++++++++++++++++++++--------- 2 files changed, 38 insertions(+), 15 deletions(-) diff --git a/package.json b/package.json index dd42afe6..df8882ed 100644 --- a/package.json +++ b/package.json @@ -43,8 +43,8 @@ "json5": "2.1.0", "jsondiffpatch": "0.3.11", "keyboardjs": "github:jean-emmanuel/KeyboardJS", - "loop-protect": "github:jean-emmanuel/loop-protect#v1.0.1", "licensify": "3.1.3", + "loop-protect": "github:jean-emmanuel/loop-protect#v1.0.1", "mathjs": "5.8.0", "minimatch": "3.0.4", "nanohtml": "1.5.0", diff --git a/src/client/app/widgets/utils.js b/src/client/app/widgets/utils.js index c02ae036..d9a7c11f 100644 --- a/src/client/app/widgets/utils.js +++ b/src/client/app/widgets/utils.js @@ -113,7 +113,7 @@ module.exports = { sandbox.style.display = 'none' sandbox.sandbox = 'allow-same-origin' - document.body.appendChild(sandbox) + document.documentElement.appendChild(sandbox) // block requests sandbox.contentWindow.document.open() @@ -125,38 +125,61 @@ module.exports = { loopProtect.hit = function(line){ throw 'Potential infinite loop found on line ' + line } - - sandbox.contentWindow.__parsers = {} sandbox.contentWindow.__protect = loopProtect + + var _Function = sandbox.contentWindow.Function, + parsers = {}, + timeouts = {}, + intervals = {} + + sandbox.contentWindow.console = console + + document.documentElement.removeChild(sandbox) + function evaljs(code, defaultContext) { - sandbox.contentWindow.__parsers[code] = sandbox.contentWindow.Function( - loopProtect('"use strict";' + code) + var contextInit = '', + contextKeys = [], + contextValues = [] + + if (defaultContext) { + for (var k in defaultContext) { + contextInit += `var ${k} = ${k} || ${JSON.stringify(defaultContext[k])}` + contextKeys.push(k) + contextValues.push(defaultContext[k]) + } + } + + parsers[code] = new _Function( + '__VARS', ...contextKeys, + loopProtect('"use strict";' + contextInit + code) .replace(/;\n(if \(__protect.*break;)\n/g, ';$1') // prevent loop protect from breaking stack linenumber + .replace(/(VAR_[0-9]+)/g, '__VARS.$1') ) return (context)=>{ var ret, err, k - // set context - for (k in context) { - sandbox.contentWindow[k] = context[k] + var __VARS = {} + for (var k in context) { + var index = contextKeys.indexOf(k) + if (index !== -1) { + contextValues[index] = context[k] + } else { + __VARS[k] = context[k] + } } + contextValues.unshift(__VARS) // evaluate try { - ret = sandbox.contentWindow.__parsers[code]() + ret = parsers[code].apply(null, contextValues) } catch(e) { err = e } - // clean context - for (k in context) { - delete sandbox.contentWindow[k] - } - if (err) throw err return ret