Best secure single running app guard on windows - windows

I would like to improve the way how an application is checking that another instance is not already running. Right now we are using named mutexes with checking of running processes.
The goal is to prevent security attacks (as this is security software). My idea right now is that "bulletproof" solution is only to write an driver, that will serve this kind of information and will authenticate client via signed binaries.
Does anyone solved such problem?
What are your opinions and recommendations?

First, let me say that there is ultimately no way to protect your process from agents that have administrator or system access. Even if you write a rootkit driver that intercepts all system calls (a difficult and unsafe practice in of itself), there are still ways to use admin access to get in. You have the wrong design if this is a requirement.
If you set up your secure process to run as a service, you can use the Service Control Manager to start it. The SCM will only start one instance, will monitor that it stays up, allow you to define actions to execute if it crashes, and allow you to query the current status. Since this is controlled by the SCM and the service database can only be modified by administrators, an attacking process would not be able to spoof it.

I don't think there's a secure way of doing this. No matter what kind of system-unique, or user-unique named object you use - malicious 3rd party software can still use the exact same name and that would prevent your application from starting at all.
If you use the method of checking the currently executing processes, and checking if no executable with the same name is running - you'd run into problems, if the malicious software has the same executable name. If you also check the path, of that executable - then it would be possible to run two copies of your app from different locations.
If you create/delete a file when starting/finishing - that might be tricked as well.
The only thing that comes to my mind is you may be able to achieve the desired effect by putting all the logic of your app into a COM object, and then have a GUI application interact with it through COM interfaces. This would, only ensure, that there is only one COM object - you would be able to run as many GUI clients as you want. Note, that I'm not suggesting this as a bulletproof method - it may have it's own holes (for example - someone could make your GUI client to connect to a 3rd party COM object, by simply editing the registry).
So, the short answer - there is no truly secure way of doing this.

I use a named pipe¹, where the name is derived from the conditions that must be unique:
Name of the application (this is not the file name of the executable)
Username of the user who launched the application
If the named pipe creation fails because a pipe with that name already exists, then I know an instance is already running. I use a second lock around this check for thread (process) safety. The named pipe is automatically closed when the application terminates (even if the termination was due to an End Process command).
¹ This may not be the best general option, but in my case I end up sending data on it at a later point in the application lifetime.

In pseudo code:
numberofapps = 0
for each process in processes
if path to module file equals path to this module file
increment numberofapps
if number of apps > 1
exit
See msdn.microsoft.com/en-us/library/ms682623(VS.85).aspx for details on how to enumerate processes.

Related

Deploy go web project on windows server 2008

My project: go - 1.12.5; gin-gonic; vue-cli - 3.8.2.
On windows server 2008 go under the local account, run main.exe - works well. But when log off my account, all local account programs are closed, including my go server.
The first thing I did was try to configure IIS for my GO. Nothing good came of it.
Then I tried to run main.exe from the SYSTEM account psexec -s c:\rafd\main.exe. When log off the process does not close. But the frontend is in my account and SYSTEM does not see the local files (js, html, css) of my project
Tell me how to start the Go server, to after log off my project did not stop life
Two ways to approach it.
Go with ISS (or another web server).
Should you pick this option, you have further choices:
Leave your project's code as is, but
Make sure it's able to be told which socket to listen for connections on—so that you can tell it to listen, say, on localhost:8080.
For instance, teach your program to accept a command-line parameter for that—such as -listen or whatever.
Configure IIS in a way so that it reverse-proxies incoming HTTP requests on a certain virtual host and/or path prefix to a running instance of your server. You'll have to make the IIS configuration—the socket it proxies the requests to—and the way IIS starts your program agree with each other.
Rework the code to use FastCGI protocol instead.
This basically amounts to using net/fastcgi instead of net/http.
The upside is that IIS (even its dirt-old versions) support FastCGI out of the box.
The downsides are that FastCGI is beleived to be slightly slower than plain HTTP in Go, and that you'll lose the ability to run your program in the standalone mode.
Turn your program into a proper Windows™ service or "wrap" it with some helper tool to make it a Windows™ service.
The former is cleaner as it allows your program to actually be aware of control requests the Windows Service Management subsystem would send to you. You could also easily turn your program into a shrink-wrapped product, if/when needed. You could start with golang.org/x/sys/windows/svc.
The latter may be a bit easier, but YMMV.
If you'd like to explore this way, look for tools like srvany, nssm, winsv etc.
Note that of these, only srvany is provided by Microsoft® and, AFAIK, it's missing since Win7, W2k8, so your best built-in bet might be messing with sc.exe.
In either case, should you pick this route, you'll have to deal with the question of setting up proper permissions on your app's assets.
This question is reasonably complex in itself since there are many moving parts involved.
For a start, you have to make sure your assets are tried to be accessed not from "the process' current directory"—which may be essentially random when it runs as a service—but either from the place the process was explicitly told about when run (via command-line option or whatever) or figured out somehow using a reasonably engeneered guess (and this is a complicated topic in itself).
Next, you either have to make sure the account your Windows™ uses to run your service really has the permissions to access the place your assets are stored in.
Another possibility is to add a dedicated account and make the SCM use it for running your service.
Note that in either case proper error handling and their reporting is paramount: when your program is being run non-interactively, you want to know when something goes wrong: socket failed to be opened or listened on, assets not found, access was denied when trying to open an asset file, and so on—in all these cases you have to 1) handle the error, and 2) report it in a way you can deal with it.
For a non-interactive Windows™ program the best way may be to use the Event Log (say, via golang.org/x/sys/windows/svc/eventlog).
Simplest solutions would be using windows schedular.
Start your exe file on system logon with highest privilage in background. So whenever your system will logon it will start your exe and make runnign in background.
You can refer this answer,
How do I set a Windows scheduled task to run in the background?

Ways to find out if the process is created by system (by pid) on macOS?

I'm implementing API which allows to launch other apps (using NSTask) inside VFS (FUSE on macOS). After VFS is mounted a bunch of processes start accessing launched VFS in which my app works, and I'd like to implement some kind of filtering mechnism which will allow to detect whether process which is accessing the VFS is created by system (and potentially safe) or not, and if so it'll be granted an access to the file system where my app runs.
So far I'm able to get basic information of the process by it's pid. For example: process path, uid, ppid, code signature of the process etc (using Security framework, libproc etc)
I've done a couple of tests and see that there are process with uid != 0 and still critical for my app to run (if I deny access to them app which is started in VFS crashes) (e.g. /usr/libexec/secinitd, /System/Library/CoreServices/Dock.app/Contents/MacOS/Dock), so looks like approach with filtering processes by pids, uids, ppids might not work.
So the question is: is it possible to distinguish whether process which is accessing my app was created by system and is potentially safe? I also don't want to do too much work by denying accees to critical system processes which will allow the app to successfully start and run in VFS.
Judging from the comment thread, your threat model is data theft via malware etc.
In this case, you can trust almost nothing, so the best way is probably to maintain an explicit whitelist of processes which are allowed to access your mount point, and block access to everything else by default. Log any processes to which access is denied, and allow the user to reverse that decision and add them to the whitelist. In other words, let the user decide what applications they consider safe.
Your said that according to your inspection, there were several processes which were mandatory for the process to run, so why won't use try-and-error approach.
You deploy you FUSE drive on clean environment and record all processes that attempt to access your files - try to prevent each process and keep only those which crash your apps, and add them to a white-list.
Of course that this list is subject to change in different macOS versions, but it can give you the general idea.
Alternatively, you can break your app into couple of parts. for example, put the sensitive logic inside separated dylib file, and prevent access to this file only.. since dylib is not the main executable in your app, I believe fewer processes require mandatory access it.

How to prevent my process from CreateToolhelp32Snapshot?

Is there a way to prevent another process from detecting my process by using CreateToolhelp32Snapshot?
If you are in a environment where you need to protect users from themselves then these users need to be non-admin users and you can simply create a service or task that runs as a different user so it cannot be killed.
If you absolutely need to hide the process and your chosen method is injection & hooking then there are at least 6 things you need to hook in user-mode:
The toolhelp API
The NT4 process API in psapi.dll
The undocumented native NT API
The terminal server API
Performance counters
WMI
A "better" solution is to remove your process from the PsActiveProcessHead list but you need to be in kernel-mode to do that and that means writing a custom driver. If you go down this route your program will be labeled as malware/rootkit by some security tools (and rightly so).

How to identify/authorize the sender of a message in a named pipe? (CreateNamedPipe)

I've created a communication between two applications using named pipes.
The first application creates a named pipe with CreateNamedPipe and reads the received messages with ReadFile sent by the second application. Both applications are able to communicate that way as intended.
Is it somehow possible to identify the sender of a received message?
Without some sort of identification (like getting the sender exe path) or authorization every other application could use that pipe to send messages to my application.
(Edit) Further details, because it seems it's important in this case:
The application that creates the pipe is running as a Windows service.
Both applications run locally on the same system.
The GetNamedPipeClientProcessId() will give you the process ID of the client process. You can then open a handle to the process with OpenProcess() and call GetModuleFileNameEx() to determine what application is running in that process. You can then vet the application in whatever way you think best, e.g., you might want to check the identity of the digital certificate or you might prefer to just check that the pathname is as you expect it to be.
Note that attempting to restrict access to a particular application rather than a particular user is never going to be robust; an attacker could always take control of the approved application and replace its code with their own. Basically it isn't going to be more than a speed bump, but if you feel it is worth doing, it can be done.
If what you really want to know is what user has connected, you should instead be using ImpersonateNamedPipeClient() as already suggested in the comments, followed by OpenThreadToken() and so on. Or better still, set the permissions when creating the named pipe so that only the authorized users are able to connect in the first place.
Now that you've clarified that the client runs with elevated privileges, I can make a more concrete recommendation: do both of the above. Configure the permissions on the named pipe so that only members of the Administrators group can access it; that will ensure that only applications running with elevated privilege can access it. Checking the executable as well won't hurt, but it isn't sufficient by itself, because an attacker could launch a copy of your application, suppress the requested elevatation, and inject their own code into the process. (Or, as conio points out, modify their own process to make it look as if they are running your executable; GetModuleFileNameEx() is not intended to be used as a security measure, so it makes no effort to avoid spoofing.)

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.

Resources