Why CreateProcessAsUser fails with "Access denied" when called from service child process - windows-services

I am trying to run process as other user from my service using CreateProcessAsUser function. The example of code was found here CreateProcessAsUser from c++ service creates process but no console.
OS - Windows 10
My code is working fine, when i run it in main service process. But I need run same code from child service process. And in this case CreateProcessAsUser returns 0 and GetLastError = 5 (Access Dennied).
Child service process is created by next call
CreateProcess(NULL, "d:\\child.exe", NULL, NULL, FALSE, 0u, NULL, NULL, &si.StartupInfo, &pi)
My code is working inside "child.exe" binary and should just create one more process, that starts "d:\test.exe" binary in this way
CreateProcessAsUser(hUserTokenDup,
NULL,
"d:\\test.exe",
NULL,
NULL,
FALSE,
CREATE_NEW_CONSOLE | /*CREATE_BREAKAWAY_FROM_JOB |*/ NORMAL_PRIORITY_CLASS,
NULL,
NULL,
&si,
&pi);
For test I moved code to start "test.exe" to same place where "child.exe" is starting (to service main process) and "test.exe" starts fine. For test I replaced CreateProcessAsUser on CreateProcess with same parameters (except user token) and test.exe also starts fine.
But I need start "test.exe" from service child process (from "child.exe") and start it by CreateProcessAsUser. I tryed a lot of solutions from internet (add CREATE_BREAKAWAY_FROM_JOB, use DuplicateTokenEx, use linkedToken, enable all possible privilegies and so on) but no solution helped. I do not expected any difference between service process and child process. But looks like something different and I cannot find what it is.
Can anybody advice, what is a difference between main server process and its child process?

My colleagues found the solution.
I publish it here:
Service child process could start sub-process after flags JOB_OBJECT_LIMIT_BREAKAWAY_OK|JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK has been passed to SetInformationJobObject function in server process before creating service child process. After that calls
WTSGetActiveConsoleSessionId(..
WTSQueryUserToken(...
CreateProcessAsUser(...CREATE_BREAKAWAY_FROM_JOB
work fine event without creating duplicate handle

Related

Lua script in FreeSWITCH exits bridge immediately when bypass_media = true

How do I make the script wait for the bridge to terminate before continuing when I have "bypass_media" set to true?
This snippet -
freeswitch.consoleLog("err","session before="..tostring(session:ready()).."\n")
session:execute("set","bypass_media=true")
session:execute("bridge","sofia/gateway/carrierb/12345678")
freeswitch.consoleLog("err","session after="..tostring(session:ready()).."\n")
from an audio perspective, it works perfectly with bridge_media set to either true or false, and a wireshark trace shows the audio either passing through (false) or end to end (true).
But with bypass set to true, the script continues without pausing, and the session is no longer ready (session:ready() == false).
The channel seems to go into a hibernate state, but I have housekeeping to do after the bridge is finished which I simply cannot do.
Same happens if i do the bridge in XML dialplan, immediately carries on causing my housekeeping to fire early.
FreeSWITCH (Version 1.6.20 git 43a9feb 2018-05-07 18:56:11Z 64bit)
Lua 5.2
EDIT 1 -
I can get "api_hangup_hook=lua housekeeping.lua" to work, but then I have to pass tons of variables and it fires up a new process/thread/whatever, which seems a little overkill unless that's the only way.
I have a workaround, but would still like an answer to the question if anyone has one (ie how to stop the bridge exiting immediately).
If I set this before the bridge :
session:execute("set","bypass_media=true")
session:execute("set","session_in_hangup_hook=true")
session:execute("set","api_hangup_hook=lua housekeeping.lua "..<vars>)
then "housekeeping.lua" fires when the bridge actually terminates (which is long after the script does).
In housekeeping.lua I can then do :
session:getVariable("billmsec")
and it seems to have the correct values in them, allowing me to do my housekeeping.
My problem with this is the uncertainty of playing with variables from a session that appears to have gone away from a script that fires at some point in the future.
Anyway, it'll have to do until I can find out how to keep control inside the original script.

Default process flags

Is there a way to instruct the Erlang VM to apply a set of process flags to every new process that is spawned in the system?
For example in testing environment I would like every process to have save_calls flag set.
One way for doing this is to combine the Erlang tracing functionalities with a .erlang file.
Specifically, you could either use the low-level tracing capabilities provided by erlang:trace/3 or you could simply exploit the dbg:tracer/2 function to create a new tracing process which executes your custom handler function every time a tracing message is received.
To automate things a bit, you could then create an Erlang Start Up File in the directory where you're running your code or in your home directory. The Erlang Start Up File is a special file, called .erlang, which gets executed every time you start the run-time system.
Something like the following should do the job:
% -*- Erlang -*-
erlang:display("This is automatically executed.").
dbg:tracer(process, {fun ({trace, Pid, spawn, Pid2, {M, F, Args}}, Data) ->
process_flag(Pid2, save_calls, Data),
Data;
(_Trace, Data) ->
Data
end, 100}).
dbg:p(new, [procs, sos]).
Basically, I'm creating a new tracing process, which will trace processes (first argument). I'm specifying an handler function to get executed and some initial data. In the handler function, I'm setting the save_calls flag for newly spawned processes, whilst I'm ignoring all other tracing messages. I set the save_calls' option to 100, using the Initial Data parameter. In the last call, I'm telling dbg that I'm interested only in newly created processes. I'm also setting the sos (set_on_spawn) option to ensure inheritance of the tracing flags.
Finally, note how you need to use a variant of the process_flag function, which takes an extra argument (the Pid of the process you want to set the flag for).

ServiceController seems to be unable to stop a service

I'm trying to stop a Windows service on a local machine (the service is Topshelf.Host, if that matters) with this code:
serviceController.Stop();
serviceController.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
timeout is set to 1 hour, but service never actually gets stopped. Strange thing with it is that from within Services MMC snap-in I see it in "Stopping" state first, but after a while it reverts back to "Started". However, when I try to stop it manually, an error occurs:
Windows could not stop the Topshelf.Host service on Local Computer.
Error 1061: The service cannot accept control messages at this time.
Am I missing something here?
I know I am quite late to answer this but I faced a similar issue , i.e., the error: "The service cannot accept control messages at this time." and would like to add this as a reference for others.
You can try killing this service using powershell (run powershell as administrator):
#Get the PID of the required service with the help of the service name, say, service name.
$ServicePID = (get-wmiobject win32_service | where { $_.name -eq 'service name'}).processID
#Now with this PID, you can kill the service
taskkill /f /pid $ServicePID
Either your service is busy processing some big operation or is in transition to change the state. hence is not able to accept anymore input...just think of it as taking more than it can chew...
if you are sure that you haven't fed anything big to it, just go to task manager and kill the process for this service or restart your machine.
I had exact same problem with Topshelf hosted service. Cause was long service start time, more than 20 seconds. This left service in state where it was unable to process further requests.
I was able to reproduce problem only when service was started from command line (net start my_service).
Proper initialization for Topshelf service with long star time is following:
namespace Example.My.Service
{
using System;
using System.Threading.Tasks;
using Topshelf;
internal class Program
{
public static void Main()
{
HostFactory.Run(
x =>
{
x.Service<MyService>(
s =>
{
MyService testServerService = null;
s.ConstructUsing(name => testServerService = new MyService());
s.WhenStarted(service => service.Start());
s.WhenStopped(service => service.Stop());
s.AfterStartingService(
context =>
{
if (testServerService == null)
{
throw new InvalidOperationException("Service not created yet.");
}
testServerService.AfterStart(context);
});
});
x.SetServiceName("my_service");
});
}
}
public sealed class MyService
{
private Task starting;
public void Start()
{
this.starting = Task.Run(() => InitializeService());
}
private void InitializeService()
{
// TODO: Provide service initialization code.
}
[CLSCompliant(false)]
public void AfterStart(HostControl hostStartedContext)
{
if (hostStartedContext == null)
{
throw new ArgumentNullException(nameof(hostStartedContext));
}
if (this.starting == null)
{
throw new InvalidOperationException("Service start was not initiated.");
}
while (!this.starting.Wait(TimeSpan.FromSeconds(7)))
{
hostStartedContext.RequestAdditionalTime(TimeSpan.FromSeconds(10));
}
}
public void Stop()
{
// TODO: Provide service shutdown code.
}
}
}
I've seen this issue as well, specifically when a service is start pending and I send it a stop programmatically which succeeds but does nothing. Also sometimes I see stop commands to a running service fail with this same exception but then still actually stop the service. I don't think the API can be trusted to do what it says. This error message explanation is quite helpful...
http://technet.microsoft.com/en-us/library/cc962384.aspx
I run into a similar issue and found out it was due to one of the services getting stuck in a state of start-pending, stop pending, or stopped.
Rebooting the server or trying to restart services did not work.
To solve this, I run the Task Manager in the server and in the "Details" tab I located the services that were stuck and killed the process by ending the task. After ending the task I was able to restart services without problem.
In brief:
1. Go to Task Manager
2. Click on "Detail" tab
3. Locate your service
4. Right click on it and stop/kill the process.
That is it.
I know it was opened while ago, but i am bit missing the option with Windows command prompt, so only for sake of completeness
Open Task Manager and find respective process and its PID i.e PID = 111
Eventually you can narrow down the executive file i.e. Image name = notepad.exe
in command prompt use command TASKKILL
example: TASKKILL /F /PID 111 ; TASKKILL /F /IM notepad.exe
I had this exact issue internally when starting and stopping a service using PowerShell (Via Octopus Deploy). The root cause for the service not responding to messages appeared to be related to devs accessing files/folders within the root service install directory via an SMB connection (looking at a config file with notepad/explorer).
If the service gets stuck in that situation then the only option is to kill it and sever the connections using computer management. After that, service was able to be redeployed fine.
May not be the exact root cause, but something we now check for.
I faced the similar issue. This error sometimes occur because the service can no longer accept control messages, this may be due to disk space issues in the server where that particular service's log file is present.
If this occurs, you can consider the below option as well.
Go to the location where the service exe & its log file is located.
Free up some space
Kill the service's process via Task manager
Start the service.
I just fought this problem while moving code from an old multi partition box to a newer single partition box. On service stop I was writing to D: and since it didn't exist anymore I got a 1061 error. Any long operation during the OnStop will cause this though unless you spin the call off to another thread with a callback delegate.

Showing HTML Help (chm) from interactive service on XP

I have a C++ App than can optionally run as Windows Service on XP and interacts with the Desktop (yes, I know it's bad practice but it's been around for a long time!)
Retrofitting html help to it I've discovered HtmlHelp() doesn't work from a service. I've tried running hh.exe using CreateProcess() and ShellExecute() with no success. On the other hand, running Write using CreateProcess works fine, so there must be something different about hh.exe. No amount of googling has shed any light. How can I fire up a chm file from a service?
PROCESS_INFORMATION ProcInfo;
STARTUPINFO si;
memset(&si, '\0', sizeof(STARTUPINFO));
si.cb = sizeof(STARTUPINFO);
//si.lpDesktop = "winsta0\\default"; // <-- doesn't make any difference
char *helpcmd = "hh.exe c:\\help\myhelpfile.chm";
BOOL bSuccess = ::CreateProcess(NULL, helpcmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, &ProcInfo);
Finally found an answer to this:
Under the registry key:
HKLM\SOFTWARE\Microsoft\HTMLHelp\1.x\HHRestrictions
Make a new DWORD value key:
EnableNonInteractiveUser
And set the value to 1.
This will allow an interactive service process on XP to show HTML Help.
If your service process is already running you may need to restart it before this will work (the need to do this or not depends on how your program run-time system starts the HTML Help viewer - cached results mean that it might not work until restart.)
At this stage its unknown to me if the same change will work for Vista, Win7 or Win8.

Windows Service Starts then Stops

I have a Windows Service that I inherited from a departed developer. The Windows Service is running just fine in the QA environment. When I install the service and run it locally, I receive this error:
Service cannot be started. System.InvalidOperationException: The requested Performance Counter is not a custom counter, it has to be initialized as ReadOnly.
Here is the code:
ExternalDataExchangeService exchangeService = new ExternalDataExchangeService();
workflowRuntime.AddService(exchangeService);
workflowRuntime.AddService(new SqlTrackingService(AppContext.SqlConnectionImportLog));
ChallengerWorkflowService challengerWorkflowService = new ChallengerWorkflowService();
challengerWorkflowService.SendDataEvent += new EventHandler<SendDataEventArgs>(challengerWorkflowService_SendDataEvent);
workflowRuntime.AddService(challengerWorkflowService);
workflowRuntime.StartRuntime(); <---- Exception is thrown here.
Check for installer code. Often you will find counters are created within an installation (which is going to of been run under admin privledges on client site) and the code then uses them as though they exist - but will not try create them because they do not expect to have the permissions.
If you just get the source and then try run it, the counters / counter classes do not exist so you fall over immediately. (Alternatively check whether the counter exists / you have local admin if they wrote the code to create it in the service.)
Seen it before so mentioned it.
Attach Debugger and break on InvalidOperationException (first-chance, i.e. when thrown)?

Resources