Is there anything similar to the OS X InputManager on Windows? - windows

Is there anything similar on Windows what would achieve the same as the InputManager on OS X?

If you are looking to inject code into processes (which is what Input Managers are most commonly used for), the Windows equivalents are:
AppInit_DLLs to automatically load your DLL into new processes,
CreateRemoteThread to start a new thread in a particular existing process, and
SetWindowsHookEx to allow the capture of window events (keyboard, mouse, window creating, drawing, etc).
All of these methods require a DLL which will be injected into the remote process. C would be the best language to write such a DLL in as such a DLL needs to be quite light weight as to not bog the system down. RPC methods such as named pipes can be used to communicate to a master process should this be required.
Googling for these three APIs will turn up general sample code for these methods.

I'm pretty sure Windows has an API that developers can use to create new kinds of text input systems. I gather there are a wide variety of text input systems in use in non-Roman-derived markets, many of which are provided by third parties.
It's unclear if that's what you were really asking about, though, because you just assumed everyone knows what you would want to use an Input Manager for on Mac OS X.
If you want to create a new type of input method, ask how to do that.
If you want to get your own code running inside other applications, ask how to do that.
Don't just assume people can read your mind when asking questions, and don't assume that they have the same experience that you do and will recognize all the same platform-specific terminology.

Related

minifilter vs. API Hooking for file system operations monitoring \ filtering

I need to develop an application that monitors, and potentially filters (rejects the calls), file operations.
It appears that developing a minifilter is the "standard" solution.
another potential method is using API hooks.
are these relevant solutions? (I read in some places the an API hook may not be suitable - but no explanation was given)
are there other options?
API hooking (at least in kernel space) is essentially not supported by microsoft. On x64 (starting from Vista and up) patchguard will usually kill the machine if it detects SSDT hooking or any change whatsoever in critical components of the system. API hooking is very hard to get on a system-wide level because the synchronization primitives that windows uses are not exported so even if you manage to hook the code there is not guarantee that the machine won't crash due to a funky value of EIP at a given moment (this is especially valid when you are unloading a driver that has hooked a function).
Probably your best bet to do it - without using minifilter driver is to try and to direct memory kernel object hooking. You might want to look at OBJECT_TYPE_INITIALIZER definition structure which every object windows has (FILE, EVENT, PORT etc - google around to see them) has as its member. You are particularly interested in the *Procedure function pointers.
It all comes down to what you want/need to accomplish.
If you just need file operations (in the kernel level, file open / file close), and you need it system-wide than I would go with minifilter. It is a long, tedious and time-consuming road, but safer (check out Sysinternals procmon to see what you can get using this method).
If you need a more application-specific control, or if you would like control over the WINAPI level, go with API hooking. It is easier to develop, but there are lots of "mines" that blow up in your face during the way (check out EasyHook, its doing a pretty good job with minimum work).
good luck!
If you are preventing user access to certain resources (files) from a security perspective the correct way is a minifilter. This is because it's the only way you are sure that the user cannot access the filtered resources.
If you use API hook you can intercept calls at kernel32.dll (CreateFileW, FindFirstFile, etc., etc.) but an attacker can uses Native API (ntdll.dl). Of course, you can intercept at Native level (it's more difficult since it's undocumented) but attackers can use differents APIs at kernel switch level. At that level it's not portable to hook. It's almost impossible to prevent creative attackers to access to resources using API hook, that's why it's not recommended for security software.
In my opinion, API hooking is a good option for monitoring. If you want to see what an application is doing, it's very good to use API hook since you can intercept higher level functions than in kernel-mode.
If you can accomplish the task without the hooks - do it. Because hooking is not a supported way of developing applications. There is a lot of pitfalls and antivirus software will treat your application as more dangerous. Also you may face problems with newer/older versions of operating system.
But take into consideration that user-mode code is much easier then kernel-mode. So if user-mode hooks can satisfy your requirements then you may think about them.
I got a follow up question by mail, so i'm adding here the solution we used
The project was canceled before it wen't live, but we evaluated a product (Eldos CallbackFilter) that allows writing kernel filters using user space code.
The product has a generic kernel driver that communicates with user space code that defines the filtering logic.
I would have to contradict LordDoskias as, OBJECT_TYPE_INITIALIZER is not a documented object and this can, has and will change with OS patches and updates.
Do not approach this problem this was as it will only cause more problems and not solve anything.
Not to mention the patch guard which will BSOD the system if you modify system structures.
If you want to restrict access to files there is no way around it than simply using a minifilter. There are several Microsoft samples here that you can draw inspiration from and also learn to implement your driver the correct and supported way.
Lastly and more importantly it is illusory to think that you will be able to block everything you want by hooking techniques and I will just give you one example: mapped files.
Here is a scenario involving notepad which uses mapped files to write it's data to disk.
CreateFile -> obtains file handle -> you see this
CreateFileMapping -> obtains mapping handle -> you don't see this
CloseHandle(FileHandle) -> you see this
MapViewOfFile returning a memory buffer being page backed by the file -> you don't see this
Modify the memory buffer -> you don't see this
Unmap and close the FileMappingHandle -> you don't see this
Async the memory manager's system worker threads make paging writes to the file to keep it in sync. Even after all the handles have been closed or during the in-memory change of the buffer, depending when the OS wants. -> you don't see this
This is what you are missing with hooking. And this is just one scenario. There is a multitude of them, so please do things the right way.
How would that change if you use a minifilter ?
You would of course catch the CreateFile, CreateFileMapping as well ( check FltAcquireForSectionSynchronization callback) and then from the minifilter you will see all the PAGING_WRITE coming from the memory manager (see IoGetTopLevelIrp()) in your Write dispatch callback.
Good luck further.

Guidance : I want to work at Process Information level

I couldn't find a suitable title for this. I'm going to express my query with examples.
Consider following softwares:
Process explorer from sysinternals (an advanced task manager)
Resource Manager : resmon.exe (lists each and every fine detail about resource usage about each process).
For me these softwares seems like miracles. I wonder how these are even made. C'mon how a user process can know such fine details about other processes? Who tells this software, what processes are running and what all resources are utilized? Which dlls are used? etc..
Does windows operating system give these software that information? I mean though (obviously the most lower level api) WIN32API. Are there some functions,which on calling return these values
abstractly say:
GetAllRunningProcesses()
GetMemoryUsedByProcess(Process* proc)
etc..
Other similar applications are
network Packet Capture software. How does it get information about all those packets? It clearly sits just infront of the NIC card. How is it possible?
Anti-virus: It scans memory for viruses. Intercepts other processes. Acts like a sandbox for the user application space. How? How??
If its WIN32API. I swear, I'm going to master it.
I don't want to create a multi-threaded application. I want to get information about other multithreaded applications.
I don't want to create a program which communicates using sockets. I want to learn how to learn how to capture all communication packets.
I actually want to work at the lower level. But I don't know, what should I learn. Please guide me in proper direction.
This is really a pretty open-ended question. For things like a list of running processes, look up "PSAPI" or "Toolhelp32". For memory information about a particular process, you can use VirtualQuery.
Capturing network packets is normally done by installing a device driver. If you look, you should be able to find a fair amount about how to write device drivers, though don't expect to create wonders overnight, and do expect to crash your machine a few times in the process (device drivers run in kernel mode, so it's easy for a mistake to crash the machine hard).
I can't say as much with any certainty about anti-virus, because I've never tried to write one. My immediate guess would be that their primary technique is API hooking. There's probably more to it than that, but offhand I've never spent enough time looking at them to know what.
Mark Russinovich's classic, Windows Internals, is the go-to book if you want to get deep in this kind of stuff. I notice that the just-released 5th edition includes Vista. Here's a sample chapter to peek at.
If you like Process Explorer, this is the guy who wrote that, and there are lots of examples using it in the book.
Plus, at 1232 hardcover pages, you can use it to press your clothes.

Call another program's functions?

So I have this program that I really like, and it doesn't support Applescript. I'd like to automate it a little bit. Now, I know that I could use applescript to tell the program to tell the menu to tell the submenu to tell the menuitem to activate or whatever, but frankly I don't like applescript very much anyway.
When I open the NIB file in IB, I can see the messages that are being sent to FirstResponder; for example, the Copy menu item sends "copy:". Is there any way for me to invoke this directly from another program?
No. It's called protected memory for a reason, you know. The other program is completely insulated from your application. There are ways to put code into other apps, but (a) it's very inadvisable (b) requires root privileges, which means the rest of your app needs to be ROCK SOLID AND IMPREGNABLE, and (c) writing such code is a black art requiring knowledge of the operating system kernel interfaces, virtual memory management, the ABI, the internals of the linker/loader, assembler programming, and the operational parameters and other specifics of the particular processor upon which your app happens to be running.
Really, AppleEvents and other such IPC mechanisms are there for a reason.
Your other alternatives (all of which are a bit hacky, to be honest, and give you the fairly significant burden of ensuring the target app is in the state you want/expect) the access the data you're looking for are:
The Accessibility APIs from the ApplicationServices framework, through which you can traverse the UI tree to grab the text from wherever you need it directly, or can activate the menu item. Access for your app has to be explicitly granted by the user, however (although this is much the same as the requirement for UI scripting).
You can use the CoreGraphics APIs (within the ApplicationServices framework again) to send keyboard events to the target application (or just to the system) directly. This would mean sending four events: Command-down, C-down, C-up, Command-up.
None of these are ideal. To be honest, your best approach would be to look at your requirements and figure out how you can best engineer around the problem by changing those requirements in some way, i.e. instead of grabbing something directly, ask the user to provide some input, etc.
You might be interested in SIMBL or in mach_inject. SIMBL is a daemon (in my fork based on mach_inject, in the original version based on injection via some ScriptingAdditions hack) which does the injection for you, so you just need to put a bundle with your code into the SIMBL directory and SIMBL will inject it for you into the target application. Or you can do so yourself via mach_inject. Or probably more convenient, mach_inject_framework which injects and runs code which just loads some framework.
I think Jim may overstate the point a bit; he's not wrong, but it seems misleading. There are lots of ways to cause a Cocoa program to execute its own code under you control (Carbon is harder). The Accessibility API is very commonly used this way (so commonly that I expect it to be repurposed eventually). Fscript can give you all kinds of access to the innards of another Cocoa program. While Input Managers may well exit the scene at some point, SIMBL is still out there today to do this kind of stuff.
Whether you like Applescript or not, Apple Events are the primary way Apple provides for inter-program control. Have you double-checked Script Editor's Open Library function to find out if the program really does have any Applescript support? You can code Apple Events entirely in Objective-C these days using Leopard's Scripting Bridge. I wrote up a tutorial if you like (it's still under-documented by Apple).
Cocoa is a reverse-engineer's dream. The same guys who host SIMBL have a nice intro to the subject. "Wolf" also writes a lot of useful information on this.
Jim's right. Many of these approaches can completely destabilize the system if done incorrectly (sometimes even if done correctly). I don't do much of this stuff on my production systems; I need them to work. But there are a lot of things you can make a Mac app do, and it's a good part of a Mac developer's training to understand how all the pieces really work.

Best way to inject functionality into a binary

What would be the best way of inserting functionality into a binary application (3d party, closed source).
The target application is on OSX and seems to have been compiled using gcc 3+. I can see the listing of functions implemented in the binary and have debugged and isolated one particular function which I would like to remotely call.
Specifically, I would like to call this function - let's call it void zoomByFactor(x,y) - when I receive certain data from a complex HIDevice.
I can easily modify or inject instructions into the binary file itself (ie. the patching does not need to occur only in RAM).
What would you recommend as a way of "nicely" doing this?
Edit:
I do indeed need to entire application. So I can't ditch it and use a library. (For those who need an ethical explanation: this is a proprietary piece of CAD software whose company website hasn't been updated since 2006. I have paid for this product (quite a lot of money for what it is, really) and have project data which I can not easily migrate away from it. The product suits me just fine as it is, but I want to use a new HID which I recently got. I've examined the internals of the application, and I'm fairly confident that I can call the correct function with the relevant data and get it to work properly).
Here's what I've done so far, and it is quite gheto.
I've already modified parts of the application through this process:
xxd -g 0 binary > binary.hex
cat binary.hex | awk 'substitute work' > modified.hex
xxd -r modified.hex > newbinary
chmod 777 newbinary
I'm doing this kind of jumping through hoops because the binary is almost 100 megs large.
The jist of what I'm thinking is that I'd jmp somewhere in the main application loop, launch a thread, and return to the main function.
Now, the questions are: where can I insert the new code? do I need to modify symbol tables? alternatively, how could I make a dylib load automatically so that the only "hacking" I need to do is inserting a call to a normally loaded dylib into the main function?
For those interested in what I've ended up doing, here's a summary:
I've looked at several possibilities. They fall into runtime patching, and static binary file patching.
As far as file patching is concerned, I essentially tried two approaches:
modifying the assembly in the code
segments (__TEXT) of the binary.
modifying the load commands in the
mach header.
The first method requires there to be free space, or methods you can overwrite. It also suffers from extremely poor maintainability. Any new binaries will require hand patching them once again, especially if their source code has even slightly changed.
The second method was to try and add a LC_ LOAD_ DYLIB entry into the mach header. There aren't many mach-o editors out there, so it's hairy, but I actually modified the structures so that my entry was visible by otool -l. However, this didn't actually work as there was a dyld: bad external relocation length at runtime. I'm assuming I need to muck around with import tables etc. And this is way too much effort to get right without an editor.
Second path was to inject code at runtime. There isn't much out there to do this. Even for apps you have control over (ie. a child application you launch). Maybe there's a way to fork() and get the initialization process launched, but I never go that.
There is SIMBL, but this requires your app to be Cocoa because SIMBL will pose as a system wide InputManager and selectively load bundles. I dismissed this because my app was not Cocoa, and besides, I dislike system wide stuff.
Next up was mach_ inject and the mach_star project. There is also a newer project called
PlugSuit hosted at google which seems to be nothing more than a thin wrapper around mach_inject.
Mach_inject provides an API to do what the name implies. I did find a problem in the code though. On 10.5.4, the mmap method in the mach_inject.c file requires there to be a MAP_ SHARED or'd with the MAP_READ or else the mmap will fail.
Aside from that, the whole thing actually works as advertised. I ended up using mach_ inject_ bundle to do what I had intended to do with the static addition of a DYLIB to the mach header: namely launching a new thread on module init that does its dirty business.
Anyways, I've made this a wiki. Feel free to add, correct or update information. There's practically no information available on this kind of work on OSX. The more info, the better.
In MacOS X releases prior to 10.5 you'd do this using an Input Manager extension. Input Manager was intended to handle things like input for non-roman languages, where the extension could popup a window to input the appropriate glyphs and then pass the completed text to the app. The application only needed to make sure it was Unicode-clean, and didn't have to worry about the exact details of every language and region.
Input Manager was wildly abused to patch all sorts of unrelated functionality into applications, and often destabilized the app. It was also becoming an attack vector for trojans, such as "Oompa-Loompa". MacOS 10.5 tightens restrictions on Input Managers: it won't run them in a process owned by root or wheel, nor in a process which has modified its uid. Most significantly, 10.5 won't load an Input Manager into a 64 bit process and has indicated that even 32 bit use is unsupported and will be removed in a future release.
So if you can live with the restrictions, an Input Manager can do what you want. Future MacOS releases will almost certainly introduce another (safer, more limited) way to do this, as the functionality really is needed for language input support.
I believe you could also use the DYLD_INSERT_LIBRARIES method.
This post is also related to what you were trying to do;
I recently took a stab at injection/overriding using the mach_star sources. I ended up writing a tutorial for it since documentation for this stuff is always so sketchy and often out of date.
http://soundly.me/osx-injection-override-tutorial-hello-world/
Interesting problem. If I understand you correctly, you'd like to add the ability to remotely call functions in a running executable.
If you don't really need the whole application, you might be able to strip out the main function and turn it into a library file that you can link against. It'll be up to you to figure out how to make sure all the required initialization occurs.
Another approach could be to act like a virus. Inject a function that handles the remote calls, probably in another thread. You'll need to launch this thread by injecting some code into the main function, or wherever else is appropriate. Most likely you'll run into major issues with initialization, thread safety, and/or maintaining proper program state.
The best option, if its available, is to get the vendor of your application to expose a plugin API that lets you do this cleanly and reliably in a supported manner.
If you go with either hack-the-binary route, it'll be time consuming and brittle, but you'll learn a lot in the process.
On Windows, this is simple to do, is actually very widely done and is known as DLL/code injection.
There is a commercial SDK for OSX which allows doing this: Application Enhancer (free for non-commercial use).

Is it possible to list named events in Windows?

I would like to create events for certain resources that are used across various processes and access these events by name. The problem seems to be that the names of the events must be known to all applications referring to them.
Is there maybe a way to get a list of names events in the system?
I am aware that I might use some standard names, but it seems rather inflexible with regard to future extensibility (all application would require a recompile).
I'm afraid, I can't even consider ZwOpenDirectoryObject, because it is described as needing Windows XP or higher, so it is out of question. Thanks for the suggestion though.
I am a little unsure about shared memory, because I haven't tried it so far. Might do some reading in that area I guess. Configuration files and registry are a slight problem, because they do tend to fail with Vista due to access problems. I am a bit afraid, that shared memory will have the same problem.
The idea with ProcessExplorer sounds promising. Does anyone know an API that could be used for listing events for a process? And, does it work without administrative rights?
Thank you for the clarification.
There is not really a master process. It is more of a driver dll that is used from different processes and the events would be used to "lock" resources used by these processes.
I am thinking about setting up a central service that has sufficient access rights even under Vista. It will certainly complicate things, but it might be the only thing left facing the problems with security.
No, there is not any facility to enumerate named events. You could enumerate all objects in the respective object manager directory using ZwOpenDirectoryObject and then filter for events. But this routine is undocumented and therefore should not be used without good reason.
Why not use a separate mechanism to share the event names? You could list them in a configuration file, a registry key or maybe even in shared memory.
Do not mix up the user mode ZwOpenDirectoryObject with the kernel mode ZwOpenDirectoryObject -- the kernel mode API (http://msdn.microsoft.com/en-us/library/ms800966.aspx) indeed seems to available as of XP only, but the user mode version should be available at least since NT 4. Anyway, I would not recommend using ZwOpenDirectoryObject.
Why should configuration files and registry keys fail on Vista? Of course, you have to get the security settings right -- but you would have to do that for your named events as well -- so there should not be a big difference here. Maybe you should tell us some more details about the nature of your processes -- do they all run within the same logon session or do they run as different users even? And is there some master process or who creates the events in the first place?
Frankly, I tend to find the Process Explorer idea to be not a very good one. Despite the fact that you probably will not be able to accomplish that without using undocumented APIs and/or a device driver, I do not think that a process should be spelunking around in the handle table of another process just to find out the names of some kernel objects. And, of course, the same security issues apply again.
ProcessExplorer is able to enumerate all the named events held by some specific process. You could go over the entire process list and do something similar although I have now clue as to what API is used to get the list...

Resources