Construct Process Tree in Windows - windows

To construct a process tree in Windows "C" given a PID, which one is a good approach to go for Win2k, XP, Windows Server 2008, Windows 7.
ZwQuerySystemInformation
NtQuerySystemInformation
CreateToolhelp32Snapshot
I remember ToolHelp had issue in leaking memory for win2k. Please correct me if I am wrong.
And using ZwQuerySystemInformation/NtQuerySystemInformation, I am not sure what the // System Information Class 5 structure should be for 64-bit architecture. Can someone provide pointers to it?
-Karthik

Off the top of my head, the documented ways to list processes include:
WTSEnumerateProcesses (Must delayload, call will fail if Terminal Services/Fastuserswitching is off)
EnumProcesses (Only a list of PID's)
CreateToolhelp32Snapshot
Performance Counters
WMI

Related

Do all user mode processes started in Windows go through CreateProcess?

Is there any bottleneck above the physical the cpu and HAL? Or are there multiple ways a process could start under Windows XP, Vista, or 7, that don't invovle CreateProcess at some point?
Given the comment on your question:
Building an Anti-Executable driver, just planning, wondering if controlling createprocess would be enough.
No it wouldn't be enough if security is your concern. There is NtCreateProcess below that one for example. And those aren't the only ones.
The best way provided by the system is a file system filter driver. In fact the WDK comes with samples that require only a moderate amount of change to do what you're asking. Since you asked about XP you can use a minifilter if you can get away with support for XP SP1 and later.
PsSetLoadImageNotifyRoutine and PsSetCreateProcessNotifyRoutine are unfortunately only notifications. So they don't allow to do anything about the event that they notify about. And you really shouldn't attempt to work around this.
In the old times I have seen some clever implementations using SSDT hooks on ZwCreateSection that would exchange the returned handle with one to an executable that shows an error message. Since the executable itself sees the original command line, it can then show a nice error message informing the user that the command has been banned for reasons xyz. However, with Vista and later and even on XP and 2003 64bit (x64), it's going to be harder to write the SSDT hooks. Not to mention that everyone would frown upon it, that it requires quite extensive experience to get it right (and even then it often has flaws that can cause havoc) and that you can forget any certifications you may be aspiring for in the Windows Logo process.
Conclusion: use a file system filter driver to deny access to unwanted executables. With a minifilter the learning curve will be moderate, with a legacy filter I'll recommend you take a few courses first and then start your first attempts.
Looking through a quick disassembly of CreateProcess, it appears that the two main things it does are:
Call NtCreateUserProcess (this is syscall 0xAA) to actually create the process structures in the kernel (PEB, etc.)
Start the new process with a call to NtResumeThread (syscall 0x4F).
The Windows Internals books certainly detail this process very well.
I'm not sure if there are designated hooks in the kernel which would allow you to create your anti-executable driver. It used to be that you could hook the "System Service Dispatch Table" to change how these system calls behaved. But now, technologies like PatchGuard prevent a driver from doing this (and allowing the system to run).

How to know if a process is running in Windows in C++, WinAPI?

How do I know in a windows program if a process is running if I only know the exe file name ?
The process in question is TeamSpeak3 ts3client_win64.exe for 64 bit and ts3client_win32.exe for 32 bit.
I am using C++
Use the CreateToolhelp32Snapshot function to create a snapshot of the current process table, then use the Process32First and Process32Next functions to iterate the snapshot. You can get the name for each executable file by looking at the szExeName field of the PROCESSENTRY32 structure.
See the MSDN example for a sample of how to use these functions.
The advantage of this approach is that, unlike any EnumProcesses-based solution, it doesn't suffer from race conditions: with EnumProcesses it can happen that a process gets destroyed after you finished enumerating the processes but before you got around to opening the process (or reading our the process executable name).
You can use a combination of EnumProcesses, OpenProcess, and GetModuleFileNameEx (or alternatively, QueryFullProcessImageName for Vista or later). MSDN even has an example.
Windows NT has several APIs for enumerating processes.
EnumProcesses
ToolHelp
NtQuerySystemInformation (discouraged)
WMI's Win32_Process (works remotely)

Windows system call issue in W2K8

I am having a problem with windows system function “EnumProcessModules()” that is defined in psapi.dll. In our component we use this function to retrieve modules in a specified process. This function is working well as long as we run the program on a 32-bit OS. However, this function fails when we run the program on a 64-bit OS (e.g. W2K8 R2). As you all know we are targeting Clay and Brick on W2K8 R2s. This is a known problem as per the following discussion in MSDN. One work around that was suggested in that thread is to compile the code as 64-bit. To us that is not an option, at least not yet. Do you have any suggestions? Any pointers/suggestions/ideas will be appreciated.
http://social.msdn.microsoft.com/forums/en-US/winserver2008appcompatabilityandcertification/thread/c7d7e3fe-f8e5-49c3-a16f-8e3dec5e8cf8/
If your existing code must continue being compiled as 32-bit, one possibility would be to create a small 64-bit executable that enumerates the processes via EnumProcessModulesEx. The 32-bit process could spawn the 64-bit process when necessary to do that work. Then use some kind of IPC to transfer the information back to the 32-bit process. Depending on what is needed, that part could be as low tech as writing a file to disk and reading it from the first process (or pipes, shared memory, sockets, etc.).

How can I see what is on the Desktop Heap

I have an application that is using about 100k more of the Desktop Heap in this version then it did last version. Is there a way I can see what is on the Desktop Heap and how big the individual objects are? Using Dheapmon I was able to see what percentage of the heap I was using, but I want more details.
Stolen from a comment on a blog post here
Let me
give a little background on how
desktop heap allocations are made. The
desktop heaps are in kernel mode
virtual address space, so individual
desktop heap allocations have to be
made by a component running in kernel
mode. In particular, win32k.sys is the
only kernel mode component that makes
desktop heap allocations. win32k.sys
in the kernel mode side of Win32, and
it includes both the window manager
(USER) and GDI. It is the window
manager piece of win32k.sys that uses
desktop heap. The functionality of the
window manager is exposed to processes
running in user mode through
user32.dll. It is user32.dll that
exports user mode callable functions
that are implemented in win32k.sys. So
if a process does not load user32.dll,
it will not use desktop heap.
Regarding your question about setting
a breakpoint that will catch desktop
heap allocations... yes, there is such
a function - win32k!DesktopAlloc.
However, this is a kernel mode
function, and to set a breakpoint on
it will require that you use a kernel
debugger.
That sounds all scary complicated to me who has never ventured away from user-mode in Windows.
When I had a similar problem I just put break points all over the startup portion of our application. At each break I would watch the level of allocated handles and what dhelpmon told me. Doing a sort of binary search I started to narrow down where the allocations were happening.
Dheapmon is the only tool I know of for looking directly at the desktop heap, but have you tried looking at your application with a tool like Winspector to look for glaring differences between the two versions (say, some type of control in your application now contains far more windows)? Any chance the application has switched to a newer version of IE? I seem to remember IE7 being much more desktop heap-intensive than IE6...
You can walk the heap using the Win32 API call HeapWalk. You can call GetProcessHeap to get all the heaps available to the process if you need to walk more than just the default heap.

Invoke Blue Screen of Death using Managed Code

Just curious here: is it possible to invoke a Windows Blue Screen of Death using .net managed code under Windows XP/Vista? And if it is possible, what could the example code be?
Just for the record, this is not for any malicious purpose, I am just wondering what kind of code it would take to actually kill the operating system as specified.
The keyboard thing is probably a good option, but if you need to do it by code, continue reading...
You don't really need anything to barf, per se, all you need to do is find the KeBugCheck(Ex) function and invoke that.
http://msdn.microsoft.com/en-us/library/ms801640.aspx
http://msdn.microsoft.com/en-us/library/ms801645.aspx
For manually initiated crashes, you want to used 0xE2 (MANUALLY_INITIATED_CRASH) or 0xDEADDEAD (MANUALLY_INITIATED_CRASH1) as the bug check code. They are reserved explicitly for that use.
However, finding the function may prove to be a bit tricky. The Windows DDK may help (check Ntddk.h) - I don't have it available at the moment, and I can't seem to find decisive info right now - I think it's in ntoskrnl.exe or ntkrnlpa.exe, but I'm not sure, and don't currently have the tools to verify it.
You might find it easier to just write a simple C++ app or something that calls the function, and then just running that.
Mind you, I'm assuming that Windows doesn't block you from accessing the function from user-space (.NET might have some special provisions). I have not tested it myself.
I do not know if it really works and I am sure you need Admin rights, but you could set the CrashOnCtrlScroll Registry Key and then use a SendKeys to send CTRL+Scroll Lock+Scroll Lock.
But I believe that this HAS to come from the Keyboard Driver, so I guess a simple SendKeys is not good enough and you would either need to somehow hook into the Keyboard Driver (sounds really messy) or check of that CrashDump has an API that can be called with P/Invoke.
http://support.microsoft.com/kb/244139
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\i8042prt\Parameters
Name: CrashOnCtrlScroll
Data Type: REG_DWORD
Value: 1
Restart
I would have to say no. You'd have to p/invoke and interact with a driver or other code that lives in kernel space. .NET code lives far removed from this area, although there has been some talk about managed drivers in future versions of Windows. Just wait a few more years and you can crash away just like our unmanaged friends.
As far as I know a real BSOD requires failure in kernel mode code. Vista still has BSOD's but they're less frequent because the new driver model has less drivers in kernel mode. Any user-mode failures will just result in your application being killed.
You can't run managed code in kernel mode. So if you want to BSOD you need to use PInvoke. But even this is quite difficult. You need to do some really fancy PInvokes to get something in kernel mode to barf.
But among the thousands of SO users there is probably someone who has done this :-)
You could use OSR Online's tool that triggers a kernel crash. I've never tried it myself but I imagine you could just run it via the standard .net Process class:
http://www.osronline.com/article.cfm?article=153
I once managed to generate a BSOD on Windows XP using System.Net.Sockets in .NET 1.1 irresponsibly. I could repeat it fairly regularly, but unfortunately that was a couple of years ago and I don't remember exactly how I triggered it, or have the source code around anymore.
Try live videoinput using directshow in directx8 or directx9, most of the calls go to kernel mode video drivers. I succeded in lots of blue screens when running a callback procedure from live videocaptureing source, particulary if your callback takes a long time, can halt the entire Kernel driver.
It's possible for managed code to cause a bugcheck when it has access to faulty kernel drivers. However, it would be the kernel driver that directly causes the BSOD (for example, uffe's DirectShow BSODs, Terence Lewis's socket BSODs, or BSODs seen when using BitTorrent with certain network adapters).
Direct user-mode access to privileged low-level resources may cause a bugcheck (for example, scribbling on Device\PhysicalMemory, if it doesn't corrupt your hard disk first; Vista doesn't allow user-mode access to physical memory).
If you just want a dump file, Mendelt's suggestion of using WinDbg is a much better idea than exploiting a bug in a kernel driver. Unfortunately, the .dump command is not supported for local kernel debugging, so you would need a second PC connected over serial or 1394, or a VM connected over a virtual serial port. LiveKd may be a single-PC option, if you don't need the state of the memory dump to be completely self-consistent.
This one doesn't need any kernel-mode drivers, just a SeDebugPrivilege. You can set your process critical by NtSetInformationProcess, or RtlSetProcessIsCritical and just kill your process. You will see same bugcheck code as you kill csrss.exe, because you set same "critical" flag on your process.
Unfortunately, I know how to do this as a .NET service on our server was causing a blue screen. (Note: Windows Server 2008 R2, not XP/Vista).
I could hardly believe a .NET program was the culprit, but it was. Furthermore, I've just replicated the BSOD in a virtual machine.
The offending code, causes a 0x00000f4:
string name = string.Empty; // This is the cause of the problem, should check for IsNullOrWhiteSpace
foreach (Process process in Process.GetProcesses().Where(p => p.ProcessName.StartsWith(name, StringComparison.OrdinalIgnoreCase)))
{
Check.Logging.Write("FindAndKillProcess THIS SHOULD BLUE SCREEN " + process.ProcessName);
process.Kill();
r = true;
}
If anyone's wondering why I'd want to replicate the blue screen, it's nothing malicious. I've modified our logging class to take an argument telling it to write direct to disk as the actions prior to the BSOD weren't appearing in the log despite .Flush() being called. I replicated the server crash to test the logging change. The VM duly crashed but the logging worked.
EDIT: Killing csrss.exe appears to be what causes the blue screen. As per comments, this is likely happening in kernel code.
I found that if you run taskkill /F /IM svchost.exe as an Administrator, it tries to kill just about every service host at once.

Resources