ses 0.18.7 → 0.18.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -15,7 +15,7 @@ import {
15
15
  regexpPrototype,
16
16
  globalThis,
17
17
  } from './commons.js';
18
- import { InertCompartment } from './compartment-shim.js';
18
+ import { InertCompartment } from './compartment.js';
19
19
 
20
20
  /**
21
21
  * Object.getConstructorOf()
@@ -1,395 +1,35 @@
1
- // Copyright (C) 2018 Agoric
2
- //
3
- // Licensed under the Apache License, Version 2.0 (the "License");
4
- // you may not use this file except in compliance with the License.
5
- // You may obtain a copy of the License at
6
- //
7
- // http://www.apache.org/licenses/LICENSE-2.0
8
- //
9
- // Unless required by applicable law or agreed to in writing, software
10
- // distributed under the License is distributed on an "AS IS" BASIS,
11
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- // See the License for the specific language governing permissions and
13
- // limitations under the License.
14
-
15
1
  // @ts-check
16
2
 
17
- import { makeEnvironmentCaptor } from '@endo/env-options';
18
- import {
19
- FERAL_FUNCTION,
20
- FERAL_EVAL,
21
- TypeError,
22
- arrayFilter,
23
- globalThis,
24
- is,
25
- ownKeys,
26
- stringSplit,
27
- noEvalEvaluate,
28
- } from './commons.js';
29
- import { makeHardener } from './make-hardener.js';
30
- import { makeIntrinsicsCollector } from './intrinsics.js';
31
- import whitelistIntrinsics from './permits-intrinsics.js';
32
- import tameFunctionConstructors from './tame-function-constructors.js';
33
- import tameDateConstructor from './tame-date-constructor.js';
34
- import tameMathObject from './tame-math-object.js';
35
- import tameRegExpConstructor from './tame-regexp-constructor.js';
36
- import enablePropertyOverrides from './enable-property-overrides.js';
37
- import tameLocaleMethods from './tame-locale-methods.js';
38
- import {
39
- setGlobalObjectConstantProperties,
40
- setGlobalObjectMutableProperties,
41
- setGlobalObjectEvaluators,
42
- } from './global-object.js';
43
- import { makeSafeEvaluator } from './make-safe-evaluator.js';
44
- import { initialGlobalPropertyNames } from './permits.js';
45
- import { tameFunctionToString } from './tame-function-tostring.js';
46
- import { tameDomains } from './tame-domains.js';
47
-
48
- import { tameConsole } from './error/tame-console.js';
49
- import tameErrorConstructor from './error/tame-error-constructor.js';
50
- import { assert, makeAssert } from './error/assert.js';
51
- import { getAnonymousIntrinsics } from './get-anonymous-intrinsics.js';
52
- import { makeCompartmentConstructor } from './compartment-shim.js';
53
- import { tameHarden } from './tame-harden.js';
54
- import { tameSymbolConstructor } from './tame-symbol-constructor.js';
55
-
56
- /** @typedef {import('../types.js').LockdownOptions} LockdownOptions */
57
-
58
- const { Fail, details: d, quote: q } = assert;
59
-
60
- /** @type {Error=} */
61
- let priorLockdown;
62
-
63
- // Build a harden() with an empty fringe.
64
- // Gate it on lockdown.
65
- /**
66
- * @template T
67
- * @param {T} ref
68
- * @returns {T}
69
- */
70
- const safeHarden = makeHardener();
71
-
72
- /**
73
- * @callback Transform
74
- * @param {string} source
75
- * @returns {string}
76
- */
3
+ // We import this first to fail as fast as possible if the shim has been
4
+ // transformed or embedded in a way that causes it to run in sloppy mode.
5
+ // See https://github.com/endojs/endo/blob/master/packages/ses/error-codes/SES_NO_SLOPPY.md
6
+ import './assert-sloppy-mode.js';
7
+ import { globalThis } from './commons.js';
8
+ import { repairIntrinsics } from './lockdown.js';
77
9
 
78
10
  /**
79
- * @callback CompartmentConstructor
80
- * @param {object} endowments
81
- * @param {object} moduleMap
82
- * @param {object} [options]
83
- * @param {Array<Transform>} [options.transforms]
84
- * @param {Array<Transform>} [options.__shimTransforms__]
11
+ * @param {import('./lockdown.js').LockdownOptions} options
85
12
  */
86
-
87
- // TODO https://github.com/endojs/endo/issues/814
88
- // Lockdown currently allows multiple calls provided that the specified options
89
- // of every call agree. With experience, we have observed that lockdown should
90
- // only ever need to be called once and that simplifying lockdown will improve
91
- // the quality of audits.
92
-
93
- const assertDirectEvalAvailable = () => {
94
- let allowed = false;
95
- try {
96
- allowed = FERAL_FUNCTION(
97
- 'eval',
98
- 'SES_changed',
99
- `\
100
- eval("SES_changed = true");
101
- return SES_changed;
102
- `,
103
- )(FERAL_EVAL, false);
104
- // If we get here and SES_changed stayed false, that means the eval was sloppy
105
- // and indirect, which generally creates a new global.
106
- // We are going to throw an exception for failing to initialize SES, but
107
- // good neighbors clean up.
108
- if (!allowed) {
109
- delete globalThis.SES_changed;
110
- }
111
- } catch (_error) {
112
- // We reach here if eval is outright forbidden by a Content Security Policy.
113
- // We allow this for SES usage that delegates the responsibility to isolate
114
- // guest code to production code generation.
115
- allowed = true;
116
- }
117
- if (!allowed) {
118
- // See https://github.com/endojs/endo/blob/master/packages/ses/error-codes/SES_DIRECT_EVAL.md
119
- throw TypeError(
120
- `SES cannot initialize unless 'eval' is the original intrinsic 'eval', suitable for direct-eval (dynamically scoped eval) (SES_DIRECT_EVAL)`,
121
- );
122
- }
13
+ globalThis.lockdown = options => {
14
+ const hardenIntrinsics = repairIntrinsics(options);
15
+ globalThis.harden = hardenIntrinsics();
123
16
  };
124
17
 
125
18
  /**
126
- * @param {LockdownOptions} [options]
127
- * @returns {() => void} repairIntrinsics
19
+ * @param {import('./lockdown.js').LockdownOptions} options
128
20
  */
129
- export const repairIntrinsics = (options = {}) => {
130
- // First time, absent options default to 'safe'.
131
- // Subsequent times, absent options default to first options.
132
- // Thus, all present options must agree with first options.
133
- // Reconstructing `option` here also ensures that it is a well
134
- // behaved record, with only own data properties.
135
- //
136
- // The `overrideTaming` is not a safety issue. Rather it is a tradeoff
137
- // between code compatibility, which is better with the `'moderate'`
138
- // setting, and tool compatibility, which is better with the `'min'`
139
- // setting. See
140
- // https://github.com/Agoric/SES-shim/blob/master/packages/ses/README.md#enabling-override-by-assignment)
141
- // for an explanation of when to use which.
142
- //
143
- // The `stackFiltering` is not a safety issue. Rather it is a tradeoff
144
- // between relevance and completeness of the stack frames shown on the
145
- // console. Setting`stackFiltering` to `'verbose'` applies no filters, providing
146
- // the raw stack frames that can be quite versbose. Setting
147
- // `stackFrameFiltering` to`'concise'` limits the display to the stack frame
148
- // information most likely to be relevant, eliminating distracting frames
149
- // such as those from the infrastructure. However, the bug you're trying to
150
- // track down might be in the infrastrure, in which case the `'verbose'` setting
151
- // is useful. See
152
- // [`stackFiltering` options](https://github.com/Agoric/SES-shim/blob/master/packages/ses/lockdown-options.md#stackfiltering-options)
153
- // for an explanation.
154
-
155
- const { getEnvironmentOption: getenv } = makeEnvironmentCaptor(globalThis);
156
-
157
- const {
158
- errorTaming = getenv('LOCKDOWN_ERROR_TAMING', 'safe'),
159
- errorTrapping = getenv('LOCKDOWN_ERROR_TRAPPING', 'platform'),
160
- unhandledRejectionTrapping = getenv(
161
- 'LOCKDOWN_UNHANDLED_REJECTION_TRAPPING',
162
- 'report',
163
- ),
164
- regExpTaming = getenv('LOCKDOWN_REGEXP_TAMING', 'safe'),
165
- localeTaming = getenv('LOCKDOWN_LOCALE_TAMING', 'safe'),
166
- consoleTaming = getenv('LOCKDOWN_CONSOLE_TAMING', 'safe'),
167
- overrideTaming = getenv('LOCKDOWN_OVERRIDE_TAMING', 'moderate'),
168
- stackFiltering = getenv('LOCKDOWN_STACK_FILTERING', 'concise'),
169
- domainTaming = getenv('LOCKDOWN_DOMAIN_TAMING', 'safe'),
170
- evalTaming = getenv('LOCKDOWN_EVAL_TAMING', 'safeEval'),
171
- overrideDebug = arrayFilter(
172
- stringSplit(getenv('LOCKDOWN_OVERRIDE_DEBUG', ''), ','),
173
- /** @param {string} debugName */
174
- debugName => debugName !== '',
175
- ),
176
- __hardenTaming__ = getenv('LOCKDOWN_HARDEN_TAMING', 'safe'),
177
- dateTaming = 'safe', // deprecated
178
- mathTaming = 'safe', // deprecated
179
- ...extraOptions
180
- } = options;
181
-
182
- evalTaming === 'unsafeEval' ||
183
- evalTaming === 'safeEval' ||
184
- evalTaming === 'noEval' ||
185
- Fail`lockdown(): non supported option evalTaming: ${q(evalTaming)}`;
186
-
187
- // Assert that only supported options were passed.
188
- // Use Reflect.ownKeys to reject symbol-named properties as well.
189
- const extraOptionsNames = ownKeys(extraOptions);
190
- extraOptionsNames.length === 0 ||
191
- Fail`lockdown(): non supported option ${q(extraOptionsNames)}`;
192
-
193
- priorLockdown === undefined ||
194
- // eslint-disable-next-line @endo/no-polymorphic-call
195
- assert.fail(
196
- d`Already locked down at ${priorLockdown} (SES_ALREADY_LOCKED_DOWN)`,
197
- TypeError,
198
- );
199
- // See https://github.com/endojs/endo/blob/master/packages/ses/error-codes/SES_ALREADY_LOCKED_DOWN.md
200
- priorLockdown = TypeError('Prior lockdown (SES_ALREADY_LOCKED_DOWN)');
201
- // Tease V8 to generate the stack string and release the closures the stack
202
- // trace retained:
203
- priorLockdown.stack;
204
-
205
- assertDirectEvalAvailable();
206
-
207
- /**
208
- * Because of packagers and bundlers, etc, multiple invocations of lockdown
209
- * might happen in separate instantiations of the source of this module.
210
- * In that case, each one sees its own `firstOptions` variable, so the test
211
- * above will not detect that lockdown has already happened. We
212
- * unreliably test some telltale signs that lockdown has run, to avoid
213
- * trying to lock down a locked down environment. Although the test is
214
- * unreliable, this is consistent with the SES threat model. SES provides
215
- * security only if it runs first in a given realm, or if everything that
216
- * runs before it is SES-aware and cooperative. Neither SES nor anything
217
- * can protect itself from corrupting code that runs first. For these
218
- * purposes, code that turns a realm into something that passes these
219
- * tests without actually locking down counts as corrupting code.
220
- *
221
- * The specifics of what this tests for may change over time, but it
222
- * should be consistent with any setting of the lockdown options.
223
- */
224
- const seemsToBeLockedDown = () => {
225
- return (
226
- globalThis.Function.prototype.constructor !== globalThis.Function &&
227
- // @ts-ignore harden is absent on globalThis type def.
228
- typeof globalThis.harden === 'function' &&
229
- // @ts-ignore lockdown is absent on globalThis type def.
230
- typeof globalThis.lockdown === 'function' &&
231
- globalThis.Date.prototype.constructor !== globalThis.Date &&
232
- typeof globalThis.Date.now === 'function' &&
233
- // @ts-ignore does not recognize that Date constructor is a special
234
- // Function.
235
- // eslint-disable-next-line @endo/no-polymorphic-call
236
- is(globalThis.Date.prototype.constructor.now(), NaN)
237
- );
238
- };
239
-
240
- if (seemsToBeLockedDown()) {
241
- // See https://github.com/endojs/endo/blob/master/packages/ses/error-codes/SES_MULTIPLE_INSTANCES.md
242
- throw TypeError(
243
- `Already locked down but not by this SES instance (SES_MULTIPLE_INSTANCES)`,
244
- );
245
- }
246
-
247
- /**
248
- * 1. TAME powers & gather intrinsics first.
249
- */
250
-
251
- tameDomains(domainTaming);
252
-
253
- // Replace Function.prototype.toString with one that recognizes
254
- // shimmed functions as honorary native functions.
255
- const markVirtualizedNativeFunction = tameFunctionToString();
256
-
257
- const { addIntrinsics, completePrototypes, finalIntrinsics } =
258
- makeIntrinsicsCollector();
259
-
260
- const tamedHarden = tameHarden(safeHarden, __hardenTaming__);
261
- addIntrinsics({ harden: tamedHarden });
262
-
263
- addIntrinsics(tameFunctionConstructors());
264
-
265
- addIntrinsics(tameDateConstructor(dateTaming));
266
- addIntrinsics(tameErrorConstructor(errorTaming, stackFiltering));
267
- addIntrinsics(tameMathObject(mathTaming));
268
- addIntrinsics(tameRegExpConstructor(regExpTaming));
269
- addIntrinsics(tameSymbolConstructor());
270
-
271
- addIntrinsics(getAnonymousIntrinsics());
272
-
273
- completePrototypes();
274
-
275
- const intrinsics = finalIntrinsics();
276
-
277
- /**
278
- * Wrap console unless suppressed.
279
- * At the moment, the console is considered a host power in the start
280
- * compartment, and not a primordial. Hence it is absent from the whilelist
281
- * and bypasses the intrinsicsCollector.
282
- *
283
- * @type {((error: any) => string | undefined) | undefined}
284
- */
285
- let optGetStackString;
286
- if (errorTaming !== 'unsafe') {
287
- optGetStackString = intrinsics['%InitialGetStackString%'];
288
- }
289
- const consoleRecord = tameConsole(
290
- consoleTaming,
291
- errorTrapping,
292
- unhandledRejectionTrapping,
293
- optGetStackString,
294
- );
295
- globalThis.console = /** @type {Console} */ (consoleRecord.console);
296
-
297
- // @ts-ignore assert is absent on globalThis type def.
298
- if (errorTaming === 'unsafe' && globalThis.assert === assert) {
299
- // If errorTaming is 'unsafe' we replace the global assert with
300
- // one whose `details` template literal tag does not redact
301
- // unmarked substitution values. IOW, it blabs information that
302
- // was supposed to be secret from callers, as an aid to debugging
303
- // at a further cost in safety.
304
- // @ts-ignore assert is absent on globalThis type def.
305
- globalThis.assert = makeAssert(undefined, true);
306
- }
307
-
308
- // Replace *Locale* methods with their non-locale equivalents
309
- tameLocaleMethods(intrinsics, localeTaming);
310
-
311
- /**
312
- * 2. WHITELIST to standardize the environment.
313
- */
314
-
315
- // Remove non-standard properties.
316
- // All remaining function encountered during whitelisting are
317
- // branded as honorary native functions.
318
- whitelistIntrinsics(intrinsics, markVirtualizedNativeFunction);
319
-
320
- // Initialize the powerful initial global, i.e., the global of the
321
- // start compartment, from the intrinsics.
322
-
323
- setGlobalObjectConstantProperties(globalThis);
324
-
325
- setGlobalObjectMutableProperties(globalThis, {
326
- intrinsics,
327
- newGlobalPropertyNames: initialGlobalPropertyNames,
328
- makeCompartmentConstructor,
329
- markVirtualizedNativeFunction,
330
- });
331
-
332
- if (evalTaming === 'noEval') {
333
- setGlobalObjectEvaluators(
334
- globalThis,
335
- noEvalEvaluate,
336
- markVirtualizedNativeFunction,
337
- );
338
- } else if (evalTaming === 'safeEval') {
339
- const { safeEvaluate } = makeSafeEvaluator({ globalObject: globalThis });
340
- setGlobalObjectEvaluators(
341
- globalThis,
342
- safeEvaluate,
343
- markVirtualizedNativeFunction,
344
- );
345
- } else if (evalTaming === 'unsafeEval') {
346
- // Leave eval function and Function constructor of the initial compartment in-tact.
347
- // Other compartments will not have access to these evaluators unless a guest program
348
- // escapes containment.
349
- }
350
-
351
- /**
352
- * 3. HARDEN to share the intrinsics.
353
- *
354
- * We define hardenIntrinsics here so that options are in scope, but return
355
- * it to the caller because we intend to eventually allow vetted shims to run
356
- * between repairs and the hardening of intrinsics and so we can benchmark
357
- * repair separately from hardening.
358
- */
359
-
360
- function hardenIntrinsics() {
361
- // Circumvent the override mistake.
362
- // TODO consider moving this to the end of the repair phase, and
363
- // therefore before vetted shims rather than afterwards. It is not
364
- // clear yet which is better.
365
- // @ts-ignore enablePropertyOverrides does its own input validation
366
- enablePropertyOverrides(intrinsics, overrideTaming, overrideDebug);
367
-
368
- // Finally register and optionally freeze all the intrinsics. This
369
- // must be the operation that modifies the intrinsics.
370
- tamedHarden(intrinsics);
371
-
372
- // Reveal harden after lockdown.
373
- // Harden is dangerous before lockdown because hardening just
21
+ globalThis.repairIntrinsics = options => {
22
+ const hardenIntrinsics = repairIntrinsics(options);
23
+ // Reveal hardenIntrinsics after repairs.
24
+ globalThis.hardenIntrinsics = () => {
25
+ // Reveal harden after hardenIntrinsics.
26
+ // Harden is dangerous before hardenIntrinsics because hardening just
374
27
  // about anything will inadvertently render intrinsics irreparable.
375
28
  // Also, for modules that must work both before or after lockdown (code
376
29
  // that is portable between JS and SES), the existence of harden in global
377
30
  // scope signals whether such code should attempt to use harden in the
378
31
  // defense of its own API.
379
32
  // @ts-ignore harden not yet recognized on globalThis.
380
- globalThis.harden = tamedHarden;
381
-
382
- // Returning `true` indicates that this is a JS to SES transition.
383
- return true;
384
- }
385
-
386
- return hardenIntrinsics;
387
- };
388
-
389
- /**
390
- * @param {LockdownOptions} [options]
391
- */
392
- export const lockdown = (options = {}) => {
393
- const hardenIntrinsics = repairIntrinsics(options);
394
- hardenIntrinsics();
33
+ globalThis.harden = hardenIntrinsics();
34
+ };
395
35
  };