How do you open NTFS metadata/System Files: $LogFile, $Volume, $Bitmap? - windows

I am running on 64-bit Windows 7.
I want to get the FileID associated with some of the NTFS System Files. Some of them ("$Mft", "$MftMirr") I can open but others ("$LogFile" and "$Bitmap") fail with an "access denied" error or invalid parameter ("$Volume").
I have tried doing that as an administrator and running as a local service but they still fail.
I am using the following:
/* open the file for checking the File ID */
h = CreateFileW (
argv[i] , // _In_ LPCTSTR lpFileName,
FILE_READ_ATTRIBUTES , // _In_ DWORD dwDesiredAccess,
FILE_SHARE_DELETE |
FILE_SHARE_READ |
FILE_SHARE_WRITE , // _In_ DWORD dwShareMode,
NULL , // _In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes,
OPEN_EXISTING , // _In_ DWORD dwCreationDisposition,
FILE_ATTRIBUTE_NORMAL| FILE_FLAG_BACKUP_SEMANTICS, // _In_ DWORD dwFlagsAndAttributes,
NULL // _In_opt_ HANDLE hTemplateFile
);
if (h == INVALID_HANDLE_VALUE) {
err = GetLastError();
wprintf(L"Can't open: '%s'. err:%u(0x%x)\n", argv[i], err, err);
continue;
}
I did set the following privileges as well (I know it is an overkill but I didn't know which one would work): SE_TCB_NAME, SE_DEBUG_NAME, SE_SECURITY_NAME, SE_BACKUP_NAME, SE_RESTORE_NAME, SE_MANAGE_VOLUME_NAME

You can use fget or ntfscopy that are mentioned here:
http://blog.opensecurityresearch.com/2011/10/how-to-acquire-locked-files-from.html

Related

What's wrong with Detours hook applying to CreateFile?

I ran into some troubles when attempting a Detours hook on CreateFile in this small program:
#include <windows.h>
#include <iostream>
int main(HINSTANCE hinst, HINSTANCE hPrevInstance, LPSTR cmdLine, int showCmd)
{
HANDLE file;
DWORD bytesRead, bytesWritten, pos;
TCHAR msg[1000];
std::cout << "Start creating file \"SampleFile.txt\"" << std::endl;
file = CreateFile(L"C:\\TestHook\\SampleFile.txt", GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
std::cout << "\"SampleFile.txt\" added into C folder" << std::endl;
CloseHandle(file);
return 0;
}
There is a DLL applied:
#include<windows.h>
#include<windows.h>
#include "C:\Detours\Detours-4.0.1\include\detours.h"
static HANDLE(WINAPI* TrueCreateFile)(LPCWSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode,
LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes,
HANDLE hTemplateFile) = CreateFileW;
__declspec(dllexport) HANDLE WINAPI MyCreateFile(LPCTSTR lpFileName, DWORD dwDesiredAccess, DWORD
dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile)
{
HANDLE hookFile = CreateFile(L"C:\\TestHook\\hookYouGo.txt", GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL, NULL);
std::cout << "CreateFile() is hooked...Meet other file name than you want" << std::endl;
CloseHandle(hookFile);
return hookFile;
}
BOOL WINAPI DLLMain(HINSTANCE hinst, DWORD reason_for_call, LPVOID lpReserved)
{
std::cout << "test" << std::endl;
if (reason_for_call = DLL_PROCESS_ATTACH)
{
DetourRestoreAfterWith();
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourAttach(&(PVOID&)TrueCreateFile, MyCreateFile);
DetourTransactionCommit();
}
return TRUE;
}
Once executing in Visual Studio '19 (OS Windows 10), it adds a new file into the target folder, but another than I expect. Instead of hookYouGo.txt, SampleHook.txt appears there as if hook attachment failed. Looking into API monitor after process finish, I don't find any evidence that DLL was applied as orderly as well. In command line, it's just the same, since I launch withdll.exe that runs into outputs like statements on SampleFile, but DLL stuff seems beyond that process. Both withdll.exe and main func program and DLL are inside the same folder, sure.
You are doing it the wrong way, you must get the function address in order to hook it.
Like this:
static HANDLE(WINAPI* TrueCreateFile)(LPCWSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode,
LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes,
HANDLE hTemplateFile);
TrueCreateFile HookCreateFile;
HookCreateFile = (TrueCreateFile)GetProcAddress(GetModuleHandle("Kernel32.dll"), "CreateFile");
Then do the actual hooking:
DetourAttach(&(PVOID&)HookCreateFile, MyCreateFile);

CreateProcess usage for executable wrapper for Windows?

TL;DR:
CreateProcess(?, ?, ?, ...) for:
Pass current process params (i.e. "batchfile" %*)
correctly connect stdin and stdout
creation flags?
I have the following problem:
I need to launch a given 3rd party executable with a custom environment and custom parameters. (Both semi-fixed)
I cannot use a batch file, because the (again, 3rd party) side invoking the module directly calls CreateProcess
I need to pass on any additional paramers passed
So, what I'd like to do is create a very simple executable launcher that would be the equivalent of a batch file like:
set PATH=...
set WHATEVER=...
...\3rd-pty-tool.exe -switch1 -switch2 %*
exit /B %ERRORLEVEL%
And I certainly don't want to mess with any bat2exe converter stuff - just too ugly when I have Visual Studio around anyway.
Running another executable via CreateProcess is trivial in principle:
STARTUPINFO info={sizeof(info)};
PROCESS_INFORMATION processInfo;
if (CreateProcess(?, ?, ?, ?, ?, ?, ?, ?, &info, &processInfo))
{
WaitForSingleObject(processInfo.hProcess, INFINITE);
CloseHandle(processInfo.hProcess);
CloseHandle(processInfo.hThread);
}
Setting up the environment for the child process via _putenv et al. is also pretty easy.
What is not trivial to me is however what to pass on to CreateProcess:
BOOL WINAPI CreateProcess(
_In_opt_ LPCTSTR lpApplicationName,
_Inout_opt_ LPTSTR lpCommandLine,
_In_opt_ LPSECURITY_ATTRIBUTES lpProcessAttributes,
_In_opt_ LPSECURITY_ATTRIBUTES lpThreadAttributes,
_In_ BOOL bInheritHandles,
_In_ DWORD dwCreationFlags,
_In_opt_ LPVOID lpEnvironment,
_In_opt_ LPCTSTR lpCurrentDirectory,
_In_ LPSTARTUPINFO lpStartupInfo,
_Out_ LPPROCESS_INFORMATION lpProcessInformation
);
How to I get at the %* equivalent for the current Win32 process?
Pass only lpApplicationName, only lpCommandLine or both?
What to do about handle inheritance and creation flags?
How to I correctly forward / return stdin and stdout?
Not a dupe: CreateProcess to execute Windows command
Should be reasonably straightforward.
BOOL WINAPI CreateProcess(
_In_opt_ LPCTSTR lpApplicationName,
_Inout_opt_ LPTSTR lpCommandLine,
_In_opt_ LPSECURITY_ATTRIBUTES lpProcessAttributes,
_In_opt_ LPSECURITY_ATTRIBUTES lpThreadAttributes,
_In_ BOOL bInheritHandles,
_In_ DWORD dwCreationFlags,
_In_opt_ LPVOID lpEnvironment,
_In_opt_ LPCTSTR lpCurrentDirectory,
_In_ LPSTARTUPINFO lpStartupInfo,
_Out_ LPPROCESS_INFORMATION lpProcessInformation
);
Let's take it in order.
lpApplicationName - if you have the full path to the executable you want to run, put it here. That ensures that you get the executable you were expecting, even if another executable with the same name is on the PATH.
lpCommandLine - the first element is the executable name. If you've specified lpApplicationName this doesn't need to be fully qualified, or even be the executable's actual name, but it does need to be present. This must be a writable buffer, it cannot be a constant string.
If your extra arguments can go at the end of the command line, this is easy:
wchar_t buffer[1024];
wcscpy_s(buffer, _countof(buffer), GetCommandLine());
wcscat_s(buffer, _countof(buffer), L" -switch1 -switch2");
Otherwise, you'll need to parse the command line to find the right place to insert the arguments, something like this:
while (*lpCmdLine == L' ') lpCmdLine++;
while (ch = *lpCmdLine)
{
if (ch == L'"') for (lpCmdLine++; ch = *lpCmdLine; lpCmdLine++) if (ch == L'"') break;
if (ch == L' ') break;
lpCmdLine++;
}
while (*lpCmdLine == L' ') lpCmdLine++;
lpProcessAttributes and lpThreadAttributes - NULL.
bInheritHandles - TRUE, since you want the child to inherit the standard handles.
dwCreationFlags - none needed in your scenario, so 0.
lpEnvironment - NULL to pass the current environment. In some situations you'd want to explicitly construct a new environment, or a modified copy of your environment, but since your process exists only to launch the child that shouldn't be necessary.
lpCurrentDirectory - NULL to inherit your current directory.
lpStartupInfo - call GetStartupInfo to fill this out with the same settings as the current process, or just leave it empty as in the code you posted.
lpProcessInformation - this is an output parameter, used as shown in your code. In your scenario, where one application is standing in for another, you might want to keep the process handle and use it to wait for the child process to exit before exiting yourself. (This isn't necessary if you know that your parent won't get confused if you exit before your child does.)
You don't need to do anything special about the standard handles, apart from ensuring that bInheritHandles is set. The default is for the child to keep the same standard handles as the parent.

Error 42: Symbol Undefined _CreateWindowW#44 when trying to register non existing windows function binding

I try to write simple show_window function but that which uses wide chars, there are no examples anywhere in D of that, only I could find windows creation that uses narrow-string and try now to rewrite that (I know bad english). So I'm failing even at proper registering unicode winapi bindings.
import core.runtime;
import core.sys.windows.windows;
import std.c.windows.windows;
pragma(lib, "gdi32.lib");
pragma(lib, "user32.lib");
struct WNDCLASSW { UINT style; WNDPROC lpfnWndProc; int cbClsExtra; int cbWndExtra; HINSTANCE hInstance; HICON hIcon; HCURSOR hCursor; HBRUSH hbrBackground; LPCWSTR lpszMenuName; LPCWSTR lpszClassName; }
extern(Windows) HWND CreateWindowW(LPCWSTR lpClassName, LPCWSTR lpWindowName, DWORD dwStyle, int x, int y, int nWidth, int nHeight, HWND hWndParent, HMENU hMenu, HINSTANCE hInstance, LPVOID lpParam );
extern(Windows)
int WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int iCmdShow) {
HWND hWnd = CreateWindowW("wndClassName",
"window caption", WS_SYSMENU | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, HWND_DESKTOP, null, hInstance, null);
return 0;
}
and that produces:
Error 42: Symbol Undefined _CreateWindowW#44
Modern versions of Windows do not implement CreateWindow(). It is an ancient winapi function that dates from the 1980s and has been replaced by CreateWindowEx(). In the WinUser.h SDK header, CreateWindowW is a macro that actually calls CreateWindowExW(), passing 0 for the extra dwExStyle argument.
You must use CreateWindowExW() instead.

C++ monitor running processes in the background?

I've been trying to write a program in C++ that will monitor running processes in the background and terminate a certain one if it's detected to be running. I have written a program that will do so, however the only way I can think of to do this is to use an infinite WHILE loop that keeps checking for the program. This, as you can imagine, constantly uses CPU power and resources to be constantly looping. In task manager, you can see that most processes that are running are always using 0% of the CPU. My question is: How can I write or modify this program to run in the background, utilizing 0% of the CPU until it detects the process it's supposed to terminate?
My entire program is below. In this example, I have used "Notepad.exe" in WinMain as the process the program should be terminating.
#include <Windows.h>
#include <iostream>
#include <tlhelp32.h>
#include <string>
#define TA_FAILED 0
#define TA_SUCCESS_CLEAN 1
#define TA_SUCCESS_KILL 2
DWORD WINAPI TerminateApp(DWORD dwPID, DWORD dwTimeout);
DWORD WINAPI Terminate16App(DWORD dwPID, DWORD dwThread, WORD w16Task, DWORD dwTimeout);
typedef struct {
DWORD dwID;
DWORD dwThread;
} TERMINFO;
BOOL CALLBACK TerminateAppEnum( HWND hwnd, LPARAM lParam ) ;
DWORD WINAPI TerminateApp( DWORD dwPID, DWORD dwTimeout ) {
HANDLE hProc ;
DWORD dwRet ;
// If we can't open the process with PROCESS_TERMINATE rights,
// then we give up immediately.
hProc = OpenProcess(SYNCHRONIZE|PROCESS_TERMINATE, FALSE,
dwPID);
if(hProc == NULL) {
return TA_FAILED ;
}
// TerminateAppEnum() posts WM_CLOSE to all windows whose PID
// matches your process's.
EnumWindows((WNDENUMPROC)TerminateAppEnum, (LPARAM) dwPID) ;
// Wait on the handle. If it signals, great. If it times out,
// then you kill it.
if(WaitForSingleObject(hProc, dwTimeout)!=WAIT_OBJECT_0)
dwRet=(TerminateProcess(hProc,0)?TA_SUCCESS_KILL:TA_FAILED);
else
dwRet = TA_SUCCESS_CLEAN ;
CloseHandle(hProc) ;
return dwRet ;
}
BOOL CALLBACK TerminateAppEnum( HWND hwnd, LPARAM lParam ) {
DWORD dwID ;
GetWindowThreadProcessId(hwnd, &dwID) ;
if(dwID == (DWORD)lParam) {
PostMessage(hwnd, WM_CLOSE, 0, 0) ;
}
return TRUE ;
}
DWORD FindProcessId(const std::string& processName);
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow) {
std::string process1 = "Notepad.exe";
while (1) {
TerminateApp(FindProcessId(process1),0);
}
return 0;
}
DWORD FindProcessId(const std::string& processName) {
PROCESSENTRY32 processInfo;
processInfo.dwSize = sizeof(processInfo);
HANDLE processesSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (processesSnapshot == INVALID_HANDLE_VALUE) {
return 0;
}
Process32First(processesSnapshot, &processInfo);
if (!processName.compare(processInfo.szExeFile)) {
CloseHandle(processesSnapshot);
return processInfo.th32ProcessID;
}
while (Process32Next(processesSnapshot, &processInfo)) {
if (!processName.compare(processInfo.szExeFile)) {
CloseHandle(processesSnapshot);
return processInfo.th32ProcessID;
}
}
CloseHandle(processesSnapshot);
return 0;
}
You can use WMI and event notification to find when processes are created and destroyed. __InstanceCreationEvent is what you need to look for.
Creation of a resource: __InstanceCreationEvent
Suppose you are interested in receiving a notification if Notepad is run on a certain computer. When Notepad runs, a corresponding process is created. Processes can be managed by using WMI and are represented by the Win32_Process class. When Notepad starts running, a corresponding instance of the Win32_Process class becomes available through WMI. If you have registered your interest in this event (by issuing the appropriate event notification query), the availability of this instance results in the creation of an instance of the __InstanceCreationEvent class.

How to execute another program from a Visual C++ Application

I am doing a software project with Visual Studio Professional 2010.
In the form that I am making, I would like to put a link to open Microsoft Paint. How can I execute another application (MSPaint) from mine?
Call ShellExecute() passing open as the verb and mspaint.exe as the filename.
ShellExecute(
MainFormWindowHandle,
"open",
"mspaint.exe",
NULL,
NULL,
SW_SHOW
);
My contribution a complete example:
Go to Visual Studio, create a new Win32 C++ Project (not console), and paste the following code in the source file will appear:
// Win32Project1.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
#include "Win32Project1.h"
#include "shellapi.h"
int APIENTRY _tWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPTSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
ShellExecuteA ( NULL, "open",
"your.exe",
"your params",
"working dir", SW_SHOW);
return TRUE;
}
Myself I contribute the following code which can be used in Windows
#include <iostream>
#include<Windows.h>
using namespace std;
int main()
{
STARTUPINFO si;
PROCESS_INFORMATION pi;
DWORD dwProcessId = 0;
DWORD dwThreadId = 0;
ZeroMemory(&si, sizeof(si));
ZeroMemory(&pi, sizeof(pi));
bool bCreateProcess = NULL;
bCreateProcess = CreateProcess((Location of Paint path),0,0,0,0,0,0,0,&si, pi);
//Instead of 0 NULL can also be used
if (bCreateProcess == FALSE)
cout << " Creation Process Failed ";
else
cout << " Process Executedd ";
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}

Resources