Tuesday, March 22, 2011

Launching external process from a service (vc++/win32)

Microsoft has managed to make this much more difficult than it used to be.  CreateProcessWithLogonW() no longer functions they way it should.  It does require an SID from the user that is launching the process, so LOCALSYSTEM will not work.  However, even if you change the ID the service is running as, the process will not launch properly.

I am posting this example as there are wildly conflicting information out there and most is incorrect.  You may need to change the permissions of the launching user.

This will work:

HANDLE hToken;
if(LogonUser(<ID>,<DOMAIN>,<PWD>,LOGON32_LOGON_INTERACTIVE,0,&hToken))
{
STARTUPINFO si;
ZeroMemory( &si, sizeof(STARTUPINFO) );
si.cb = sizeof(STARTUPINFO);
si.dwFlags |= STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
PROCESS_INFORMATION pi;
ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));
if(!CreateProcessAsUser(hToken,  NULL, <CMDLINE>
, NULL, NULL,TRUE, CREATE_NEW_CONSOLE, NULL, NULL,&si,&pi))
{
    DWORD dw=GetLastError();
   //FAILED!
}else{
    //SUCCESS!
}
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}else{
    DWORD dw=GetLastError();
   //FAILED!
}

No comments:

Post a Comment