fishhook 0.2.8.post10__tar.gz → 0.3__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.2.8.post10
3
+ Version: 0.3
4
4
  Summary: Allows for runtime hooking of static class functions
5
5
  Home-page: https://github.com/chilaxan/fishhook
6
6
  Author: chilaxan
@@ -11,6 +11,8 @@ Classifier: Operating System :: OS Independent
11
11
  Requires-Python: >=3.8
12
12
  Description-Content-Type: text/markdown
13
13
  License-File: LICENSE
14
+ Requires-Dist: capstone
15
+ Requires-Dist: keystone-engine
14
16
 
15
17
  # Fishhook
16
18
 
@@ -51,6 +53,27 @@ def imag(self):
51
53
  ...
52
54
  return orig.imag
53
55
  ```
56
+
57
+ # fishhook.asm
58
+
59
+ This submodule allows for more in-depth C level hooks.
60
+ For obvious reasons, this is vastly unstable, mostly provided as an experiment.
61
+ Originally created as a way to grab a reference to the Interned strings dictionary.
62
+
63
+ ```py
64
+ from fishhook import asm
65
+ from ctypes import py_object, pythonapi
66
+
67
+ @asm.hook(pythonapi.PyDict_SetDefault, restype=py_object, argtypes=[py_object, py_object, py_object])
68
+ def setdefault(self, key, value):
69
+ if key == 'MAGICVAL':
70
+ return self
71
+ return pythonapi.PyDict_SetDefault(self, key, value)
72
+
73
+ pythonapi.PyUnicode_InternFromString.restype = py_object
74
+ interned = pythonapi.PyUnicode_InternFromString(b'MAGICVAL')
75
+ ```
76
+
54
77
  #### Links
55
78
 
56
79
  [Github](https://github.com/chilaxan/fishhook)
@@ -37,6 +37,27 @@ def imag(self):
37
37
  ...
38
38
  return orig.imag
39
39
  ```
40
+
41
+ # fishhook.asm
42
+
43
+ This submodule allows for more in-depth C level hooks.
44
+ For obvious reasons, this is vastly unstable, mostly provided as an experiment.
45
+ Originally created as a way to grab a reference to the Interned strings dictionary.
46
+
47
+ ```py
48
+ from fishhook import asm
49
+ from ctypes import py_object, pythonapi
50
+
51
+ @asm.hook(pythonapi.PyDict_SetDefault, restype=py_object, argtypes=[py_object, py_object, py_object])
52
+ def setdefault(self, key, value):
53
+ if key == 'MAGICVAL':
54
+ return self
55
+ return pythonapi.PyDict_SetDefault(self, key, value)
56
+
57
+ pythonapi.PyUnicode_InternFromString.restype = py_object
58
+ interned = pythonapi.PyUnicode_InternFromString(b'MAGICVAL')
59
+ ```
60
+
40
61
  #### Links
41
62
 
42
63
  [Github](https://github.com/chilaxan/fishhook)
@@ -0,0 +1,118 @@
1
+ #include <Python.h>
2
+
3
+ #if !defined(_WIN32)
4
+ #include <unistd.h>
5
+ #include <stdio.h>
6
+ #include <stdlib.h>
7
+ #include <errno.h>
8
+ #include <sys/mman.h>
9
+ #else
10
+ #include <Windows.h>
11
+ #include <Memoryapi.h>
12
+ #endif
13
+
14
+ #if !defined(_WIN32)
15
+ int PREAD = PROT_READ;
16
+ int PWRITE = PROT_WRITE;
17
+ int PEXEC = PROT_EXEC;
18
+ #else
19
+ int PREAD = 1 << 1;
20
+ int PWRITE = 1 << 2;
21
+ int PEXEC = 1 << 3;
22
+ #endif
23
+
24
+ void changeProts(Py_buffer buffer, int prots) {
25
+ unsigned long long address = (unsigned long long)buffer.buf;
26
+ size_t length = buffer.len;
27
+ #if !defined(_WIN32)
28
+ int pagesize = sysconf(_SC_PAGE_SIZE);
29
+ unsigned long long addr_align = address & ~(pagesize - 1);
30
+ unsigned long long mem_end = (address + length) & ~(pagesize - 1);
31
+ if ((address + length) > mem_end) {
32
+ mem_end += pagesize;
33
+ }
34
+ size_t memlen = mem_end - addr_align;
35
+ mprotect((void *)addr_align, memlen, prots);
36
+ #else
37
+ int old;
38
+ int flags;
39
+ if (prots & PREAD && prots & PWRITE && prots & PEXEC) {
40
+ flags = PAGE_EXECUTE_READWRITE;
41
+ } else if (prots & PREAD && prots & PWRITE) {
42
+ flags = PAGE_READWRITE;
43
+ } else if (prots & PREAD && prots & PEXEC) {
44
+ flags = PAGE_EXECUTE_READ;
45
+ } else {
46
+ flags = PAGE_READONLY;
47
+ }
48
+ VirtualProtect((LPVOID)address, length, flags, &old);
49
+ #endif
50
+ }
51
+
52
+ void invalidateInstructionCache(void *addr, size_t length) {
53
+ #if defined(__x86_64__) || defined(_M_X64)
54
+ // x86 invalidates cache for us
55
+ #elif defined(__has_builtin)
56
+ #if __has_builtin(__builtin___clear_cache)
57
+ __builtin___clear_cache((char*)addr, (char*)(addr + length));
58
+ #endif
59
+ #else
60
+ #error "cannot determine way to clear instruction cache (required on arm64, otherwise make an issue here: https://github.com/chilaxan/fishhook)"
61
+ #endif
62
+ }
63
+
64
+ static PyObject *method_writeExecutableMemory(PyObject *self, PyObject *args, PyObject *kwargs) {
65
+ PyObject* target = NULL;
66
+ PyObject* src = NULL;
67
+ int prot_after = PREAD | PEXEC;
68
+
69
+ Py_buffer target_buf, src_buf;
70
+
71
+ static char *kwlist[] = { "target", "src", "prot_after", NULL };
72
+ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OO|i", kwlist, &target, &src, &prot_after)) {
73
+ return NULL;
74
+ }
75
+
76
+ if (
77
+ PyObject_GetBuffer(target, &target_buf, PyBUF_FULL_RO) == -1
78
+ || PyObject_GetBuffer(src, &src_buf, PyBUF_FULL_RO) == -1
79
+ ) {
80
+ return NULL;
81
+ }
82
+
83
+ if (target_buf.len != src_buf.len) {
84
+ PyErr_SetString(PyExc_ValueError, "target and dest must be the same length");
85
+ return NULL;
86
+ }
87
+
88
+ changeProts(target_buf, PREAD | PWRITE);
89
+ memcpy(target_buf.buf, src_buf.buf, target_buf.len);
90
+ changeProts(target_buf, prot_after);
91
+ invalidateInstructionCache(target_buf.buf, target_buf.len);
92
+
93
+ PyBuffer_Release(&target_buf);
94
+ PyBuffer_Release(&src_buf);
95
+ Py_RETURN_NONE;
96
+ }
97
+
98
+ static PyMethodDef AsmMethods[] = {
99
+ {"writeExecutableMemory", (PyCFunction) method_writeExecutableMemory, METH_VARARGS | METH_KEYWORDS, "write src into target executable memory"},
100
+ {NULL, NULL, 0, NULL}
101
+ };
102
+
103
+
104
+ static struct PyModuleDef asmmodule = {
105
+ PyModuleDef_HEAD_INIT,
106
+ "fishhook._asm",
107
+ "provides writeExecutableMemory function",
108
+ -1,
109
+ AsmMethods
110
+ };
111
+
112
+ PyMODINIT_FUNC PyInit__asm(void) {
113
+ PyObject* module = PyModule_Create(&asmmodule);
114
+ PyModule_AddIntConstant(module, "PREAD", PREAD);
115
+ PyModule_AddIntConstant(module, "PWRITE", PWRITE);
116
+ PyModule_AddIntConstant(module, "PEXEC", PEXEC);
117
+ return module;
118
+ }
@@ -0,0 +1,105 @@
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
@@ -65,15 +65,20 @@ def build_unlock_lock():
65
65
  cls_mem = allocate_structs(assert_cls(cls))
66
66
  flags = cls.__flags__
67
67
  try:
68
- return flags
68
+ return flags, cls_mem[tp_dict_offset] == 0
69
69
  finally:
70
70
  if sys.version_info[0:2] <= (3, 9):
71
71
  cls_mem[flag_offset] |= Py_TPFLAGS_HEAPTYPE
72
72
  elif sys.version_info[0:2] >= (3, 10):
73
73
  cls_mem[flag_offset] &= ~Py_TPFLAGS_IMMUTABLE
74
74
 
75
- def lock(cls, flags=None):
75
+ def lock(cls, flags=None, should_have_null_tp_dict=False):
76
76
  cls_mem = getmem(assert_cls(cls))
77
+ if should_have_null_tp_dict:
78
+ materialized_dict_addr = cls_mem[tp_dict_offset]
79
+ if materialized_dict_addr:
80
+ cls_mem[tp_dict_offset] = 0
81
+ getmem(materialized_dict_addr, 8)[0] -= 1 # clear materialized dict
77
82
  if flags is None:
78
83
  if sys.version_info[0:2] <= (3, 9):
79
84
  cls_mem[flag_offset] &= ~Py_TPFLAGS_HEAPTYPE
@@ -98,6 +103,14 @@ def newref(obj):
98
103
  getmem(obj)[0] += 1
99
104
  return obj
100
105
 
106
+ class Template:pass
107
+ template_mem = getmem(Template)
108
+ tp_base_offset = find_offset(template_mem, id(Template.__base__))
109
+ tp_basicsize_offset = find_offset(template_mem, Template.__basicsize__)
110
+ tp_flags_offset = find_offset(template_mem, Template.__flags__)
111
+ tp_dict_offset = find_offset(template_mem, id(getdict(Template)))
112
+ tp_bases_offset = find_offset(template_mem, id(Template.__bases__))
113
+
101
114
  def patch_object():
102
115
  '''
103
116
  adds fake class to inheritance chain so that object can be modified
@@ -106,12 +119,6 @@ def patch_object():
106
119
  into all lookups by modifying type.__bases__?
107
120
  '''
108
121
 
109
- int_mem = getmem(int)
110
- tp_base_offset = find_offset(int_mem, id(int.__base__))
111
- tp_basicsize_offset = find_offset(int_mem, int.__basicsize__)
112
- tp_flags_offset = find_offset(int_mem, int.__flags__)
113
- tp_dict_offset = find_offset(int_mem, id(getdict(int)))
114
- tp_bases_offset = find_offset(int_mem, id(int.__bases__))
115
122
  fake_addr = alloc(sizeof(object))
116
123
  fake_mem = getmem(fake_addr, sizeof(object))
117
124
  fake_mem[0] = 1
@@ -141,19 +148,29 @@ patch_object()
141
148
  def force_setattr(cls, attr, value):
142
149
  flags = None
143
150
  try:
144
- flags = unlock(cls)
151
+ flags, should_have_null_tp_dict = unlock(cls)
152
+ if should_have_null_tp_dict: # added for 3.12+ to ensure consistent state
153
+ getdict(cls)[attr] = value
145
154
  setattr(cls, attr, value)
146
155
  finally:
147
- lock(cls, flags)
156
+ lock(cls, flags, should_have_null_tp_dict)
148
157
  pythonapi.PyType_Modified(py_object(cls))
149
158
 
150
159
  def force_delattr(cls, attr):
151
160
  flags = None
152
161
  try:
153
- flags = unlock(cls)
154
- delattr(cls, attr)
162
+ flags, should_have_null_tp_dict = unlock(cls)
163
+ if should_have_null_tp_dict: # added for 3.12+ to ensure consistent state
164
+ del getdict(cls)[attr]
165
+ try:
166
+ delattr(cls, attr)
167
+ except AttributeError:
168
+ # for some attributes that are not cached
169
+ # delattr does not have a consistent state
170
+ # luckily, seems like we can ignore it
171
+ pass
155
172
  finally:
156
- lock(cls, flags)
173
+ lock(cls, flags, should_have_null_tp_dict)
157
174
  pythonapi.PyType_Modified(py_object(cls))
158
175
 
159
176
  NULL = object()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: fishhook
3
- Version: 0.2.8.post10
3
+ Version: 0.3
4
4
  Summary: Allows for runtime hooking of static class functions
5
5
  Home-page: https://github.com/chilaxan/fishhook
6
6
  Author: chilaxan
@@ -11,6 +11,8 @@ Classifier: Operating System :: OS Independent
11
11
  Requires-Python: >=3.8
12
12
  Description-Content-Type: text/markdown
13
13
  License-File: LICENSE
14
+ Requires-Dist: capstone
15
+ Requires-Dist: keystone-engine
14
16
 
15
17
  # Fishhook
16
18
 
@@ -51,6 +53,27 @@ def imag(self):
51
53
  ...
52
54
  return orig.imag
53
55
  ```
56
+
57
+ # fishhook.asm
58
+
59
+ This submodule allows for more in-depth C level hooks.
60
+ For obvious reasons, this is vastly unstable, mostly provided as an experiment.
61
+ Originally created as a way to grab a reference to the Interned strings dictionary.
62
+
63
+ ```py
64
+ from fishhook import asm
65
+ from ctypes import py_object, pythonapi
66
+
67
+ @asm.hook(pythonapi.PyDict_SetDefault, restype=py_object, argtypes=[py_object, py_object, py_object])
68
+ def setdefault(self, key, value):
69
+ if key == 'MAGICVAL':
70
+ return self
71
+ return pythonapi.PyDict_SetDefault(self, key, value)
72
+
73
+ pythonapi.PyUnicode_InternFromString.restype = py_object
74
+ interned = pythonapi.PyUnicode_InternFromString(b'MAGICVAL')
75
+ ```
76
+
54
77
  #### Links
55
78
 
56
79
  [Github](https://github.com/chilaxan/fishhook)
@@ -2,10 +2,12 @@ LICENSE
2
2
  README.md
3
3
  setup.py
4
4
  fishhook/__init__.py
5
+ fishhook/_asmmodule.c
5
6
  fishhook/asm.py
6
7
  fishhook/fishhook.py
7
8
  fishhook/tests.py
8
9
  fishhook.egg-info/PKG-INFO
9
10
  fishhook.egg-info/SOURCES.txt
10
11
  fishhook.egg-info/dependency_links.txt
12
+ fishhook.egg-info/requires.txt
11
13
  fishhook.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ capstone
2
+ keystone-engine
@@ -5,18 +5,20 @@ with open("README.md", "r") as fh:
5
5
 
6
6
  setuptools.setup(
7
7
  name="fishhook",
8
- version="0.2.8-10",
8
+ version="0.3",
9
9
  author="chilaxan",
10
10
  author_email="chilaxan@gmail.com",
11
11
  description="Allows for runtime hooking of static class functions",
12
12
  long_description=long_description,
13
13
  long_description_content_type="text/markdown",
14
14
  url="https://github.com/chilaxan/fishhook",
15
- packages=setuptools.find_packages(),
15
+ packages=['fishhook'],
16
16
  classifiers=[
17
17
  "Programming Language :: Python :: 3",
18
18
  "License :: OSI Approved :: MIT License",
19
19
  "Operating System :: OS Independent",
20
20
  ],
21
21
  python_requires='>=3.8',
22
+ ext_modules=[setuptools.Extension('fishhook._asm', sources=['fishhook/_asmmodule.c'])],
23
+ install_requires=['capstone', 'keystone-engine']
22
24
  )
@@ -1,58 +0,0 @@
1
- from ctypes import util
2
- from ctypes import *
3
- import atexit
4
-
5
- '''
6
- Allows for hooking internal C funtions and redirecting them to python code
7
- Originally used for grabbing a reference to the CPython interened strings table
8
- '''
9
-
10
- base_size = sizeof(c_void_p)
11
- libc = cdll.LoadLibrary(util.find_library('c'))
12
-
13
- PAGE_SIZE = libc.getpagesize()
14
- MEM_READ = 1
15
- MEM_WRITE = 2
16
- MEM_EXEC = 4
17
- ENDIAN = 'little' if memoryview(b'\1\0').cast('h')[0]==1 else 'big'
18
-
19
- libc.mprotect.argtypes = (c_void_p, c_size_t, c_int)
20
- libc.mprotect.restype = c_int
21
-
22
- def mprotect(addr, size, flags):
23
- addr_align = addr & ~(PAGE_SIZE - 1)
24
- mem_end = (addr + size) & ~(PAGE_SIZE - 1)
25
- if (addr + size) > mem_end:
26
- mem_end += PAGE_SIZE
27
- memlen = mem_end - addr_align
28
- libc.mprotect(addr_align, memlen, flags)
29
-
30
- def addr(cfunc):
31
- ptr = c_void_p.from_address(addressof(cfunc))
32
- return ptr.value
33
-
34
- def hook(cfunc, restype=c_int, argtypes=()):
35
- cfunctype = PYFUNCTYPE(restype, *argtypes)
36
- cfunc.restype, cfunc.argtypes = restype, argtypes
37
- o_ptr = addr(cfunc)
38
- mprotect(o_ptr, 5, MEM_READ | MEM_WRITE | MEM_EXEC)
39
- mem = (c_ubyte*5).from_address(o_ptr)
40
- default = mem[:]
41
- def wrapper(func):
42
- @cfunctype
43
- def injected(*args, **kwargs):
44
- try:
45
- mem[:] = default
46
- return func(*args, **kwargs)
47
- finally:
48
- mem[:] = jmp
49
- n_ptr = addr(injected)
50
- offset = n_ptr - o_ptr - 5
51
- jmp = b'\xe9' + (offset & ((1 << 32) - 1)).to_bytes(4, ENDIAN)
52
- mem[:] = jmp
53
- @atexit.register
54
- def unhook():
55
- mem[:] = default
56
- injected.unhook = unhook
57
- return injected
58
- return wrapper
File without changes
File without changes