CreateprocessAsUserA Using LogonUserA - c++

LPCSTR lpszUsername = "admin user";
LPCSTR lpszDomain = "DESKTOP-H60GO83";
LPCSTR lpszPassword = "password";
DWORD dwLogonType = LOGON32_LOGON_INTERACTIVE;
DWORD dwLogonProvider = LOGON32_PROVIDER_WINNT40;
PHANDLE hToken;
LogonUserA(
lpszUsername,
lpszDomain,
lpszPassword,
dwLogonType,
dwLogonProvider,
hToken);
memset(&sui, 0, sizeof(sui));
sui.cb = sizeof(sui);
LPTSTR lpApplicationName = "C:\\Windows\\System32\\cmd.exe ";
CreateProcessAsUserA(
hToken,
lpApplicationName,
NULL,
NULL,
NULL,
TRUE,
NULL,
NULL,
NULL,
&sui,
&pi
);
That's my code. What am I doing wrong? Process exits immediately when the console loads.
I need this to add to my reverse shell.
I used CreateProcess() and it worked. I'm using CreateProcessAsUserA() to give my shell admin privileges.

You are not using the hToken variable correctly.
You have declared an uninitialized pointer to a HANDLE, but are not pointing it at a valid HANDLE. You are then passing that bad pointer to LogonUserA(), which is undefined behavior. And then you are passing that bad pointer to CreateProcessAsUserA(), which doesn't even want a pointer to a HANDLE to begin with, it wants the actual HANDLE instead.
You are also not checking for errors from the API calls.
Try this instead:
LPCSTR lpszUsername = "admin user";
LPCSTR lpszDomain = "DESKTOP-H60GO83";
LPCSTR lpszPassword = "password";
DWORD dwLogonType = LOGON32_LOGON_INTERACTIVE;
DWORD dwLogonProvider = LOGON32_PROVIDER_WINNT40;
HANDLE hToken = NULL; // <-- no P !
if (!LogonUserA(
lpszUsername,
lpszDomain,
lpszPassword,
dwLogonType,
dwLogonProvider,
&hToken)) // <-- add & !
{
// error handling...
}
STARTUPINFO sui;
memset(&sui, 0, sizeof(sui));
sui.cb = sizeof(sui);
PROCESS_INFORMATION pi;
LPTSTR lpApplicationName = "C:\\Windows\\System32\\cmd.exe";
if (!CreateProcessAsUserA(
hToken,
lpApplicationName,
NULL,
NULL,
NULL,
TRUE,
NULL,
NULL,
NULL,
&sui,
&pi
))
{
// error handling ...
}
...
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);

/*
author: #......MARSHA4CODING
*/
#include <iostream>
#include <windows.h>
using namespace std;
STARTUPINFO sui;
PROCESS_INFORMATION pi;
int main(){
LPCSTR lpszUsername = "ADMIN";
LPCSTR lpszDomain = " DESKTOP-
H60GO73";
LPCSTR lpszPassword = "PASSWORD" ;
DWORD dwLogonType =
LOGON32_LOGON_INTERACTIVE;
DWORD dwLogonProvider =
LOGON32_PROVIDER_DEFAULT ;
HANDLE hToken = NULL; // <-- no P !
if (!LogonUserA(
lpszUsername,
lpszDomain,
lpszPassword,
dwLogonType,
dwLogonProvider,
&hToken)) // <-- add & !
{
DWORD rx2 = GetLastError();
return rx2;
}
STARTUPINFO sui;
memset(&sui, 0, sizeof(sui));
sui.cb = sizeof(sui);
PROCESS_INFORMATION pi;
LPTSTR lpApplicationName =
"C:\\Windows\\System32\\cmd.exe";
HANDLE phNewToken; // stores either the
Primary or Impersonation token gotten
from DuplicateTokenEx
//LPSECURITY_ATTRIBUTES
lpTokenAttributes
//SECURITY_IMPERSONATION_LEVEL
ImpersonationLevel
if(!DuplicateTokenEx(hToken,
0,lpTokenAttributes,
ImpersonationLevel,1,phNewToken)){
cout<<"Duplication Error";
}
if (!CreateProcessAsUserA(
hToken,
lpApplicationName,
NULL,
NULL,
NULL,
TRUE,
NULL,
NULL,
NULL,
&sui,
&pi
))
{
DWORD rx2 = GetLastError();
return rx2;
}
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
return 0;
}
I think the issue is with the
DuplicateTokenEx();
function because the token I'm supposed to get from the
LogonUserA();
Will be used to generate either a Primary or Impersonation Token with
DuplicateTokenEx(); function
So my challenge right now is with the
TokenAttributes and Impersonationlevel when using
DuplicateTokenEx(): function I don't know what to write there, Pardon my silly Questions.

Related

Anyone has experience on using GetAppContainerNamedObjectPath?

Recently I came across a Windows API called GetAppContainerNamedObjectPath. But I have no idea on how I can use it.
I found a msdn page for this api (https://learn.microsoft.com/en-us/windows/win32/api/securityappcontainer/nf-securityappcontainer-getappcontainernamedobjectpath). But it does not have a right example and remarks, parameters are written poorly.
I am getting ERROR_INVALID_PARAMETER(87) error at the end, which tells me something's wrong with the parameters that I put. Here's what I've tried.
#define TokenIsAppContainer 29
#define TokenAppContainerSid 31
#define TokenAppContainerNumber 32
typedef struct _TOKEN_APPCONTAINER_INFORMATION {
PSID TokenAppContainer;
} TOKEN_APPCONTAINER_INFORMATION, *PTOKEN_APPCONTAINER_INFORMATION;
void GetAppContainerProcessInfo(CString & procName)
{
DWORD dwSize = 0;
DWORD dwResult;
HANDLE hToken;
PTOKEN_APPCONTAINER_INFORMATION pAppCoInfo;
WCHAR wcsDebug[1024] = {0,};
WCHAR * pwSID = NULL;
typedef BOOL (WINAPI *_LPGETAPPCONTAINERNAMEOBJECTPATH)(HANDLE, PSID, ULONG, LPWSTR, PULONG);
static _LPGETAPPCONTAINERNAMEOBJECTPATH lpGetAppContainerNamedObjectPath = NULL;
if (0 == lpGetAppContainerNamedObjectPath)
{
HMODULE hKernel32 = LoadLibraryExW(L"kernel32.dll", NULL, 0);
if (hKernel32)
{
lpGetAppContainerNamedObjectPath = reinterpret_cast<_LPGETAPPCONTAINERNAMEOBJECTPATH>(GetProcAddress(hKernel32, "GetAppContainerNamedObjectPath"));
}
}
if (lpGetAppContainerNamedObjectPath)
{
DWORD processId = (DWORD)_ttoi((LPCTSTR)procName);
//HANDLE hProcess = GetProcessHandleByProcessName(procName);
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processId);
if(!OpenProcessToken(hProcess, TOKEN_QUERY, &hToken))
{
dwResult = GetLastError();
swprintf_s( wcsDebug, _countof(wcsDebug), L"OpenProcessToken Error(%u) PID(%d)\n", dwResult, processId );
AfxMessageBox(wcsDebug);
return;
}
if (!GetTokenInformation(hToken, (TOKEN_INFORMATION_CLASS) TokenAppContainerSid, NULL, dwSize, &dwSize))
{
dwResult = GetLastError();
if( dwResult != ERROR_INSUFFICIENT_BUFFER )
{
swprintf_s( wcsDebug, _countof(wcsDebug), L"GetTokenInformation Error %u\n", dwResult );
AfxMessageBox(wcsDebug);
return;
}
}
pAppCoInfo = (PTOKEN_APPCONTAINER_INFORMATION) GlobalAlloc( GPTR, dwSize );
if (!GetTokenInformation(hToken, (TOKEN_INFORMATION_CLASS) TokenAppContainerSid, pAppCoInfo, dwSize, &dwSize))
{
dwResult = GetLastError();
swprintf_s( wcsDebug, _countof(wcsDebug), L"GetTokenInformation Error %u\n", dwResult );
AfxMessageBox(wcsDebug);
return;
}
WCHAR wcsNamedObjectPath[MAX_PATH];
ULONG ulRetlen = 0;
BOOL bRet = lpGetAppContainerNamedObjectPath(hToken, pAppCoInfo->TokenAppContainer, _countof(wcsNamedObjectPath), wcsNamedObjectPath, &ulRetlen );
if (bRet)
{
swprintf_s( wcsDebug, _countof(wcsDebug), L"GetAppContainerNamedObjectPath Path(%s)\n", wcsNamedObjectPath );
AfxMessageBox(wcsDebug);
}
else
{
dwResult = GetLastError();
swprintf_s( wcsDebug, _countof(wcsDebug), L"GetAppContainerNamedObjectPath Error %u\n", dwResult );
AfxMessageBox(wcsDebug);
}
if (pwSID)
LocalFree(pwSID);
CloseHandle(hToken)
CloseHandle(hProcess);
}
}
As a side-note, I have tried using wchar_t * and dynamically allocate the memory buffer by calling GetAppContainerNamedObjectPath twice. But still had no chance. Return length does not return a meaningful value.
if you call RtlGetLastNtStatus(); instead GetLastError(); after GetAppContainerNamedObjectPath you will got
STATUS_INVALID_PARAMETER_MIX - An invalid combination of parameters was specified.
this give you more info compare simply invalid parameter.
then look for function signature
BOOL
WINAPI
GetAppContainerNamedObjectPath(
_In_opt_ HANDLE Token,
_In_opt_ PSID AppContainerSid,
_In_ ULONG ObjectPathLength,
_Out_writes_opt_(ObjectPathLength) LPWSTR ObjectPath,
_Out_ PULONG ReturnLength
);
the Token and AppContainerSid declared with In_opt -- this mean that this parameters is optional, and you can pass 0 in place one of it. then ask your self - for what you query token for TokenAppContainerSid ? are system can not do this for you if you pass this token to api ? obvious can. so you not need do this yourself. really you need pass Token to api and in this case AppContainerSid must be 0. or you can pass AppContainerSid to api and in this case Token must be 0. when both AppContainerSid and Token not zero - you and got STATUS_INVALID_PARAMETER_MIX
also as side note - you not need open process with PROCESS_ALL_ACCESS if you need get it token. the PROCESS_QUERY_LIMITED_INFORMATION is enough
really api not do big magic. it return to you
AppContainerNamedObjects\<Sid>
path, where string form of app container sid.(some like S-1-15-2-...)

::SendMessage(apphwnd, WM_GETTEXTLENGTH, 0, 0) return 0

I use ::CreateProcess to create a subprocess, and use ::EnumWindows(&EnumWindowsProc, processInfo.dwThreadId) to get the subprocess's window handle, assign this handle to a global variable apphwnd, then I use length = ::SendMessage(apphwnd, WM_GETTEXTLENGTH, 0, 0); but the length is sometimes is zero.
Why is my subprocess's window handle valid but the windowText sometimes has no value? When can I operate on the window handle correctly after CreateProcess is done?
Here is EnumWindowsProc code :
HWND apphwnd;
int CALLBACK EnumWindowsProc(HWND hwnd, LPARAM param)
{
CString str;
DWORD pID;
DWORD TpID = GetWindowThreadProcessId(hwnd, &pID);//get process id
std::string hwndProcessName = GetProcessNameByHandle(hwnd);
if (TpID == (DWORD)param)
{
apphwnd = hwnd;//hwnd is the window handle
return false;
}
return true;
}
Here is my StartProcess function code:
PROCESS_INFORMATION StartProcess(LPCTSTR program, LPCTSTR args, int sleepTime = 500, STARTUPINFO *pstartupInfo = NULL, DWORD dwCreationFlags = 0, bool isWaitInput = false)
{
HANDLE hProcess = NULL;
PROCESS_INFORMATION processInfo;
STARTUPINFO startupInfo;
::ZeroMemory(&startupInfo, sizeof(startupInfo));
startupInfo.cb = sizeof(startupInfo);
if(::CreateProcess(program, (LPTSTR)args,
NULL, // process security
NULL, // thread security
FALSE, // no inheritance
dwCreationFlags, // no startup flags
NULL, // no special environment
NULL, // default startup directory
&startupInfo,
&processInfo))
{
Sleep(500);
if (true)
{
WaitForInputIdle(processInfo.hProcess, INFINITE);
}
apphwnd = NULL;
hProcess = processInfo.hProcess;
while(true)
{
::EnumWindows(&EnumWindowsProc, processInfo.dwThreadId);//Iterate all windows
if (apphwnd)
{
break;
}
}
} /* success */
return processInfo;
}
Here is what Spy++ shows:

CreateProcessAsUser fail,use GetLastError() to get the error code is 1314

I use win7 os and the develop environment is vs2005.
The situation is I want to create the process as current account's priviledge.(such as: in the normal account ,right click the program choice "run as admin" )
I refer to other people's way:
1.get the token of the process explorer.exe;
2.improve the priviledge;
3.use the CreateProcessAsUser to create a process.
But the CreateProcessAsUser failed,and use GetLastError() to get the error code is 1314.
Because of that, I think I'am crazy now.
Can you tell me what's wrong in my program. Thank you!!!
#include <iostream>
using namespace std;
#include "windows.h"
#include "tlhelp32.h"
BOOL GetProcessTokenByName(HANDLE &hToken, LPTSTR szProcessName)
{
// var init
STARTUPINFO st;
PROCESS_INFORMATION pi;
PROCESSENTRY32 ps;
HANDLE hSnapshot;
ZeroMemory(&st, sizeof(STARTUPINFO));
ZeroMemory(&pi, sizeof(PROCESS_INFORMATIO
N));
st.cb = sizeof(STARTUPINFO);
ZeroMemory(&ps,sizeof(PROCESSENTRY32));
ps.dwSize = sizeof(PROCESSENTRY32);
// find the explorer.exe
hSnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0);
if(hSnapshot == INVALID_HANDLE_VALUE)
{
return FALSE;
}
if(!Process32First(hSnapshot,&ps))
{
return FALSE;
}
do
{
wprintf(_T("%s , %u\n"), ps.szExeFile, ps.th32ProcessID);
// compare the process name
if(lstrcmpi(ps.szExeFile,szProcessName)==0)
{ // find
//*lpPID = ps.th32ProcessID;
//CloseHandle(hSnapshot);
//return TRUE;
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, ps.th32ProcessID);
BOOL bRet = FALSE;
HANDLE tmpToken;
if( OpenProcessToken(hProcess, /*TOKEN_QUERY*/TOKEN_ALL_ACCESS, &tmpToken) )
{
bRet = DuplicateTokenEx(
tmpToken, //_In_ HANDLE hExistingToken,
MAXIMUM_ALLOWED, //_In_ DWORD dwDesiredAccess,
NULL, //_In_opt_ LPSECURITY_ATTRIBUTES lpTokenAttributes,
SecurityIdentification, //_In_ SECURITY_IMPERSONATION_LEVEL ImpersonationLevel,
TokenPrimary, //_In_ TOKEN_TYPE TokenType,
&hToken //_Out_ PHANDLE phNewToken
);
//DWORD dwSessionId = WTSGetActiveConsoleSessionId();
//SetTokenInformation(hToken,TokenSessionId,(void*)dwSessionId,sizeof(DWORD));
//SetPrivilege(hToken, SE_ASSIGNPRIMARYTOKEN_NAME, TRUE);
}
else
{
printf("OpenProcessToken error: %u\n", GetLastError());
}
CloseHandle (hSnapshot);
return (bRet);
}
}while(Process32Next(hSnapshot,&ps));
// didn't find
CloseHandle(hSnapshot);
return FALSE;
}
BOOL RunasUser( )
{
HANDLE hToken;
if( GetProcessTokenByName( hToken, _T("explorer.exe") ) )
{
if( hToken != INVALID_HANDLE_VALUE )
{
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(STARTUPINFO));
si.cb= sizeof(STARTUPINFO);
si.lpDesktop = TEXT("winsta0\\default");
{
TOKEN_PRIVILEGES tp;
tp.PrivilegeCount =1;
if(!LookupPrivilegeValue(NULL,SE_ASSIGNPRIMARYTOKEN_NAME/*SE_DEBUG_NAME*/,&tp.Privileges[0].Luid))
{
printf("LookupPrivilegeValue value Error: %u\n",GetLastError());
}
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if(!AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), (PTOKEN_PRIVILEGES)NULL, NULL) )
{
printf("Adjust Privilege value Error: %u\n",GetLastError());
}
}
printf("Adjust Privilege\n");
{
TOKEN_PRIVILEGES tp;
tp.PrivilegeCount =1;
if(!LookupPrivilegeValue(NULL,SE_INCREASE_QUOTA_NAME/*SE_DEBUG_NAME*/,&tp.Privileges[0].Luid))
{
printf("LookupPrivilegeValue value Error: %u\n",GetLastError());
}
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if(!AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), (PTOKEN_PRIVILEGES)NULL, NULL) )
{
printf("Adjust Privilege value Error: %u\n",GetLastError());
}
}
BOOL bResult = CreateProcessAsUser(
hToken, //_In_opt_ HANDLE hToken,
_T("D:\\GetMac.exe"), //_In_opt_ LPCTSTR lpApplicationName,
NULL, //_Inout_opt_ LPTSTR lpCommandLine,
NULL, //_In_opt_ LPSECURITY_ATTRIBUTES lpProcessAttributes,
NULL, //_In_opt_ LPSECURITY_ATTRIBUTES lpThreadAttributes,
FALSE, //_In_ BOOL bInheritHandles,
NORMAL_PRIORITY_CLASS, //_In_ DWORD dwCreationFlags,
NULL, //_In_opt_ LPVOID lpEnvironment,
NULL, //_In_opt_ LPCTSTR lpCurrentDirectory,
&si, //_In_ LPSTARTUPINFO lpStartupInfo,
&pi //_Out_ LPPROCESS_INFORMATION lpProcessInformation
);
CloseHandle(hToken);
if( bResult )
{
//succeed
return TRUE;
}
else
{ //fail
DWORD dwErr = GetLastError();
printf( "error: %u\n", dwErr );
}
}
}
else
{
printf("GetProcessTokenByName fail\n");
}
return FALSE;
}
int _tmain(int argc, _TCHAR* argv[])
{
BOOL bRet = RunasUser();
printf("result: %d\n", bRet);
system("pause");
return 0;
}

CreateProcessWithLogonW get standard output

I found the below comment on Microsoft's documentation site:
Also, CreateProcessWithLogonW rejects STD handles (0/1/2) i.e. what GetStdHandle() returns by default, when using STARTF_USESTDHANDLES. It returns error 6, invalid handles, because 0/1/2 are not "real" handles. The only way we found to redirect the console input/output was to create custom handles (pipes) and use those instead (e.g. even just as dummy handles that you don't use). This is missing functionality from CreateProcessWithLogonW, because CreateProcess (and maybe CreateProcessAsUser, I didn't verify that) accepts STD handles.
This points to creating custom pipes.
I found this StackOverflow answer which points to using things such as "SafeFileHandle". This is apparently C++/CLI which I am not familiar with how to use. I am using Visual C++ and therefore "native" C++?
I am looking for a simple solution of how to fix this issue. I am a newbie in C++ and the CLI thing confused me because I simply don't know how to use it, or make Visual C++ compatible with it.
Given my normal C++ and my question, HOW EXACTLY would I create the custom pipe which will allow me to get the standard output?
Here is my code:
#include "stdafx.h"
void DisplayError(LPWSTR pszAPI)
{
LPVOID lpvMessageBuffer;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM,
NULL, GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPWSTR)&lpvMessageBuffer, 0, NULL);
//
//... now display this string
//
wprintf(L"ERROR: API = %s.\n", pszAPI);
wprintf(L" error code = %d.\n", GetLastError());
wprintf(L" message = %s.\n", (LPWSTR)lpvMessageBuffer);
//
// Free the buffer allocated by the system
//
LocalFree(lpvMessageBuffer);
ExitProcess(GetLastError());
}
void _tmain(int argc, WCHAR *argv[])
{
STARTUPINFO si;
ZeroMemory( &si, sizeof(STARTUPINFO) );
si.cb = sizeof(STARTUPINFO);
HANDLE pipe1 = CreateNamedPipe(L"\\\\.\\pipe\\pipe1", PIPE_ACCESS_DUPLEX,
PIPE_WAIT, 1024, 1024, 1024, 60, NULL);
HANDLE pipe2 = CreateNamedPipe(L"\\\\.\\pipe\\pipe2", PIPE_ACCESS_DUPLEX,
PIPE_WAIT, 1024, 1024, 1024, 60, NULL);
si.dwFlags |= STARTF_USESHOWWINDOW;
si.dwFlags = STARTF_USESTDHANDLES;
si.hStdOutput = pipe1;
si.hStdError = pipe2;
DWORD dwSize;
HANDLE hToken;
LPVOID lpvEnv;
PROCESS_INFORMATION pi = {0};
WCHAR szUserProfile[256] = L"";
si.cb = sizeof(STARTUPINFO);
if (argc != 4)
{
wprintf(L"Usage: %s [user#domain] [password] [cmd]", argv[0]);
wprintf(L"\n\n");
return;
}
//
// TO DO: change NULL to '.' to use local account database
//
if (!LogonUser(argv[1], NULL, argv[2], LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT, &hToken))
DisplayError(L"LogonUser");
if (!CreateEnvironmentBlock(&lpvEnv, hToken, TRUE))
DisplayError(L"CreateEnvironmentBlock");
dwSize = sizeof(szUserProfile)/sizeof(WCHAR);
if (!GetUserProfileDirectory(hToken, szUserProfile, &dwSize))
DisplayError(L"GetUserProfileDirectory");
//
// TO DO: change NULL to '.' to use local account database
//
if (!CreateProcessWithLogonW(argv[1], NULL, argv[2],
LOGON_WITH_PROFILE, NULL, argv[3],
CREATE_UNICODE_ENVIRONMENT, lpvEnv, szUserProfile,
&si, &pi))
DisplayError(L"CreateProcessWithLogonW");
if (!DestroyEnvironmentBlock(lpvEnv))
DisplayError(L"DestroyEnvironmentBlock");
CloseHandle(hToken);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
I tried this and I am getting no output on the console window. As I said, I checked the answer on StackOverflow and this whole C++/CLI thing confuses me. If someone knows a simple solution to redirecting the output using a custom pipe using Visual C++, let me know.
And if I did anything wrong above, let me know as well.
EDIT:
After following the suggestions given by Remy's answer. I came up with the following code, which yields an error code 3: The system cannot find the path specified.
#include "stdafx.h"
HANDLE g_hChildStd_IN_Rd = NULL;
HANDLE g_hChildStd_IN_Wr = NULL;
HANDLE g_hChildStd_OUT_Rd = NULL;
HANDLE g_hChildStd_OUT_Wr = NULL;
HANDLE g_hInputFile = NULL;
int BUFSIZE = 1064;
void CreateChildProcess(void);
void WriteToPipe(void);
void ReadFromPipe(void);
void ErrorExit(PTSTR);
void DisplayError(LPWSTR pszAPI)
{
LPVOID lpvMessageBuffer;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM,
NULL, GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPWSTR)&lpvMessageBuffer, 0, NULL);
//
//... now display this string
//
wprintf(L"ERROR: API = %s.\n", pszAPI);
wprintf(L" error code = %d.\n", GetLastError());
wprintf(L" message = %s.\n", (LPWSTR)lpvMessageBuffer);
//
// Free the buffer allocated by the system
//
LocalFree(lpvMessageBuffer);
ExitProcess(GetLastError());
}
void _tmain(int argc, WCHAR *argv[])
{
SECURITY_ATTRIBUTES saAttr;
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0) )
ErrorExit(TEXT("StdoutRd CreatePipe"));
if ( ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0) )
ErrorExit(TEXT("Stdout SetHandleInformation"));
if (! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0))
ErrorExit(TEXT("Stdin CreatePipe"));
if ( ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
ErrorExit(TEXT("Stdin SetHandleInformation"));
/////////////////////////////Start CreateChildProcess////////
STARTUPINFO si;
ZeroMemory( &si, sizeof(STARTUPINFO) );
si.cb = sizeof(STARTUPINFO);
si.dwFlags |= STARTF_USESHOWWINDOW;
si.dwFlags |= STARTF_USESTDHANDLES;
si.hStdError = g_hChildStd_OUT_Wr;
si.hStdOutput = g_hChildStd_OUT_Wr;
si.hStdInput = g_hChildStd_IN_Rd;
DWORD dwSize;
HANDLE hToken;
LPVOID lpvEnv;
PROCESS_INFORMATION pi = {0};
WCHAR szUserProfile[256] = L"";
si.cb = sizeof(STARTUPINFO);
if (argc != 4)
{
wprintf(L"Usage: %s [user#domain] [password] [cmd]", argv[0]);
wprintf(L"\n\n");
return;
}
//
// TO DO: change NULL to '.' to use local account database
//
if (!LogonUser(argv[1], NULL, argv[2], LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT, &hToken))
DisplayError(L"LogonUser");
if (!CreateEnvironmentBlock(&lpvEnv, hToken, TRUE))
DisplayError(L"CreateEnvironmentBlock");
dwSize = sizeof(szUserProfile)/sizeof(WCHAR);
if (!GetUserProfileDirectory(hToken, szUserProfile, &dwSize))
DisplayError(L"GetUserProfileDirectory");
//
// TO DO: change NULL to '.' to use local account database
//
if (!CreateProcessWithLogonW(argv[1], NULL, argv[2],
LOGON_WITH_PROFILE, NULL, argv[3],
CREATE_UNICODE_ENVIRONMENT, lpvEnv, szUserProfile,
&si, &pi))
DisplayError(L"CreateProcessWithLogonW");
if (!DestroyEnvironmentBlock(lpvEnv))
DisplayError(L"DestroyEnvironmentBlock");
CloseHandle(hToken);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
/////////////////////////////End CreateChildProcess///////////
if (argc == 1)
ErrorExit(TEXT("Please specify an input file.\n"));
g_hInputFile = CreateFile(
argv[3],
GENERIC_READ,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_READONLY,
NULL);
if ( g_hInputFile == INVALID_HANDLE_VALUE )
ErrorExit(TEXT("CreateFile"));
WriteToPipe();
printf( "\n->Contents of %s written to child STDIN pipe.\n", argv[1]);
printf( "\n->Contents of child process STDOUT:\n\n", argv[1]);
ReadFromPipe();
}
void WriteToPipe(void)
// Read from a file and write its contents to the pipe for the child's STDIN.
// Stop when there is no more data.
{
DWORD dwRead, dwWritten;
CHAR chBuf[4096];
BOOL bSuccess = FALSE;
for (;;)
{
bSuccess = ReadFile(g_hInputFile, chBuf, BUFSIZE, &dwRead, NULL);
if ( ! bSuccess || dwRead == 0 ) break;
bSuccess = WriteFile(g_hChildStd_IN_Wr, chBuf, dwRead, &dwWritten, NULL);
if ( ! bSuccess ) break;
}
// Close the pipe handle so the child process stops reading.
if ( ! CloseHandle(g_hChildStd_IN_Wr) )
ErrorExit(TEXT("StdInWr CloseHandle"));
}
void ReadFromPipe(void)
// Read output from the child process's pipe for STDOUT
// and write to the parent process's pipe for STDOUT.
// Stop when there is no more data.
{
DWORD dwRead, dwWritten;
CHAR chBuf[4096];
BOOL bSuccess = FALSE;
HANDLE hParentStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
for (;;)
{
bSuccess = ReadFile( g_hChildStd_OUT_Rd, chBuf, BUFSIZE, &dwRead, NULL);
if( ! bSuccess || dwRead == 0 ) break;
bSuccess = WriteFile(hParentStdOut, chBuf,
dwRead, &dwWritten, NULL);
if (! bSuccess ) break;
}
}
void ErrorExit(PTSTR lpszFunction)
// Format a readable error message, display a message box,
// and exit from the application.
{
LPVOID lpMsgBuf;
LPVOID lpDisplayBuf;
DWORD dw = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0, NULL );
lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
(lstrlen((LPCTSTR)lpMsgBuf)+lstrlen((LPCTSTR)lpszFunction)+40)*sizeof(TCHAR));
StringCchPrintf((LPTSTR)lpDisplayBuf,
LocalSize(lpDisplayBuf) / sizeof(TCHAR),
TEXT("%s failed with error %d: %s"),
lpszFunction, dw, lpMsgBuf);
MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK);
LocalFree(lpMsgBuf);
LocalFree(lpDisplayBuf);
ExitProcess(1);
}
Use anonymous pipes via CreatePipe(), not named pipes via CreateNamedPipe(). See MSDN for an example:
Creating a Child Process with Redirected Input and Output

Problems with opening a process with DEBUG flags

I'm trying to open a process with my debugger using CreateProcess with the DEBUG_PROCESS and DEBUG_ONLY_THIS_PROCESS flags and the the process is opened, but then when I try to call SymInitialize with the handle I receive, it fails.
This is my code:
#include <windows.h>
#include <stdio.h>
#include <dbghelp.h>
#pragma (lib, "dbghelp.lib");
bool EnablePrivilege(LPCTSTR lpszPrivilegeName, BOOL bEnable)
{
HANDLE hToken;
TOKEN_PRIVILEGES tp;
LUID luid;
bool ret;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY | TOKEN_READ, &hToken))
return FALSE;
if (!LookupPrivilegeValue(NULL, lpszPrivilegeName, &luid))
return FALSE;
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = luid;
tp.Privileges[0].Attributes = bEnable ? SE_PRIVILEGE_ENABLED : 0;
ret = AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(tp), NULL, NULL);
CloseHandle(hToken);
return ret;
}
void main()
{
EnablePrivilege(SE_DEBUG_NAME, TRUE);
STARTUPINFOA startInfo;
PROCESS_INFORMATION processInfo;
ZeroMemory( &startInfo, sizeof(startInfo) );
startInfo.cb = sizeof(startInfo);
ZeroMemory( &processInfo, sizeof(processInfo) );
DWORD creationFlags = DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS | PROCESS_VM_READ | PROCESS_QUERY_INFORMATION;
const char* comLine = "Some process path and name";
// Start the child process.
if( CreateProcessA( NULL, // No module name (use command line)
(LPSTR)comLine, //argv[1], // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
creationFlags, // No creation flags
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&startInfo, // Pointer to STARTUPINFO structure
&processInfo ) // Pointer to PROCESS_INFORMATION structure
== false )
{
printf("FAIL!");
return;
}
SetLastError(0);
bool ok = SymInitialize(processInfo.hProcess, NULL, true);
int err = GetLastError();
}
If I call CreateProcess with no creation flags, symInitialize succeed.
What am I doing wrong?
Your error is result of calling MAKE_HRESULT macro as
MAKE_HRESULT(ERROR_SEVERITY_ERROR, FACILITY_NULL, ERROR_INVALID_DATA)
So your error code is not trash. Documentaion doesn't say what kind of data might be invalid in this context. I will try to see what exactly is causing the problem.
EDIT:
This code works for me
#include <windows.h>
#include <stdio.h>
#include <dbghelp.h>
#include <WinError.h>
bool EnablePrivilege(LPCTSTR lpszPrivilegeName, BOOL bEnable)
{
HANDLE hToken;
TOKEN_PRIVILEGES tp;
LUID luid;
bool ret;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY | TOKEN_READ, &hToken))
return FALSE;
if (!LookupPrivilegeValue(NULL, lpszPrivilegeName, &luid))
return FALSE;
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = luid;
tp.Privileges[0].Attributes = bEnable ? SE_PRIVILEGE_ENABLED : 0;
ret = AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(tp), NULL, NULL);
CloseHandle(hToken);
return ret;
}
void main()
{
EnablePrivilege(SE_DEBUG_NAME, TRUE);
STARTUPINFOA startInfo;
PROCESS_INFORMATION processInfo;
ZeroMemory( &startInfo, sizeof(startInfo) );
startInfo.cb = sizeof(startInfo);
ZeroMemory( &processInfo, sizeof(processInfo) );
DWORD creationFlags = DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS | PROCESS_VM_READ | PROCESS_QUERY_INFORMATION;
const char* comLine = "C:\\Windows\\Notepad.exe";
// Start the child process.
if( CreateProcessA( NULL, // No module name (use command line)
(LPSTR)comLine,// argv[1], // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
creationFlags, // No creation flags
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&startInfo, // Pointer to STARTUPINFO structure
&processInfo ) // Pointer to PROCESS_INFORMATION structure
== false )
{
printf("FAIL!");
return;
}
SetLastError(0);
bool ok = SymInitialize(processInfo.hProcess, NULL, true);
HRESULT err = HRESULT_FROM_WIN32(GetLastError());
}
I don't know why it doesn't for you - I am running windows XP, it might be a difference. For me SymInitialize returns true, and GetLastError returns 0x800700cb, which means only that it didn't found evirnment variable pointing it to directory with symbol files.
This might be stupid question, but perhaps you are missing some debugging libraries in your system? Have you tried installing eg. Debugging Tools for
Windows? I would reccomend 'Download Debugging Tools from the Windows SDK' option - read the description. I guess every programming IDE around would install it for you or have you install it before debugging anything, but it's always best to check.
When process is just created with DEBUG_PROCESS flag no symbols are loaded. It is required to wait for some LOAD_DLL_DEBUG_EVENT and then call SymInitialize().