fishhook 0.3__tar.gz → 0.3.2__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,10 +1,10 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: fishhook
3
- Version: 0.3
3
+ Version: 0.3.2
4
4
  Summary: Allows for runtime hooking of static class functions
5
- Home-page: https://github.com/chilaxan/fishhook
6
- Author: chilaxan
7
- Author-email: chilaxan@gmail.com
5
+ Author-email: chilaxan <chilaxan@gmail.com>
6
+ License: MIT
7
+ Project-URL: repository, https://github.com/chilaxan/fishhook
8
8
  Classifier: Programming Language :: Python :: 3
9
9
  Classifier: License :: OSI Approved :: MIT License
10
10
  Classifier: Operating System :: OS Independent
@@ -57,7 +57,7 @@ void invalidateInstructionCache(void *addr, size_t length) {
57
57
  __builtin___clear_cache((char*)addr, (char*)(addr + length));
58
58
  #endif
59
59
  #else
60
- #error "cannot determine way to clear instruction cache (required on arm64, otherwise make an issue here: https://github.com/chilaxan/fishhook)"
60
+ // cannot determine way to clear instruction cache (required on arm64, otherwise make an issue here: https://github.com/chilaxan/fishhook)
61
61
  #endif
62
62
  }
63
63
 
@@ -0,0 +1,71 @@
1
+ from ctypes import *
2
+ import platform
3
+ import weakref
4
+
5
+ if platform.system() == 'Windows':
6
+ raise RuntimeError('fishhook.asm does not currently work on Windows')
7
+
8
+ from ._asm import writeExecutableMemory
9
+ from .fishhook import getmem
10
+ from .jit import TRAMPOLINE
11
+
12
+ '''
13
+ Allows for hooking internal C funtions and redirecting them to python code
14
+ Originally used for grabbing a reference to the CPython interened strings table
15
+ '''
16
+
17
+ def addr(cfunc):
18
+ ptr = c_void_p.from_address(addressof(cfunc))
19
+ return ptr.value
20
+
21
+ def make_storage(**registers):
22
+ class _RegisterStorage(Structure):
23
+ pass
24
+ _RegisterStorage._fields_ = [
25
+ (register, typ) for register, typ in registers.items()
26
+ ]
27
+ return _RegisterStorage()
28
+
29
+ def hook(cfunc, restype=c_int, argtypes=(), registers=None):
30
+ cfunctype = PYFUNCTYPE(restype, *argtypes)
31
+ cfunc.restype, cfunc.argtypes = restype, argtypes
32
+ o_ptr = addr(cfunc)
33
+ def wrapper(func):
34
+ if registers:
35
+ storage = make_storage(**registers)
36
+ regs = list(registers)
37
+ else:
38
+ storage = None
39
+ regs = ()
40
+ @cfunctype
41
+ def injected(*args, **kwargs):
42
+ try:
43
+ writeExecutableMemory(mem, default)
44
+ if storage:
45
+ kwargs['registers'] = storage
46
+ return func(*args, **kwargs)
47
+ finally:
48
+ writeExecutableMemory(mem, trampoline)
49
+ n_ptr = addr(injected)
50
+ trampoline = TRAMPOLINE(n_ptr, storage, regs)
51
+ mem = getmem(o_ptr, len(trampoline), 'c')
52
+ default = mem.tobytes()
53
+ writeExecutableMemory(mem, trampoline)
54
+ def unhook():
55
+ writeExecutableMemory(mem, default)
56
+ # reset memory back to default if hook is deallocated
57
+ weakref.finalize(injected, unhook)
58
+ injected.unhook = unhook
59
+ return injected
60
+ return wrapper
61
+
62
+ def get_interned_strings_dict():
63
+ @hook(pythonapi.PyDict_SetDefault, restype=py_object, argtypes=[py_object, py_object, py_object])
64
+ def setdefault(self, key, value):
65
+ if key == 'MAGICVAL':
66
+ return self
67
+ return pythonapi.PyDict_SetDefault(self, key, value)
68
+
69
+ pythonapi.PyUnicode_InternFromString.restype = py_object
70
+ interned = pythonapi.PyUnicode_InternFromString(b'MAGICVAL')
71
+ return interned
@@ -0,0 +1,115 @@
1
+ from ctypes import *
2
+ import sys
3
+ import platform
4
+
5
+ try:
6
+ import capstone as CS
7
+ except ModuleNotFoundError as err:
8
+ if err.name == 'distutils':
9
+ # capstone depends on distutils and pkg_resources, but in most configs does not need them
10
+ # 3.12+ has deprecated these modules
11
+ # we can stub them out and re-attempt the import
12
+ class stub:
13
+ def __getattr__(self, attr):
14
+ return self
15
+ def __call__(self, *args):
16
+ return ''
17
+
18
+ sys.modules['distutils'] = stub()
19
+ sys.modules['distutils.sysconfig'] = stub()
20
+ sys.modules['pkg_resources'] = stub()
21
+ import capstone as CS
22
+
23
+ import keystone as KS
24
+
25
+ ENDIAN = 'LITTLE' if memoryview(b'\1\0').cast('h')[0]==1 else 'BIG'
26
+ BIT_SIZE = sys.maxsize.bit_length() + 1
27
+ ARCH = platform.machine().upper()
28
+ if ARCH == 'AMD64' or 'X86' in ARCH:
29
+ ARCH = 'X86'
30
+
31
+ if ARCH == 'AARCH64':
32
+ ARCH = 'ARM64'
33
+
34
+ assert ARCH in ['ARM64', 'X86'], f'Unsupported/Untested Architecture: {ARCH}'
35
+
36
+ def maketools():
37
+ cs_arch = getattr(CS, f'CS_ARCH_{ARCH}')
38
+ cs_mode = getattr(CS, f'CS_MODE_{ENDIAN}_ENDIAN')
39
+ ks_arch = getattr(KS, f'KS_ARCH_{ARCH}')
40
+ ks_mode = getattr(KS, f'KS_MODE_{ENDIAN}_ENDIAN')
41
+ if ARCH == 'X86':
42
+ cs_mode += getattr(CS, f'CS_MODE_{BIT_SIZE}')
43
+ ks_mode += getattr(KS, f'KS_MODE_{BIT_SIZE}')
44
+
45
+ return CS.Cs(cs_arch, cs_mode), KS.Ks(ks_arch, ks_mode)
46
+
47
+ DECOMPILER, COMPILER = maketools()
48
+
49
+ fragements = {
50
+ 'ARM64': {
51
+ 'push': 'str {0}, [sp, #-16]!;',
52
+ 'pop': 'ldr {0}, [sp], #16;',
53
+ 'load_const': 'ldr {0}, =0x{1:x};',
54
+ 'call': 'blr {0};',
55
+ 'ret': 'ret;',
56
+
57
+ 'store_mem': 'str {0}, [{1}, #0x{2:x}];',
58
+ 'read_mem': 'ldr {0}, [{1}, #0x{2:x}];'
59
+ },
60
+ 'X86': {
61
+ 'push': 'push {0};',
62
+ 'pop': 'pop {0};',
63
+ 'load_const': 'mov {0}, 0x{1:x};',
64
+ 'call': 'call {0};',
65
+ 'ret': 'ret;',
66
+
67
+ 'store_mem': 'mov {3} ptr [{1} + 0x{2:x}], {0};',
68
+ 'read_mem': 'mov {0}, {3} ptr [{1} + 0x{2:x}];'
69
+ }
70
+ }
71
+
72
+ def size_to_typ(n):
73
+ if ARCH == 'X86':
74
+ if n == 1:
75
+ return 'BYTE'
76
+ elif n == 2:
77
+ return 'WORD'
78
+ elif n == 4:
79
+ return 'DWORD'
80
+ elif n == 8:
81
+ return 'QWORD'
82
+ else:
83
+ raise RuntimeError(f'x86 memory size {n} is unsupported')
84
+
85
+ def inst(n, *args):
86
+ return fragements[ARCH][n].format(*args)
87
+
88
+ TMP_REG = 'lr' if ARCH == 'ARM64' else 'r15'
89
+
90
+ def TRAMPOLINE(address, storage=None, registers=()):
91
+ if storage:
92
+ header = footer = inst('load_const', TMP_REG, addressof(storage))
93
+ for register in registers:
94
+ field = getattr(type(storage), register)
95
+ offset = field.offset
96
+ typ = size_to_typ(field.size)
97
+ header += inst('store_mem', register, TMP_REG, offset, *((typ,) if typ else ()))
98
+ footer += inst('read_mem', register, TMP_REG, offset, *((typ,) if typ else ()))
99
+ else:
100
+ header = footer = ''
101
+
102
+ payload = '\n'.join([
103
+ inst('push', TMP_REG),
104
+ header,
105
+ inst('load_const', TMP_REG, address),
106
+ inst('call', TMP_REG),
107
+ footer,
108
+ inst('pop', TMP_REG),
109
+ inst('ret')
110
+ ])
111
+
112
+ payload, _ = COMPILER.asm(payload)
113
+ if payload is None:
114
+ raise RuntimeError('unable to build payload')
115
+ return bytes(payload)
@@ -1,10 +1,10 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: fishhook
3
- Version: 0.3
3
+ Version: 0.3.2
4
4
  Summary: Allows for runtime hooking of static class functions
5
- Home-page: https://github.com/chilaxan/fishhook
6
- Author: chilaxan
7
- Author-email: chilaxan@gmail.com
5
+ Author-email: chilaxan <chilaxan@gmail.com>
6
+ License: MIT
7
+ Project-URL: repository, https://github.com/chilaxan/fishhook
8
8
  Classifier: Programming Language :: Python :: 3
9
9
  Classifier: License :: OSI Approved :: MIT License
10
10
  Classifier: Operating System :: OS Independent
@@ -1,10 +1,12 @@
1
1
  LICENSE
2
2
  README.md
3
+ pyproject.toml
3
4
  setup.py
4
5
  fishhook/__init__.py
5
6
  fishhook/_asmmodule.c
6
7
  fishhook/asm.py
7
8
  fishhook/fishhook.py
9
+ fishhook/jit.py
8
10
  fishhook/tests.py
9
11
  fishhook.egg-info/PKG-INFO
10
12
  fishhook.egg-info/SOURCES.txt
@@ -0,0 +1,29 @@
1
+ [project]
2
+ name = "fishhook"
3
+ version = "0.3.2"
4
+ description = "Allows for runtime hooking of static class functions"
5
+ authors = [
6
+ { name = "chilaxan", email = "chilaxan@gmail.com" },
7
+ ]
8
+ license = { text = "MIT" }
9
+ readme = "README.md"
10
+ classifiers = [
11
+ "Programming Language :: Python :: 3",
12
+ "License :: OSI Approved :: MIT License",
13
+ "Operating System :: OS Independent",
14
+ ]
15
+ requires-python = ">=3.8"
16
+ dependencies = [
17
+ "capstone",
18
+ "keystone-engine",
19
+ ]
20
+
21
+ [project.urls]
22
+ repository = "https://github.com/chilaxan/fishhook"
23
+
24
+ [build-system]
25
+ requires = ["setuptools"]
26
+ build-backend = "setuptools.build_meta"
27
+
28
+ [tool.setuptools]
29
+ packages = ["fishhook"]
@@ -0,0 +1,7 @@
1
+ import setuptools
2
+
3
+ setuptools.setup(
4
+ ext_modules=[
5
+ setuptools.Extension("fishhook._asm", sources=["fishhook/_asmmodule.c"])
6
+ ],
7
+ )
@@ -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
fishhook-0.3/setup.py DELETED
@@ -1,24 +0,0 @@
1
- import setuptools
2
-
3
- with open("README.md", "r") as fh:
4
- long_description = fh.read()
5
-
6
- setuptools.setup(
7
- name="fishhook",
8
- version="0.3",
9
- author="chilaxan",
10
- author_email="chilaxan@gmail.com",
11
- description="Allows for runtime hooking of static class functions",
12
- long_description=long_description,
13
- long_description_content_type="text/markdown",
14
- url="https://github.com/chilaxan/fishhook",
15
- packages=['fishhook'],
16
- classifiers=[
17
- "Programming Language :: Python :: 3",
18
- "License :: OSI Approved :: MIT License",
19
- "Operating System :: OS Independent",
20
- ],
21
- python_requires='>=3.8',
22
- ext_modules=[setuptools.Extension('fishhook._asm', sources=['fishhook/_asmmodule.c'])],
23
- install_requires=['capstone', 'keystone-engine']
24
- )
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes