How to launch an executable from memory? - macos

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.

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!

Related

Can WriteProcessMemory fail but report that it didn't?

I'm trying to use Rust's Windows WriteProcessMemory in a project of mine in order to replicate the process hollowing technique. Although I use it in nearly exactly the same way in another place in the project, I'm having trouble getting this one to work. It looks to me like the whole buffer isn't getting copied to the location I enter, and/or the u8 integers are being squished into u64s when written.
The WriteProcessMemory call returns BOOL(1), which evaluates to true, and makes me think it is running successfully. If I provide the lpnumberofbyteswritten variable, it comes back as the same size as the shellcode buffer I intended to write. But the memory doesn't look right if I read it after writing, and the shellcode doesn't run properly (whereas in the other place in my project it does). Have I made a silly mistake? If so, does anyone see where?
Thank you!

Is there any way to determine if a program uses a specific Windows API functions?

Ok, it may be a bit difficult to explain:
Suppose someone creates a Windows application (using C# or any other language) that uses the GetDesktopWindow() function on the user32.dll to capture a Screenshot and then sends this image to any online service.
Since it's custom made application, no anti-virus software will be able to determine that it's a virus because it's still an unknown application for it. Also, there are legitimate uses for such API, so it's not necessarily a virus, it can be a harmless window capture tool or some kind of espionage tool.
What I want to know is: Is there any way to see what a specific EXE file does regarding the Windows functions? Can I know if "myapp.exe" uses GetDesktopWindow() of user32.dll?
This is only one example. There are plenty other Windows endpoints that I would like to know when they're used by any application.
Is there a way to do that?
It depends to what lengths you want to go doing that. It's essentially a game of cat and mouse - bad actors will attempt to find new ways to circumvent your detection by jumping through some obscure hoops, you will add more sophisticated detection methods for those tricks, they will think of new tricks, and so on.
Also, it depends on whether you want to statically or dynamically determine that, and whether you actually want to know if GetDesktopWindow is called or if "the program gets a handle to the desktop window" (which can be achieved in other ways as well).
Here is a non-exhaustive list of ideas:
You could statically determine whether the function is imported by looking at the import directory. Research the PE file structure to find out more. This article may help.
This method of detection can be easily circumvented by dynamically importing the function using LoadLibrary and GetProcAddress.
You could scan the file for the string GetDesktopWindow to detect possible usage for dynamic import.
This method of detection can be easily circumvented by packing, encrypting or otherwise obfuscating the name of the dynamically imported function.
You could dynamically observe whether the GetDesktopWindow function gets called by registering an AppInit_DLL or a global hook which is injected into every new process and hook the GetDesktopWindow function from inside the process by overwriting its first bytes with a jump to your own code, notifying your detection component somehow, executing the original bytes and jumping back. (Microsoft Detours can help there.)
This method of detection can be circumvented if the target notices the hook and removes it before calling, since its in its own process space. (You could also do some tricks with acting like a debugger and setting a hardware breakpoint on the first instruction of GetDesktopWindow, but yet again there would be ways to detect or circumvent that since the target could also modify the debug registers.)
You could build a driver that does this from kernel-mode instead, but now we are getting really deep.
Note that until now we focused on the actual GetDesktopWindow function from user32.dll. But what if the target will just use a different way to achieve its goal of getting a desktop window handle?
The desktop window handle for the current thread is stored in the TIB (thread information block) which is accessible via fs:[18] from user mode. You can see this in the GetDesktopWindow source code of ReactOS which is pretty accurate compared to Microsoft's actual implementation (which you can verify by looking at it in a debugger). The target could therefore just access the TIB and extract this value, without even calling GetDesktopWindow at all.
The target could just take a known top-level window such as the shell's hidden compatibility window which you'll get via GetShellWindow() or - to avoid detection of GetShellWindow too - for example FindWindow(NULL, "Program Manager") (or even a newly created window!) and call GetAncestor(hWnd, GA_PARENT) on it to get the desktop window handle.
I'm sure, with some creativity, your adversaries will come up with more clever ideas than these.
Also, if we take this one step further and take a look at the ultimate goal of taking a screenshot, there as well exist other ways to achieve that. First example coming to mind: They could use keybd_event to emulate pressing the PrnSc key and then read the screenshot out of the clipboard data.
So it's all a matter of how far you want to take this.
By the way, you may find the drltrace project interesting - it is a library call tracer.

Windows: redirect ReadFile to run process and pipe it's stdout

I was wondering how hard it would be to create a set-up under Windows where a regular ReadFile on certain files is being redirected by the file system to actually run (e.g. ShellExecute) those files, and then the new process' stdout is being used as the file content streamed out to the ReadFile call to the callee...
What I envision the set-up to look like, is that you can configure it to denote a certain folder as 'special', and that this extra functionality is then only available on that folder's content (so it doesn't need to be disk-wide). It might be accessible under a new drive letter, or a path parallel to the source folder; the location it is hooked up to is irrelevant to me.
To those of you that wonder if this is a classic xy problem: it might very well be ;) It's just that this idea has intrigued me, and I want to know what possibilities there are. In my particular case I want to employ it to #include content in my C++ code base, where the actual content included is being made up on the spot, different on each compile round. I could of course also create a script to create such content to include, call it as a pre-build step and leave it at that, but why choose the easy route.
Maybe there are already ready-made solutions for this? I did an extensive Google search for it, but came out empty handed. But then I'm not sure I already know all the keywords involved to do a good search...
When coding up something myself, I think a minifilter driver might be needed intercepting ReadFile calls, but then it must at that spot run usermode apps from kernel space - not a happy marriage I assume. Or use an existing file system driver framework that allows for usermode parts, but I found the price of existing solutions to be too steep for my taste (several thousand dollars).
And I also assume that a standard file system (minifilter) driver might be required to return a consistent file size for such files, although the actual data size returned through ReadFile would of course differ on each call. Not to mention negating any buffering that takes place.
All in all I think that a create-it-yourself solution will take quite some effort, especially when you have never done Windows driver development in your life :) Although I see myself quite capable of learning up on it, the time invested will be prohibitive I think.
Another approach might be to hook ReadFile calls from the process doing the ReadFile - via IAT hooking, or via code injection. But I want this solution to more work 'out-of-the-box', i.e. all ReadFile requests for these special files trigger the correct behavior, regardless of origin. In my case I'd need to intercept my C++ compiler (G++) behavior, but that one is called on the fly by the IDE, so I see no easy way to detect it's startup and hook it up quickly before it does it's ReadFiles. And besides, I only want certain files to be special in this regard; intercepting all ReadFiles for a certain process is overkill.
You want something like FUSE (which I used with profit many times), but for Windows. Apparently there's Dokan, I've never used it but seems to be well known enough (and, at very least, can be used as an inspiration to see "how it's done").

Can I obtain a task in KEXT?

Just wondering if it is possible to obtain a task for a given proc_t inside a kext.
I have tried task_for_pid() which didn't work for some reason that I don't remember.
I tried proc_task(proc_t p) from sys/proc.h but I can't load my kext since that function is not exported.
I guess that I'm doing something wrong but I can't quite figure out what. Assuming I can get the task for a process, I'd like to use some mach calls and allocate memory, write memory and whatnot but for that, I would need the task I believe.
After some research it would appear that it's not the case.
There is proc_task() defined in proc.h but it's under the #ifdef KERNEL_PRIVATE. The KEXT will compile albeit the warning.
In order to use that function, you have to add the com.apple.kpi.private in the list of dependencies but even that will fail since you are most likely NOT Apple :)
Only Apple kexts may link against com.apple.kpi.private.
Anyway, the experiment was interesting in the sense that other APIs such as vm_read, vm_write etc. are not available to use inside a KEXT (which probably makes sense since they are declared in a vm_user.h and I suppose are reserved for user mode).
I'm not aware of a public direct proc_t->task_t lookup KPI, unfortunately.
However, in some cases, you might be able to get away with using current_task() and holding on to that pointer for as long as you need it. Use task_reference and task_deallocate for reference counting (but don't hold references forever obviously, otherwise they'll never be freed). You can also access the kernel's task (corresponding to process 0) anytime via the global variable kernel_task.

Get Function memory address

I have foo.exe which is using some of Windows API functions. I want to get memory addresses of those functions, how do I do that? Any software available which I can use?
Note, that I am looking for non-programatically way of doing that.
Thanks
I am looking for non-programatically way of doing that.
Either this is not possible or it doesn't make any sense. Likely both.
You see, in order to call one of the Windows API functions, a program must import it from the DLL that contains the function of interest. This requires that DLL to be loaded into the address space of that program's process. And because each process has its own address space, each process gets its own unique instance (or copy) of the DLL. That means that the "memory address" of functions provided by DLLs is going to be different in each process.
Retrieving this information non-programmatically just doesn't make sense. Even if you could get it, it wouldn't do you any good.
I could probably provide better advice if you edited your question to explain what you're hoping to accomplish, rather than just asking about the approach you already settled upon.
The addresses of exported functions can be different for every process that loads the DLL. The GetProcAddress function can tell you what they are for your process.

Resources