kmaork / hypno Goto Github PK
View Code? Open in Web Editor NEWInject python code into a running python process
License: MIT License
Inject python code into a running python process
License: MIT License
Can check if the target process has a different /proc/<pid>/task/<pid>/ns/mnt
. If it does, create the shared library in /proc/pid/root
instead in the current filesystem. Python's tempfile module doesn't support searching for a tempdir in a different filesystem, and it caches it for the whole process once it's found. So maybe we can create a subprocess, nsenter the target filesystem, and then continue normally. Alternatively, just copy the logic in tempfile
or assume that /tmp
is writable.
This would save disk space and increase performance.
A possible edge case can occur if the library is installed on a mount, in which case hard links cannot be created directly to the library (this happened to me while working with wsl - the files were located on the mounted windows filesystem).
In that case we should copy the library to some location on the local disk and create hard links from there, but we have to consider possible collisions/races with other instances (and versions) of hypno.
Using Windows 7, Python 3.8.10, hypno 1.0.3, pyinjector 1.3.0
py -m hypno <pid> "import traceback; traceback.print_stack()"
Traceback (most recent call last):
File "C:\Program Files\Python38\lib\site-packages\pyinjector\api.py", line 71, in attach
yield injector
File "C:\Program Files\Python38\lib\site-packages\pyinjector\api.py", line 94, in inject
handle = injector.inject(encoded_library_path)
injector.InjectorException: ('injector_inject', -5, 'LoadLibrary in the target process failed: win32 error code 1114')
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Program Files\Python38\lib\runpy.py", line 194, in _run_module_as_main
return _run_code(code, main_globals, None,
File "C:\Program Files\Python38\lib\runpy.py", line 87, in _run_code
exec(code, run_globals)
File "C:\Program Files\Python38\lib\site-packages\hypno\__main__.py", line 20, in <module>
main()
File "C:\Program Files\Python38\lib\site-packages\hypno\__main__.py", line 16, in main
inject_py(parsed_args.pid, parsed_args.python_code)
File "C:\Program Files\Python38\lib\site-packages\hypno\api.py", line 49, in inject_py
inject(pid, str(temp.name))
File "C:\Program Files\Python38\lib\site-packages\pyinjector\api.py", line 97, in inject
return handle
File "C:\Program Files\Python38\lib\contextlib.py", line 131, in __exit__
self.gen.throw(type, value, traceback)
File "C:\Program Files\Python38\lib\site-packages\pyinjector\api.py", line 77, in attach
raise exception_cls(func_name, ret_val, error_str) from e
pyinjector.api.InjectorError: Injector failed with -5 calling injector_inject: LoadLibrary in the target process failed: win32 error code 1114
This error occurred after I did: "pip install hypno".
ERROR: Failed building wheel for hypno
Running setup.py clean for hypno
Failed to build hypno
Installing collected packages: hypno
Running setup.py install for hypno ... error
ERROR: Command errored out with exit status 1:
command: 'c:\users\user\appdata\local\programs\python\python37\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\user\AppData\Local\Temp\pip-install-kvu296dw\hypno_e95e0e11b75f4dfd899bc3900de3c056\setup.py'"'"'; file='"'"'C:\Users\user\AppData\Local\Temp\pip-install-kvu296dw\hypno_e95e0e11b75f4dfd899bc3900de3c056\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(file) if os.path.exists(file) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\user\AppData\Local\Temp\pip-record-zqsrahm6\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\user\appdata\local\programs\python\python37\Include\hypno'
cwd: C:\Users\user\AppData\Local\Temp\pip-install-kvu296dw\hypno_e95e0e11b75f4dfd899bc3900de3c056
Complete output (18 lines):
running install
running build
running build_py
creating build
creating build\lib.win-amd64-3.7
creating build\lib.win-amd64-3.7\hypno
copying hypno\hypno.py -> build\lib.win-amd64-3.7\hypno
copying hypno_init_.py -> build\lib.win-amd64-3.7\hypno
copying hypno_main_.py -> build\lib.win-amd64-3.7\hypno
running build_ext
building 'hypno.injection' extension
creating build\temp.win-amd64-3.7
creating build\temp.win-amd64-3.7\Release
creating build\temp.win-amd64-3.7\Release\hypno
C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.16.27023\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Ic:\users\user\appdata\local\programs\python\python37\include -Ic:\users\user\appdata\local\programs\python\python37\include "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.16.27023\ATLMFC\include" "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.16.27023\include" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\cppwinrt" /Tchypno/injection.c /Fobuild\temp.win-amd64-3.7\Release\hypno/injection.obj
injection.c
hypno/injection.c(3): fatal error C1083: Cannot open include file: 'dlfcn.h': No such file or directory
error: command 'C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.16.27023\bin\HostX86\x64\cl.exe' failed with exit status 2
----------------------------------------
ERROR: Command errored out with exit status 1: 'c:\users\user\appdata\local\programs\python\python37\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\user\AppData\Local\Temp\pip-install-kvu296dw\hypno_e95e0e11b75f4dfd899bc3900de3c056\setup.py'"'"'; file='"'"'C:\Users\user\AppData\Local\Temp\pip-install-kvu296dw\hypno_e95e0e11b75f4dfd899bc3900de3c056\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(file) if os.path.exists(file) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\user\AppData\Local\Temp\pip-record-zqsrahm6\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\user\appdata\local\programs\python\python37\Include\hypno' Check the logs for full command output.`
hypno/injection.c(3): fatal error C1083: 无法打开包括文件: “dlfcn.h”: No such file or directory
Can we have wheels for 3.11, pretty please? 🙏
I have no idea what to do after this. I'm on windows 10.
C:\Users\dmale>hypno 17752 x=1
~~ATTACHING
RET ZERO-VALUE: 0 EXCEPTION_MAP: {-8: <class 'pyinjector.pyinjector.InjectorPermissionError'>} UNDER: ATTACH
+FINISHED ATTACHING FUNCTION
~~INJECTING **didn't finish the injecting part**
RET VALUE: -5 EXCEPTION_MAP: None UNDER: INJECT
~~DEATTACHING
RET ZERO-VALUE: 0 EXCEPTION_MAP: None UNDER: DEATTACH
+FINISHED DEATTACHING FUNCTION
Traceback (most recent call last):
File "C:\Users\dmale\AppData\Local\Programs\Python\Python37\Scripts\hypno-script.py", line 11, in <module>
load_entry_point('hypno==0.1.3', 'console_scripts', 'hypno')()
File "C:\Users\dmale\AppData\Local\Programs\Python\Python37\lib\site-packages\hypno-0.1.3-py3.7-win-amd64.egg\hypno\__main__.py", line 16, in main
inject_py(parsed_args.pid, parsed_args.python_code)
File "C:\Users\dmale\AppData\Local\Programs\Python\Python37\lib\site-packages\hypno-0.1.3-py3.7-win-amd64.egg\hypno\hypno.py", line 20, in inject_py
inject(pid, str(copied_lib))
File "C:\Users\dmale\AppData\Local\Programs\Python\Python37\lib\site-packages\pyinjector\pyinjector.py", line 91, in inject
injector.inject(library_path)
File "C:\Users\dmale\AppData\Local\Programs\Python\Python37\lib\site-packages\pyinjector\pyinjector.py", line 79, in inject
call_c_func(libinjector.injector_inject, self.injector_p, library_path, custom_msg='INJECT') #<-------- HERE THE ERROR HAPPENS
File "C:\Users\dmale\AppData\Local\Programs\Python\Python37\lib\site-packages\pyinjector\pyinjector.py", line 56, in call_c_func
raise exception_cls(func.__name__, ret)
pyinjector.pyinjector.InjectorError: injector_inject returned -5, see error code definition in injector/include/injector.h
Python 3.11.2 (main, Feb 12 2023, 00:48:52) [GCC 12.2.0]
Type 'copyright', 'credits' or 'license' for more information
IPython 8.5.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: import madbg
In [2]: madbg.attach_to_process(3453466)
---------------------------------------------------------------------------
InjectorError Traceback (most recent call last)
Cell In [2], line 1
----> 1 madbg.attach_to_process(3453466)
File /usr/lib/python3/dist-packages/madbg/api.py:34, in attach_to_process(pid, port, connect_timeout)
32 def attach_to_process(pid: int, port=DEFAULT_PORT, connect_timeout=DEFAULT_CONNECT_TIMEOUT):
33 ip = '127.0.0.1'
---> 34 _inject_set_trace(pid, ip, port)
35 connect_to_debugger(ip, port, timeout=connect_timeout)
File /usr/lib/python3/dist-packages/madbg/api.py:28, in _inject_set_trace(pid, ip, port)
26 assert isinstance(port, int)
27 sig_num = DEBUGGER_CONNECTED_SIGNAL.value
---> 28 inject_py(pid, f'__import__("signal").signal({sig_num},lambda _,f:__import__("madbg").set_trace(f,"{ip}",{port}))')
29 os.kill(pid, sig_num)
File /usr/lib/python3/dist-packages/hypno/hypno.py:42, in inject_py(pid, python_code)
40 temp.write(lib[code_addr + len(python_code) + 1:])
41 try:
---> 42 inject(pid, str(temp.name))
43 except InjectorError as e:
44 # On Windows we are failing the load on purpose so the library will be immediately unloaded
45 if not WINDOWS or e.ret_val != -5 or e.error_str != \
46 "LoadLibrary in the target process failed: " \
47 "A dynamic link library (DLL) initialization routine failed.":
File /usr/lib/python3/dist-packages/pyinjector/pyinjector.py:103, in inject(pid, library_path)
101 injector = Injector.attach(pid)
102 try:
--> 103 return injector.inject(library_path)
104 finally:
105 injector.detach()
File /usr/lib/python3/dist-packages/pyinjector/pyinjector.py:87, in Injector.inject(self, library_path)
85 assert os.path.isfile(library_path), f'Library not found at "{library_path.decode()}"'
86 handle = c_void_p()
---> 87 call_c_func(libinjector.injector_inject, self.injector_p, library_path, pointer(handle))
88 return handle.value
File /usr/lib/python3/dist-packages/pyinjector/pyinjector.py:66, in call_c_func(func, exception_map, *args)
64 exception_map = {} if exception_map is None else exception_map
65 exception_cls = exception_map.get(ret, InjectorError)
---> 66 raise exception_cls(func.__name__, ret, libinjector.injector_error())
InjectorError: injector_inject returned -5: dlopen failed
Trying to load the lib (saved from /tmp) directly (am i doing this right 😅 ) from ipython3
does not work, too:
In [1]: import ctypes
In [2]: ctypes.CDLL?
In [3]: ctypes.CDLL('/tmp/hypno61cl3r9b.so')
---------------------------------------------------------------------------
OSError Traceback (most recent call last)
Cell In [3], line 1
----> 1 ctypes.CDLL('/tmp/hypno61cl3r9b.so')
File /usr/lib/python3.11/ctypes/__init__.py:376, in CDLL.__init__(self, name, mode, handle, use_errno, use_last_error, winmode)
373 self._FuncPtr = _FuncPtr
375 if handle is None:
--> 376 self._handle = _dlopen(self._name, mode)
377 else:
378 self._handle = handle
OSError: /tmp/hypno61cl3r9b.so: failed to map segment from shared object
This is on debian unstable with packages created using stdeb:
ii python3-hypno 1.0.0-1 amd64 A tool/library allowing to inject python code into a running
ii python3-madbg 1.3.1-1 all A fully-featured remote debugger for python
ii python3-pyinjector 1.1.1-1 amd64 A tool/library allowing dynamic library injection into runni
I had to disable some tests to get it to build, maybe that's part of the problem...?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.