2

Anyone knows anything about running executable from memory in OSX? anything like this:

char *exeFile[size];
loadFromFile(exeFile, "/path/to/data");
execute(exeFile);

I want do that for security reasons. for example It is possible to encrypt exe and decrypt it before launch.

mh taqia
  • 3,506
  • 1
  • 24
  • 35
  • That isn't possible AFAIK; you can use the `exec()` family of calls (after a `fork()` of course) but you cannot encrypt the executable. – trojanfoe Aug 01 '12 at 08:16
  • It is possible, the UPX exe compressor do that, decompress binary data and execute it. – mh taqia Aug 01 '12 at 08:26
  • That is code inside the executable itself; not something the parent process does while loading the executable. – trojanfoe Aug 01 '12 at 08:30
  • Well, how can execute memory inside the executable itself? (I load target executable into memory). – mh taqia Aug 01 '12 at 08:51
  • Loading an executable is more than just loading it into memory, as you would with plain data; the executable requires relocating and numerous other things before it will work. You cannot do what you want to do other than decrypting your file to a temporary file, `exec`ing that file and then deleting it. – trojanfoe Aug 01 '12 at 08:55
  • This is prevalent task in Windows platform, like: http://stackoverflow.com/questions/6395493/execute-an-exe-file-from-resource-into-memory – mh taqia Aug 01 '12 at 10:44

1 Answers1

4

Well, yes, you can do it but its complex. I don't have access to working code right now but I do know others that are/have used it. The key is "NSCreateObjectFileImageFromMemory()", which is deprecated, but that said a few big apps like Skype reputed use it so its probably not going to disappear anytime soon (YMMV).

You have to allocate a memory buffer that's a multiple of the pagesize with vm_allocate. Copy the mach-o executable of the same architecture as the current process to there. Call NSCreateObjectFileImageFromMemory() which returns an object image. Then call successively NSLinkModule, NSLookupSymbolInModule and NSAddressOfSymbol. That last one gets you an actual function pointer to call.

This should give you most of what you need to know, and if you search you may find code that does it too. Good luck!

David H
  • 40,852
  • 12
  • 92
  • 138