In my setup.dll i have the folowing:
#include "stdafx.h"
#include "ce_setup.h"
TCHAR Message[] = _T("TERMS & CONDITIONS\r\n ")
_T("Do you agree to terms? \r\n");
codeINSTALL_INIT Install_Init
(
HWND hwndParent,
BOOL fFirstCall,
BOOL fPreviouslyInstalled,
LPCTSTR pszInstallDir
)
{
if (!fFirstCall || ::MessageBoxW(0, Message, _T("RmapGeneric"), MB_YESNO) == IDYES)
return codeINSTALL_INIT_CONTINUE;
else
return codeINSTALL_INIT_CANCEL;
}
codeINSTALL_EXIT Install_Exit
(
HWND hwndParent,
LPCTSTR pszInstallDir,
WORD cFailedDirs,
WORD cFailedFiles,
WORD cFailedRegKeys,
WORD cFailedRegVals,
WORD cFailedShortcuts
)
{
PROCESS_INFORMATION pi = {0};
codeINSTALL_EXIT cie = codeINSTALL_EXIT_DONE;
TCHAR szPath[MAX_PATH];
_tcscpy(szPath, pszInstallDir);
_tcscat(szPath, _T("\\"));
_tcscat(szPath, _T("Application.exe"));
MessageBox(GetForegroundWindow(), szPath, L"status", MB_OK);
if (!CreateProcess(szPath, NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL, &pi))
{
MessageBox(GetForegroundWindow(), szPath, L"failed", MB_OK);
cie = codeINSTALL_EXIT_UNINSTALL;
}
return cie;
}
While the first function works, the Install_Exit does not.
All i want is that after the installation the application automaticly starts.
Any suggestions what am i doing wrong?
There's nothing completely obvious as to what's wrong. Are you certain that the target executable is in that folder? Have you called GetLastError to see why it's failing?
Ok i found the problem in .DEF file
I forgot to export the exit function :S
Related
I have a redirected printer port that use redmon (redirect port monitor) with a postscript printer driver to convert postscript to pdf and apply some other effects like watermarks, overlays, etc.
In win 7 all work fine but in windows 10 the process run under system user account.
In the configuration window of the printer port there is a flag called "Run as user" and in win7, checking this flag let the job running under the user account.
In Windows 10 it seems not working.
Any suggestion will be very appreciated.
Thank you.
Roy
I had a similar problem. I needed the user that printed the document to select the type of document and a patient ID. Then print the document to our EHR system as a PDF. Works in Windows 7 when "Run as User" is checked, but not on Windows 10. Redmon always runs the program as "SYSTEM". So I added a bit to the beginning of the program to check the user name. If it is "SYSTEM" the program looks for the an interactive user on the system by finding an instance of explorer.exe. If more than one interactive user is logged onto the system this will fail. Not a problem for my task. The program then starts another instance of itself running as the same user as explorer.exe, passing the same command line. A pipe is used so that stdin from the first instance can be piped to stdin on the second instance. Another limitation is that on a 64 bit OS, a 64 bit version of the program must be used. Otherwise explorer.exe may not be found.
The following code is what I placed at the beginning of my program. Don't be fooled by the program starting at main(). I am using a GUII toolkit that has WinMain() in it and then calls main(). I have only tested the code on ASCII programs. I tried to use the ASCII version of calls so that it would work with non-ASCII programs, but I am not sure I got all of them.
The LogInfoSys("Hello World"); function just writes to a log file.
Good luck.
#include <Windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>
#include <time.h>
#include <direct.h>
#include <process.h>
#include <sqlext.h>
#include <Psapi.h>
#include <tlhelp32.h>
int main(int argc, char *argv[])
{
int error;
char msg[1024];
DWORD *processIDs;
int processCount;
HANDLE hProcess = NULL;
HANDLE hToken;
char userName[64];
char progName[1024];
int i, j;
char nameMe[256];
char domainMe[256];
PTOKEN_USER ptuMe = NULL;
PROCESS_INFORMATION procInfo;
STARTUPINFO startUpInfo;
HMODULE *hMod;
DWORD cbNeeded;
SECURITY_ATTRIBUTES saAttr;
HANDLE hChildStd_IN_Rd = NULL;
HANDLE hChildStd_IN_Wr = NULL;
i = 64; // Get user name, if it is "SYSTEM" redirect input to output to a new instance of the program
GetUserNameA(userName, &i);
if (_stricmp(userName, "system") == 0)
{
LogInfoSys("Running as SYSTEM");
processIDs = (DWORD *)calloc(16384, sizeof(DWORD)); // Look for explorer.exe running. If found that should be the user we want to run as.
EnumProcesses(processIDs, sizeof(DWORD) * 16384, &i); // If there is more than one that is OK as long as they are both being run by the same
processCount = i / sizeof(DWORD); // user. If more than one user is logged on, this will be a problem.
hMod = (HMODULE *)calloc(4096, sizeof(HMODULE));
hProcess = NULL;
for (i = 0; (i < processCount) && (hProcess == NULL); i++)
{
if (processIDs[i] == 11276)
Sleep(0);
if (processIDs[i] != 0)
{
hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processIDs[i]);
if (hProcess != NULL)
{
cbNeeded = 0;
error = EnumProcessModules(hProcess, hMod, sizeof(HMODULE) * 4096, &cbNeeded);
if (error == 0)
{
error = GetLastError();
Sleep(0);
}
progName[0] = 0;
error = GetModuleBaseNameA(hProcess, hMod[0], progName, 1024);
if (error == 0)
{
error = GetLastError();
Sleep(0);
}
if (_stricmp(progName, "explorer.exe") != 0)
{
CloseHandle(hProcess);
hProcess = NULL;
}
else
{
LogInfoSys("Found explorer.exe");
}
}
}
}
LogInfoSys("After looking for processes.");
nameMe[0] = domainMe[0] = 0;
if (hProcess != NULL)
{
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
if (!CreatePipe(&hChildStd_IN_Rd, &hChildStd_IN_Wr, &saAttr, 0)) // Create a pipe for the child process's STDIN.
LogInfoSys("Stdin CreatePipe error");
if (!SetHandleInformation(hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0)) // Ensure the write handle to the pipe for STDIN is not inherited.
LogInfoSys("Stdin SetHandleInformation errir");
if (OpenProcessToken(hProcess, TOKEN_ALL_ACCESS, &hToken) != 0)
{
GetStartupInfo(&startUpInfo);
startUpInfo.cb = sizeof(STARTUPINFO);
startUpInfo.lpReserved = NULL;
startUpInfo.lpDesktop = NULL;
startUpInfo.lpTitle = NULL;
startUpInfo.dwX = startUpInfo.dwY = 0;
startUpInfo.dwXSize = 0;
startUpInfo.dwYSize = 0;
startUpInfo.dwXCountChars = 0;
startUpInfo.dwYCountChars = 0;
startUpInfo.dwFillAttribute = 0;
startUpInfo.dwFlags |= STARTF_USESTDHANDLES;
startUpInfo.wShowWindow = 0;
startUpInfo.cbReserved2 = 0;
startUpInfo.lpReserved = NULL;
startUpInfo.hStdInput = hChildStd_IN_Rd;
startUpInfo.hStdOutput = NULL;
startUpInfo.hStdError = NULL;
GetModuleFileName(NULL, progName, 1024);
i = CreateProcessAsUserA(hToken, progName, GetCommandLine(), NULL, NULL, TRUE, NORMAL_PRIORITY_CLASS, NULL, NULL, &startUpInfo, &procInfo);
if (i == 0)
{
i = GetLastError();
}
do
{
i = (int)fread(msg, 1, 1024, stdin);
if (i > 0)
WriteFile(hChildStd_IN_Wr, msg, i, &j, NULL);
} while (i > 0);
}
}
LogInfoSys("End of running as SYSTEM.");
exit(0);
}
/**********************************************************************************************************
*
* End of running as SYSTEM and start of running as the user that printed the document (I hope).
*
**********************************************************************************************************/
exit(0);
}
If I put the WNDCLASSEX wcex variable definition out of main function (as global variable) the class will be registered successfully
#include <windows.h>
WNDCLASSEX wcex;
int main()
{
wcex.cbSize = sizeof ( WNDCLASSEX );
wcex.lpszClassName = "Success" ;
if ( !RegisterClassEx ( &wcex ) )
{
MessageBox ( NULL, "Failed to register window class.", "Error", MB_OK );
}
}
But If I put it inside the main function, It will not be registered
#include <windows.h>
int main()
{
WNDCLASSEX wcex;
wcex.cbSize = sizeof ( WNDCLASSEX );
wcex.lpszClassName = "Success" ;
if ( !RegisterClassEx ( &wcex ) )
{
MessageBox ( NULL, "Failed to register window class.", "Error", MB_OK );
}
}
I can't figure out the reason, kindly help in this issue.
Thanks in advance.
Objects with static storage duration are zero-initialized1). Your second example is semantically different in that wcex (automatic storage duration) holds random values. To match the semantics, use WNDCLASSEX wcex = { 0 }; instead.
1) Assuming you are using a C++ compiler. The rules for C are different.
I am trying to code an alternative to LoadLibrary function, based on the idea of calling the function LdrLoadDll from ntdll.
This function needs as a parameter the dll file to load, in a UNICODE_STRING format.
I really can't get what I am doing wrong here (string seems to be correctly initialized), but when LdrLoadDll is called, I get the following error:
Unhandled exception in "Test.exe" (NTDLL.DLL): 0xC0000005: Access Violation.
I use Visual C++ 6.0 for this test, and I am using Windows 7 64 bit.
I post full code here, thanks in advance for any help:
#include <Windows.h>
typedef LONG NTSTATUS; //To be used with VC++ 6, since NTSTATUS type is not defined
typedef struct _UNICODE_STRING { //UNICODE_STRING structure
USHORT Length;
USHORT MaximumLength;
PWSTR Buffer;
} UNICODE_STRING;
typedef UNICODE_STRING *PUNICODE_STRING;
typedef NTSTATUS (WINAPI *fLdrLoadDll) //LdrLoadDll function prototype
(
IN PWCHAR PathToFile OPTIONAL,
IN ULONG Flags OPTIONAL,
IN PUNICODE_STRING ModuleFileName,
OUT PHANDLE ModuleHandle
);
/**************************************************************************
* RtlInitUnicodeString (NTDLL.#)
*
* Initializes a buffered unicode string.
*
* RETURNS
* Nothing.
*
* NOTES
* Assigns source to target->Buffer. The length of source is assigned to
* target->Length and target->MaximumLength. If source is NULL the length
* of source is assumed to be 0.
*/
void WINAPI RtlInitUnicodeString(
PUNICODE_STRING target, /* [I/O] Buffered unicode string to be initialized */
PCWSTR source) /* [I] '\0' terminated unicode string used to initialize target */
{
if ((target->Buffer = (PWSTR) source))
{
unsigned int length = lstrlenW(source) * sizeof(WCHAR);
if (length > 0xfffc)
length = 0xfffc;
target->Length = length;
target->MaximumLength = target->Length + sizeof(WCHAR);
}
else target->Length = target->MaximumLength = 0;
}
NTSTATUS LoadDll( LPCSTR lpFileName)
{
HMODULE hmodule = GetModuleHandleA("ntdll.dll");
fLdrLoadDll _LdrLoadDll = (fLdrLoadDll) GetProcAddress ( hmodule, "LdrLoadDll" );
int AnsiLen = lstrlenA(lpFileName);
BSTR WideStr = SysAllocStringLen(NULL, AnsiLen);
::MultiByteToWideChar(CP_ACP, 0, lpFileName, AnsiLen, WideStr, AnsiLen);
UNICODE_STRING usDllFile;
RtlInitUnicodeString(&usDllFile, WideStr); //Initialize UNICODE_STRING for LdrLoadDll function
::SysFreeString(WideStr);
NTSTATUS result = _LdrLoadDll(NULL, LOAD_WITH_ALTERED_SEARCH_PATH, &usDllFile,0); //Error on this line!
return result;
}
void main()
{
LoadDll("Kernel32.dll");
}
in
_LdrLoadDll(NULL, LOAD_WITH_ALTERED_SEARCH_PATH, &usDllFile,0);
last parameter can't be zero
you can't call SysFreeString before you call _LdrLoadDll,
since the usDllFile.buffer parameter points to this string
Before I get into to my question,let me explain what I am exactly doing.I have a main Process say ProcessA,I have hooked ProcessA and also injected dll(say myDll.dll) into the process space of ProcessA.Now at one point ProcessA kicks on another process which is ProcessB.Both the process A and B are in totally different Process memory space.I want to share the myDll.dll(which is inserted in processA sapce) in ProcessB(actually ProcessB's processSpace).Can it be done using pipe line method or any other suitable method.
thanks in advance.
The code of DLL will be automatically shared by different processes. For optimization only you should choose a good base address of the DLL (see http://msdn.microsoft.com/en-US/library/f7f5138s.aspx).
To share data between processes you can for example use Shared Memory objects or just place some variables which you need to share to a section which you mark as shared (see http://support.microsoft.com/kb/100634 and http://msdn.microsoft.com/en-us/library/h90dkhs0.aspx for details). To mark section ".SHAREDSECTIONNAME" as shared you can use
#pragma comment(linker, "/section:.SHAREDSECTIONNAME,RWS")
To have no conflicts in writing/reading from the shared memory you should use a named Event or Mutex exactly like in all other cases of multiprocess communication.
UPDATED based on the comment: If you create the child process yourself you receive the handle to the child process with full rights. So you have enough rights to make DLL infection with respect of CreateRemoteThread API. Here is a working code in C which start CMD.EXE and inject a MyTest.dll in the address space:
#include <Windows.h>
int main()
{
STARTUPINFO si = { sizeof(STARTUPINFO) };
PROCESS_INFORMATION pi = {0};
TCHAR szCommandLine[4096] = TEXT("CMD.EXE");
BOOL bIsSuccess;
DWORD dwStatus;
LPCTSTR pszLibFile = TEXT("C:\\Oleg\\MyTest\\Release\\MyTest.dll");
PTSTR pszLibFileRemote = NULL;
HANDLE hThread = NULL;
int cb;
HMODULE hModule = NULL;
bIsSuccess = CreateProcess (NULL, szCommandLine, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, &si, &pi);
// Calculate the number of bytes needed for the DLL's pathname
cb = (1 + lstrlen(pszLibFile)) * sizeof(TCHAR);
__try {
PTHREAD_START_ROUTINE pfnThreadRtn;
// Allocate space in the remote process for the pathname
pszLibFileRemote = (PTSTR) VirtualAllocEx (pi.hProcess, NULL, cb, MEM_COMMIT, PAGE_READWRITE);
if (pszLibFileRemote == NULL) __leave; // error
// Copy the DLL's pathname to the remote process's address space
if (!WriteProcessMemory (pi.hProcess, pszLibFileRemote, (PVOID) pszLibFile, cb, NULL)) __leave;
// Get the real address of LoadLibraryW in Kernel32.dll
// Real address of Kernel32.dll in dwProcessId and in our Process MUST be the same !!!
// Remote Process MUST have Kernel32.dll loaded (SMSSS.EXE and System havn't)!!!
#ifdef UNICODE
pfnThreadRtn = (PTHREAD_START_ROUTINE) GetProcAddress (GetModuleHandle(TEXT("Kernel32")), "LoadLibraryW");
#else
pfnThreadRtn = (PTHREAD_START_ROUTINE) GetProcAddress (GetModuleHandle(TEXT("Kernel32")), "LoadLibraryA");
#endif
if (pfnThreadRtn == NULL) __leave;
// Create a remote thread that calls LoadLibraryW(DLLPathname)
hThread = CreateRemoteThread (pi.hProcess, NULL, 0, pfnThreadRtn, (LPVOID)pszLibFileRemote, 0, NULL);
if (hThread == NULL) __leave;
dwStatus = ResumeThread (pi.hThread);
// Wait for the remote thread to terminate
if (WaitForSingleObject (hThread, INFINITE) != WAIT_OBJECT_0) __leave;
GetExitCodeThread (hThread, (PDWORD)&hModule);
// hModule is the address in the destination process (CMD.EXE)
// of the injected DLL
// You can verify that it is really loaded for example with respect of
// Process Explorer (http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx)
}
__finally {
// Free the remote memory that contained the DLL's pathname
if (pszLibFileRemote != NULL)
bIsSuccess = VirtualFreeEx (pi.hProcess, pszLibFileRemote, 0, MEM_RELEASE);
if (hThread != NULL)
bIsSuccess = CloseHandle (hThread);
if (pi.hProcess != NULL)
bIsSuccess = CloseHandle (pi.hProcess);
if (pi.hThread != NULL)
bIsSuccess = CloseHandle (pi.hThread);
}
return 0;
}
I'm developing a COM dll which is an add-in to MSoffice. Since I'm not creating any logs within add-in I would like to add a crash report generator into my add-in.
Hopefully 'Minidump' would be the best choice, but I have never use Minidump inside a COM object.
I appreciate if somebody can point out possibilities of creating such crash dump with minidump
inside a COM object.
Thank You
I suspect you should be able to use the technique described here, create a minidump.
The actual implementation is
straightforward. The following is a
simple example of how to use
MiniDumpWriteDump.
#include <dbghelp.h>
#include <shellapi.h>
#include <shlobj.h>
int GenerateDump(EXCEPTION_POINTERS* pExceptionPointers)
{
BOOL bMiniDumpSuccessful;
WCHAR szPath[MAX_PATH];
WCHAR szFileName[MAX_PATH];
WCHAR* szAppName = L"AppName";
WCHAR* szVersion = L"v1.0";
DWORD dwBufferSize = MAX_PATH;
HANDLE hDumpFile;
SYSTEMTIME stLocalTime;
MINIDUMP_EXCEPTION_INFORMATION ExpParam;
GetLocalTime( &stLocalTime );
GetTempPath( dwBufferSize, szPath );
StringCchPrintf( szFileName, MAX_PATH, L"%s%s", szPath, szAppName );
CreateDirectory( szFileName, NULL );
StringCchPrintf( szFileName, MAX_PATH, L"%s%s\\%s-%04d%02d%02d-%02d%02d%02d-%ld-%ld.dmp",
szPath, szAppName, szVersion,
stLocalTime.wYear, stLocalTime.wMonth, stLocalTime.wDay,
stLocalTime.wHour, stLocalTime.wMinute, stLocalTime.wSecond,
GetCurrentProcessId(), GetCurrentThreadId());
hDumpFile = CreateFile(szFileName, GENERIC_READ|GENERIC_WRITE,
FILE_SHARE_WRITE|FILE_SHARE_READ, 0, CREATE_ALWAYS, 0, 0);
ExpParam.ThreadId = GetCurrentThreadId();
ExpParam.ExceptionPointers = pExceptionPointers;
ExpParam.ClientPointers = TRUE;
bMiniDumpSuccessful = MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(),
hDumpFile, MiniDumpWithDataSegs, &ExpParam, NULL, NULL);
return EXCEPTION_EXECUTE_HANDLER;
}
void SomeFunction()
{
__try
{
int *pBadPtr = NULL;
*pBadPtr = 0;
}
__except(GenerateDump(GetExceptionInformation()))
{
}
}