Register performance counter without lodctr - windows

I am looking for an approach to register to XML-based performance counters without using lodctr executable.
While this question and this question has given some insight to the problem, none gives a proper resolution.
The function LoadPerfCounterTextStrings seems to do the trick, but doesn't seem to take XML as input (i.e. /M argument for lodctr command). The function would anyway call the lodctr command but will save the programmer from calling lodctr.exe programmatically.
Is there an approach to call this function (or any other) that would behave as if:
lodctr.exe /M:xmlfile.xml
?
Just an additional information that LoadPerfCounterTextStrings is available in Windows XP, however, the new API (perflib 2) is available only after Vista. I am using V2.

I don't think it is possible, at least with a documented way. If you'd find and use some undocumented way, it may break with some OS/service pack or with future versions of Windows.
Best bet is you call LODCTR and UNLODCTR for installation/registration of performance counters within your process. Since these are command line tools, they would probably show up with a command (black) console window. You may hide with input/output redirection with pipes, so that console window doesn't appear.
Note that these tools don't take up much of time or resources, so calling these EXEs from your process won't take up much time (user won't notice, and even won't be able to easily figure out with some process monitoring tool).
Note that registering/unregistering PC is a rare activity - hence Microsoft won't bother to provide you a nice callable Windows API.

Related

Is there a more reliable Win32 syscall tracing method than procmon?

I'm building a Haskell command-line application in Windows 10, and am trying to debug an issue around the Windows 260-character file path limitation by tracing system calls and seeing which ones fail.
I've used procmon (https://learn.microsoft.com/en-us/sysinternals/downloads/procmon) for this, which seems quite nice, but although it displays many related log entries, I was surprised to find that it doesn't display an entry for the particular CreateFileW call that actually exceeds 260 chars and crashes my application.
I briefly tried Win32 API Monitor (https://www.apimonitor.com) but couldn't make heads or tails of it; it seems better suited to attaching to already-running GUI applications than command-line applications that need to be launched in a particular directory, etc.
Is there a better alternative to these, or a better approach?
#RemyLebeau's comment was the one I needed:
"I was surprised to find that it doesn't display an entry for the
particular CreateFileW call that actually exceeds 260 chars and
crashes my application"
Because there is nothing for it to log. The call likely gets rejected at the higher level API layer, when the input data is first
validated, long before it reaches the file system layer. Procmon logs
lower level activity, not higher level APIs. Tools like API Monitor
are what you are looking for. If you are having trouble with it, ask a
new question about that.
My eventual solution to the problem that inspired this was to upgrade from base-4.11 to base-4.12 which handles windows paths > 260 chars better.
I don't think I'd even need the registry switch anymore.

windows api - detect when file of certain type is opened

Is it possible to have certain code executed whenever a file of a certain type is opened? In my case, I want to "listen" for when video files (".avi, mp4, etc.") are opened (either via the windows file explorer shell, or maybe directly from a video player?), so that I can store a history of played videos.
An hour's worth of googling turned up nothing, so I turn to you stackoverflow. Please point me in the right direction.
Thanks.
The best (and only reasonable way) to capture file system events (open/read/write) from arbitrary processes is by writing a File System MiniFilter
If you're developing a commercial product, please refrain from "hooking" Usermode APIs like CreateFile. Doing so requires numerous, platform-specific hacks, and is a compatibility nightmare.
I wouldn't hook CreateFile for this job. Windows has mechanisms built-in to handle jobs like this much more cleanly.
The easy way to handle this would be with ReadDirectoryChangesW with the FILE_NOTIFY_CHANGE_LAST_ACCESS flag. Any time a file is opened, its last-access time will be updated, so this tells you any time the file was opened.
Although it's pretty rare, that can "miss" changes under rare circumstances1. If you must have 100% accuracy (instead of, say, 99.9%), you can read change journals instead, but it's a fair amount of extra work for an advantage you may not care about.
1. There is one circumstance that isn't (necessarily) rare that you might care about though: ReadDirectoryChangesW will only work when/if your program is running. Change journals will let you know about things that happened even when your code isn't running at all.

Windows Shutdown - Shutdown command or ExitWindowsEx

I want to know which is the best practice when a piece of software needs to restart, shutdown, logoff or hibernate Windows:
Use ExitWindowsEx API
Use Shutdown command and its parameters
What is the advantages and disadvantages of each approach?
Thanks
I always prefer calling the API (ExitWindowsEx, InitiateSystemShutdown).
Pro API
GetLastError can be used to diagnose errors
You get access to the full API, not just the things exposed by a utility
You don't have to worry about filesystem redirection and whether the tool exists in the home versions of Windows
The documented interface stays the same, command line switches could change or be different in a different language
Pro external tool
Makes some difficult tasks easy to perform (Some things require undocumented API's)
Few bugs, and if there are bugs they are not yours ;)
They are different.
Using API, you can apply more logic in your program, e.g. get the current state, etc.
Using the command, you can just perform the actions.

How to read some data from a Windows application memory?

I have an application, which displays me some data. I need to attach to this app's process, find the data I need in memory (one single number, actually), and save it somewhere. This application doesn't seem to use standard windows controls, so things aren't going to be as simple as reading controls data using AutoIt or something similar.
Currently I'm a self-learner database guy and have quite shallow knowledge about windows apps debugging. Not even sure if I asked my question correctly enough.
So, can you give me some starter guidelines about, say, what should I read first, and general directions I should work on?
Thanks.
To read memory of other application you need to open the process with respect of OpenProcess with at least PROCESS_VM_READ access rights and then use ReadProcessMemory to read any memory address from the process. If you are an administrator or have debug privilege you will be able to open any process with maximal access rights, you need only to enable SeDebugPrivilege before (see for example http://support.microsoft.com/kb/131065).
If you don't know a much about the memory of the destination process you can just enumerate the memory blocks with respect of VirtualQueryEx (see How does one use VirtualAllocEx do make room for a code cave? as an example where I examine the program code. The program data you can examine in the same way).
The most practical problem which I see is that you ask your question in too general way. If you explain more what kind of the data you are looking for I could probably suggest you a better way. For example if you could see the data somewhere you could examine the corresponding windows and controls with respect of Spy++ (a part of Visual Studio Tools). The most important are the class of windows (or controls) and the messages which will be send at the moment when the most interesting window are displayed. You can also use Process Monitor to trace all file and registry access at the time when the windows with the interesting information will be displayed. At least at the beginning you should examine the memory of the process with ReadProcessMemory at the moment when the data which you are looking for are displayed on the window.
If you will have no success in your investigations I'd recommend you to insert in your question more information.
My primary advice is: try to find any other method of integration than this. Even if you succeed, you'll be hostage to any kinds of changes in the target process, and possibly in the Windows O/S. What you are describing is behaviour most virus scanners should flag and hinder: if not now, then in the future.
That said, you can take a look at DLL injection. However, it sounds as if you're going to have to debug the heck out of the target process at the disassembly level: otherwise, how are you going to know what memory address to read?
I used to know the windows debugging API but it's long lost memory. How about using ollydbg:
http://www.ollydbg.de/
And controlling that with both ollydbg script and autoit?
Sounds interesting... but very difficult. Since you say this is a 'one-off', what about something like this instead?
Take a screenshot of this application.
Run the screenshot through an OCR program
If you are able to read the text you are looking for in a predictable way, you're halfway there!
So now if you can read a OCR'd screenshot of your application, it is a simple matter of writing a program that does the following:
Scripts the steps to get the data on the screen
Creates a screenshot of the data in question
Runs it through an OCR program like Microsoft Office Document Imaging
Extracts the relevant text and does 'whatever' with it.
I have done something like this before with pretty good results, but I would say it is a fragile solution. If the application changes, it stops working. If the OCR can't read the text, it stops working. If the OCR reads the wrong text, it might do worse things than stop working...
As the other posters have said, reaching into memory and pulling out data is a pretty advanced topic... kudos to you if you can figure out a way to do that!
I know this may not be a popular answer, due to the nature of what this software is used for, but programs like CheatEngine and ArtMoney allow you to search through all the memory reserved by a process for a given value, then refine the results till you find the address of the value you're looking for.
I learned this initially while trying to learn how to better protect my games after coming across a trainer for one of them, but have found the technique occasionally useful when debugging.
Here is an example of the technique described above in use: https://www.youtube.com/watch?v=Nv04gYx2jMw&t=265

Intercept BIG application execution after DLL injection

I must intercept execution in very big application in many places.
What programs I can use to do this? What techniques exists for this problems?
Manually reverse engineering and adding hooks is maybe not optimal solution for this problem, because application is very big and some part of application can be updated in some time, i think with some tools or good practices for this problem i can do this faster, anyone know how to do?
Anybody help me?
seeing as the tools part has been covered, here is something for the techniques.
Depending what it is you need to hook and whether or not there is protection invloved, there are a few methods:
Relative call/jmp patching in the virtualized binary: this is the simplest, but also a lot of work if you can't automatically find all references to a function, this probably won't work in this cause due to your criteria.
IAT/EAT hooking: this is use for imports(IAT) and exports(EAT), great if your targeting a known importted/exported set of API functions. a good example of this can be found here or here
Hot-Patching: Windows XP SP2 introduced something called "hot-patching" (used for realtime system function updates), where all its (the WinAPI) functions start with a 'mov edi,edi', allowing a relative jump to be patched into the free space created above every hot-patchable function(one can do it too). this is generally used for programs that checksum there IAT's or have other funny forms of protection, more info can be found here and here
Code-Caving: capturing execution flow by placing redirections in arbitrary code space. see here, here or here
VFT/COM Redirection: basically overwriting entries in a objects virtual function table, useful for OOP/COM based applications. see this
There are a lot of 3rd party libraries, most famous would probably be MS Detours, one can also look at APIHijack or a mini-hook engine.
Ofcourse nothing can substitute for the initial poking you'll need to do with a debugger like ollydbg, but knowing the method your gonna use can drastically short them amount time time spent poking around
Some details on what exactly you need to do (e.g. how do you determine where to break) would be nice. Depending on your situation, something like Pin might work.
I suggest using Deviare API Hook. It's the easiest way you can do what you need. It has some COM objects that you can use to hook an application from a different process. In your process you get full parameter information and you can use it in any programming language (I'm using C# and it works like a charm).
If you need to intercept registry API I suggest using Deviare to debug what you need to intercept but then you will have to make your own hooks, otherwise, you'll find performance issues.
You can do API Hooking if you are interested in intercepting method calls.
Or use some disassembler like softice or ollydbg or win32dasm.

Resources