Prevent C# app from process kill - c#

How can I protect my C# app from someone killing its process via taskman or programmatically?
Here is my scenario:
App A is an MFC app developed by another team. It has an unpublished text-based remote interface that is enabled via a backdoor.
I'm developing app B, a C# WinForms app which interacts with A. B enables A's backdoor when it needs remote access closes it when finished (or on failure).
I'm exploring ways users could abuse B in order to gain access to A's hidden functionality, such as killing B's process after it has enabled A's remote interface. I'd like have one last chance for B to close A's backdoor when that happens.
B uses localhost to interact with A, so I'm not worried about the power-down scenario.
I'm looking for a solution that doesn't involve changing A.
I'm not expecting to be able to stop Dark Tangent (though that would be a bonus), but right now a script kiddie could have his way with this design :)
These apps run on Windows XP, but will also soon support Vista & 7.
Thanks in advance,
Jim

I'm willing shut the app down when they try but need to do some things first.
Having necessary steps at program shutdown leads to fragile programs that break easily. Even if you could prevent someone from killing your program via the task manager, you cannot stop them from turning off the computer, or even pulling the cable out of the wall. Whatever task that was so vitally important to complete will be lost. And what if there is a power cut? Again your task won't complete and your vital clean up code will not be run.
Instead you should make your program robust to failures at any point. Use transactions, and always save state to files atomically - make sure that you always have at least one valid copy of your data. Don't overwrite important files in a way that they become temporarily invalid.
Finally, you can add a dialog box to your program that when they try to close it, warns them that the program needs to shut down properly. If you make your shutdown fast users won't want to kill it and will let it terminate properly. If your shutdown takes ages then people will try to kill it. If you are nice to your users, they will be nice to you too.
If shutting down fast means that the user will lose some unfinished work then warn them about this and give them the opportunity to wait for the task to finish, but if they really want to quit your program then let them quit.

You can't - as long as the user has the right to call TerminateProcess on your program, you can't prevent End Process from killing you immediately in task manager. Raymond Chen posted on this some time ago: The arms race between programs and users

You really, really, really don't want to do this. It makes users very angry!! However, if it is supposed to be a service, run it as a service account and don't give admin rights to users.

Short answer: you can't and you shouldn't.
Long answer: You can try to start a second 'helper' process, that checks every x seconds if your app is still running. If it isn't, it restarts it.
If you want a process to run for a long time just don't trust users to keep it running, consider windows services. They are designed for this.

I think everybody has missed the point. If I read it correctly (after your edit) you wish to know when you are being "killed" so you can shut down gracefully?
The point of "killing" is that you "can't" stop it. There are of course workarounds like using a second app to revive a killed app, but that has nothing to do with simply being able to shut down gracefully.
The best approach is to either run as a service (so you can't be killed, just asked to shut down), or to restructure the way your app works so that it doesn't need to "tidy up" before it quits. When an app is quit, most resources it holds are automatically cleaned up, so it's only really your own data that you have to close cleanly. Approaches you could try are:
Frequently commit your state to disk so that you don't lose much (or anything) if you are unexpectedly quit. (Remember to flush all I/O streams to be sure they are committed to disk)
Save information to disk that allows you to detect an unexpected shutdown the next time your program runs, so it is able to detect and rectify whatever problems might have been caused by being killed.
Tell your users not to be idiots, and quit your application nicely. Poke them in the eye if they ignore you. Usually after no more than two times they listen :-)

In order to prevent your application from being terminated, you run your application as another user (i.e. as a service, or as another user account), and limit users to be Standard User.
This way no malicious users can kill your process, since only administrators can kill it, and that is a privilege that you, apparently, don't trust anyone with.
It has the advantage of following the intended design of the operating system.

#Jim
If App A can receive modification requests
Preferably, I would an architecture where all App B's are registered upon opening the backdoor and are required to ping App A with the registration at an interval so that App A can close it's own backdoor upon App B not informing it that it still needs access. This is still not perfectly secure but App A should not be structured with such an interface without some sort of self regulation for "secure" means of communication.
Or, you could suggest App A be modified to check for valid processes and if none are found while it's backdoor is open then it gets closed (this is spoofable since it goes by processed name).
Otherwise, it sounds like App B should shut the backdoor as often as possible when it does not need immediate access.
Requiring an App B to provide security of access to App A is a poor model indeed.

As far as i know you can't, and even if you could you really shouldn't. imagine how annoying it would be if you couldn't force kill an application.
If its important that your application keep running you could always create a windows service that "pings" the application to ensure it is running (you could use named pipes, sockets, pid files... whatever). if the service detects that the process has died then it can just restart it. this is probably your best bet.

When the application initiates for the first time could you not execute a 3rd ap/process that is running in the background and attempts to callback to App B every so ofter, so when that App B is closed.. App C can see that and executes a procedure to close App A's backdoor.
So that when App B closes successfully via the intended Close button it will disable App C from checking App B is still working fine...
Im not really the best with C# at the moment but looking at your problem thats probably one of the ways i would try to do it..
Also if App B checks App C aswell then if App C has gone down App B will close the backdoor if it can.
As the others say this may not be a good idea tho.

Related

How can I force the deletion of locked files in C#

I have a scenario where I must delete a file. I don't know and don't care who holds the file. I must delete it and they can crush for all I care. (I don't want to kill the locking task)
the only solution that comes to my mind is to use http://www.emptyloop.com/unlocker/ command line interface.
MoveFileEx is not and option as I cannot restart the machine.
is there any more C#ish method/library for this?
im not thrilled using console application API
in case it is not clear.I know the risk involved and I don't need a lecture of why this is a bad practice. if you know how to do what I asked. thank you very much!
if you want to lecture why this is bad - just don't find someone else to bother##
I can't give you a solution but can point you into a direction.
Window's Process Explorer has a function that can make you search for handles:
When you then select that handle you go to the process owning that handle and you can right click on it and Close the handle and also relieve the lock that process has on that file.
So basically you need to find out which API calls Process explorer is using and execute them yourself in your application.
I think what you are asking for is impossible due to the nature of a lock.
How would you feel if another program could just snatch your files and wipe them as you were reading data?
I believe these unlockers detect the process and try to force it to release it's lock 1 way or another(maybe even shutting their process down).
While this may work for most applications some will be more aggressive (think virus scanners for example).
So maybe you need to ask yourself if you want to increase your chances of getting a lock or if you need to be absolutely sure to get a lock.
Edit:
Assuming you can terminate the locker process and you really want to clear those files(no matter the consequences) you could find the process that holds the lock and shut it down.
In this thread they give a few solutions for tracking which process holds a lock(in c# code) via either handle, win32 dll's or even plan .NET code.
Disclaimer Be aware that shutting down a process like this will have a terrible impact on the consistency of that program and you might even do more bad then good(suppose it's writing it's status the the database for example and halfway it gets terminated)

Best Practices of fault toleration and reliability for scheduled tasks or services

I have been working on many applications which run as windows service or scheduled tasks.
Now, i want to make sure that these applications will be fault tolerant and reliable. For example; i have a service that runs every hour. if the service crashes while its operating or running, i d like the application to run again for the same period (there are several things involved with this including transactions of data processing) , to avoid data loss. moreover, i d like the program to report the error with details. My goal is to avoid data loss and not falling behind for running the program.
I have built a class library that a user can import into a project. Library is supposed to keep information of running instance of the program, ie. program reads and writes information of running interval, running status etc. This data is stored in a database.
I was curious, if there are some best practices to make the scheduled tasks/ windows services fault tolerant and reliable.
Edit : I am talking about independent tasks or services which on different servers. and my goal is to make sure that the service will keep running, report any failures and recover from them.
I'm interested in what other people have to say, but I'll give you a few points that I've stumbled across:
Make an event handler for Unhandled Exceptions. This way you can clean up resources, write to a log file, email an administrator, or anything you need to instead of having it crash.
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(AppUnhandledExceptionEventHandler);
Override any servicebase event handlers you need in the main part of your application. OnStart and OnStop are pretty crucial, but there are many others you can use. http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicebase%28v=VS.71%29.aspx
Beware of timers. Windows forms timers won't work right in a service. User System.Threading.Timers or System.Timers.Timer. Best Timer for using in a Windows service
If you are updating on a thread, make sure you use a lock() or monitor in key sections to make sure everything is threadsafe.
Be careful not to use anything user specific, as a service runs without a specific user context. I noticed some of my SQL connection strings were no longer working for windows authorizations, etc. Also have heard people having trouble with mapped drives.
Never make a service with a UI. In fact for Vista and 7 they make it nearly impossible to do anyway. It shouldn't require user interaction, the most you can do is send a message with a WIN32 function. MSDN claims making interactive services is bad practice. http://msdn.microsoft.com/en-us/library/ms683502%28VS.85%29.aspx
For debugging purposes, it is way cool to make a service run as a console application until you get it doing what you want it to. Awesome tutorial: http://mycomponent.blogspot.com/2009/04/create-debug-install-windows-service-in.html
Anyway, hope that helps a little, but that is just a couple thing I poked around to find on my own.
Something obvious - don't run all your tasks at the same time. Try to schedule them so only one task is using some expensive resource at any time (if possible). For example, if you need to send out newsletters and some specific notifications, schedule them at different times. If two tasks need to clean up something in the database, let the one run after another.
Also schedule tasks to run outside of normal business hours - at night obviously.

Guaranteed way to force application running continuously (overriding taskkill, task manager etc.)

I have a C# security/monitoring application that I need to have running no matter what. However, I can not remove privileges or restrict access to parts of the OS (Windows).
I thought of having a protection service running which monitors continuously if an application is running, and starts it back up when the application is killed somehow, while the application monitors the protection service and starts the service if the service is killed. To my knowledge you can't simultaneously kill multiple processes at the same time.
Any better idea to guarantee that an application is always running?
The Windows team gets requests like this all the time:
"I want to make a process that can never be killed".
"Well I want to make a tool that can kill any process".
One of those two people is going to be disappointed.
"I want to make a window that is always on top of all other windows no matter what"
"I also want to make a window that is always on top of all other windows no matter what"
One of those two people is going to be disappointed.
"I want to make a process that does not show up in any list of processes no matter how cleverly the listing program is trying to find me"
"I want to make a program that lists all processes, no matter how cleverly the process is trying to hide".
One of those two people is going to be disappointed.
And so on.
I think you're going to be one of the disappointed people.
There is no guarantee - if the user has enough privilege it can terminate your program or any other monitoring code you have running that will restart your application.
Imagine if this were true - every piece of spyware on the planet would be using it.
I would write your program as a windows service - configure it to run automatically on startup, and to restart automatically if it is terminated unexpectedly. You cannot do any better than this since the user must be allowed to control the computer.

How can I make a program that's impossible to be killed in Windows?

We are making a Jabber client for our internal use in our company and somehow we need to catch the moment when the user tries to kill the program to actually restart it or just make impossible for the user to kill the client.
Is this possible?
Our Jabber client will be written in C#.
How would I go about accomplishing this?
What you are asking for has implications far beyond what you are being asked to accomplish. For example, if the process cannot be killed, how can Windows shut down normally?
I don't know your boss, so you will have to gauge their level of understanding for yourself. If a user/manager asked me for this, I would have to probe deeper to find what they really mean. My suspicion is that your users want the default close behavior to minimize to the system tray rather than exit the program, similar to most instant message clients, rather then not be able to ever close the program at all.
let me first say, this is a horrible idea.
but...if you must do it, the way I see malicious software and spam hounds do it is to create 3 running processes, one is the main process and the other two will monitor and restart any killed process. it's very difficult for the average user to kill 3 processes simultaneously.
Sounds like a virus.
Since this is internal, you could create a separate windows service that monitors the active processes. If the process of your jabber client isn't there, you could just relaunch it.
Then use permissions to keep them from accessing the Windows Service to disable it.
I think you should go ask the requirement designer what they mean by app that is impossible to "kill." What are they getting at with the word "kill"?
Not allowing a user to close their program
Prevent standard use of X button in window?
Minimize to task tray?
Not allow them to close the app in Task Manager?
Not allowing the OS to close their program
The requirement is ambiguous enough that I'd go talk to the requirement designer/boss to get a better idea of what they want.
Not only does this sound like a bad idea (it is abusive to your users) but you will not be able to prevent users from killing the process itself.
You would have to run two separate processes - one to run the application and a second one to monitor the first one and restart it if necessary.
You can't. You can make it harder, but not impossible. See The arms race between programs and users.
You'll have to reduce their user rights until they can't kill processes.
Control it with a Windows Service. Easy to do in C#. Lock down permissions to stop the service.
Note: I think the answers of "this is impossible/horrible/evil" are perhaps missing your point. A service is specifically designed 'keep going', which is what you're asking about.
More importantly, WHY are you rewriting a jabber client when so many good ones, like Miranda and Pidgin already exist? If it's for logging, you can easily do that server side on your Jabber server, and not rely on the clients.
If it's to prevent other IM services, robust firewall rules will help stop that (but it won't prevent it from the super geniuses who'll proxy AIM+Gtalk over https to their home servers).
You can catch most signals with handlers, except for SIGKILL.
You can create a watch dog windows process that respawns your application in the event it's terminated.
If you want, you can name this process something very innocuous sounding like "sysmon" so it doesn't look as sketchy.
I do hope this is a requirement for work, and not your way to bringing about the downfall of man.
sounds like you have access to the jabber client. Can you make it poll to a separate location with it's status and startup time? You aren't disabling the ability to kill it... but at least you can track it and respond from there.
Shouldn't this be controlled by your desktop group? We have PCs in a few kiosks that allow associates to check personal e-mail and stuff (Gmail, Yahoo, Hotmail, etc...), and the user permissions on those PCs will not allow users to kill processes.
Kind of annoying if IE locks up, but I can understand the reasoning.
Sounds like a case of this
Promise to suspend the users who kill your traffic logger Jabber client?
I agree that this is an awful idea.
Having said that, you'd create two programs (probably windows services). Both programs would monitor each other as well as functioning as the client. You would need shared memory that both processes could access to synch which client processes incoming requests.
You can prevent from the users to run TaskManager by GPO.
You can create your application as a Windows Service and prevent from the user kill the task manualy ( can be killed only from the services.msc )
Try to tie their hands :- )
go to actions and make a form closing event and in c# type e.cancel = true;
Unless you're really writing a virus, you should be able to block their ability to kill the process with permissions. Assuming they are all domain users and you are the admin.
I guess there would be a few cases where you would want to do this. You don't want users making security vulnerabilities. I can't exit or change any settings of Norton endpoint on my work computer, and it hasn't bothered me yet.
But if all the users are admins on their machines, and you want to make it impossible to close, and presumably impossible to start in safe made and remove... then you're asking: "How do I write malware?"

How to be notified a program execution and termination in c#?

is there a way to be notified when a program is executed or terminated by a user in c#? I am talking about all the programs that a user can execute, not just a certain program. I would like to be notified whenever a user execute .exe files.
I can't even think of a keyword to google.
any suggestions would be appreciated!
The closest thing I know of would be to use Hooks.
You can use WH_SHELL Hooks to receive notification any time a new, non-owned, top level window is created or destroyed by the system. This isn't the same as a process, but it's pretty close in many cases, and potentially more useful in others (since it'd show a new word document window opening after one was already opened, even though they're using a shared process).
You might be able to combine that with EnumProcess to check to see if the process list has changed. This would work for tracking windows applications (but not services or console-based applications running in an existing console).
In Microsoft .NET Framework 3.5, you can get a list of Processes and register for the Process.Exited event. I suppose someone could implement a polling system in which they continually looked for new Processes, but that doesn't really notify you when something launches.
-- EDIT --
You might find this article useful. If you're willing to write a kernel mode driver, you can control every process start and finish.
Now, if you really want to get wild, you can hook into Microsoft Detours. Here is an interesting article about that.

Categories