Windows Service: to code a software security feature - c#

i want to implement a windows service that functions as a simple license security feature for a software X. The service is meant to run independently from software X.
The rough idea:
The service is like a timebomb for a software Z installed on the machine...
Whenever the user runs software X, the service pops up a window every 30 minutes to remind the user to register software X.
If the user doesnt register the software after 1 month, the service will change the license code in a file and kill the software X process.
On the next start up, software X will read the wrong license code and starts in demo mode.
The service backs up the license code first before changing it.
When the user do register, a exe or bat file will be given for the user to run. The file restores the original license file and permanently removes the service.
Additional info:
Is it possible that if the user tries to kill the service, the service will automatically change license code and kill software X before being killed itself?
If the user changes the license code manually in the file after the service changes it, then the service will automatically change it back and kill software X.
I'm quite the newbie in programming... so i wanna ask for advice first before jumping into the project... Any advice, tips or issues/concerns i should be aware of based on your experience?
I'll most probably code it in C++ but might do it in C#(never used it before) after reading the following discussion:
Easiest language for creating a Windows service

I'm quite the newbie in programming...
so i wanna ask for advice first before
jumping into the project... Any
advice, tips or issues/concerns i
should be aware of based on your
experience?
The best advice I can give you is "newbies to programming should not attempt to write security systems". Developing a security system that actually mitigates real vulnerabilities to real attacks is incredibly difficult and requires years of real-world experience and both practical and theoretical knowledge of how exactly the operating system and framework class libraries work.
The second-best advice I can give you is to construct a detailed, accurate and complete threat model. (If you do not know how to do thread modeling then that'll be the first thing to learn. Do not attempt to rollerskate before you can crawl.) Only by having a detailed, accurate and complete threat model will you know whether your proposed security features actually mitigate the attacks on your vulnerabilities.

Whenever the user runs software X, the service pops up a window every 30 minutes to remind the user to register software X.
This is not possible. A service cannot display a window due to being on another desktop then the user. (Since Vista this is mandatory, XP did allow for showing a window.)
Is it possible that if the user tries to kill the service, the service will automatically change license code and kill software X before being killed itself?
No. A service is just another program running in the system, which can be killed at any point in time. (Only you have to be in the administrator group).
If the user changes the license code manually in the file after the service changes it, then the service will automatically change it back and kill software X.
The conclusion is, that when you break your license check into 2 parts, you get another point at which the user can break your check. You cannot prevent the user from working around your service, if it is not mandatory for your program to work.

Is it possible that if the user tries to kill the service, the service will automatically change license code and kill software X before being killed itself?
Not in general, no. If I shut down the process unconditionally (e.g. using taskkill /f command), it won't get any chance to react.
If the user changes the license code manually in the file after the service changes it, then the service will automatically change it back and kill software X.
It's possible - you can use ReadDirectoryChangesW function to watch the file and react to changes (or FileSystemWatcher class if your service is implemented in .NET). Of course, in light of the first answer above, user can just kill your service and then alter the file...

NEVER make a service for something unless it's really a system service. If you are creating an application, then you have NO BUSINESS EVER running code on the system when the application is closed unless the user explicitly requested that operation. Ideas like this are the reason we (nerds) have to deal with so much crap when people ask us to "fix my computer, it's running so slow."
I would walk from a 6-figure salary before I would ever become a part of an abomination like that.
Edit: I suppose first I'd need a 6-figure salary... some day some day

Related

C# How to preserve process across different users

For school I have to develop anti-malware software using a different approach than most other software. Instead of blacklisting harmful software, we have to whitelist programs and prevent the execution of non-whitelisted software. We've written a driver in C and the rest of the program using C# and WPF. The driver is stable and the program is doing a pretty good job. But we have one huge issue. We can't switch users.
The computer freezes as soon as we try to switch users (doesn't happen when the program is not running). We've been looking across the internet for quite some time now and we didn't find any valuable help regarding this issue.
My questions now:
How can we find out when the computer is about to switch user.
When this happens, how can we "pause" the process, switch user, and resume the software on that user without running the software twice (once for each user).
*I can't include code because we're bound to a non-disclosure agreement regarding the source code.
You should be able to use the SystemEvents.SessionEnding and SystemEvents.SessionSwitch events to detect system shutdowns and user changes.
https://msdn.microsoft.com/en-us/library/microsoft.win32.systemevents.sessionending%28v=vs.110%29.aspx
https://msdn.microsoft.com/en-us/library/microsoft.win32.systemevents.sessionswitch%28v=vs.110%29.aspx
It sounds to me as if at least parts of your program should be running as a service. Services only run one instance per machine, so there would be no need to pause and reset anything for different users.

Kick users out of an application

I have written an application that is used company wide. A lot of users have the tendency to leave the application open 24-7. This application is under development constantly as the Marketing department's needs change. Most changes are minor but often times need to be implemented quickly. Salesmen are often away from their desks or on the phone, so an intercom announcement does not always do the trick. The application is housed on a network file share and shortcutted to.
What I envision is something like a message popping up something like "The program will exit for an update in five minutes, please save your changes now." Is there a way to display this message and kick them from the exe remotely? I thought of maybe just having a database value that it checks periodically to see if an update is pending, but that seems like a cheap hack to me.
Your database check is as good as any other; I personally would recommend polling some service to which it subscribes that would do the same thing. If your app connects directly to the database, however, you're probably better off making the check in the database.
You'd be best off going with a ClickOnce deployment method, however. That would require a major architectural change, but would be best in the long run, IMO.
Pity it's not a web application. Deployment would be a snap!
Anyhow what I'd do is this. Make the application log users out after several minutes of inactivity.
Two approaches to unsaved work. Do nothing and therefore they loose it if unsaved when they are inactive and it logs them out.
As they work, a local journal of changes is kept. When they are logged out due to inactivity, logging back will use the journal to open things back up as they were.
EDIT: To prevent users from using the old version. Write a database field with a version or build number. If running version < version in db field then refuse login, and/or restart program to load new image.
You can set up a central server that the .exe sends requests to to find out when updates are available.
I would recommend that you look into WCF as a framework for your solution; there are many great references for the framework as well as posts on sites like this one. You can probably spin up a separate thread in your application that checks for updates every X minutes.
As for your specific question, "Is there way to display this message and kick them from the exe remotely?", yes it is possible, but it is more feasible to make the program automatically query for the update.
If you want to shut them down for update remotely, then you have to know where they are on the network. If the program periodically contacts a central database, then there is no need for the server to know where the program is on the network, the program can automatically reach out to the server from wherever it is.
You could use a messaging system such as RabbitMQ, or any other one, and have the applications listen to a channel in the system. Then an administrative application could send a message to the user applications forcing them to shut down.
If the changes aren't breaking changes, you might want to look at something like ClickOnce which allows you to publish updates to applications while the users are running them, though users will be running old versions of the application until it restarts.
I didn't get what you got stuck on. Just create a timer, and on user interaction, reset the timer, to e.g. 5 minutes. Then, when the timer fires, show the message box, and create another timer, when that one fires, just kill the current process.
Rather tangential answer but if the issue is people leaving workstations up and logged on then take a look at something like nightwatchman from www.1e.com that powers down the PC after x period of inactivity. Sell it to your company as "doing your bit for the environment" and saving wasted electricity costs.

Prevent a process from being killed in C#?

Ok, the title is my question.
No, this ain't for malware. It is for a parental control program for my own netbook.
Yes, I am tired of my brother's friends visiting porn sites on my laptop when I am away.
Oh, yes, I have red other questions and don't do the "You can't!" thing. It must be possible.
Well, you could run several processes, and when one of them is killed, one of the others would launch a replacement. You can also run a service that would monitor the process and launch another process when the process is killed.
Sorry, I can't comment so I've posted this as a 'answer'.
A few things to consider:
Is a 13 year old or his friends going to notice a process in taskmanager that shouldn't be there? (for example a second explorer.exe, svchost.exe etc.)
What are you trying to actually achieve as there may be other ways to do what it is you want. Are you trying to block them from going on certain sites? Are you trying to monitor what they do? Are you trying to prove to your mum what they are doing? Something else?
Unless you are trying to block them, will they care about anything you may have running? Would they bother to look for 'logging' software running on the PC? I would guess that they wouldn't bother to even open task manager unless the sites weren't working.
If you are trying to give proof or monitor your pc, running a VNC service in the background allows you to connect a viewer from another computer so that you/your mum can watch a live view of what they are up to.
If you want to monitor the sites then you have a wide range of options: keylogging software, browser logging software, proxy software or logging software on your router
If you want to block the sites then you also have a wide range of solutions: hosts file, dns based blocking (e.g. openDNS), blocking software on the pc (e.g. netnanny), blocking software on the router, etc.
Remember: If you are trying to block sites remember that nothing will block 100% of websites. You will only achieve 1 of 2 things: (Ideally) it becomes too much effort trying to find sites not blocked and they use another computer for their porn -or- they persist and find a way around it/to disable it/sites that it doesn't catch
what about unstoppable service ? MSDN
Yes, it is possible, I recently wanted to do the same thing, just came across what is known as Protected Windows Services.
I know this requires a lot of effort but when it's successfully implemented there's no way not even Admin can kill the process.
You'll need to write an additional ELAM Driver for this to work :ELAM Prerequisites - Microsoft Docs
Here is the link where it is described
Register service as protected service
Posted this answer as an Idea ...... If there's any problem I'll delete it.

Updating a Running Service with another Version? [C#]

I need to find a reliable way to update a running Windows Service (Service.exe).
The service is run under the LocalSystem account whereas the logged-in user is in a non-admin User account.
My current solution would be as follows:
- The Service.exe checks for updates (files) regularily
- When an update it found it starts another service (Launcher.exe) that would stop the Service.exe, copy over the files, restart Service.exe, then stop itself
After doing some online-reading and from some of my previous forum posts I beleive this would be the appropriate solution - but before I go ahead I wanted to check with all the guru's and see if I am forgetting something important or if there is a better way.
I did read-up on some method of self-updating (loading & unloading assemblies, etc...) but it just seemed very unsure and I need this to be as robust as possible - if it fails it means someone needs to manually intervene.
Any help or hints would be much appreciated.
Thanks,
The download / stop / apply changes / restart procedure is a fairly common and robust one. I definitely wouldn't try to get into the business of doing it without restarting. It may well be possible in many cases, but it's going to be a lot harder to get right.
Don't forget to make sure you can update the updater, by the way...
You could write a bootstrapper service as well.
Basically it's a lightweight service that you install, it watches a directory for dll's that match a certain interface.
Anything that matches, it loads up and runs as a service inside of itself.
Have it load two dlls to start. One is your service, the other is your update service.
Since there is virtually no code in the bootstrapper it shouldn't need to be updated.
But your updater will be able to update itself, and the service dll periodically.
How your updater works is up to you. We found that having a publish location on our network, and just watching the folder for updates, additions and delete's and synching the local dll folder was sufficient, but you could have it monitor a config file that point to dlls all over if that is what is needed (had to do that for one worldwide update system).
It's a bit tricky to get it all setup and working correctly. But once it is, it works great.
That is quite the right solution, however somebody (usually the main service) needs to carry code to update the launcher.
The launcher cannot do itself for what should be obvious reasons.
I do a double launcher (launcher spawns second service that updates both) to simplify update checks.
BTW even in the UNIX world we apply the same basic steps only we overwrite the running binary while the service is still running. In the Windows world you can do the same thing by renaming all files you are about to overwrite out of the way first.

What could cause a Windows Service to hang when a Console App doing the exact same thing using the exact same base libraries doesn't?

I hate asking questions like this - they're so undefined... and undefinable, but here goes.
Background:
I've got a DLL that is the guts of an application that is a timed process. My timer receives a configuration for the interval at which it runs and a delegate that should be run when the interval elapses. I've got another DLL that contains the process that I inject.
I created two applications, one Windows Service and one Console Application. Each of the applications read their own configuration file and load the same libraries pushing the configured timer interval and delegate into my timed process class.
Problem:
Yesterday and for the last n weeks, everything was working fine in our production environment using the Windows Service. Today, the Windows Service will run for a period of around 20-30 minutes and hangs (with a timer interval of 30 secods), but the console application runs without issue and has for the past 4 hours. Detailed logging doesn't indicate any failure. It's as if the Windows Service just...dies quietly - without stopping.
Given that my Windows Service and Console Applications are doing the exact same thing, I can only think that there is something that is causing the Windows Service process to hang - but I have no idea what could be causing that. I've checked the configuration files, and they're both identical - I even copied and pasted the contents of one into the other just to be sure. No dice.
Can anyone make suggestions as to what might cause a Windows Service to hang, when a counterpart Console Application using the same base libraries doesn't; or can anyone point me in the direction of tools that would allow me to diagnose what could be causing this issue?
Thanks for everyone's help - still digging.
You need to figure out what changed on the production server. At first, the IT guys responsible will swear that nothing changed but you have to be persistent. i've seen this happen to often i've lost count. Software doesn't spoil. Period. The change must have been to the environment.
Difference in execution: You have two apps running the same code. The most likely difference (and culprit) is that the service is running with a different set of security credentials than your console app and might fall victim to security vagaries. Check on that first. Which Windows account is running the service? What is its role and scope? Is there any 3rd party security software running on the server and perhaps Killing errant apps? Do you have to register your service with a 3rd party security service? Is your .Net assembly properly signed? Are your .Net assemblies properly registered and configured on the server? Last but not least, don't forget that a debugger user, which you most likely are, gets away with a lot more stuff than many other account types.
Another thought: Since timing seems to be part of the issues, check the scheduled tasks on the machine. Perhaps there's a process that is set to go off every 30 minutes that is interfering with your own.
You can debug a Windows service by running it interactively within Visual Studio. This may help you to isolate the problem by setting (perhaps conditional) breakpoints.
Alternatively, you can use the Visual Studio "Attach to process" dialog window to find the service process and attach to it with the "Debug CLR" option enabled. Again this allows you to set breakpoints as needed.
Are you using any assertions? If an assertion fires without being re-directed to write to a log file, your service will hang. If the code throws an unhandled exception, perhaps because of a memory leak, then your service process will crash. If you set the Service Control Manager (SCM) to restart your process in the event of a crash, you should be able to see that the service has been restarted. As you have identical code running in both environments, these two situations don't seem likely. But remember that your service is being hosted by the SCM, which means a very different environment to the one in which your console app is running.
I often use a "heartbeat", where each active thread in the service sends a regular (say every 30 seconds) message to a local MSMQ. This enables manual or automated monitoring, and should give you some clues when these heartbeat messages stop arriving.
Annother possibility is some sort of permissions problem, because the service is probably running with a different local/domain user to the console.
After the hang, can you use the SCM to stop the service? If you can't, then there is probably some sort of thread deadlock problem. After the service appears to hang, you can go to a command-line and type sc queryex servicename. This should give you the current STATE of the service.
I would probably put in some file logging just to see how far the program is getting. It may give you a better idea of what is looping/hanging/deadlocked/crashing.
You can try these techniques
Logging start logging the flow of the code in the service. Have this parameter based so you dont have a deluge after you are done. You should log all function names, parameters, timestamps.
Attach Debugger Locally or Remotely attach a debugger with the code to the running service, set appropriate breakpoints (can be based on the data gathered from logging)
PerfMon Run this utility and gather information about the machine that the service is running on for any additional clues (high CPU spikes, IO spikes, excessive paging, etc)
Microsoft provides a good resource on debugging a Windows Service. That essentially sounds like what you'd have to do given that your question is so generic. With that said, has any changes been made to the system over the last few days that could aversely affect the service? Have you made any updates to the code that change the way the service might possibly work?
Again, I think you're going to have to do some serious debugging to find your problem.
What type of timer are you using in the windows service? I've seen numberous people on SO have problems with timers and windows services. Here is a good tutorial just to make sure you are setting it up correctly and using the right type of timer. Hope that helps.
Another potential problem in reference to psasik's answer is if your application is relying on something only available when being run in User Mode.
Running in service mode runs in (is it desktop0?) which can cause some issues in my experience if you are trying to determine states of something that can only be seen in user mode.
Smells like a threading issue to me. Is there any threading or async work being done at all? One crucial question is "does the service hang on the same line of code or same method every time?" Use your logging to find out the last thing that happens before a hang, and if so, post the problem code.
One other tool you may consider is a good profiler. If it is .NET code, I believe RedGate ANTS can monitor it and give you a good picture of any threadlock scenarios.

Categories

Resources