-
Notifications
You must be signed in to change notification settings - Fork 1
/
startSES.js
2145 lines (2010 loc) · 84.3 KB
/
startSES.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (C) 2011 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Make this frame SES-safe or die trying.
*
* <p>Assumes ES5 plus a WeakMap that conforms to the anticipated ES6
* WeakMap spec. Compatible with ES5-strict or anticipated ES6.
*
* //requires ses.es5ProblemReports, ses.logger
* //requires ses.severities, ses.updateMaxSeverity
* //requires ses.is
* //requires ses.makeCallerHarmless, ses.makeArgumentsHarmless
* //requires ses.inBrowser
* //requires ses.noFuncPoison
* //requires ses.verifyStrictFunctionBody, ses.makeDelayedTamperProof
* //requires ses.getUndeniables, ses.earlyUndeniables
* //requires ses.getAnonIntrinsics
* //requires ses.kludge_test_FREEZING_BREAKS_PROTOTYPES
* //optionally requires ses.mitigateSrcGotchas
* //provides ses.startSES ses.resolveOptions, ses.securableWrapperSrc
* //provides ses.makeCompiledExpr ses.prepareExpr
* //provides ses._primordialsHaveBeenFrozen
*
* @author Mark S. Miller,
* @author Jasvir Nagra
* @requires WeakMap
* @overrides ses, console, eval, Function, cajaVM
*/
var ses;
/**
* The global {@code eval} function available to script code, which
* may or not be made safe.
*
* <p>The original global binding of {@code eval} is not
* SES-safe. {@code cajaVM.eval} is a safe wrapper around this
* original eval, enforcing SES language restrictions.
*
* <p>If {@code TAME_GLOBAL_EVAL} is true, both the global {@code
* eval} variable and {@code sharedImports.eval} are set to the safe
* wrapper. If {@code TAME_GLOBAL_EVAL} is false, in order to work
* around a bug in the Chrome debugger, then the global {@code eval}
* is unaltered and no {@code "eval"} property is available on {@code
* sharedImports}. In either case, SES-evaled-code and SES-script-code
* can both access the safe eval wrapper as {@code cajaVM.eval}.
*
* <p>By making the safe eval available on {@code sharedImports} only
* when we also make it be the genuine global eval, we preserve the
* property that SES-evaled-code differs from SES-script-code only by
* having a subset of the same variables in globalish scope. This is a
* nice-to-have that makes explanation easier rather than a hard
* requirement. With this property, any SES-evaled-code that does not
* fail to access a global variable (or to test whether it could)
* should operate the same way when run as SES-script-code.
*
* <p>See doc-comment on cajaVM for the restriction on this API needed
* to operate under Caja translation on old browsers.
*/
var eval;
/**
* The global {@code Function} constructor is always replaced with a
* safe wrapper, which is also made available as
* {@code sharedImports.Function}.
*
* <p>Both the original Function constructor and this safe wrapper
* point at the original {@code Function.prototype}, so {@code
* instanceof} works fine with the wrapper. {@code
* Function.prototype.constructor} is set to point at the safe
* wrapper, so that only it, and not the unsafe original, is
* accessible.
*
* <p>See doc-comment on cajaVM for the restriction on this API needed
* to operate under Caja translation on old browsers.
*/
var Function;
/**
* A new global exported by SES, intended to become a mostly
* compatible API between server-side Caja translation for older
* browsers and client-side SES verification for newer browsers.
*
* <p>Under server-side Caja translation for old pre-ES5 browsers, the
* synchronous interface of the evaluation APIs (currently {@code
* eval, Function, cajaVM.{compileExpr, confine, compileModule, eval,
* Function}}) cannot reasonably be provided. Instead, under
* translation we expect
* <ul>
* <li>Not to have a binding for {@code "eval"} on
* {@code sharedImports}, just as we would not if
* {@code TAME_GLOBAL_EVAL} is false.
* <li>The global {@code eval} seen by scripts is either unaltered (to
* work around the Chrome debugger bug if {@code TAME_GLOBAL_EVAL}
* is false), or is replaced by a function that throws an
* appropriate EvalError diagnostic (if {@code TAME_GLOBAL_EVAL}
* is true).
* <li>The global {@code Function} constructor, both as seen by script
* code and evaled code, to throw an appropriate diagnostic.
* <li>The {@code Q} API to always be available, to handle
* asynchronous, promise, and remote requests.
* <li>The evaluating methods on {@code cajaVM} -- currently {@code
* compileExpr, confine, compileModule, eval, and Function} -- to
* be remote promises for their normal interfaces, which therefore
* must be invoked with {@code Q.post}.
* <li>Since {@code Q.post} can be used for asynchronously invoking
* non-promises, invocations like
* {@code Q.post(cajaVM, 'eval', ['2+3'])}, for example,
* will return a promise for a 5. This should work both under Caja
* translation and (TODO(erights)) under SES verification when
* {@code Q} is also installed, and so is the only portable
* evaluating API that SES code should use during this transition
* period.
* <li>TODO(erights): {@code Q.post(cajaVM, 'compileModule',
* [moduleSrc]} should eventually pre-load the transitive
* synchronous dependencies of moduleSrc before resolving the
* promise for its result. It currently would not, instead
* requiring its client to do so manually.
* </ul>
*/
var cajaVM;
/**
* <p>{@code ses.startSES} should be called before any other potentially
* dangerous script is executed in this frame.
*
* <p>If {@code ses.startSES} succeeds, the evaluation operations on
* {@code cajaVM}, the global {@code Function} contructor, and perhaps
* the {@code eval} function (see doc-comment on {@code eval} and
* {@code cajaVM}) will only load code according to the <i>loader
* isolation</i> rules of the object-capability model, suitable for
* loading untrusted code. If all other (trusted) code executed
* directly in this frame (i.e., other than through these safe
* evaluation operations) takes care to uphold object-capability
* rules, then untrusted code loaded via these safe evaluation
* operations will be constrained by those rules. TODO(erights):
* explain concretely what the trusted code must do or avoid doing to
* uphold object-capability rules.
*
* <p>On a pre-ES5 platform, this script will fail cleanly, leaving
* the frame intact. Otherwise, if this script fails, it may leave
* this frame in an unusable state. All following description assumes
* this script succeeds and that the browser conforms to the ES5
* spec. The ES5 spec allows browsers to implement more than is
* specified as long as certain invariants are maintained. We further
* assume that these extensions are not maliciously designed to obey
* the letter of these invariants while subverting the intent of the
* spec. In other words, even on an ES5 conformant browser, we do not
* presume to defend ourselves from a browser that is out to get us.
*
* @param global ::Record(any) Assumed to be the real global object
* for some frame. Since {@code ses.startSES} will allow global
* variable references that appear at the top level of the
* whitelist, our safety depends on these variables being
* frozen as a side effect of freezing the corresponding
* properties of {@code global}. These properties are also
* duplicated onto the virtual global objects which are
* provided as the {@code this} binding for the safe
* evaluation calls -- emulating the safe subset of the normal
* global object.
* TODO(erights): Currently, the code has only been tested when
* {@code global} is the global object of <i>this</i>
* frame. The code should be made to work for cross-frame use.
* @param whitelist ::Record(Permit) where
* Permit = true | false | "*" | "maybeAccessor" | Record(Permit).
* Describes the subset of naming paths starting from {@code
* sharedImports} that should be accessible. The <i>accessible
* primordials</i> are all values found by navigating these
* paths starting from {@code sharedImports}. All
* non-whitelisted properties of accessible primordials are
* deleted, and then {@code sharedImports} and all accessible
* primordials are frozen with the whitelisted properties
* frozen as data properties. TODO(erights): fix the code and
* documentation to also support confined-ES5, suitable for
* confining potentially offensive code but not supporting
* defensive code, where we skip this last freezing step. With
* confined-ES5, each frame is considered a separate protection
* domain rather that each individual object.
* @param limitSrcCharset ::F([string])
* Given the sourceText for a strict Program, return a record with an
* 'error' field if it is not in the limited character set that SES
* should process; otherwise, return a record with a 'programSrc' field
* containing the original program text with Unicode escapes.
* @param atLeastFreeVarNames ::F([string], Record(true))
* Given the sourceText for a strict Program,
* atLeastFreeVarNames(sourceText) returns a Record whose
* enumerable own property names must include the names of all the
* free variables occuring in sourceText. It can include as
* many other strings as is convenient so long as it includes
* these. The value of each of these properties should be
* {@code true}. TODO(erights): On platforms with Proxies
* (currently only Firefox 4 and after), use {@code
* with(aProxy) {...}} to intercept free variables rather than
* atLeastFreeVarNames.
* @param extensions ::F([], Record(any)]) A function returning a
* record whose own properties will be copied onto cajaVM. This
* is used for the optional components which bring SES to
* feature parity with the ES5/3 runtime at the price of larger
* code size. At the time that {@code startSES} calls {@code
* extensions}, {@code cajaVM} exists but should not yet be
* used. In particular, {@code extensions} should not call
* {@code cajaVM.def} during this setup, because def would then
* freeze priordials before startSES cleans them (removes
* non-whitelisted properties). The methods that
* {@code extensions} contributes can, of course, use
* {@code cajaVM}, since those methods will only be called once
* {@code startSES} finishes.
*/
ses.startSES = function(global,
whitelist,
limitSrcCharset,
atLeastFreeVarNames,
extensions) {
"use strict";
/////////////// KLUDGE SWITCHES ///////////////
/////////////////////////////////
// The following are only the minimal kludges needed for the current
// Firefox or the current Chrome Beta. At the time of
// this writing, these are Firefox 4.0 and Chrome 12.0.742.5 dev
// As these move forward, kludges can be removed until we simply
// rely on ES5.
/**
* <p>TODO(erights): isolate and report this.
*
* <p>Workaround for Chrome debugger's own use of 'eval'
*
* <p>This kludge is safety preserving but not semantics
* preserving. When {@code TAME_GLOBAL_EVAL} is false, no {@code
* sharedImports.eval} is available, and the 'eval' available as a
* global to trusted (script) code is the original 'eval', and so is
* not safe.
*/
//var TAME_GLOBAL_EVAL = true;
var TAME_GLOBAL_EVAL = false;
/**
* If this is true, then we redefine these to work around a
* stratification bug in the Chrome debugger. To allow this, we have
* also whitelisted these four properties in whitelist.js
*/
//var EMULATE_LEGACY_GETTERS_SETTERS = false;
var EMULATE_LEGACY_GETTERS_SETTERS = true;
/**
* freezeGlobalProp below defines several possible platform
* behaviors regarding what is needed to freeze a property on the
* global object. If TRY_GLOBAL_SIMPLE_FREEZE_FIRST, we first try a
* strategy we call <i>simple freezing</i> first, which works on
* platforms implementing the <i>legacy behavior</i> or <i>simple
* behavior</i>, before proceeding to the strategy that should work
* on any expected platform behavior. If
* TRY_GLOBAL_SIMPLE_FREEZE_FIRST is false, then we only follow the
* strategy that should work on any expected platform behavior. As
* of August 5, 2015, with TRY_GLOBAL_SIMPLE_FREEZE_FIRST false, v8
* (Chrome and Opera) fails by crashing the page, and JSC (Safari)
* fails in undiagnosed ways, both for undiagnosed reasons.
*
* <p>TODO(erights): Diagnose how v8 and JSC fail when
* TRY_GLOBAL_SIMPLE_FREEZE_FIRST is false, and report these
* problems.
*/
//var TRY_GLOBAL_SIMPLE_FREEZE_FIRST = false;
var TRY_GLOBAL_SIMPLE_FREEZE_FIRST = true;
//////////////// END KLUDGE SWITCHES ///////////
// Problems we can work around but repairES5 cannot repair.
var NONCONFIGURABLE_OWN_PROTO =
ses.es5ProblemReports.NONCONFIGURABLE_OWN_PROTO.afterFailure;
var INCREMENT_IGNORES_FROZEN =
ses.es5ProblemReports.INCREMENT_IGNORES_FROZEN.afterFailure;
var dirty = true;
var hop = Object.prototype.hasOwnProperty;
var getProto = Object.getPrototypeOf;
var defProp = Object.defineProperty;
var gopd = Object.getOwnPropertyDescriptor;
var gopn = Object.getOwnPropertyNames;
var keys = Object.keys;
var freeze = Object.freeze;
var create = Object.create;
/**
* repairES5 repair_FREEZING_BREAKS_PROTOTYPES causes Object.create(null) to
* be impossible. This falls back to a regular object. Each use of it
* should be accompanied by an explanation of why it is sufficiently
* safe.
*/
function createNullIfPossible() {
try {
return create(null);
} catch (e) {
return {};
}
}
/**
* {@code opt_mitigateOpts} is an alleged record of which gotchas to
* mitigate. Passing no {@code opt_mitigateOpts} performs all the
* default mitigations. Returns a well behaved options record.
*
* <p>See {@code prepareExpr} for documentation of the mitigation
* options and their effects.
*/
function resolveOptions(opt_mitigateOpts) {
if (opt_mitigateOpts === void 0 || opt_mitigateOpts === null) {
opt_mitigateOpts = {};
}
function resolve(opt, defaultOption) {
return opt in opt_mitigateOpts ? opt_mitigateOpts[opt] : defaultOption;
}
var options = {};
options.maskReferenceError = resolve('maskReferenceError', true);
options.parseFunctionBody = resolve('parseFunctionBody', false);
options.sourceUrl = resolve('sourceUrl', void 0);
options.rewriteTopLevelVars = resolve('rewriteTopLevelVars', true);
options.rewriteTopLevelFuncs = resolve('rewriteTopLevelFuncs', true);
options.rewriteFunctionCalls = resolve('rewriteFunctionCalls', true);
options.rewriteTypeOf = resolve('rewriteTypeOf',
!options.maskReferenceError);
options.forceParseAndRender = resolve('forceParseAndRender', false);
return options;
}
ses.resolveOptions = resolveOptions;
/**
* The function ses.mitigateSrcGotchas, if defined, is a function
* which, given the sourceText for a strict Program, returns a
* rewritten program with the same semantics as the original but
* with some of the ES5 gotchas mitigated -- those that can be
* mitigated by source analysis or source-to-source rewriting. The
* {@code options} are assumed to already be canonicalized by {@code
* resolveOptions} and says which mitigations to apply.
*/
function mitigateIfPossible(funcBodySrc, options) {
var safeError;
if ('function' === typeof ses.mitigateSrcGotchas) {
if (INCREMENT_IGNORES_FROZEN) {
options.rewritePropertyUpdateExpr = true;
options.rewritePropertyCompoundAssignmentExpr = true;
}
try {
return ses.mitigateSrcGotchas(funcBodySrc, options, ses.logger);
} catch (error) {
// Shouldn't throw, but if it does, the exception is potentially from a
// different context with an undefended prototype chain; don't allow it
// to leak out.
try {
safeError = new Error(error.message);
} catch (metaerror) {
throw new Error(
'Could not safely obtain error from mitigateSrcGotchas');
}
throw safeError;
}
} else {
return '' + funcBodySrc;
}
}
/**
* Use to tamper proof a function which is not intended to ever be
* used as a constructor, since it nulls out the function's
* prototype first.
*/
function constFunc(func) {
func.prototype = null;
return freeze(func);
}
function fail(str) {
debugger;
throw new EvalError(str);
}
if (typeof WeakMap === 'undefined') {
fail('No built-in WeakMaps, so WeakMap.js must be loaded first');
}
if (EMULATE_LEGACY_GETTERS_SETTERS) {
(function(){
function legacyDefineGetter(sprop, getter) {
sprop = '' + sprop;
if (hop.call(this, sprop)) {
defProp(this, sprop, { get: getter });
} else {
defProp(this, sprop, {
get: getter,
set: undefined,
enumerable: true,
configurable: true
});
}
}
legacyDefineGetter.prototype = null;
defProp(Object.prototype, '__defineGetter__', {
value: legacyDefineGetter,
writable: false,
enumerable: false,
configurable: false
});
function legacyDefineSetter(sprop, setter) {
sprop = '' + sprop;
if (hop.call(this, sprop)) {
defProp(this, sprop, { set: setter });
} else {
defProp(this, sprop, {
get: undefined,
set: setter,
enumerable: true,
configurable: true
});
}
}
legacyDefineSetter.prototype = null;
defProp(Object.prototype, '__defineSetter__', {
value: legacyDefineSetter,
writable: false,
enumerable: false,
configurable: false
});
function legacyLookupGetter(sprop) {
sprop = '' + sprop;
var base = this, desc = void 0;
while (base && !(desc = gopd(base, sprop))) { base = getProto(base); }
return desc && desc.get;
}
legacyLookupGetter.prototype = null;
defProp(Object.prototype, '__lookupGetter__', {
value: legacyLookupGetter,
writable: false,
enumerable: false,
configurable: false
});
function legacyLookupSetter(sprop) {
sprop = '' + sprop;
var base = this, desc = void 0;
while (base && !(desc = gopd(base, sprop))) { base = getProto(base); }
return desc && desc.set;
}
legacyLookupSetter.prototype = null;
defProp(Object.prototype, '__lookupSetter__', {
value: legacyLookupSetter,
writable: false,
enumerable: false,
configurable: false
});
})();
} else {
delete Object.prototype.__defineGetter__;
delete Object.prototype.__defineSetter__;
delete Object.prototype.__lookupGetter__;
delete Object.prototype.__lookupSetter__;
}
/**
* By this time, WeakMap has already monkey patched Object.freeze if
* necessary, so we can do the tamperProofing delayed from
* repairES5.js
*/
var tamperProof = ses.makeDelayedTamperProof();
/**
* Code being eval'ed by {@code cajaVM.eval} sees {@code
* sharedImports} as its top-level {@code this}, as if {@code
* sharedImports} were the global object.
*
* <p>{@code sharedImports}'s properties are exactly the whitelisted
* global variable references. These properties, both as they appear
* on the global object and on this {@code sharedImports} object,
* are frozen and so cannot diverge. This preserves the illusion.
*
* <p>For code being evaluated by {@code cajaVM.compileExpr} and its
* ilk, the {@code imports} provided to the compiled function is bound
* to the top-level {@code this} of the evaluated code. For sanity,
* this {@code imports} should first be initialized with a copy of the
* properties of {@code sharedImports}, but nothing enforces this.
*/
var sharedImports = createNullIfPossible();
// createNullIfPossible safety: If not possible, the imports will include
// Object.prototype's properties. This has no effect on Caja use, because
// we make the global object be the Window which inherits Object.prototype,
// and is not a security risk since the properties are ambiently available.
var MAX_NAT = Math.pow(2, 53) - 1;
/**
* Is allegenNum a number in the contiguous range of exactly and
* unambiguously representable natural numbers (non-negative integers)?
*
* <p>See <a href=
* "https://code.google.com/p/google-caja/issues/detail?id=1801"
* >Issue 1801: Nat must include at most (2**53)-1</a>
* and <a href=
* "https://mail.mozilla.org/pipermail/es-discuss/2013-July/031716.html"
* >Allen Wirfs-Brock's suggested phrasing</a> on es-discuss.
*/
function Nat(allegedNum) {
if (typeof allegedNum !== 'number') {
throw new RangeError('not a number');
}
if (allegedNum !== allegedNum) { throw new RangeError('NaN not natural'); }
if (allegedNum < 0) { throw new RangeError('negative'); }
if (allegedNum % 1 !== 0) { throw new RangeError('not integral'); }
if (allegedNum > MAX_NAT) { throw new RangeError('too big'); }
return allegedNum;
}
(function startSESPrelude() {
/**
* The unsafe* variables hold precious values that must not escape
* to untrusted code. When {@code eval} is invoked via {@code
* unsafeEval}, this is a call to the indirect eval function, not
* the direct eval operator.
*/
var unsafeEval = eval;
var UnsafeFunction = Function;
/**
* Fails if {@code exprSource} does not parse as a strict
* Expression production.
*
* <p>To verify that exprSrc parses as a strict Expression, we
* verify that, when surrounded by parens and followed by ";", it
* parses as a strict FunctionBody, and that when surrounded with
* double parens it still parses as a strict FunctionBody. We
* place a newline before the terminal token so that a "//"
* comment cannot suppress the close paren or parens.
*
* <p>We never check without parens because not all
* expressions, for example "function(){}", form valid expression
* statements. We check both single and double parens so there's
* no exprSrc text which can close the left paren(s), do
* something, and then provide open paren(s) to balance the final
* close paren(s). No one such attack will survive both tests.
*
* <p>Note that all verify*(allegedString) functions now always
* start by coercing the alleged string to a guaranteed primitive
* string, do their verification checks on that, and if it passes,
* returns that. Otherwise they throw. If you don't know whether
* something is a string before verifying, use only the output of
* the verifier, not the input. Or coerce it early yourself.
*/
function verifyStrictExpression(exprSrc) {
exprSrc = ''+exprSrc;
ses.verifyStrictFunctionBody('( ' + exprSrc + '\n);');
ses.verifyStrictFunctionBody('(( ' + exprSrc + '\n));');
return exprSrc;
}
/**
* Make a virtual global object whose initial own properties are
* a copy of the own properties of {@code sharedImports}.
*
* <p>Further uses of {@code copyToImports} to copy properties
* onto this imports object will overwrite, effectively shadowing
* the {@code sharedImports}. You should shadow by overwriting
* rather than inheritance so that shadowing makes the original
* binding inaccessible.
*
* <p>The returned imports object is extensible and all its
* properties are configurable and non-enumerable. Once fully
* initialized, the caller can of course freeze the imports
* objects if desired. A reason not to do so it to emulate
* traditional JavaScript intermodule linkage by side effects to a
* shared (virtual) global object.
*
* <p>See {@code copyToImports} for the precise semantics of the
* property copying.
*/
function makeImports() {
var imports = createNullIfPossible();
// createNullIfPossible safety: similar to comments about sharedImports.
copyToImports(imports, sharedImports);
return imports;
}
/**
* For all the own properties of {@code from}, copy their
* descriptors to {@code imports}, except that each property
* added to {@code imports} is unconditionally configurable
* and non-enumerable.
*
* <p>By copying descriptors rather than values, any accessor
* properties of {@code env} become accessors of {@code imports}
* with the same getter and setter. If these do not use their
* {@code this} value, then the original and any copied properties
* are effectively joined. If the getter/setter do use their
* {@code this}, when accessed with {@code imports} as the base,
* their {@code this} will be bound to the {@code imports} rather
* than {@code from}. If {@code from} contains writable value
* properties, this will copy the current value of the property,
* after which they may diverge.
*
* <p>We make these configurable so that {@code imports} can
* be further configured before being frozen. We make these
* non-enumerable in order to emulate the normal behavior of
* built-in properties of typical global objects, such as the
* browser's {@code window} object.
*/
function copyToImports(imports, from) {
gopn(from).forEach(function(name) {
var desc = gopd(from, name);
desc.enumerable = false;
desc.configurable = true;
defProp(imports, name, desc);
});
return imports;
}
/**
* Make a frozen scope object which reflects all access onto
* {@code imports}, for use by {@code with} to prevent
* access to any {@code freeNames} other than those found on the.
* {@code imports}.
*/
function makeScopeObject(imports, freeNames, options) {
var scopeObject = createNullIfPossible();
// createNullIfPossible safety: The inherited properties should
// always be shadowed by defined properties if they are relevant
// (that is, if they occur in freeNames).
// Note: Although this loop is a bottleneck on some platforms,
// it does not help to turn it into a for(;;) loop, since we
// still need an enclosing function per accessor property
// created, to capture its own unique binding of
// "name". (Embarrasing fact: despite having often written about
// this very danger, I engaged in this mistake in a misbegotten
// optimization attempt here.)
freeNames.forEach(function interceptName(name) {
var desc = gopd(imports, name);
if (!desc || desc.writable !== false || desc.configurable) {
// If there is no own property, or it isn't a non-writable
// value property, or it is configurable. Note that this
// case includes accessor properties. The reason we wrap
// rather than copying over getters and setters is so the
// this-binding of the original getters and setters will be
// the imports rather than the scopeObject.
desc = {
get: function scopedGet() {
if (name in imports) {
// Note that, if this GET is on behalf of an
// unmitigated function call expression, this function
// will be called with a this-binding of the scope
// object rather than undefined.
return imports[name];
}
if (options.maskReferenceError) {
// if it were possible to know that the getter call
// was on behalf of a typeof expression, we'd return
// {@code void 0} here only for that
// case. Unfortunately, without parsing or proxies,
// that isn't possible. To fix this more accurately by
// parsing and rewriting instead, when available, set
// maskReferenceError to false and rewriteTypeOf to
// true.
return void 0;
}
throw new ReferenceError('"' + name +
'" is not defined in this scope.');
},
set: function scopedSet(newValue) {
if (name in imports) {
imports[name] = newValue;
return;
}
throw new TypeError('Cannot set "' + name + '"');
},
enumerable: false
};
}
desc.enumerable = false;
var existing = gopd(scopeObject, name);
if (existing) {
if (name === '__proto__') {
if (NONCONFIGURABLE_OWN_PROTO) {
return;
} else {
// we should be able to override it
}
} else {
throw new Error('New symptom: ' + name + ' in null-proto object');
}
}
defProp(scopeObject, name, desc);
});
return freeze(scopeObject);
}
/**
* Given SES source text that must not be run directly using any
* of the built-in unsafe evaluators on this platform, we instead
* surround it with a prelude and postlude.
*
* <p>Evaluating the resulting expression return a function that
* <i>can</i> be called to execute the original expression safely,
* in a controlled scope. See "makeCompiledExpr" for precisely the
* pattern that must be followed to call the resulting function
* safely.
*
* Notice that the source text placed around {@code exprSrc}
* <ul>
* <li>brings no variable names into scope, avoiding any
* non-hygienic name capture issues (except as necessary to
* work around the NONCONFIGURABLE_OWN_PROTO bug), and
* <li>does not introduce any newlines preceding exprSrc, so
* that all line numbers which a debugger might report are
* accurate wrt the original source text, and except for the
* first line, all the column numbers are accurate too.
* </ul>
*/
function securableWrapperSrc(exprSrc) {
exprSrc = verifyStrictExpression(exprSrc);
return '(function() { ' +
// non-strict code, where this === scopeObject
'with (this) { ' +
'return function() { ' +
'"use strict"; ' +
// workaround for Chrome bug where makeScopeObject cannot
// intercept __proto__ -- make sure it doesn't also leak global
// access
(NONCONFIGURABLE_OWN_PROTO ? 'var __proto__; ' : '') +
'return (' +
// strict code, where this === imports
'' + exprSrc + '\n' +
'); ' +
'}; ' +
'} ' +
'})\n';
}
ses.securableWrapperSrc = securableWrapperSrc;
/**
* See <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-7.3"
* >ECMAScript 5 Line Terminators</a>
*/
var hasLineTerminator = /[\u000A\u000D\u2028\u2029]/;
function verifyOnOneLine(text) {
text = ''+text;
if (hasLineTerminator.test(text)) {
throw new TypeError("Unexpected line terminator: " + text);
}
return text;
}
/**
* Given a wrapper function, such as the result of evaluating the
* source that securableWrapperSrc returns, and a list of all the
* names that we want to intercept to redirect to the imports,
* return a corresponding <i>compiled expr</i> function.
*
* <p>A compiled expr function, when called on an imports
* object, evaluates the original expression in a context where
* all its free variable references that appear in freeNames are
* redirected to the corresponding property of imports.
*/
function makeCompiledExpr(wrapper, freeNames, options) {
if (dirty) { fail('Initial cleaning failed'); }
function compiledCode(imports) {
var scopeObject = makeScopeObject(imports, freeNames, options);
return wrapper.call(scopeObject).call(imports);
};
compiledCode.prototype = null;
return compiledCode;
}
ses.makeCompiledExpr = makeCompiledExpr;
// Maintain the list of mitigation options documented below in
// coordination with the list of mitigation options in
// html-emitter.js's evaluateUntrustedExternalScript.
// See https://code.google.com/p/google-caja/issues/detail?id=1893
/**
* Compiles {@code exprSrc} as a strict expression into a function
* of an {@code imports}, that when called evaluates {@code
* exprSrc} in a virtual global environment whose {@code this} is
* bound to that {@code imports}, and whose free variables refer
* only to the properties of that {@code imports}.
*
* <p>The optional {@code opt_mitigateOpts} can be used to control
* which transformations are applied to src, if they are
* available. If {@code opt_mitigateOpts} is {@code undefined ||
* null} then all default transformations are applied. Otherwise
* the following option keys can be used.
* <ul>
* <li>maskReferenceError: Getting a free variable name that is
* absent on the imports object will throw a ReferenceError,
* even if gotten by an unmitigated {@code typeof}. With this
* set to true (the default), getting an absent variable will
* result in {@code undefined} which fixes the behavior of
* unmitigated {@code typeof} but masks normal ReferenceError
* cases. This is a less correct but faster alternative to
* rewriteTypeOf that also works when source mitigations are
* not available.
* <li>parseFunctionBody: check the src is syntactically
* valid as a function body.
* <li>rewriteTopLevelVars: transform vars to properties of global
* object. Defaults to true.
* <li>rewriteTopLevelFuncs: transform funcs to properties of
* global object. Defaults to true.
* <li>rewriteFunctionCalls: transform function calls, e.g.,
* {@code f()}, into calls ensuring that the function gets
* called with a this-binding of {@code undefined}, e.g.,
* {@code (1,f)()}. Defaults to true. <a href=
* "https://code.google.com/p/google-caja/issues/detail?id=1755"
* >Currently unimplemented</a>.
* <li>rewriteTypeOf: rewrite program to support typeof
* barevar. rewriteTypeOf is only needed if maskReferenceError
* is false. If omitted, it defaults to the opposite of
* maskReferenceError.
* </ul>
*
* <p>When SES is provided primitively, it should provide an
* analogous {@code compileProgram} function that accepts a
* Program and return a function that evaluates it to the
* Program's completion value. Unfortunately, this is not
* practical as a library without some non-standard support from
* the platform such as a parser API that provides an AST.
* TODO(jasvir): Now that we're parsing, we can provide compileProgram.
*
* <p>Thanks to Mike Samuel and Ankur Taly for this trick of using
* {@code with} together with RegExp matching to intercept free
* variable access without parsing.
*/
function prepareExpr(exprSrc, opt_mitigateOpts) {
// Force exprSrc to be a string that can only parse (if at all) as
// an expression.
exprSrc = '(' + exprSrc + '\n)';
var options = resolveOptions(opt_mitigateOpts);
exprSrc = mitigateIfPossible(exprSrc, options);
// This is a workaround for a bug in the escodegen renderer that
// renders expressions as expression statements
if (exprSrc[exprSrc.length - 1] === ';') {
exprSrc = exprSrc.substr(0, exprSrc.length - 1);
}
var wrapperSrc = securableWrapperSrc(exprSrc);
var freeNames = atLeastFreeVarNames(exprSrc);
var suffixSrc;
var sourceUrl = options.sourceUrl;
if (sourceUrl) {
sourceUrl = verifyOnOneLine(sourceUrl);
// Placing the sourceURL inside a line comment at the end of
// the evaled string, in this format, has emerged as a de
// facto convention for associating the source info with this
// evaluation. See
// http://updates.html5rocks.com/2013/06/sourceMappingURL-and-sourceURL-syntax-changed
// http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl
// https://developers.google.com/chrome-developer-tools/docs/javascript-debugging#breakpoints-dynamic-javascript
// TODO(erights): Should validate that the sourceURL is a
// valid URL of a whitelisted protocol, where that whitelist
// does not include "javascript:". Not doing so at this time
// does not itself introduce a security vulnerability, as long
// as the sourceURL is all on one line, since the text only
// appears in a JavaScript line comment. Separate hazards may
// appear when the alleged URL reappears in a stack trace, but
// it is the responsibility of that code to handle those URLs
// safely.
suffixSrc = '\n//# sourceURL=' + sourceUrl + '\n';
} else {
suffixSrc = '';
}
return def({
options: options,
wrapperSrc: wrapperSrc,
suffixSrc: suffixSrc,
freeNames: freeNames
});
}
ses.prepareExpr = prepareExpr;
/**
*
*/
function compileExpr(exprSrc, opt_mitigateOpts) {
var prep = prepareExpr(exprSrc, opt_mitigateOpts);
var wrapper = unsafeEval(prep.wrapperSrc + prep.suffixSrc);
var result = makeCompiledExpr(wrapper, prep.freeNames, prep.options);
return freeze(result);
}
/**
* Evaluate an expression as confined to these endowments.
*
* <p>Evaluates {@code exprSrc} in a tamper proof ({@code
* def()}ed) environment consisting of a copy of the shared
* imports and the own properties of {@code opt_endowments} if
* provided. Return the value the expression evaluated to. Since
* the shared imports provide no abilities to cause effects, the
* endowments are the only source of eval-time abilities for the
* expr to cause effects.
*/
function confine(exprSrc, opt_endowments, opt_mitigateOpts) {
// not necessary, since we only use it once below with a callee
// which is itself safe. But we coerce to a string anyway to be
// more robust against future refactorings.
exprSrc = ''+exprSrc;
var imports = makeImports();
if (opt_endowments) {
copyToImports(imports, opt_endowments);
}
def(imports);
return compileExpr(exprSrc, opt_mitigateOpts)(imports);
}
var directivePattern = (/^['"](?:\w|\s)*['"]$/m);
/**
* A stereotyped form of the CommonJS require statement.
*/
var requirePattern = (/^(?:\w*\s*(?:\w|\$|\.)*\s*=)?\s*require\s*\(\s*['"]((?:\w|\$|\.|\/)+)['"]\s*\)$/m);
/**
* As an experiment, recognize a stereotyped prelude of the
* CommonJS module system.
*/
function getRequirements(modSrc) {
var result = [];
var stmts = modSrc.split(';');
var stmt;
var i = 0, ilen = stmts.length;
for (; i < ilen; i++) {
stmt = stmts[i].trim();
if (stmt !== '') {
if (!directivePattern.test(stmt)) { break; }
}
}
for (; i < ilen; i++) {
stmt = stmts[i].trim();
if (stmt !== '') {
var m = requirePattern.exec(stmt);
if (!m) { break; }
result.push(m[1]);
}
}
return freeze(result);
}
/**
* A module source is actually any valid FunctionBody, and thus
* any valid Program.
*
* For documentation on {@code opt_mitigateOpts} see the
* corresponding parameter in {@code prepareExpr}.
*
* <p>In addition, in case the module source happens to begin with
* a streotyped prelude of the CommonJS module system, the
* function resulting from module compilation has an additional
* {@code "requirements"} property whose value is a list of the
* module names being required by that prelude. These requirements
* are the module's "immediate synchronous dependencies".
*
* <p>This {@code "requirements"} property is adequate to
* bootstrap support for a CommonJS module system, since a loader
* can first load and compile the transitive closure of an initial
* module's synchronous depencies before actually executing any of
* these module functions.
*