how to prevent multiple program loading in windows? - windows

I am developing an windows application.
what I want is to prevent this application running multiple in single OS.
(e.g. we can run multiple instance of notepad.exe, calc.exe at the same time... but I don't want this)
what is the most effective way to implement this?(preventing multiple instance of process running at same time)
I'd rather not use methods like checking process names or sharing some global file as a signal... since it is too easy to circumvent
thank you in advance

This is typically done with mutexs. When your process launches you call CreateMutex and check the return value. If it succeeded then this is the first launch, otherwise there is another instance of your process alive. Your mutex should be in the Global\ namespace. Also make sure to ReleaseMutex when your program finishes running.

What framework are you using? I'm assuming it's .Net? Here's a post from an msdn foum on the same thing.
http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/3e139912-45ea-432e-b9e0-e03640c07c9f/

You mentioned you don't want to check current process names or use a global file.
Lock the current executable
.NET example code:
System.IO.File.Open(
System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName,
System.IO.FileMode.Open,
System.IO.FileAccess.Read,
System.IO.FileShare.None);
The FileShare.None keeps any other process (like Windows Explorer) from executing the file until the app closes or the file handle (returned object) is explicitly closed.
Global Mutex
http://msdn.microsoft.com/en-us/library/windows/desktop/ms682411%28v=vs.85%29.aspx
If the mutex is a named mutex and the object existed before this
function call, the return value is a handle to the existing object,
GetLastError returns ERROR_ALREADY_EXISTS, bInitialOwner is ignored,
and the calling thread is not granted ownership. However, if the
caller has limited access rights, the function will fail with
ERROR_ACCESS_DENIED and the caller should use the OpenMutex function.
Global mutex is the easiest way. To clarify another answer you don't just check the return value you check the GetLastError value as well.

Related

Creating child process without getting memory rights to parent

I'm trying create child process without getting PROCESS_VM_WRITE rights to parent that way:
Using kernel driver with ObRegisterCallbacks I remove PROCESS_VM_WRITE access when parent try to get handle of starting child process:
In parent process I use CreateProcess function to start child process, but it fails with error that I'm not having rights.
I'm also tried to use RtlCreateUserProcess and this succeed, but as you may know process now running without subsystem and it doesn't work properly.
So for all these reasons I have three questions:
Maybe it is possible to use some ntdll.dll function which will create process properly without writing in child memory?
Maybe it is possible to hook some Nt functions and elevate all write requests during process creating to my kernel driver? If yes, what functions do I need to hook? I hooked NtWriteVirtualMemory, but ntdll.dll checks access right before call it
Maybe it is possible to finish proper process creating myself after using RtlCreateUserProcess? If yes, what function I need to use?
Not getting memory access to parent process is very critical for me as I need to protect child memory from all UserMode tricks, ObRegisterCallback is good for it, but parent process (launcher) is a big hole.
Maybe it is possible to hook some Nt functions and elevate all write requests during process creating to my kernel driver? If yes, what
functions do I need to hook? I hooked NtWriteVirtualMemory, but ntdll.dll
checks access right before call it
Yes, that's all you need to do. Hook NtWriteVirtualMemory, which is called from CreateProcessInternalW. This avoids STATUS_ACCESS_DENIED and in this case all will work.
ntdll.dll checks access right before call it
You're mistaken - nothing like this happens.
In ObjectPreCallback are you checking that the request is from your parent process and removing PROCESS_VM_WRITE only if it is? During process creation CsrClientCallServer is called, and as result csrss.exe also opens a child process. Are you sure that you're not removing PROCESS_VM_WRITE here?
Of course its also possible use RtlCreateUserProcess, but in this case you will be need connect to csrss by yourself and use undocumented and probably unstable interfaces. I think this is not the best way, but it is possible.
And no there isn't another ntdll API for creating processes with csrss connected.

Start and monitor multiple instances of one process in Windows

I have a Windows application of which I need multiple instances running, with different command line parameters. The application is quite unstable and tends to crash every 48 hours or so.
Since manual checking for failure and restarting in case of one isn't what I love to do I want to write a "manager program" for this. It would launch the program (all its instances) and then watch them. In case a process crashes it would be restarted.
In Linux I could achieve this with fork()s and pids, but this obviously is not available in Windows. So, should I try to implement a CreateProcess version or is there a better way?
When you call CreateProcess, you are returned a handle to the new process in the hProcess member of the process information struct that you pass to CreateProcess. You can use this handle to detect when the process terminates.
For instance, you can create another thread and call WaitForSingleObject(hProcess) and block until the process terminates. Then you can decide whether or not to restart it.
Or your could call GetExitCodeProcess(hProcess, &exitcode) and test exitcode. If it has the value STILL_ACTIVE then your process has not terminated. This approach based on GetExitCodeProcess necessitates polling.
If it can be run as a daemon, the simplest way to ensure it keep running is Non-Sucking Service Manager.
It will allow to run as win32 service applications not designed as services. It will monitor and restart if necessary. And the source code is included, if any customization is needed.
All you need to do is define each of your instances as a service, with the required parameters, at it will do the rest.
If you have some kind of security police limitation and can't use third party tools, then coding will be necessary. The answer from David Heffernan gives you the appropiate direction.
Or it can be done in batch, vbs or js without need of anything out of the system. WMI Win32_Process class should allow you to handle it.

Access denied error when using VirtualQueryEx

So, I wrote a program which is able to successfully read memory from most of processes using VirtualQueryEx. However, I've come across a process for which this function fails. It's not a system process, just a game process. Without Debug privileges I couldn't even open the process's handle. With them I am able to get the process's handle but still get access denied for VirtualQueryEx.
I'm not sure but maybe the process is private? If that's the case, what should I do to successfully use VirtualQueryEx function?
I've also read somewhere that I might have to suspend whole process's threads before running VirtualQueryEx, but so far I didn't need that... And when I used function Thread32First to get the first thread it gave me an error: ERROR_BAD_LENGTH...
I would be very grateful for any help in this matter!
How are you opening the process handle? From the doc:
The handle must have been opened with the PROCESS_QUERY_INFORMATION
access right, which enables using the handle to read information from
the process object.
Another possibility is that the target process and your process are different bitness (32 vs 64). In that case you either need to use MEMORY_BASIC_INFORMATION32 or something like VirtualQueryEx64 from wow64ext library.

Hookin CreateProcessEx

i would like to systemwide hook CreateProcessEx
it is redirects all windows calls into my wrapper function
where I will log names to textfile then call oruginal CreateProcessEx
Can it be easy and safely done ?
I would like hook all systemwide calls to it but not etternaly
for some period of time only.. How to do it?
If I will find the adress of this api call in ram then overvrite
it with call to my procedure, how then I will call the oryginal
function if there it is somewhat corrupted?
Hooking CreateProcess is the wrong approach for a few reasons. There is an approved mechanism for doing this sort of thing but you need a driver to be loaded. Your driver can then simply leverage the PsSetCreateProcessNotifyRoutine function.
With that said, would your needs not be served by using the auditing functionality built into Windows? Turning on process creation auditing will cause the system to write an event log entry whenever a process is created, detailing plenty of information about the process being started, including the image path.
CreateProcessEx() is a user-mode function. You have to patch it on a per-process basis. That means creating a DLL that is injected into every running process, such as by using SetWindowsHookEx() or the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows\AppInit_DLLs Registry key, and then have that DLL patch the PE Imports table of every process it is loaded into.

Setting Access permissions on Semaphore?

I am assuming that once a semaphore is created by a process, it will be accessible by any process/user.
Is it possible to put access restrictions on a particular semaphore so that it can be accessible by only certain processes/users or only certain processes can release the semaphore.
I see some problems if we make a semaphore accessible by all processes.Eg: a dummy process can read the semaphore and release the lock at wish making a false signal to the actual process that is really waiting for the semaphore lock.
All these questions are arising as I am getting very weird output with the following code snippet:
use Win32::Semaphore;
$sem = Win32::Semaphore->new(0, 1,"reliance2692")
or print "Can't create semaphore\n";
$sem = Win32::Semaphore->open("reliance2692")
or print "Can't open semaphore\n";
print "Semaphore:" . $sem . "\n";
By running the above program, I am getting the following output
Can't create semaphore
Can't open semaphore
The output shows that its failed to create a semaphore and even failed to open semaphore.
creating a semaphore might have failed if a semaphore already exists with the given name.
I don't understand why opening a semaphore failed.
Can some clarify the scenario where both creating semaphore & opening semaphore fails.
Win32::Semaphore->new calls the Windows API function CreateSemaphore and gets the process's default security descriptor, which usually means that processes running as the same user as your script can have full access whereas processes running as other accounts get no access. So, for starters, your assumption is false.
The name you choose in your Perl code is passed directly to the API function, so it's subject to the same namespace rules as all other Win32 kernel objects.
Win32::Semaphore provides no interface for specifying access restrictions. Even if it did, Windows does not provide per-process permissions. Permissions are attached to the user, not the process.
If you're getting "access denied" from new, then that suggests there's another program running that chose to use that same name for something else — maybe another semaphore, or maybe something else, like an event or a mutex — and that process is running as a different user.
If you're getting "access denied" from open, then, in addition to the possibilities for new, it could be that another process has already opened a semaphore with the same name but has not granted full permissions to other users. Win32::Semaphore->open requests SEMAPHORE_ALL_ACCESS permission.
If the semaphore has already been opened by a process running as the same user, then you should not get "access denied." Neither new nor open should fail in that case, although $^E might hold 183 (ERROR_ALREADY_EXISTS) anyway.
For the record, I'm the author of Win32::Semaphore. As mobrule and Rob have explained, Windows security is user/group based. It's not possible to have a semaphore that only certain processes can access. If any process belonging to a user can access a semaphore, then any process of that user can access that semaphore.
Normally, the default access allows only the current user to access the semaphore. Nobody's ever requested the ability to have Win32::Semaphore specify a non-default security descriptor, and the associated API is non-trivial. If somebody created a module to manage a SECURITY_ATTRIBUTES structure, I'd be happy to add support for that to Win32::Semaphore and the related IPC modules. Win32-Security does not appear to be that module, although it might be a start.
If you need a semaphore to work across multiple users, your only solution right now is to create the semaphore outside of Win32::Semaphore, passing an appropriate SECURITY_ATTRIBUTES pointer. You could do that with a small helper program written in C, or using Inline::C. (Remember that once created, a semaphore exists as long as any process has an open handle to it, so your helper program needs to keep the semaphore handle open until you've called Win32::Semaphore->open on it.)
From Win32::Semaphore pod
$semaphore = Win32::Semaphore->new($initial, $maximum, [$name])
Constructor for a new semaphore object. $initial is the initial count, and $maximum is
the maximum count for the semaphore. If $name is omitted or undef, creates an unnamed
semaphore object.
If $name signifies an existing semaphore object, then $initial and $maximum are ignored
and the object is opened. If this happens, $^E will be set to 183
(ERROR_ALREADY_EXISTS).
If I'm reading this correctly, if your call to Win32::Semaphore->new refers to an existing semaphore, then the new call will open the semaphore as well, and the subsequent open call will be redundant (it's not clear to me from the pod what should happen if you open a sempahore that is already open).
Perhaps you could step through the code, checking the value of $sem as well as $! and $^E at each step.
Additional reply: the Windows API does have methods for setting access control of semaphores, but
they don't appear to be exposed in the Perl Win32::Semaphore module
access control can't be set unless it was already allowed by the other process that created the semaphore
I don't know if you have any good options for this problem. Can you modify the process that creates the semaphore to relax access restrictions? Ask the Win32::Semaphore author to update his module? Try to fix Win32::Semaphore yourself?

Resources