Code Monkey home page Code Monkey logo

near-membrane's Introduction

JavaScript Near Membrane Library

This library implements a "near membrane" that can connect two Realms (the Incubator Realm, and the Child Realm) running on the same process. As a result, the Child Realm will emulate the capabilities of the Incubator Realm, plus the distortions defined as part of the near membrane configuration. Code evaluated inside the Child Realm will function as if it is evaluated in the Incubator Realm, exhibiting identity continuity, while preserving the integrity of the Incubator Realm by limiting the side effects that such code can have.

Goals

  • Code executed inside the sandboxed environment cannot observe the sandbox.
  • Mutations on the object graph should only affect the sandboxed environment.

Non-goals

  • This library does not provide security guarantees, those must be implemented on top of the distortion mechanism.

Terminology

In order to make it easier to explain how this library works, we use a color code to identify objects and values in general from both sides of the sandbox:

  • Blue Realm is the Incubator Realm.
  • Red Realm is the Child Realm that is sandboxed by this library.
  • Blue Object, Blue Array, Blue Function, and Blue Values denote values that belong to the Blue Realm.
  • Red Object, Red Array, Red Function, and Red Values denote values that belong to the Red Realm.
  • Blue Proxy denote a Proxy created in the Blue Realm with a target that belongs to the Red Value.
  • Red Proxy denotes a proxy created in the Red Realm with a target being a Blue Value.

Design

This library implements a near membrane to sandbox a JavaScript environment object graph. This membrane is responsible for connecting the Blue Realm with a Red Realm, and it does that by remapping global references in the Red Realm to be Red Proxies (proxies of Blue Values).

This membrane modulates the communication between the two sides, specifically by creating proxies around objects, arrays and functions, while letting other primitives values travel safely throughout the membrane.

Cross-sandbox communication

Since you can have multiple sandboxes associated to the Blue Realm, there is a possibility that they communicate with each other. This communication relies on the marshaling principle to avoid wrapping proxies over proxies when values are bounced between sandboxes via the Blue Realm. It does that by preserving the identity of the Blue Proxies observed by the Blue Realm. The Blue Realm is in control at all times, and the only way to communicate between sandboxes is to go through the Blue Realm.

Implementation Details

Implementation in Browsers

In browsers, since we don't have a way to create a light-weight Realm that is synchronously accessible (that will be solved in part by the stage 3 ShadowRealms Proposal), we are forced to use a same-domain iframe in order to isolate the code to be evaluated inside a sandbox for a particular window.

Detached iframes

Since the iframes have many ways to reach out to the opener/top window reference, we are forced to use a detached iframe, which is, on itself, a complication. A detached iframe's window is a window that does not have any host behavior associated to it, in other words, this window does not have an origin after disconnecting the iframe, which means it can't execute any DOM API without throwing an error. Luckily for us, the JavaScript intrinsics, and all JavaScript language features specified by ECMA262 and ECMA402 are still alive and kicking in that iframe, except for one feature, dynamic imports in a form of import(specifier).

To mitigate the issue with dynamic imports, we are forced to transpile the code that attempts to use this feature of the language, otherwise it will just fail to fetch the module because there is no origin available at the host level. However, transpiling dynamic imports is a very common way to bundle code for production systems today.

Unforgeables

The window reference in the detached iframe, just like any other window reference in browsers, contains various unforgeable descriptors, these are descriptors installed in Window, and other globals that are non-configurable, and therefor this library cannot remove them or replace them with a Red Proxy. Must notable, we have the window's prototype chain that is completely unforgeable:

window -> Window.prototype -> WindowProperties.prototype -> EventTarget.prototype

What we do in this case is to keep the identity of those unforgeable around, but changing the descriptors installing on them, and any other method that expects these identities to be passed to them. This make them effectively harmless because they don't give any power.

Additionally, there are other unforgeables like location that are host bounded, in that case, we don't have to do much since the detaching mechanism will automatically invalidate them.

These can only be virtualized via transpilation if they need to be available inside the sandbox. Such transpilation process is not provided as part of this library.

Requirements

The only requirement for the in-browser sandboxing mechanism described above is the usage of eval as the main mechanism for evaluating code inside the sandbox. This means your CSP rules should include at least script-src: 'unsafe-eval' in order for this library to function.

Performance

Even though this library is still experimental, we want to showcase that it is possible to have a membrane that is fairly fast. The main feature of this library is the laziness aspect of the Red Proxies. Those proxies are only going to be initialized when one of the proxy's traps is invoked the first time. This allow us to have a sandbox creation process that is extremely fast.

Additionally, since existing host JavaScript environments are immense due to the amount of APIs that they offer, most programs will only need a very small subset of those APIs, and this library only activates the portions of the object graph that are observed by the executed code, making it really light weight compared to other implementations.

Finally, Blue Proxies are not lazy, they are initialized the first time they go through the membrane even if they are not used by the Blue Realm. This could be changed in the future if it becomes a bottleneck. For now, since this is a less common case, it seems to be fine.

Where can I use this library?

We do not know the applications of this library just yet, but we suspect that there are many scenarios where it can be useful. Here are some that we have identified:

  • Sandbox code to preserve the integrity of the app creating the sandbox, all code inside the sandbox will not observe that it is being sandboxed, but will not cause any integrity change that can cause the app's code to malfunction.
  • Sandbox for polyfills: if you need to evaluate code that requires different set of polyfills and environment configuration, you could sandbox it without distortions.
  • Limiting capabilities: if you need to evaluate code that should not have access to certain capabilities (global objects, getter, setters, etc.) you could sandbox it with a set of distortions to accommodate such limitations.
  • Time-sensitive: If you need to evaluate code that should not observe time or should simulate a different time-frame, you should sandbox it with a set of distortions that can adjust the timers.

The Code

  • This library is distributed via npm packages @locker/near-membrane-base, @locker/near-membrane-dom and @locker/near-membrane-node.
  • This library is implemented using TypeScript, and produces the proper TypeScript types, in case you care about it.
  • Few tests are provided as of now, but the plan is to rely on existing tests (e.g.: WPT or ECMA262) to validate that the near membrane created by this library is a high-fidelity membrane.
  • The src/ folder contains the library code, while the dist/ folder will contain the compiled distributable code produced by executing the build script from package.json.
  • This library does not have any runtime dependency, in fact it is very tiny.

Challenges

Debuggability

  • Debugging is still very challenging considering that dev-tools are still catching up with the Proxies. Chrome for example has differences displaying proxies in the console vs the watch panel.

Additionally, there is an existing bug in ChromeDev-tools that prevent a detached iframe to be debugged (https://bugs.chromium.org/p/chromium/issues/detail?id=1015462).

WindowProxy

The window reference in the iframe, just like any other window reference in browsers, exhibit a bizarre behavior, the WindowProxy behavior. This has two big implications for this implementation when attempting to give access to other window references coming from same domain iframes (e.g.: sandboxing the main app + one iframe):

  • each window will require a new detached iframe to sandbox each of them, but if the iframe navigates to another page, the window reference remains the same, but the internal of the non-observable real window are changing. Otherwise distortions defined for the sandbox will not apply to the identity of the methods from the same-domain iframe.
  • GCing the sandbox when the iframe navigates out is tricky due to the fact that the original iframe's window reference remains the same, and it is used by few of the internal maps.

For those reasons, we do not support accessing other realm instances from within the sandbox at the moment.

Browsers Support and Stats

  • Modern browsers with support for ES6 Proxy and WeakMaps.
  • This library: ~3kb minified/gzip for browsers, ~2kb for node (no external dependencies).

near-membrane's People

Contributors

arcadeteddy avatar caridy avatar dejang avatar dependabot[bot] avatar dgitin avatar garychangsf avatar ionline247 avatar jasonschroeder-sfdc avatar jdalton avatar kumavis avatar leobalter avatar manuel-jasso avatar nrobertdehault avatar rwaldron avatar tedconn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

near-membrane's Issues

remap AsyncFunction constructor and friends.

We remap Function but miss (async () => {}).constructor (AsyncFunction), (function* a() {}).constructor (GeneratorFunction), and (async function* a() {}).constructor (AsyncGeneratorFunction).

cache the browser/node descriptor maps and reference

as today, every time you create a new env, the outer realm global object is inspected to extra all the info needed to build the sandbox, this information should be extracted during evaluation time rather than creation to avoid poisoning and other non-deterministic behavior.

the consumer of this package should be responsible for preparing the env before loading this package.

another alternative is to extra them once during the creation of the first sandbox, but that probably suffer from the same kind of problems.

The owner of the sandbox can also do extra mapping in case that the initial state of the outer realm is not exactly what they want, or they can attempt to create the proper distortion.

[investigation] symbols should be remapped

As today, symbols are considered primitive, but the following code leaks today:

Symbol().constructor.__proto__ === Function.prototype

based on the assumption that we let symbols to pass through the membrane.

and additionally problem to be looked at here is the Symbol.from().

[browsers] Impossible to observe unhandled rejection from within a sandbox

In browsers, the HostPromiseRejectionTracker depends on the identity of the Promise Intrinsic Object, which means there is no way to capture unhandled rejection produced by the Promise inside the sandbox, e.g.:

    const iframe = document.createElement('iframe');
    document.body.appendChild(iframe);
    const { contentWindow: { eval: iframeEval } } = iframe;
    // adding listeners
    window.addEventListener('error', e => console.error('onerror in outer window', e));
    window.addEventListener('unhandledrejection', e => console.error('captured onunhandledrejection in outer window with reason: ', e.reason));
    iframeEval(`
        window.addEventListener('error', e => console.error('onerror in iframe', e));
        window.addEventListener('unhandledrejection', e => console.error('captured onunhandledrejection in iframe with reason: ', e.reason));
    `);
    // trying Promise intrinsic object from iframe:
    iframeEval(`
        new Promise((resolve, reject) => {
            reject('rejection Promise intrinsic from iframe');
        });
    `);
    // trying Promise intrinsic object from outer realm:
    iframeEval(`
        new top.Promise((resolve, reject) => {
            reject('rejection Promise intrinsic from outer realm');
        });
    `);

From within the sandbox, when you do window.addEventListener('unhandledrejection') you are observing unhandled rejection from the outer realm, but that doesn't include those unhandled rejection from within the sandbox.

This seems to be a problem to be solved, it is not a security/leaking problem, but a capability problem.

Question: Is it possible to use Child Realm in browser without access to browser-specific API?

It looks like the library fits our goals perfectly exhibiting identity continuity, preserving the integrity of the Incubator Realm. But we need our sandboxes to be as restricted by available API as possible. Actually we need a JS execution sandbox with ES-default intrinsics (nor browser neither node specific) + ability to provide some set of globals. Is it possible to achieve with this library? I have feeling that it should be by using @locker/near-membrane-base with some parts from @locker/near-membrane-dom but the lack of documentation makes reasoning quite hard.

Not work with exotic object

Reproduction:

import { AsyncCall } from 'https://cdn.skypack.dev/[email protected]'
import createIframeVirtualEnvironment from 'http://cdn.skypack.dev/@locker/near-membrane-dom'

const exoticObject = AsyncCall(null, {
    channel: { on() {}, send() {} },
})

const vm = createIframeVirtualEnvironment(globalThis)

debugger
const obj = vm.evaluate(`e => e.foo`)(exoticObject)

// obj should be a function.

build inconsistenly fails

secure-javascript-environment on ๎‚  master [?] is ๐Ÿ“ฆ v0.1.0 via โฌข v10.16.0 
โ‡ก0% โžœ yarn build
yarn run v1.19.1
$ ttsc & rollup -c

examples/web-components/platform.js โ†’ examples/web-components/bundle.js...
[!] Error: Could not resolve '../../lib/browser-realm.js' from examples/web-components/platform.js
Error: Could not resolve '../../lib/browser-realm.js' from examples/web-components/platform.js
    at error (/home/xyz/Development/secure-javascript-environment/node_modules/rollup/dist/rollup.js:5362:30)
    at ModuleLoader.handleMissingImports (/home/xyz/Development/secure-javascript-environment/node_modules/rollup/dist/rollup.js:12200:17)
    at ModuleLoader.<anonymous> (/home/xyz/Development/secure-javascript-environment/node_modules/rollup/dist/rollup.js:12091:30)
    at Generator.next (<anonymous>)
    at fulfilled (/home/xyz/Development/secure-javascript-environment/node_modules/rollup/dist/rollup.js:41:28)

error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

secure-javascript-environment on ๎‚  master [?] is ๐Ÿ“ฆ v0.1.0 via โฌข v10.16.0 
โ‡ก0% โžœ yarn build
yarn run v1.19.1
$ ttsc & rollup -c

examples/web-components/platform.js โ†’ examples/web-components/bundle.js...
[!] Error: Could not resolve '../../lib/browser-realm.js' from examples/web-components/platform.js
Error: Could not resolve '../../lib/browser-realm.js' from examples/web-components/platform.js
    at error (/home/xyz/Development/secure-javascript-environment/node_modules/rollup/dist/rollup.js:5362:30)
    at ModuleLoader.handleMissingImports (/home/xyz/Development/secure-javascript-environment/node_modules/rollup/dist/rollup.js:12200:17)
    at ModuleLoader.<anonymous> (/home/xyz/Development/secure-javascript-environment/node_modules/rollup/dist/rollup.js:12091:30)
    at Generator.next (<anonymous>)
    at fulfilled (/home/xyz/Development/secure-javascript-environment/node_modules/rollup/dist/rollup.js:41:28)

error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

secure-javascript-environment on ๎‚  master [?] is ๐Ÿ“ฆ v0.1.0 via โฌข v10.16.0 
โ‡ก0% โžœ yarn build
yarn run v1.19.1
$ ttsc & rollup -c

examples/web-components/platform.js โ†’ examples/web-components/bundle.js...
created examples/web-components/bundle.js in 136ms
Done in 0.41s.

secure-javascript-environment on ๎‚  master [?] is ๐Ÿ“ฆ v0.1.0 via โฌข v10.16.0 
โ‡ก0% โžœ yarn build
yarn run v1.19.1
$ ttsc & rollup -c

examples/web-components/platform.js โ†’ examples/web-components/bundle.js...
created examples/web-components/bundle.js in 101ms
Done in 0.32s.

[investigation] can we support live arrays instead of replicating them

There are two main reasons for the current cloning mechanism for arrays:

  • it reduces the risk of poisoning (but does not eliminated complete because of array-like objects are very effective replacement).
  • Array.prototype.length, which is not a traditional accessor backed up by an internal slot.

Is is possible to solve this in a way that an array instance crossing the membrane can be proxified and its identity preserved by remapping the prototype of the proxy?

Live objects support

Some distortions may need to work with live objects, such as localStorage or sessionStorage. There may be others but the concept is the same.

I have identified an issue with the following scenario (code runs in the secure environment):

localStorage.setItem('foo', 'foo');
localStorage.setItem('bar', 'bar');

console.log(Object.keys(localStorage)); // returns [] should return 2

The issue seems to lie in SecureProxyHandler.initialize which makes a snapshot of the object the first time it is being seen and then never updates the properties on recurrent calls. With localStorage this occurs when we access the getter on the window object thus all other traps will disregard future properties added on this object.

Enable async/await tests for Firefox and Safari

The membrane/async-await.spec.js tests fail in Firefox and Safari. At the moment we are not testing with Safari, but CI fails with Firefox. For now and until we find a solution, disable async/await tests for these browsers.

Escapable via RangeError caused by stack overflow on chrome

Problem

It turns out chrome decide the prototype of RangeError by the function being called instead of caller.

So the RangeError behaves like a unforgeable hidden property on function. And can be exploited by stack overflow.

Maybe we should also add this to the proposal-preserve-virtualizability.

Or better, open another PR to standardize stack overflow behavior to stop similar problem once and for all.

POC

import createSecureEnvironment from '../lib/browser-realm.js';

function distortionCallback(t) {
    if (t === alert) {
        return () => {
            console.error('forbidden');
        }
    }
    return t;
}

const secureGlobalThis = createSecureEnvironment(distortionCallback);

secureGlobalThis.eval(`
    debugger;

    function getLimit (depth = 1) {
        try {
            return getLimit(depth + 1)
        } catch (err) {
            return depth
        }
    }

    console.log(getLimit())

    let err

    function exhaust(depth, cb) {
        try {
            if (depth > 0) {
                exhaust(depth - 1, cb)
            } else {
                cb('something')
            }
        } catch (_err) {
            err =_err
        }
    }

    const log = console.log

    exhaust(getLimit() - 1, log)

    debugger

    console.log(err, err instanceof RangeError)
    console.log((new (err.constructor.constructor('alert()')))())

    debugger
`);

Tested on chrome 78.0.3904.108

May be also exploitable on firefox, but firefox randomized the stack size. So these kind of exploit can't be done reliable. (Will likely requires thousands of try, and each one only has 0.01% chance to exploit the problem successfully)

Potential workaround (because it isn't really fixable)

Instead of construct the proxy and proxy handler inside the main document, construct them in the iframe and use rpc style payload to exchange information with main document.

(So you at least won't leak main document's reference to the sandboxed code directly)

Similar experiment project I wrote

Conclusion

It means (on chrome) you are all set if any function reference construct in main window was exposed to the iframe, because the iframe don't even need to run the function body to exploit the RangeError

Question about `liveTargetCallback`

I was hunting a bug of code running with near-membrane where code could not edit the style of an element. Something like this evaluated inside won't affect the DOM. This bug was only present in Chrome but not in Firefox (both latest versions)

const el = document.getElementById('test');
test.style.background = 'red'; // won't actually set the style.

By chance while reading the library code and searching through I found this unit test

describe('@@lockerLiveValue', () => {

And implementing the same approach using liveTargetCallback and marking with a symbol fixed this issue for Chrome.

That leads me to the question how does liveTargetCallback work?

I appreciate if you can illustrate the concept a bit more since there's no documentation and I'm still trying to digest the library code and understand how it works.

Is an already imported module importable from within the disconnected iframe?

This is another question from SES meeting. If the disconnected iframe imports one module over the network before it is disconnected, can the disconnected iframe access that module again?

The only way to import a module (again) is via a dynamic import, which could be done via eval() as follow:

eval(`import('./same/path.js')`);

Distortions for window do not get wired

The following distortion seems to not get triggered. It seems like it is completely bypassed in favor of something else. The property is still surrounded in a SecureProxy.

const originalLocalStorageGetter = Reflect.getOwnPropertyDescriptor(window, 'localStorage').get;

function patchedLocalStorageGetter() { return {} };

const evaluator = createSecureEnvironment(new Map([[originalLocalStorageGetter, patchedLocalStorageGetter]]));

evaluator('console.log(localStorage)');

Errors and sourcemaps inside Virtualenvironment

hello.

I am experimenting with near-membrane to isolate plugins executions.

I am using near-membrane-dom to load the plugins code, I create a virtual environment, load the code in a string and use evalute to get the code executed.

  const response = await fetch(pathToPluginJsCode);
  const code = await response.text();
   const env = createVirtualEnvironment(window, {
      // distortions are interceptors to modify the behavior of objects when
      // the code inside the sandbox tries to access them
      distortionCallback(v) {
          // pluginDistortionMap is the distortion definitions, not 
          return pluginDistortionMap.get(v) ?? v;
     },
    endowments: Object.getOwnPropertyDescriptors({
        // plugins normally run inside system js. I'm using this as mechanism to
        // resolve their deps and execute the code
        define(deps: string[], jsModule: () =>  void) => {
             const realDeps = resolveDeps(deps);
             const pluginExport = code.apply(null, realDeps);
             pluginExport.execute(); // the logic is a bit more complex but not relevant for this case.
        },
      }),
);
  • Errors generated inside the virtual environment get printed in the browser console as Uncaught Proxy(Object)ย {} Do you know a good way to unwrap this object to present it human-readable?
  • I found I can use the instrumentation to partially process these errors myself and I could parse the error stack trace and re-create it and print it nicely (even though the original error is thrown anyway)
  • The error itself contains only the error name and message, but the stacktrace, as expected, points you to the near-membrane wrapping code which is not useful to know which actual line of the plugin throw the error.
  • Because we evaluate the plugin code as text there's no references to lines of code inside it.

Generally speaking, is there a way to get what line of code generated the error inside the virtual environment? or maybe there's another way to evaluate the plugin's code that doesn't rely on a string so meaningful errors can be generated? There is little to none documentation and I feel force to ask here

Thanks in advance and amazing work in this library.

feature request: improve debug experience by set-up a private field on the proxy when possible

image

This is possible when two realms can exchange objects. By setting a private field on it, we can improve the developer experience because they can know what is under this proxy.

This is also safe because the private field is not accessible outside the class body, if the class never read it, it is impossible to leak.

I have implemented this feature in my environment binding (where Node vm and Web iframe is both impossible), but I hope this feature can be in the upstream.

realm of thrown errors.

This is more of a question. With esm I was hiding the internals of the loader in another realm but would expose API points to the user's realm. When errors were thrown from the internal realm I had to ensure the errors produced were of the user's realm. I see that the secure-javascript-environment throws errors in places. Is there any cross-realm leak concern there?

raw value as a property of the secure handler could be an issue

@erights asked about this.target as RawTarget in the secure handler code, which means that we have an internal object graph that combines raw and secure objects. At first glance this is not a problem because we never expose that handler, we only pass it into an already cached Proxy constructor, but it is weird that we try to keep them all very separated except for this instance. We could use a weakmap instead. Also, the same applies for the other part of the membrane, a raw handler has a direct reference to a secure target.

The only reason why this is important is for developer productivity, because in the devtool, they can inspect the proxy and access the real target from the handler since the proxy target is the shadow target.

split or expose shared utils

I noticed in the creation of distortion callbacks that we could use the shared utils to avoid prototype methods of arrays, maps, sets, etc. We could expose this as its own scoped package or promote use of @caridy/sjs/lib/shared (seems a bit like reaching for internals that way though).

Code Coverage Instrumentation Failed At redEnvFactory

Istanbul instruments all source code. Unfortunately, redEnvFactory is coerced to a string, it's missing a reference to the code coverage function that is in the outer scope. This causes an undefined access error when the red factory function is ran in the red realm.

@jdalton

Question: `eval` vs `Function(code)()`

I recently stumbled upon the script-src: unsafe-eval restriction in another project and got around it by using Function(code)() instead.

I was wondering if you guys tried that route to remove that requirement and, if you don't mind, what problems have you encountered?

`Symbol.toStringTag` checks for proxies

This is just a todo to remember to address the Symbol.toStringTag check for proxies. The issue is proxies will Object.prototype.toString.call(proxied) as either an [object Object] or a [object Function] but not as anything else. In those cases the proxied value will need to project a Symbol.toStringTag value to cover it.

For reference you can see this and this.

Proxy traps to handle `Object` and `Reflect` APIs consistently.

Throwing errors is appropriate for Object methods like Object.defineProperty when run in strict mode code. However, Reflect.defineProperty should return false without throwing an error. The proxy traps need to be constructed in a way to handle this. To solve this in esm I did two things.

Since we own the secure realm though we can monkey-patch Reflect to avoid throwing and return booleans.

for in is subject to poisoning

we might not need to change them all, assuming that the outer realm is safe, only need to be protected when interacting with SecureObjects. another alternative is to not use it at all, and just assume that no one is safe.

Turn getGlobalThis() into a constant

I noticed this function will modify Object.prototype whenever it is called (if globalThis is not available). Can this be turned into a constant instead of a function so that it's done once?

ConsoleInfo and ConsoleError

We should pluck the console.info and console.error methods off as ConsoleInfo and ConsoleError. Previous versions of console needed them bound so we can bind them:

const bind = uncurry(Function.prototype.bind);
const ConsoleError = bind(console.error, console);
const ConsoleInfo = bind(console.info, console);

or if we only bind them there and don't need the helper anywhere else

const ConsoleError = console.error.bind(console);
const ConsoleInfo = console.info.bind(console);

[investigation] what other intrinsics should be remapped

Today, the following list is remapped:

[
    'Object',
    'Function',
    'URIError',
    'TypeError',
    'SyntaxError',
    'ReferenceError',
    'RangeError',
    'EvalError',
    'Error',
]

But there are a lot more pieces that can be remapped safety. Additionally we have issues with intrinsic accessors accessing internal slots that will not work with the remapping of the intrinsic prototypes, which might requires a lot more patching on the intrinsics in the sandbox before using the sandbox.

Sandbox bypass on firefox

Steps to reproduce:

$ git clone https://github.com/caridy/secure-javascript-environment
$ cd secure-javascript-environment
$ npm install
$ npm start

Go to http://localhost:8080/examples/invalid-fetch.html

Edit invalid-fetch.js to contain the following snippet in secureGlobalThis.eval()

location='javascript:alert(top.fetch)'; // FF only

What should happen?

No access to native fetch() since it is distorted

What happens instead?

Access to native fetch(), none of the code goes through the distortion map as location is not proxied.

Implement workaround for FF bug 543435: window.document instance replacement for blank pages

This is the link to the original bug in FF:
https://bugzilla.mozilla.org/show_bug.cgi?id=543435

Since this bug is not going to be fixed, we need a workaround for the cases when keepAlive is set to true. Which causes a problem in the membrane since the identity of the document changes at the macrotask, and it is not the original identity after creation that is mapped to the outer window document.

@jdalton came up with a quick solution to this problem, which is tested here:
https://jsbin.com/segokef/1/edit?html,js,console,output

Basically, after creation and insertion of the iframe, just use document.open().close() in the iframe, that forces FF to never replace the document because it might have been mutated, which means the identity of the document will remain the same forever.

doesn't respect frozen properties of the primary realm

In the primary realm:

document.bar = { a:1, b: 2 }
Object.freeze(document.bar)
Object.isFrozen(document.bar) // => true

Within the shadow realm:

document.bar.c = 3
document.bar // => { a:1, b:2, c:3 }
Object.isFrozen(document.bar) // => false

Unforgeable TrustedTypes could be a problem

When @jdalton was trying canary, he found some issues with TrustedTypes, specifically, the new global is unforgeable, forcing this library to add more offenders for the membrane.

Ref: https://w3c.github.io/webappsec-trusted-types/dist/spec/#trusted-types

Few questions arise:

  1. why making TrustedTypes unforgeable? Does it really solve any issue?
  2. if it remains unforgeable? how to deal with this via the membrane? do we need to replace its descriptors? or should we remap them?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.