HOWTO: Tag a process - windows

I am using CreateProcessAsUser() to make processes. I would like to tag some of them so that later on, given a process ID/handle I can work out whether or not it was I who launched them.
Are there any techniques for marking a process natively like this. I want my solution to be stateless, hence a table of PIDs is not suitable - nor is checking the parent of the process to see if I made it (the processes are reparented).
Any ideas? Thanks!

if you are targeting Windows Vista or Windows Server 2008, then you may use InitializeProcThreadAttributeList() and add the attribute list to the process through the STARTUPINFOEX structure when calling CreateProcess(). however, you have to destroy the attribute list yourself before the process terminates, and it does not seem to be the case from what i understand...
if the process have a window, you can also use window properties, but here again you have to destroy the property list when the window is destroyed, and you don't control this neither...
i am afraid you will have to resort to something else. can you explain why a table of PIDs is unsuitable ? i suspect it is because your "launcher" may terminate and have to find its processes again when it is restarted. in this case you should consider serializing those informations to disk when starting a process, and read them back when restarting (plus some additional checks to verify the validity of the serialized informations).

Related

ReadDirectoryChangesW and determining which process caused the change

How can I determine which processes are making changes to which files.
I did find this:
FileSystemWatcher: how to know which process made the change?
But I'm curious if anything has changed lately? Is it possible yet to determine which process is making changes to the file system, either using ReadDirectoryChangesW or anything else? I'd prefer not to have to write or use a kernel driver.
Create a security audit on the files you want to track. The information will be recorded in the security event log.
While it may be possible to find out the process that changes a file using kernel drivers (for example, process monitor), there will always be a problem identifying the process in case the folder is shared on the network, and a process on another computer modifies the file over the network.
Even the kernel drivers would in this case identify the network share process as the one accessing the file, not the process on the other computer.
I can't seem to comment yet. I would be interested in your Python code that creates a security audit on files or paths. It's a bit of a shame if it messes with the system security event log, but you can't have everything! :-)
Up until this point, I have been using GetForegroundWindow at the time of the change to eventually get the associated process. It only works well for changes initiated by the user, but that is primarily what I've been interested in. Besides background processes, the only minor issue is that sometimes a process is spawned just to accomplish a task (like a batch file) and it is non-existent by the time you want to learn more about it (like what process spawned it). I imagine that is a problem even with a security audit, though.

How to give process specific privileges in windows

I am writing some testing software that receives some source code, compiles it on the server, executes it, forward input from the database, catches output and compares it with one in the database to see if it is correct. The problem is that source code can be anything (it is written in c/c++ and compiled with visual studio cl), so I need to prevent somehow malicious users. I am automatically killing those processes if they run longer than some time, or use more memory than allowed.
The question is, can I only allow those processes only to write and read from standard in/out streams and to deny any other access rights on windows.
Please excuse my English.
Thank you in advance.
Probably Job Objects can help you (see http://msdn.microsoft.com/en-us/library/ms684161(VS.85).aspx). This very powerful feature is not good known.
Working with jobs is very easy. You can create a job with respect of CreateJobObject and set a lot of different restrictions like time, memory and some restrictions. Then You can create a process with suspended flag, assign process to the job and resume the process. Then you receive full control under the created process and all tree of child processes, which the process can create. Job feature exist since Windows 2000.
Another modern way is User Interface Privilege Isolation (UIPI) (see http://msdn.microsoft.com/en-us/library/bb625963.aspx) or the way of usage Low Integrity Processes introduced by Vista. See http://msdn.microsoft.com/en-us/library/Bb250462#dse_stlip how to create a process with Low Integrity.

What's the best way to stop multiple instances of a Windows app being launched?

Many Windows apps (like Skype or MSN for instance) don't let you start multiple instances, rather trying to run it a 2nd time just leaves the existing version running.
Is this typically done in some simple way - the start-menu shortcut is a 'wrapper' app around the main app - or is there some registry magic you can do to delegate the problem to Windows itself?
Specifically dealing with Win32 here (unmanaged C++) but happy to hear more general solutions as long as they are workable on Windows XP or later.
EDIT: this seems the best duplicate.
Named Mutex or similar OS-specfic named object. If it exists - app is running.
Lock file somewhere (in temporary directory, etc - create it on program start, remove on program end). Linux software frequently operates this way (some programs store PID in lockfile), but it isn't safe - if you suddenly lose power (electricity cut off), it is possible that lock file won't be deleted.
And you can always enum all running processes and try to find yourself.
There could be more ways to do it, but those are the first ones I could think of.
As far as i remember, there exist system-wide Mutexes. Set Mutex on first launch, if on launch already set, immediately exit.
Use CreateMutex() call an prepend the name with "Global\" should to the trick.
I just check to see if the process is already running: if it's not start the application, if it's already running bring the window to foreground. The check is done in the Main method.
I get the process name with System.Diagnostics.Process.GetCurrentProcess().ProcessName and check if it's already running System.Diagnostics.Process.GetProcessesByName(). If there are more than 1 processes focus the first of them and then exit.

On Windows, how does console window ownership work?

When a console application is started from another console application, how does console ownership work?
I see four possibilities:
The second application inherits the console from the first application for its lifetime, with the console returning to the original owner on exit.
Each application has its own console. Windows then somehow merges the content of the two into what the "console" visible to the user
The second application get a handle to the console that belongs to the first application.
The console is placed into shared memory and both applications have equal "ownership"
It's quite possible that I missed something and none of these four options adequately describe what Windows does with its consoles.
If the answer is close to option 4. My follow-up question is which of the two processes is responsible for managing the window? (Handling graphical updates when the screen needs to be refreshed / redrawn, etc)
A concrete example: Run CMD. Then, using CMD, run [console application]. The [console application] will write to what appears to be the same console window that CMD was using.
None of your four possibilities is actually the case, and the answer to your follow-on question, "Which of the two processes is responsible for managing the window?", is that neither process is responsible. TUI programs don't have to know anything about windows at all, and, under the covers, aren't necessarily even plumbed in to the GUI.
Consoles are objects, accessed via handles just like files, directories, pipes, processes, and threads. A single process doesn't "own" a console via its handle to it any more than a process "owns" any file that it has an open handle to. Handles to consoles are inherited by child processes from their parents in the same way that all other (inheritable) handles are. Your TUI application, spawned by CMD, simply inherits the standard handles that CMD said that it should inherit, when it called CreateProcess() — which are usually going to be CMD's standard input, output, and error (unless the command-line told CMD to use some other handles as the child's standard input, output, and error).
Consoles aren't dependent upon CMD. They exist as long as there are (a) any open handles to the console's input or output buffers or (b) any processes otherwise "attached" to the console. So in your example you could kill CMD, but only when you terminated the child process too would the console actually be destroyed.
The process that is in charge of displaying the GUI windows in which consoles are presented is, in Windows NT prior to version 6.1, CSRSS, the Client-Server Runtime SubSystem. The window handling code is in WINSRV.DLL, which contains the "console server" that — under the covers — Win32 programs performing console I/O make LPC calls to. In Windows NT 6.1, this functionality, for reasons covered by Raymond Chen, moved out of CSRSS into a less-privileged process that CSRSS spawns.
My guess is somewhere between 3 and 4. The console is a self-standing object, which has standard input, output and error streams. These streams are attached to the first process that uses the console. Subsequent processes can also inherit these streams if not redirected (e.g. running a command with redirect to a file.)
Normally there is no contention, since parent processes usually wait for their child process to complete, and asynchronous processes typically start their own console (e.g. try "start cmd" in a command prompt) or redirect standard output.
However, there is nothing to stop both processes writing to the output stream at the same time - the streams are shared. This can be a problem when using some runtime libraries since writes to standard output/error may not be immediately flushed, leading to mixed garbled output. In general, having to processes actively writing to the same output stream is usually not a good idea, unless you take measures to co-ordinate their output through concurrency primitives like Mutexes, Events and the like.
The way the SDK talks about it strongly resembles 1. It is an option with CreateProcess, described as follows:
CREATE_NEW_CONSOLE
The new process has a new console, instead of inheriting its parent's console (the default). For more information, see Creation of a Console.
Output however happens through handles, you'd get one with GetStdHandle(). Passing STD_OUTPUT_HANDLE returns the console handle, assuming output isn't redirected. Actual output is done through WriteFile() or WriteConsole/Output(). If both processes keep writing output to the handle then their output will be randomly intermingled. This is otherwise indistinguishable from what would happen when two programs write to the same file handle.
Logically, there's a screen buffer associated with a console. You can tinker with it with SetConsoleScreenBufferXxx(). From that point of view you could call it shared memory. The actual implementation is undiscoverable, handles abstract them away, like any Win32 API. It is sure to have changed considerably in Vista with the new conhost.exe process.
CMD 'owns' the console. When it creates a process for an app, that app inherits handles to the console. It can read and write those. When the process goes away, CMD continues ownership.
Note: I'm not entirely sure that 'ownership' is the right word here. Windows will close the Console when CMD exits, but that may be a simple setting.
Each application will run in it's own AppDomain. Each AppDomain should be running it's own console.
Ah, you're right. I was thinking about running executables within a process and forgot they start their own process - I didn't drill down far enough.
I think it's spelled out fairly well in the documentation.

Can I Get Notified When Some Process Starts?

I need to know (preferably with the least latency) when foo.exe is launched.
Right now, I have a thread that sits in a light loop (~10 Hz) and walks the process tree looking foo.exe.
This is less than elegant and I was wondering whether I could register with some part of the Windows API to get a callback when any process starts.
If no such facility is available, I am, of course, open to other methods of accomplishing this task more elegantly.
You can register yourself as a debugger for foo.exe through the Image File Execution Options. Anytime the system needs to launch foo.exe, it'll launch your app and pass foo.exe and its parameters to you. You will have to start the process yourself.
Note: as usual, some words of caution by Raymond Chen.
You can also set a system-wide message hook and for each new process your dll gets loaded, check if it's the one you care you just pass through, for foo.exe you notify yourself and then pass through. Unfortunately, that means you will be injecting your code in each process and you will be hurting the system perf a little bit. Not to mention that you can actually hose everybody if you have a bug in your code.
Possible options:
Is foo.exe under your control? If so modify the source code to send a signal.
Is foo.exe not under your control? Write an injection DLL and have it send a signal when it's loaded into the process with the right name.

Resources