-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathtracer.c
2711 lines (2279 loc) · 69.5 KB
/
tracer.c
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) 2014, Ryan O'Neill
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* NOTE: This is the RUNTIME ENGINE.
* tracer.c is the code for tracer.o which
* is injected into the protected executable.
* it must not have any linking to libc and must
* maintain position independence thus we have
* hardcoded syscall wrappers.
*/
#include "tracer.h"
#include "shared_data.h"
#include "ecrypt-sync.h"
#include <signal.h>
#define REAL_CPU_DELAY_TIME 0xf000
int global_pid;
#define PAUSE_PARENT _pause()
#define INIT_MALLOC_SIZE 4096 << 10
#define MAX_HEAP_BINS 8
#define HEAP_BLOCK_SIZE 64 // XXX NOTE: Changed from 512 to 64 (Much more space efficient for hash map)
#define CHUNK_ROUNDUP(x)(x + HEAP_BLOCK_SIZE & ~(HEAP_BLOCK_SIZE - 1))
#define CHUNK_UNUSED_INITIALIZER 0xFFFFFFFF
#define MALLOC_KEY_LEN 0x8 /* Used for encrypted chunks */
/*
* Simple implementation of Malloc
**/
/*
* Each bin has a chunk index 'void *indexTable'
* which contains an array of 'struct chunkData'.
* Chunks are 512 bytes, and no memory request
* ever returns less than a chunk size. This
* works for our purposes, but could obviously
* be refined.
*
* [INDEX 0]___________________________________
\ \ \ \
* [BIN 0][CHUNK][CHUNK][CHUNK][EMPTY][CHUNK]
*
* [INDEX 1]___________________________________
* \ \
* [BIN 1][CHUNK][EMPTY][EMPTY][CHUNK][EMPTY]
*
* HEAP CHUNK(BLOCK) SIZE: 64B
* MAXIMUM HEAP CAPACITY: 32MB
* MAXIMUM ALLOCATION SIZE PER ALLOCATION: 4MB or (4194304 Bytes)
*
*/
struct chunkData {
unsigned long chunkVaddr;
unsigned int chunkSize;
unsigned int chunkOffset;
};
struct mHandle {
unsigned char *bin;
unsigned int memOff;
unsigned int binSize;
unsigned long baseVaddr;
void *indexTable;
struct chunkData *chunkData; // we store these in indexTable mapping
int chunkCount;
int initialized;
}; // mHandle[MAX_HEAP_BINS] = {[0 ... MAX_HEAP_BINS - 1] = 0};
struct mHandle mHandle[MAX_HEAP_BINS] __attribute__((section(".data"))) = { [0 ... MAX_HEAP_BINS - 1] = 0};
unsigned int ActiveBin __attribute__((section(".data"))) = 0;
/*
* cryptMetaData_t structs are stored
* in the data segment of tracer.o and
* contain encrypted locations, their sizes
* their keys, etc.
*/
/** Defined in shared_data.h
typedef struct {
Elf64_Addr startVaddr;
Elf64_Addr endVaddr;
unsigned int size;
char symname[MAX_SYMNAM_LEN];
unsigned char origByte;
int keyLen;
uint8_t key[MAX_KEY_LEN];
} __attribute__((packed)) cryptMetaData_t;
*/
unsigned char decryptRoutine(unsigned long vaddr);
int errno;
/*
* Needed to get eip in a PIC way
*/
extern unsigned long get_ip;
unsigned long get_rip(void);
/*
* syscall wrapper function prototypes
*/
int _modify_ldt(long, void *, unsigned long);
int _fstat(long, void *);
long _lseek(long, long, unsigned int);
void Exit(long);
void *_mmap(unsigned long, unsigned long, unsigned long, unsigned long, long, unsigned long);
long _open(char *, unsigned long);
long _write(long, char *, unsigned long);
int _read(long, char *, unsigned long);
long maya_ptrace(long, long, void *, void *);
int _wait4(long, long *, long, long *);
void _pause(void);
int _clone(unsigned long, unsigned long, unsigned int, long);
int _getpid(void);
int _getppid(void);
long _kill(unsigned int, unsigned int);
int maya_sigaction(unsigned int, struct sigaction *, struct sigaction *);
int maya_gettimeofday(void *, void *);
/*
* libc functions we re-implement
*/
void * paranoid_memdup(void *, unsigned int);
void paranoid_move(void *, void *, unsigned int);
int Memcmp(const void *, const void *, size_t);
void _strcpy(char *, char *);
int _strcmp(const char *, const char *);
int _strncmp(const char *s1, const char *s2, size_t n);
int _memcmp(const void *s1, const void *s2, unsigned int n);
char * _strrchr(const char *cp, int ch);
char *_strchr(const char *s, int c);
void _memcpy(void *, void *, unsigned int);
void Memset(void *, unsigned char, unsigned int);
void FreeMem(void *);
void initMalloc(void);
void * Malloc(unsigned int);
int malloc_crypto_load(unsigned char *, const void *, unsigned int, void *);
void * malloc_crypto_store(unsigned char *, const void *, unsigned int);
int _printf(char *fmt, ...);
int _sprintf(char *, char *, ...);
char * itoa(long x, char *t);
char * itox(long x, char *t);
int _puts(char *str);
size_t _strlen(char *s);
char * _fgets(char *, size_t, int, long *);
/* salsa funcs */
static void salsa20_wordtobyte(u8 output[64],const u32 input[16]);
void ECRYPT_init(void);
void ECRYPT_keysetup(ECRYPT_ctx *x,const u8 *k,u32 kbits,u32 ivbits);
void ECRYPT_ivsetup(ECRYPT_ctx *x,const u8 *iv);
void ECRYPT_encrypt_bytes(ECRYPT_ctx *x,const u8 *m,u8 *c,u32 bytes);
void ECRYPT_decrypt_bytes(ECRYPT_ctx *x,const u8 *c,u8 *m,u32 bytes);
void ECRYPT_keystream_bytes(ECRYPT_ctx *x,u8 *stream,u32 bytes);
/*
* custom functions for tracer
*/
int create_thread(void (*fn)(void *), void *data); // similar to pthread_create()
static inline int pid_read(int, void *, const void *, size_t); // reads in data using ptrace(PEEK_TEXT, ...
void exit_thread(void); // threads must exit with exit_thread()
void maya_timeskew(void);
/*
* Obfuscation functions: Opaque branches (Can get alot more complex than this)
*/
static inline void opaque_jmp_1() __attribute__((always_inline));
static inline void opaque_jmp_2() __attribute__((always_inline));
static inline void opaque_jmp_3() __attribute__((always_inline));
/*
* Termination code
*/
typedef enum {DEADCODE, DEADBEEF, ACID, LSD25, LEETCODE} crash_type_t;
static inline void terminate(crash_type_t) __attribute__((always_inline));
/*
* Global initialized data section structures
* knowledge being the primary database of intelligence.
*/
typedef struct knowledge {
Elf64_Addr hostEntry; // original entry point
cryptInfo_t cryptinfo_text; // crypt info for .text section
cryptInfo_t cryptinfo_data; // crypt info for .data section
cryptInfo_t cryptinfo_rodata; // crypt info for .rodata section
cryptInfo_t cryptinfo_plt; // crypt info for .plt section
unsigned char fingerprint[FINGERPRINT_SIZE]; //fingerprint for host
unsigned int crypt_item_count; // number of encrypted functions
unsigned int cflow_item_count; // number of cflow entries for anti-ROP
ro_relocs_t ro_relocs; // info for applying read-only relocations
cryptMetaData_t encryptedLocations[MAX_CRYPT_POCKETS]; //array of structs for each encrypted function
nanomite_t nanomite[MAX_NANOMITES]; // array of emulated branch instruction info
} __attribute__((packed)) knowledge_t;
/*
* The sizes of Maya internal functions that are encrypted
*/
typedef struct fsizes {
unsigned int trace_thread;
unsigned int fingerprint;
unsigned int verify_fingerprint;
} __attribute__((packed)) fsizes_t;
fsizes_t __attribute__((section(".data"))) functionSizes = {0x00};
/*
* Simple hash table info
*/
#define HASHLEN 1783
typedef enum {BEGIN_ROUTINE,END_ROUTINE,INACTIVE,WAITING,UNKNOWN} funcState_enum_t;
struct routineState {
funcState_enum_t funcState;
void * (*cb)(void *);
};
typedef enum {CFLOW_HASH,FSTATE_HASH,MISC_HASH} hash_act_t;
typedef enum {VALID_RETURN,INVALID_RETURN,MARKED_CONSTRAINT,UNKNOWN_LOC,UNDEFINED_ENTRY} cfi_verdict_t;
typedef struct hashLink
{
/*
* data is currently an unused
* element.
*/
void *data;
/*
** Used only for maya_cflow_t
** hash instances.
*/
unsigned long retLocation;
unsigned long validRetAddr;
/*
* Key will be either pid, or retLocation
*/
unsigned int key;
/*
** Used for context function state
*/
struct routineState state;
struct hashLink *next;
} hashlink_t;
typedef struct hash_type
{
unsigned int elements;
unsigned int hval;
unsigned long key;
hashlink_t *head;
} HASH;
typedef struct dummy_struct {
unsigned long d1[4096];
} dummy_struct_t;
/*
* These are dummy structs that serve no purpose
* but we run a cipher on them to decoy hackers
* from the real material.
*/
dummy_struct_t dummy1 __attribute__((section(".data"))) = { 0x00 };
dummy_struct_t dummy2 __attribute__((section(".data"))) = { 0x00 };
/*
* The data that goes into the tls_data_t is injected
* into the .tdata section in the necessary spots during
* the protection phase. The tracing thread utilizes this.
*/
knowledge_t knowledge __attribute__((section(".data"))) = { 0x00 };
struct safe_access {
knowledge_t *knowledge;
void *knowledge_saveptr;
maya_cflow_t *cflow;
void *cflow_saveptr;
} safe __attribute__((section(".data"))) = { 0x00 };
maya_modes_t maya_modes __attribute__((section(".data"))) = { 0x00 };
maya_cflow_t maya_cflow[MAX_CFLOW_ITEMS] __attribute__((section(".data"))) = { 0x00 };
typedef unsigned long long _ull;
struct bootstrap_data {
unsigned char *stack;
_ull rsp;
_ull rax;
_ull rcx;
_ull rdx;
_ull rbx;
_ull rdi;
_ull rsi;
_ull r8;
_ull r9;
_ull r10;
_ull r11;
_ull r12;
_ull r13;
_ull r14;
_ull r15;
} __attribute__ ((packed));
struct bootstrap_data bootstrap __attribute__((section(".data"))) = { 0x00 };
extern unsigned long real_start;
void maya_main(void);
static inline char **getenvp(void) __attribute__((always_inline));
static inline char **getenvp(void)
{
long *args;
long *envs;
long *rbp;
int argc;
char **envp;
/* Extract argc from stack */
asm __volatile__("mov 8(%%rbp), %%rcx " : "=c" (argc));
/* Extract argv from stack */
asm __volatile__("lea 16(%%rbp), %%rcx " : "=c" (args));
/* Extract envp from stack */
asm __volatile__("lea 40(%%rbp), %%rcx " : "=c" (rbp));
rbp += ((argc * sizeof(void *)) >> 3);
envs = (long *)rbp;
envp = (char **)envs;
return envp;
}
/*
* ***** ENTRY POINT *****
* This is where the host executable transfers control to...
* where our tracing engine must carefully preserve the register
* state before spawning a thread, and beginning a trace on the
* original entry point.
*/
int _start(void)
{
/*
* This is likely the ugliest code found in mayas mind.
* The preserving of registers, we must restore them before
* the tracing thread sets rip to the entry point.
*/
__asm__ __volatile__("push %%rax \t\n"
"mov 8(%%rsp), %0\t\n"
"add $0x8, %%rsp " : "=r"(bootstrap.rax));
__asm__ __volatile__("push %%rsp \n"
"pop %0 " : "=r"(bootstrap.rsp));
__asm__ __volatile__("push %%rcx \n"
"pop %0 " : "=r"(bootstrap.rcx));
__asm__ __volatile__("push %%rdx \n"
"pop %0 " : "=r"(bootstrap.rdx));
__asm__ __volatile__("push %%rbx \n"
"pop %0 " : "=r"(bootstrap.rbx));
__asm__ __volatile__("push %%rdi \n"
"pop %0 " : "=r"(bootstrap.rdi));
__asm__ __volatile__("push %%rsi \n"
"pop %0 " : "=r"(bootstrap.rsi));
__asm__ __volatile__("push %%r8 \n"
"pop %0 " : "=r"(bootstrap.r8));
__asm__ __volatile__("push %%r9 \n"
"pop %0 " : "=r"(bootstrap.r9));
__asm__ __volatile__("push %%r10 \n"
"pop %0 " : "=r"(bootstrap.r10));
__asm__ __volatile__("push %%r11 \n"
"pop %0 " : "=r"(bootstrap.r11));
__asm__ __volatile__("push %%r12 \n"
"pop %0 " : "=r"(bootstrap.r12));
__asm__ __volatile__("push %%r13 \n"
"pop %0 " : "=r"(bootstrap.r13));
__asm__ __volatile__("push %%r14 \n"
"pop %0 " : "=r"(bootstrap.r14));
__asm__ __volatile__("push %%r15 \n"
"pop %0 " : "=r"(bootstrap.r15));
__asm__(".globl real_start\n"
"real_start:\n"
"call maya_main\n");
}
static inline void delay(int v)
{
int i, j;
for (i = 0; i < v * 5000; i++)
for (j = 0; j < 50000; j++)
;
}
void maya_timeskew(void)
{
int i, j;
for (i = 0; i < 1000; i++)
for (j = 0; j < 2000; j++)
;
}
static inline int pid_read(int pid, void *dst, const void *src, size_t len)
{
int sz = len / sizeof(void *);
int rem = len % sizeof(void *);
unsigned char *s = (unsigned char *)src;
unsigned char *d = (unsigned char *)dst;
unsigned long word;
while (sz-- != 0) {
word = maya_ptrace(PTRACE_PEEKTEXT, pid, (long *)s, NULL);
if (word == -1)
return -1;
*(long *)d = word;
s += sizeof(long);
d += sizeof(long);
}
return 0;
}
int pid_write(int pid, void *dest, const void *src, size_t len)
{
size_t rem = len % sizeof(void *);
size_t quot = len / sizeof(void *);
unsigned char *s = (unsigned char *) src;
unsigned char *d = (unsigned char *) dest;
while (quot-- != 0) {
if ( maya_ptrace(PTRACE_POKEDATA, pid, d, *(void **)s) == -1 )
goto out_error;
s += sizeof(void *);
d += sizeof(void *);
}
if (rem != 0) {
long w;
unsigned char *wp = (unsigned char *)&w;
w = maya_ptrace(PTRACE_PEEKDATA, pid, d, NULL);
if (w == -1 && errno != 0) {
d -= sizeof(void *) - rem;
w = maya_ptrace(PTRACE_PEEKDATA, pid, d, NULL);
if (w == -1 && errno != 0)
goto out_error;
wp += sizeof(void *) - rem;
}
while (rem-- != 0)
wp[rem] = s[rem];
if (maya_ptrace(PTRACE_POKEDATA, pid, (void *)d, (void *)w) == -1)
goto out_error;
}
return 0;
out_error:
#if DEBUG
_printf("[MAYA]: pid_write() failed\n");
#endif
return -1;
}
/*
* Code to get system fingerprint and check it
*/
int verify_fingerprint(void)
{
int fd, i;
unsigned char mem[FINGERPRINT_SIZE];
unsigned char fingerprint[FINGERPRINT_SIZE];
unsigned char *fp = fingerprint;
if ((fd = _open("/proc/iomem", O_RDONLY)) < 0) {
#if DEBUG
_printf("[MAYA] Unable to open /proc/iomem for reading\n");
#endif
return -1;
}
_read(fd, mem, FINGERPRINT_SIZE);
for (i = 0; i < FINGERPRINT_SIZE; i++)
fp[i] = mem[i];
#if HEAP_CRYPTO
if (Memcmp(fingerprint, safe.knowledge->fingerprint, FINGERPRINT_SIZE) == 0) {
return 1;
}
#else
if (Memcmp(fingerprint, knowledge.fingerprint, FINGERPRINT_SIZE) == 0) {
return 1;
}
#endif
return 0;
}
void fingerprint(void)
{
if (verify_fingerprint() != 1) {
#if DEBUG
_printf("[MAYA] Invalid fingerprint, exiting\n");
#endif
Exit(99);
}
}
/********* SIMPLE HASH CODE **********/
unsigned int hTrans(unsigned long v)
{
unsigned int t = (uint32_t)(v *= 1738);
return t * 33;
}
unsigned int hash(unsigned long v)
{
return ((hTrans(v) + 31) % HASHLEN);
}
void set_hash_chain_fstate(HASH *h, unsigned long key, funcState_enum_t fstate)
{
hashlink_t *cur;
for (cur = h[hash(key)].head; cur != NULL; cur = cur->next)
if (cur->key == key) {
#if VERBOSE_DEBUG
_printf("[MAYA] set function state: %x\n", fstate);
#endif
cur->state.funcState = fstate;
}
}
cfi_verdict_t get_hash_chain_cfi_retloc(HASH *h, unsigned long key)
{
hashlink_t *cur;
if (h[hash(key)].elements > 0)
return MARKED_CONSTRAINT;
return UNKNOWN_LOC;
}
cfi_verdict_t get_hash_chain_cfi_retval(HASH *h, unsigned long key, unsigned long retaddr)
{
hashlink_t *cur;
if (!h[hash(key)].elements)
return UNDEFINED_ENTRY;
for (cur = h[hash(key)].head; cur != NULL; cur = cur->next) {
if (cur->retLocation == key)
if (cur->validRetAddr == retaddr)
return VALID_RETURN;
}
return INVALID_RETURN;
}
funcState_enum_t get_hash_chain_fstate(HASH *h, unsigned long key /* key is the pid */)
{
unsigned int i;
hashlink_t *cur;
if (!h[hash(key)].elements)
return -1;
for (cur = h[hash(key)].head; cur != NULL; cur = cur->next) {
if (cur->key != key)
continue;
return cur->state.funcState;
}
return (funcState_enum_t)UNKNOWN;
}
int add_hash_item(unsigned long key, HASH *h, unsigned long x, hash_act_t action, void *data)
{
unsigned int hval = 0;
hashlink_t *tmp;
hval = hash(key);
if ((tmp = (hashlink_t *)Malloc(sizeof(hashlink_t))) == NULL)
return -1;
tmp->next = h[hval].head;
h[hval].head = tmp;
h[hval].hval = hval;
h[hval].key = key;
#if DEBUG
_printf("Added item to hash: hval(%u) key(%d <-> 0x%x) HTYPE: %s\n", hval, h[hval].key, h[hval].key, action == FSTATE_HASH ? "FSTATE" : "CFLOW");
#endif
switch(action) {
case FSTATE_HASH:
tmp->state.funcState = INACTIVE;
tmp->data = data;
tmp->key = key;
break;
case CFLOW_HASH:
tmp->retLocation = key;
tmp->validRetAddr = x;
tmp->key = key;
break;
case MISC_HASH:
tmp->data = data;
tmp->key = key;
break;
default:
return -1;
}
h[hval].elements++;
return 0;
}
HASH * init_hash_table(void)
{
HASH *link;
int i;
if ((link = (HASH *)Malloc(HASHLEN * sizeof(HASH))) == NULL)
return NULL;
for (i = 0; i < HASHLEN; i++) {
link[i].elements = 0;
link[i].head = NULL;
}
return link;
}
static inline int quick_branch(unsigned int x, unsigned int y, unsigned int z)
{
unsigned int branch[2];
branch[0] = z;
branch[1] = y;
return branch[!((!x))];
}
/*
* pt_emulate_call() emulates a call instruction using
* ptrace.
*/
void pt_emulate_call(int pid, unsigned long vaddr, unsigned long retaddr)
{
struct user_regs_struct pt_reg;
#if DEBUG
_printf("[MAYA] Emulating 'call %x'\n", vaddr);
#endif
maya_ptrace(PTRACE_GETREGS, pid, NULL, &pt_reg);
/*
* push return address onto stack
*/
_memcpy((void *)pt_reg.rsp, (void *)&retaddr, sizeof(void *));
pt_reg.rsp -= sizeof(void *);
/*
* Set instruction pointer to target
*/
pt_reg.rip = vaddr;
maya_ptrace(PTRACE_SETREGS, pid, NULL, &pt_reg);
maya_ptrace(PTRACE_CONT, pid, NULL, NULL);
}
void pt_emulate_jmp(int pid, unsigned long vaddr)
{
struct user_regs_struct pt_reg;
#if DEBUG
_printf("[MAYA] Emulating 'jmp %x'\n", vaddr);
#endif
maya_ptrace(PTRACE_GETREGS, pid, NULL, &pt_reg);
pt_reg.rip = vaddr;
maya_ptrace(PTRACE_SETREGS, pid, NULL, &pt_reg);
maya_ptrace(PTRACE_CONT, pid, NULL, NULL);
}
int trap_count __attribute__ ((section(".data"))) = {0x00};
static void sigcatch(int sig, siginfo_t *siginfo, void *ctx)
{
#if DEBUG
_printf("Caught trap!\n");
#endif
trap_count++;
}
/*
* Unfinished
*/
int detect_pin(unsigned int pid)
{
char path[256], buf[512], *p;
int fd, i;
long offset = 0;
int vsyscall = 0;
_sprintf(path, "/proc/%d/maps", pid);
fd = _open(path, O_RDONLY); // we add this as a workaround to weird fd bug
if (fd < 0)
return -1;
while (_fgets(buf, sizeof(buf), fd, &offset)) {
if ((p = _strchr(buf, '[')) != NULL) {
if (!_strncmp(p, "[vdso]", 6)) {
_fgets(buf, sizeof(buf), fd, &offset);
if ((p = _strchr(buf, '[')) != NULL) {
if (!_strncmp(p, "[vvar]", 6)) {
terminate(LSD25);
return 1;
}
else
return 0;
} else
return 0;
}
}
}
return 0;
}
int detect_thread_debuggers(unsigned int pid)
{
char buf[512], *p;
int fd, i;
long offset = 0;
fd = _open("/proc/self/status", O_RDONLY); // we add this as a workaround to weird fd bug
if (fd < 0)
return -1;
for (i = 0; i < 7; i++)
_fgets(buf, sizeof(buf), fd, &offset);
_close(fd);
/*
* If the string looks like "TracerPid: 0\n" then we aren't being
* traced by a debugger on the cloned thread
*/
p = &buf[11];
if (*p == '0') {
p++;
if (*p == 0xA)
return 0;
}
/*
* If we made it here, then we are being traced
*/
#if DISPLAY_MSG
_printf("[MAYA] I shall smite thee debugger into oblivion\n");
#endif
asm volatile("movq $0x1337C0DE, %rcx\n"
"movq %rcx, (%rsp)\n"
"ret");
return 1;
}
static inline void terminate(crash_type_t crash_type)
{
switch(crash_type) {
case DEADCODE:
__asm__ volatile("mov $0xDEADC0DE, %rcx\n"
"mov %rcx, (%rsp)\n"
"ret");
break;
case ACID:
__asm__ volatile("mov $0x4C1DC0DE, %rcx\n"
"mov %rcx, (%rsp)\n"
"ret");
break;
case LSD25:
__asm__ volatile("mov $0x15D25, %rcx\n"
"mov %rcx, (%rsp)\n"
"ret");
break;
case DEADBEEF:
__asm__ volatile("mov $0xDEADBEEF, %rcx\n"
"mov %rcx, (%rsp)\n"
"ret");
break;
case LEETCODE:
__asm__ volatile("mov $0x1337C0DE, %rcx\n"
"mov %rcx, (%rsp)\n"
"ret");
break;
}
_kill(_getppid(), -1);
}
void set_prctl_protections(void)
{
/*
* We set the thread name to something other than
* the pids original program name. This is just
* a form of obscurity to possibly prevent someone
* from seeing a thread is created and related
* to Maya. XXX should use CLONE_NEWPID as well
* to disjoint its tid from the process thread group.
*/
char tidName[] = {'l', 's', 'd', '\0'};
_prctl(PR_SET_NAME, (char *)tidName, 0, 0, 0);
if (_prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) < 0) {
#if DEBUG
_printf("_prctl failed\n");
#endif
}
}
#define MAX_PIDS 12
void trace_thread(void *arg)
{
char *dptr;
struct user_regs_struct pt_reg;
long status, ptraceOpts;
int i, j, k, b;
unsigned char *decryptBuffer;
unsigned long stackAddr;
int functionBegin = 0, maya_bp = 0, iter = 0;
siginfo_t siginfo;
#if DETECT_EMU
unsigned int elapsed, t1;
struct {
long sec;
long usec;
} tv;
#endif
int p_index = 1; // pid index
int currpid, newpid, parent;
HASH *cfi;
HASH *ctx = init_hash_table();
if (ctx == NULL) {
#if DEBUG
_printf("[MAYA] Internal (ctx)hash table allocation failure\n");
#endif
exit_thread();
}
if (maya_modes.antiexploit) {
cfi = init_hash_table();
if (cfi == NULL) {
#if DEBUG
_printf("[MAYA] Internal (cfi)hash table allocation failure\n");
#endif
exit_thread();
}
//for (i = 0; i < MAX_CFLOW_ITEMS; i++)
#if HEAP_CRYPTO
for (i = 0; i < safe.knowledge->cflow_item_count; i++)
#else
for (i = 0; i < knowledge.cflow_item_count; i++)
#endif
if (maya_cflow[i].retLocation && maya_cflow[i].retLocation != 0xDEADC0DE)
add_hash_item(
maya_cflow[i].retLocation, /* Address of 'ret' instruction */
(HASH *)cfi, /* hash pointer */
maya_cflow[i].validRetAddr, /* valid return address */
CFLOW_HASH, /* hash action */
NULL);
}
/*
* Setup simple SIGTRAP detection
*/
#if THREAD_SIGTRAP_TEST
struct sigaction act, oldact;
act.sa_flags = SA_SIGINFO;
Memset((sigset_t *)&act.sa_mask, 0, sizeof(sigset_t));
act.sa_sigaction = (void (*)(int, siginfo_t *, void *))sigcatch;
#if DEBUG
_printf("[MAYA] act.sa_sigaction: %x\n", act.sa_sigaction);
#endif
if (maya_sigaction(SIGTRAP, (struct sigaction *)&act, (struct sigaction *)NULL) == -1) {
#if DEBUG
_printf("[MAYA] sigaction failure\n");
#endif
exit_thread();
}
#endif
/*
* Get the parent PID
*/
int pid = _getppid();
#if DEBUG
_printf("[MAYA] Parent pid: %d\n", pid);
#endif
if (!maya_modes.layer0)
add_hash_item(pid, ctx, 0, FSTATE_HASH, NULL);
if (maya_ptrace(PTRACE_ATTACH, pid, 0, 0) < 0) {
#if DISPLAY_MSG
_printf("[MAYA] The Veil of Maya shall veil still; To conceil what the debugger might reveal\n");