I've seen a few sites talking about injecting DLL's (such as http://www.codeproject.com/KB/DLL/DLL_Injection_tutorial.aspx), but I'm struggling with how to get an EXE to work. any help/tips would be appreciated.
The best way I know how to explain it is "RunPE" where you execute an exe in the memory. Does that help at all?
If you're asking how to inject code into a running Python process, what you want is https://github.com/lmacken/pyrasite .
You can use the Reflective DLL Injector as described here. Metasploit project uses it to load its meterpreter plug-ins. AFAIK this is the only way to inject a DLL, as MS officially does not support "injecting" from memory, only loading from file system.
On a low level, nothing forbids you from allocating a memory region, loading code there, marking it executable.
Note, that none of these techniques are Python specific or even Python related - it is a win32 problem.
What you're talking about is re-implementing UPX in python with more stuff.
Things you would need to do in order to do this:
Change all VirtualAlloc calls to be VirtualAllocEx calls.
Change all Loadlibrary calls to be loadlibraryEX calls.
Implement the relocation fix-ups.
A better approach would probably be tweaking UPX to output a DLL instead of an executable. Then using some python DLL injection code to throw that into another process. You're going to be working with CTypes a lot if you want to do this. Fair warning...
I would recommend this book http://www.amazon.com/Gray-Hat-Python-Programming-Engineers/dp/1593271921 - especially the chapters on writing your own debugger, but it covers the metasploit and other tools as described above.
To inject a shared object (.so, .dll) into any process you can use injector with C, or pyinjector with python/shell.
To inject python code into a running python process, you can use hypno.
Related
I've to ask 1 question about python and dll functions which I'm a bit frustrated about. The question is - Can I load dll functions from windows using python? I heard of Ctype to do that, but I can’t find good tutorials for this. Is there another way to use dll files from windows to get extra functionality?
I want to call some dll to work with mouse events. I used pyautogui but it is not that useful for me. I wonder if python is good for windows applications? I know it runs on Windows however there are good dll function that can provide better functionality for windows then python original libraries. Well that’s my opinion what I think. Anyways, is it worth to work with dlls with python after all? Or I better study C# for that because I love python for simplicity and don’t want to move to C# yet.
Yes you can. The ctypes library is indeed what you need. The official doc is here https://docs.python.org/3/library/ctypes.html .
Loading DLLs pretty straightforward, but calling the functions inside can be a pain depending on the arguments types. Handling old C style error return codes is also cumbersome compared to the exception handling and general low overhead code style in Python.
99% of the time it is way easier and better to use an appropriate existing module that either implements what you need or wraps the appropriate DLL for you. For example search in PyPI which is the central repository of Python expternal modules. That's my advice.
I have a directory with several python modules in it. Each module is mutually exclusive of all the others but after lots of trial and error, I have decided that each module horks out when using the multiprocessing functionality in Python. I have used the join() function on each process and its just not working like I want.
What I am really looking for is the ability to drop new mutually exclusive python modules in to the directory and have them invoked when the directory is launched. Does anyone know how to do this?
It sounds to me like you are asking about plugin architecture and sandboxing. Does that sound right?
The plugin component has been done and written about else where. SO has code examples on basic ways to import all the files.
The sandbox part is going to be a harder. Have a look at RestrictedPython and the Restricted Execution docs and the generally older but nevertheless helpful discussion of sandboxing.
If you aren't worried about untrusted code but rather want to isolate errors you could just wrap each module in a generic try/except that handles all errors. This would make debugging hard but would ensure that an error in one module didn't bring down the whole system.
If you aren't worried about untrused code but do need to have each file totally isolated then you might be best off looking into various systems of interprocess communication. I've actually had some luck using Redis for this (which sounds ridiculous but actually has been very easy and effective).
Anyway hopefully some of that helps you. Without more information it's hard to provide more than general thoughts and a guide to better googling.
Is there a way to limit the abilities of python scripts running under an embedded interpretor? Specifically I wish to prevent the scripts from doing things like the following:
Importing python extension modules (ie .pyd modules), except those specifically allowed by the application.
Manipulating processes in any way (ie starting new processes, or terminating the application).
Any kind of networking.
Manipulating the file system (eg creating, modifying and deleting files).
No. There's no easy way to prevent those things on CPython. Your options are:
Edit CPython source code and remove things you don't want - provide mocking methods for all those things. Very error-prone and hard to do. This is the approach of Google's App Engine.
Use Restricted Python. However, with it you can't prevent your user from exhausting the memory available or running infinite eat-all-cpu loops.
Use another python implementation. PyPy has a sandbox mode you can use. Jython runs under java and I guess java can be sandboxed.
Maybe this can be helpful. You have an example provided on how to work with the ast.
What you want it Google's Unladen Swallow project that Python version of App Engine runs on.
Modules are severely restricted, ctypes are not allowed, sockets are matched against some policy or other, in other words you get a sandboxed version of Python, in line with their Java offering.
I'd like to point out that this makes the system almost useless. Well useless for anything cooler than yet another [App Engine] App. Forget monkey-patching system modules, and even access to own stack is restricted. Totally un-dynamic-like.
OT: games typically embed LUA for scripting, perhaps you should check it out.
I'm trying to create a python script that will disassemble a binary (a Windows exe to be precise) and analyze its code.
I need the ability to take a certain buffer, and extract some sort of struct containing information about the instructions in it.
I've worked with libdisasm in C before, and I found it's interface quite intuitive and comfortable.
The problem is, its Python interface is available only through SWIG, and I can't get it to compile properly under Windows.
At the availability aspect, diStorm provides a nice out-of-the-box interface, but it provides only the Mnemonic of each instruction, and not a binary struct with enumerations defining instruction type and what not.
This is quite uncomfortable for my purpose, and will require a lot of what I see as spent time wrapping the interface to make it fit my needs.
I've also looked at BeaEngine, which does in fact provide the output I need, a struct with binary info concerning each instruction, but its interface is really odd and counter-intuitive, and it crashes pretty much instantly when provided with wrong arguments.
The CTypes sort of ultimate-death-to-your-python crashes.
So, I'd be happy to hear about other solutions, which are a little less time consuming than messing around with djgcc or mingw to make SWIGed libdisasm, or writing an OOP wrapper for diStorm.
If anyone has some guidance as to how to compile SWIGed libdisasm, or better yet, a compiled binary (pyd or dll+py), I'd love to hear/have it. :)
Thanks ahead.
Well, after much meddling around, I managed to compile SWIGed libdisasm!
Unfortunately, it seems to crash python on incorrect (and sometimes correct) usage.
How I did it:
I compiled libdisasm.lib using Visual Studio 6, the only thing you need for this is the source code in whichever libdisasm release you use, and stdint.h and inttypes.h (The Visual C++ compatible version, google it).
I SWIGed the given libdisasm_oop.i file with the following command line
swig -python -shadow -o x86disasm_wrap.c -outdir . libdisasm_oop.i
Used Cygwin to run ./configure in the libdisasm root dir. The only real thing you get from this is config.h
I then created a new DLL project, added x86disasm_wrap.c to it, added the c:\PythonXX\libs and c:\PythonXX\Include folders to the corresponding variables, set to Release configuration (important, either this or do #undef _DEBUG before including python.h).
Also, there is a chance you'll need to fix the path to config.h.
Compiled the DLL project, and named the output _x86disasm.dll.
Place that in the same folder as the SWIG generated x86disasm.py and you're done.
Any suggestions for other, less crashy disasm libs for python?
You might try using ctypes to interface directly with libdisasm instead of going through a SWIG layer. It may be take more development time but AFAIK you should be able to access the underlying functionality using ctypes.
I recommend you look at Pym's disassembly library which is also the backend for Pym's online disassembler.
You can use the distorm library: https://code.google.com/p/distorm/
Here's another build: http://breakingcode.wordpress.com/2009/08/31/using-distorm-with-python-2-6-and-python-3-x-revisited/
There's also BeaEngine: http://www.beaengine.org/
Here's a Windows installer for BeaEngine: http://breakingcode.wordpress.com/2012/04/08/quickpost-installer-for-beaenginepython/
Is there any other way to debug swig extensions except for doing
gdb python stuff.py
?
I have wrapped the legacy library libkdtree++ and followed all the swig related memory managemant points (borrowed ref vs. own ref, etc.). But still, I am not sure whether my binding is not eating up memory. It would be helpful to be able to just debug step by step each publicized function: starting from Python then going to via the C glue binding into C space, and returning back.
Is there already such a possibility?
gdb 7.0 supports python scripting. It might help you in this particular case.
Well, for debugging, you use a debugger ;-).
When debugging, it may be a good idea to configure Python with '--with-pydebug' and recompile. It does additional checks then.
If you are looking for memory leaks, there is a simple way:
Run your code over and over in a loop, and look for Python's memory consumption.