fishhook 0.2.9__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.2.9
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
@@ -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,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.2.9
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
@@ -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,13 @@ 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
8
+ fishhook/jit.py
7
9
  fishhook/tests.py
8
10
  fishhook.egg-info/PKG-INFO
9
11
  fishhook.egg-info/SOURCES.txt
10
12
  fishhook.egg-info/dependency_links.txt
13
+ fishhook.egg-info/requires.txt
11
14
  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.9",
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",
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
File without changes
File without changes
File without changes