fishhook 0.3__tar.gz → 0.3.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: fishhook
3
- Version: 0.3
3
+ Version: 0.3.1
4
4
  Summary: Allows for runtime hooking of static class functions
5
5
  Home-page: https://github.com/chilaxan/fishhook
6
6
  Author: chilaxan
@@ -0,0 +1,74 @@
1
+ from ctypes import *
2
+ import platform
3
+
4
+ if platform.system() == 'Windows':
5
+ raise RuntimeError('fishhook.asm does not currently work on Windows')
6
+
7
+ import sys
8
+ import weakref
9
+ import capstone as CS
10
+ import keystone as KS
11
+ from ._asm import writeExecutableMemory
12
+ from .fishhook import getmem
13
+ from .jit import TRAMPOLINE
14
+
15
+ '''
16
+ Allows for hooking internal C funtions and redirecting them to python code
17
+ Originally used for grabbing a reference to the CPython interened strings table
18
+ '''
19
+
20
+ def addr(cfunc):
21
+ ptr = c_void_p.from_address(addressof(cfunc))
22
+ return ptr.value
23
+
24
+ def make_storage(**registers):
25
+ class _RegisterStorage(Structure):
26
+ pass
27
+ _RegisterStorage._fields_ = [
28
+ (register, typ) for register, typ in registers.items()
29
+ ]
30
+ return _RegisterStorage()
31
+
32
+ def hook(cfunc, restype=c_int, argtypes=(), registers=None):
33
+ cfunctype = PYFUNCTYPE(restype, *argtypes)
34
+ cfunc.restype, cfunc.argtypes = restype, argtypes
35
+ o_ptr = addr(cfunc)
36
+ def wrapper(func):
37
+ if registers:
38
+ storage = make_storage(**registers)
39
+ regs = list(registers)
40
+ else:
41
+ storage = None
42
+ regs = ()
43
+ @cfunctype
44
+ def injected(*args, **kwargs):
45
+ try:
46
+ writeExecutableMemory(mem, default)
47
+ if storage:
48
+ kwargs['registers'] = storage
49
+ return func(*args, **kwargs)
50
+ finally:
51
+ writeExecutableMemory(mem, trampoline)
52
+ n_ptr = addr(injected)
53
+ trampoline = TRAMPOLINE(n_ptr, storage, regs)
54
+ mem = getmem(o_ptr, len(trampoline), 'c')
55
+ default = mem.tobytes()
56
+ writeExecutableMemory(mem, trampoline)
57
+ def unhook():
58
+ writeExecutableMemory(mem, default)
59
+ # reset memory back to default if hook is deallocated
60
+ weakref.finalize(injected, unhook)
61
+ injected.unhook = unhook
62
+ return injected
63
+ return wrapper
64
+
65
+ def get_interned_strings_dict():
66
+ @hook(pythonapi.PyDict_SetDefault, restype=py_object, argtypes=[py_object, py_object, py_object])
67
+ def setdefault(self, key, value):
68
+ if key == 'MAGICVAL':
69
+ return self
70
+ return pythonapi.PyDict_SetDefault(self, key, value)
71
+
72
+ pythonapi.PyUnicode_InternFromString.restype = py_object
73
+ interned = pythonapi.PyUnicode_InternFromString(b'MAGICVAL')
74
+ return interned
@@ -0,0 +1,98 @@
1
+ from ctypes import *
2
+ import sys
3
+ import platform
4
+
5
+ import capstone as CS
6
+ import keystone as KS
7
+
8
+ ENDIAN = 'LITTLE' if memoryview(b'\1\0').cast('h')[0]==1 else 'BIG'
9
+ BIT_SIZE = sys.maxsize.bit_length() + 1
10
+ ARCH = platform.machine().upper()
11
+ if ARCH == 'AMD64' or 'X86' in ARCH:
12
+ ARCH = 'X86'
13
+
14
+ if ARCH == 'AARCH64':
15
+ ARCH = 'ARM64'
16
+
17
+ assert ARCH in ['ARM64', 'X86'], f'Unsupported/Untested Architecture: {ARCH}'
18
+
19
+ def maketools():
20
+ cs_arch = getattr(CS, f'CS_ARCH_{ARCH}')
21
+ cs_mode = getattr(CS, f'CS_MODE_{ENDIAN}_ENDIAN')
22
+ ks_arch = getattr(KS, f'KS_ARCH_{ARCH}')
23
+ ks_mode = getattr(KS, f'KS_MODE_{ENDIAN}_ENDIAN')
24
+ if ARCH == 'X86':
25
+ cs_mode += getattr(CS, f'CS_MODE_{BIT_SIZE}')
26
+ ks_mode += getattr(KS, f'KS_MODE_{BIT_SIZE}')
27
+
28
+ return CS.Cs(cs_arch, cs_mode), KS.Ks(ks_arch, ks_mode)
29
+
30
+ DECOMPILER, COMPILER = maketools()
31
+
32
+ fragements = {
33
+ 'ARM64': {
34
+ 'push': 'str {0}, [sp, #-16]!;',
35
+ 'pop': 'ldr {0}, [sp], #16;',
36
+ 'load_const': 'ldr {0}, =0x{1:x};',
37
+ 'call': 'blr {0};',
38
+ 'ret': 'ret;',
39
+
40
+ 'store_mem': 'str {0}, [{1}, #0x{2:x}];',
41
+ 'read_mem': 'ldr {0}, [{1}, #0x{2:x}];'
42
+ },
43
+ 'X86': {
44
+ 'push': 'push {0};',
45
+ 'pop': 'pop {0};',
46
+ 'load_const': 'mov {0}, 0x{1:x};',
47
+ 'call': 'call {0};',
48
+ 'ret': 'ret;',
49
+
50
+ 'store_mem': 'mov {3} ptr [{1} + 0x{2:x}], {0};',
51
+ 'read_mem': 'mov {0}, {3} ptr [{1} + 0x{2:x}];'
52
+ }
53
+ }
54
+
55
+ def size_to_typ(n):
56
+ if ARCH == 'X86':
57
+ if n == 1:
58
+ return 'BYTE'
59
+ elif n == 2:
60
+ return 'WORD'
61
+ elif n == 4:
62
+ return 'DWORD'
63
+ elif n == 8:
64
+ return 'QWORD'
65
+ else:
66
+ raise RuntimeError(f'x86 memory size {n} is unsupported')
67
+
68
+ def inst(n, *args):
69
+ return fragements[ARCH][n].format(*args)
70
+
71
+ TMP_REG = 'lr' if ARCH == 'ARM64' else 'r15'
72
+
73
+ def TRAMPOLINE(address, storage=None, registers=()):
74
+ if storage:
75
+ header = footer = inst('load_const', TMP_REG, addressof(storage))
76
+ for register in registers:
77
+ field = getattr(type(storage), register)
78
+ offset = field.offset
79
+ typ = size_to_typ(field.size)
80
+ header += inst('store_mem', register, TMP_REG, offset, *((typ,) if typ else ()))
81
+ footer += inst('read_mem', register, TMP_REG, offset, *((typ,) if typ else ()))
82
+ else:
83
+ header = footer = ''
84
+
85
+ payload = '\n'.join([
86
+ inst('push', TMP_REG),
87
+ header,
88
+ inst('load_const', TMP_REG, address),
89
+ inst('call', TMP_REG),
90
+ footer,
91
+ inst('pop', TMP_REG),
92
+ inst('ret')
93
+ ])
94
+
95
+ payload, _ = COMPILER.asm(payload)
96
+ if payload is None:
97
+ raise RuntimeError('unable to build payload')
98
+ return bytes(payload)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: fishhook
3
- Version: 0.3
3
+ Version: 0.3.1
4
4
  Summary: Allows for runtime hooking of static class functions
5
5
  Home-page: https://github.com/chilaxan/fishhook
6
6
  Author: chilaxan
@@ -5,6 +5,7 @@ fishhook/__init__.py
5
5
  fishhook/_asmmodule.c
6
6
  fishhook/asm.py
7
7
  fishhook/fishhook.py
8
+ fishhook/jit.py
8
9
  fishhook/tests.py
9
10
  fishhook.egg-info/PKG-INFO
10
11
  fishhook.egg-info/SOURCES.txt
@@ -5,7 +5,7 @@ with open("README.md", "r") as fh:
5
5
 
6
6
  setuptools.setup(
7
7
  name="fishhook",
8
- version="0.3",
8
+ version="0.3.1",
9
9
  author="chilaxan",
10
10
  author_email="chilaxan@gmail.com",
11
11
  description="Allows for runtime hooking of static class functions",
@@ -1,105 +0,0 @@
1
- from ctypes import *
2
- import platform
3
-
4
- if platform.system() == 'Windows':
5
- raise RuntimeError('fishhook.asm does not currently work on Windows')
6
-
7
- import sys
8
- import weakref
9
- import capstone as CS
10
- import keystone as KS
11
- from ._asm import writeExecutableMemory
12
- from .fishhook import getmem
13
-
14
- '''
15
- Allows for hooking internal C funtions and redirecting them to python code
16
- Originally used for grabbing a reference to the CPython interened strings table
17
- '''
18
-
19
- ENDIAN = 'LITTLE' if memoryview(b'\1\0').cast('h')[0]==1 else 'BIG'
20
- BIT_SIZE = sys.maxsize.bit_length() + 1
21
- ARCH = platform.machine().upper()
22
- if ARCH == 'AMD64' or 'X86' in ARCH:
23
- ARCH = 'X86'
24
-
25
- if ARCH == 'AARCH64':
26
- ARCH = 'ARM64'
27
-
28
- assert ARCH in ['ARM64', 'X86'], f'Unsupported/Untested Architecture: {ARCH}'
29
-
30
- arm64_trampoline = '''
31
- # we can use lr as our jump register to reduce asm size
32
- str lr, [sp, #-16]!; # save lr onto stack, have to use 16 bytes because of arm stack alignment
33
- ldr lr, =0x{address:x}; # load 64bit address into lr
34
- blr lr; # branch and link to [lr], overwriting [lr] to point next instruction at the same time
35
- ldr lr, [sp], #16; # restore lr from stack
36
- ret;
37
- '''
38
-
39
- x86_trampoline = '''
40
- # we use a callee saved register to ensure we arent corrupting anything downstream
41
- push r15; # save r15 register on stack
42
- mov r15, 0x{address:x}; # move 64bit address into r15
43
- call r15; # call r15
44
- pop r15; # restore r15
45
- ret; # return to caller
46
- '''
47
-
48
- trampolines = {
49
- 'ARM64': arm64_trampoline,
50
- 'X86': x86_trampoline
51
- }
52
-
53
- def maketools():
54
- cs_arch = getattr(CS, f'CS_ARCH_{ARCH}')
55
- cs_mode = getattr(CS, f'CS_MODE_{ENDIAN}_ENDIAN')
56
- ks_arch = getattr(KS, f'KS_ARCH_{ARCH}')
57
- ks_mode = getattr(KS, f'KS_MODE_{ENDIAN}_ENDIAN')
58
- if ARCH == 'X86':
59
- cs_mode += getattr(CS, f'CS_MODE_{BIT_SIZE}')
60
- ks_mode += getattr(KS, f'KS_MODE_{BIT_SIZE}')
61
-
62
- return CS.Cs(cs_arch, cs_mode), KS.Ks(ks_arch, ks_mode), trampolines[ARCH]
63
-
64
- DECOMPILER, COMPILER, TRAMPOLINE_ASM = maketools()
65
-
66
- def addr(cfunc):
67
- ptr = c_void_p.from_address(addressof(cfunc))
68
- return ptr.value
69
-
70
- def hook(cfunc, restype=c_int, argtypes=()):
71
- cfunctype = PYFUNCTYPE(restype, *argtypes)
72
- cfunc.restype, cfunc.argtypes = restype, argtypes
73
- o_ptr = addr(cfunc)
74
- def wrapper(func):
75
- @cfunctype
76
- def injected(*args, **kwargs):
77
- try:
78
- writeExecutableMemory(mem, default)
79
- return func(*args, **kwargs)
80
- finally:
81
- writeExecutableMemory(mem, jmp)
82
- n_ptr = addr(injected)
83
- jmp_b, _ = COMPILER.asm(TRAMPOLINE_ASM.format(address=n_ptr))
84
- jmp = bytes(jmp_b)
85
- mem = getmem(o_ptr, len(jmp), 'c')
86
- default = mem.tobytes()
87
- writeExecutableMemory(mem, jmp)
88
- def unhook():
89
- writeExecutableMemory(mem, default)
90
- # reset memory back to default if hook is deallocated
91
- weakref.finalize(injected, unhook)
92
- injected.unhook = unhook
93
- return injected
94
- return wrapper
95
-
96
- def get_interned_strings_dict():
97
- @hook(pythonapi.PyDict_SetDefault, restype=py_object, argtypes=[py_object, py_object, py_object])
98
- def setdefault(self, key, value):
99
- if key == 'MAGICVAL':
100
- return self
101
- return pythonapi.PyDict_SetDefault(self, key, value)
102
-
103
- pythonapi.PyUnicode_InternFromString.restype = py_object
104
- interned = pythonapi.PyUnicode_InternFromString(b'MAGICVAL')
105
- return interned
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes