Can I hook functions in linked libraries? - windows

Using EasyHook I have successfully hooked both exported functions and known vtable functions for various C++ classes. In all these cases target programs have used DLLs.
Provided I know the address of a function's entry point, is it possible to do the same when a library has been linked into the target program as opposed to being a separate library?

It appears with EasyHook you can hook any subroutine whose address is calculable.
In my case hooking static linked SSL_read and SSL_write in OpenSSL was as simple as identifying the offsets with my favourite debugger and then installing the hooks.
// delegate for EasyHook:
[UnmanagedFunctionPointer(CallingConvention.Cdecl,
SetLastError = true, CharSet = CharSet.Ansi)]
delegate Int32 SLL_readDelegate(IntPtr SSL_ptr, IntPtr buffer, Int32 length);
// import SSL_read (I actually did it manually, but this will work in most cases)
/* proto from ssl_lib.c -> int SSL_read(SSL *s,void *buf,int num) */
[DllImport("ssleay32.dll", SetLastError = true)]
public static extern Int32 SSL_read(IntPtr ssl, IntPtr buffer, Int32 len);
// the new routine
static Int32 SSL_readCallback(IntPtr SSL_ptr, IntPtr buffer, Int32 length)
{
/* call the imported SSL_read */
int ret = SSL_read(SSL_ptr, buffer, length);
/* TODO: your code here, e.g:
* string log_me = Marshal.PtrToString(buffer, ret);
*/
return ret;
}
Now all that's left is to install the hook:
private LocalHook sslReadHook;
public void Run(RemoteHooking.IContext InContext, String InArg1)
{
// ... initialization code omitted for brevity
/* the value for ssl_read_addr is made up in this example
* you'll need to study your target and how it's loaded(?) to
* identify the addresses you want to hook
*/
int ssl_read_addr = 0x12345678; /* made up for examples sake */
sslReadHook = LocalHook.Create(new IntPtr(ssl_read_addr),
new SSL_readDelegate(SSL_readCallback), this);
// ...
}
I should mention that in this example you'll need libeay32.dll and ssleay32.dll as the latter depends on the former.
Happy hooking!

Related

make webcam device invisible to a process

Some context:
I have an application that opens the first webcam device on Windows 10 64bit (whatever index 0 is during enumeration of devices) and does some processing on the frames. The application's source code is not accessible.
Question:
I need to make this application to work with two webcams at the same time. I thought maybe there is a way to do the following:
hide webcam 2
run application (picks up webcam 1)
hide webcam 1, unhide webcam 2
run application (picks up webcam 2)
Is there a way to do this without interrupting camera's operation? Note that both applications are running at the same time so hard-disabling a camera is not an option. Calling either a Win32 api or doing this in PowerShell is acceptable.
Thanks!
Thanks to comments on my original question, I managed to solve my problem by hooking into CM_Get_Device_Interface_List_ExW Win32 API call.
I had to verify what API is being called, so I used and API tracer tool (API monitor v2 64bit). Debugger should work too but for some reason my VS debugger did not show me any symbols (possibly missing pdbs).
The original process I tried to hook into is written in C# so I hooked into the call via an injected C# DLL containing EasyHook. Here is my code snippet (actual injection code left out):
using System;
using System.Runtime.InteropServices;
using EasyHook;
public class HookDevices : IEntryPoint
{
LocalHook FunctionLocalHook;
// construct this to hook into calls
HookDevices()
{
try
{
FunctionLocalHook = LocalHook.Create(
LocalHook.GetProcAddress("CfgMgr32.dll", "CM_Get_Device_Interface_List_ExW"),
new FunctionHookDelegate(CM_Get_Device_Interface_List_Ex_Hooked),
this);
FunctionLocalHook.ThreadACL.SetExclusiveACL(new Int32[] { 0 });
}
catch (Exception ExtInfo)
{
Debug.LogException(ExtInfo);
return;
}
}
[UnmanagedFunctionPointer(CallingConvention.StdCall,
CharSet = CharSet.Unicode,
SetLastError = true)]
delegate uint FunctionHookDelegate(
ref Guid interfaceClassGuid,
string deviceID,
IntPtr buffer,
uint bufferLength,
uint flags,
IntPtr hMachine);
[DllImport("CfgMgr32.dll",
CharSet = CharSet.Unicode,
SetLastError = true,
CallingConvention = CallingConvention.StdCall)]
static extern uint CM_Get_Device_Interface_List_ExW(
ref Guid interfaceClassGuid,
string deviceID,
IntPtr buffer,
uint bufferLength,
uint flags,
IntPtr hMachine);
// this is where we are intercepting all API accesses!
static uint CM_Get_Device_Interface_List_Ex_Hooked(
ref Guid interfaceClassGuid,
string deviceID,
IntPtr buffer,
uint bufferLength,
uint flags,
IntPtr hMachine)
{
// pass-through original API
uint ret = CM_Get_Device_Interface_List_ExW(
ref interfaceClassGuid,
deviceID,
buffer,
bufferLength,
flags,
hMachine);
// do custom logic here and re-arrange "buffer"
return ret;
}
}

GetFinalPathNameByHandle fails for device handles

If I create a File handle using CreateFile for a path like "\\?\NUL" or "\\?\pipe\", the handle is mapped to a File object that's opened for the "\Device\Null" or "\Device\NamedPipe" kernel Device object. Since the GetFinalPathNameByHandle function supports the VOLUME_NAME_NT property, which already returns strings like "\Device\HarddiskVolume1\", I thought I would be able to obtain a similar path for a device handle. However, the call always fails, either with ERROR_INVALID_FUNCTION, or ERROR_INVALID_PARAMETER, depending on the access flags the file was opened with.
In fact, almost any call to similar functions fails -- like GetFileInformationByHandle, GetFileInformationByHandleEx, and even calls to NT functions like NtQueryInformationFile -- returning STATUS_INVALID_PARAMETER. The only functions that don't fail are GetFileType (able to identify a pipe), GetVolumeInformationByHandle (able to identify the driver), and NtQueryInformationFile with FileModeInformation.
All these functions work when used on any standard file, but they are not supported for device file handles. How can I obtain path information from a device handle? Are there some Nt or Io functions that would work? Is there some other way to identify a device if the only thing I have is the handle?
As RbMm and eryksun have pointed out, the driver which implements the object must be able to handle IRP_MJ_QUERY_INFORMATION, but if it doesn't, the name of the object can be obtained via NtQueryObject, passing ObjectNameInformation (1) to it, which will obtain the OBJECT_NAME_INFORMATION structure with the object name.
Since I intended to call it with C#, here is the P/Invoke code for it:
static class Ntdll
{
[DllImport("ntdll.dll")]
static extern int NtQueryObject(
IntPtr Handle, int ObjectInformationClass,
IntPtr ObjectInformation, int ObjectInformationLength,
out int ReturnLength
);
public static int NtQueryObject(IntPtr Handle, int ObjectInformationClass, IntPtr ObjectInformation, int ObjectInformationLength)
{
int length;
int status = NtQueryObject(Handle, ObjectInformationClass, ObjectInformation, ObjectInformationLength, out length);
if(status != 0) throw new Win32Exception(RtlNtStatusToDosError(status));
return length;
}
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
public struct OBJECT_NAME_INFORMATION
{
public ushort Length;
public ushort MaximumLength;
public string Buffer;
}
[DebuggerStepThrough]
public static void NtQueryObject(IntPtr Handle, out OBJECT_NAME_INFORMATION ObjectNameInformation)
{
IntPtr buffer = Marshal.AllocHGlobal(1024);
try{
Ntdll.NtQueryObject(Handle, 1, buffer, 1024);
ObjectNameInformation = Marshal.PtrToStructure<Ntdll.OBJECT_NAME_INFORMATION>(buffer);
}finally{
Marshal.FreeHGlobal(buffer);
}
}
}
The path can be then constructed by prepending "\\?\GlobalRoot" to the Buffer member.

How can I get a Win32 HANDLE for a StorageFile or StorageFolder in UWP?

I know I can use Win32 APIs for accessing files within my own local data folder (eg, see this answered question) but I need to access files outside of my app (eg, from the Pictures Library) and the libraries I'm trying to use are all based on Win32 file HANDLEs and / or they rely on using relative filenames.
Since the only way to get at files in the Pictures Library (or to get files / folders returned from a picker) is via StorageFile objects, how can I re-use my existing code? Do I have to re-write it all to be asynchronous and rely on the WinRT storage APIs?
Starting in the "Anniversary Update" (aka "RS1" or build 10.0.14393) you are able to get a Win32 HANDLE from a StorageItem (file or folder) and to create new named files (returning a HANDLE) from within a StorageFolder. You do this using the new IStorageFolderHandleAccess and IStorageItemHandleAccess APIs.
Note: These APIs have been accidentally placed inside the WINAPI_PARTITION_DESKTOP partition (they're not desktop-specific; they're available to UWPs). This will be addressed in future SDK updates.
To use one of these new COM interfaces, you simply QI the StorageFile or StorageFolder for the interface. If the interface isn't supported, it means your app is running on a down-level OS (or perhaps the Storage Item isn't actually backed by a real file, but is rather a pseudo-file). You can use these interfaces from C++ (C++/CX or WRL) or from C#.
Here's a simple example of using a FolderPicker to have the user pick a location on their disk (which returns a brokered StorageFolder object) and then using Win32 APIs ReadFile and WriteFile to read and write a file from that location.
As noted above, we have to copy the declarations for the interface into our own code because the real SDK versions are in the wrong API partition. (I would advise against modifying the SDK files to solve the problem). So first up is our own header file, eg StorageHandleAccess.h, that copies the declarations from the SDK file WindowsStorageCOM.h:
#pragma once
// These are copied from WindowsStorageCOM.h
// You can remove this header file once the real file has been updated
// to fix the WINAPI_PARTITION_DESKTOP block
typedef interface IOplockBreakingHandler IOplockBreakingHandler;
typedef interface IStorageItemHandleAccess IStorageItemHandleAccess;
typedef interface IStorageFolderHandleAccess IStorageFolderHandleAccess;
#ifdef __cplusplus
extern "C" {
#endif
typedef /* [v1_enum] */
enum HANDLE_OPTIONS
{
HO_NONE = 0,
HO_OPEN_REQUIRING_OPLOCK = 0x40000,
HO_DELETE_ON_CLOSE = 0x4000000,
HO_SEQUENTIAL_SCAN = 0x8000000,
HO_RANDOM_ACCESS = 0x10000000,
HO_NO_BUFFERING = 0x20000000,
HO_OVERLAPPED = 0x40000000,
HO_WRITE_THROUGH = 0x80000000
} HANDLE_OPTIONS;
DEFINE_ENUM_FLAG_OPERATORS(HANDLE_OPTIONS);
typedef /* [v1_enum] */
enum HANDLE_ACCESS_OPTIONS
{
HAO_NONE = 0,
HAO_READ_ATTRIBUTES = 0x80,
HAO_READ = 0x120089,
HAO_WRITE = 0x120116,
HAO_DELETE = 0x10000
} HANDLE_ACCESS_OPTIONS;
DEFINE_ENUM_FLAG_OPERATORS(HANDLE_ACCESS_OPTIONS);
typedef /* [v1_enum] */
enum HANDLE_SHARING_OPTIONS
{
HSO_SHARE_NONE = 0,
HSO_SHARE_READ = 0x1,
HSO_SHARE_WRITE = 0x2,
HSO_SHARE_DELETE = 0x4
} HANDLE_SHARING_OPTIONS;
DEFINE_ENUM_FLAG_OPERATORS(HANDLE_SHARING_OPTIONS);
typedef /* [v1_enum] */
enum HANDLE_CREATION_OPTIONS
{
HCO_CREATE_NEW = 0x1,
HCO_CREATE_ALWAYS = 0x2,
HCO_OPEN_EXISTING = 0x3,
HCO_OPEN_ALWAYS = 0x4,
HCO_TRUNCATE_EXISTING = 0x5
} HANDLE_CREATION_OPTIONS;
EXTERN_C const IID IID_IOplockBreakingHandler;
MIDL_INTERFACE("826ABE3D-3ACD-47D3-84F2-88AAEDCF6304")
IOplockBreakingHandler : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE OplockBreaking(void) = 0;
};
EXTERN_C const IID IID_IStorageItemHandleAccess;
MIDL_INTERFACE("5CA296B2-2C25-4D22-B785-B885C8201E6A")
IStorageItemHandleAccess : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE Create(
/* [in] */ HANDLE_ACCESS_OPTIONS accessOptions,
/* [in] */ HANDLE_SHARING_OPTIONS sharingOptions,
/* [in] */ HANDLE_OPTIONS options,
/* [optional][in] */ __RPC__in_opt IOplockBreakingHandler *oplockBreakingHandler,
/* [system_handle][retval][out] */ __RPC__deref_out_opt HANDLE *interopHandle) = 0;
};
EXTERN_C const IID IID_IStorageFolderHandleAccess;
MIDL_INTERFACE("DF19938F-5462-48A0-BE65-D2A3271A08D6")
IStorageFolderHandleAccess : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE Create(
/* [string][in] */ __RPC__in_string LPCWSTR fileName,
/* [in] */ HANDLE_CREATION_OPTIONS creationOptions,
/* [in] */ HANDLE_ACCESS_OPTIONS accessOptions,
/* [in] */ HANDLE_SHARING_OPTIONS sharingOptions,
/* [in] */ HANDLE_OPTIONS options,
/* [optional][in] */ __RPC__in_opt IOplockBreakingHandler *oplockBreakingHandler,
/* [system_handle][retval][out] */ __RPC__deref_out_opt HANDLE *interopHandle) = 0;
};
#ifdef __cplusplus
}
#endif
Next up is a simple usage of the API. This example takes a StorageFolder, a filename, and a creation flag (open or create) and tries to open (or create) the named file, reads (or writes) some text from (to) the file, and writes some output to the Debug console.
The code isn't particularly useful in a real-world setting, but illustrates how to use the API. This can be used in a blank C++ XAML project to replace the MainPage.xaml.cpp file (you should only need to update the namespace):
#include "pch.h"
#include "MainPage.xaml.h"
#include <ppltasks.h>
// TODO: Replace with your namespace
#error Replace this with your real namespace
using namespace FileHandleFromStorageFolder;
// Uncomment out this line and delete the next line once the SDK is fixed
//#include <WindowsStorageCOM.h>
#include "StorageHandleAccess.h"
// For ComPtr<>
#include <wrl\client.h>
// For HandleT<>
#include <wrl\wrappers\corewrappers.h>
__declspec(noreturn) inline void ThrowWithHRESULT(HRESULT hr, const wchar_t* message)
{
using namespace Platform;
throw ref new Exception(hr, ref new String(message));
}
__declspec(noreturn) inline void ThrowWithGetLastError(const wchar_t* message)
{
using namespace Platform;
throw ref new Exception(HRESULT_FROM_WIN32(GetLastError()), ref new String(message));
}
// Test is a simple test function. Pass in one of the HANDLE_CREATION_OPTIONS values
// (eg, HCO_CREATE_ALWAYS or HCO_OPEN_ALWAYS) and the function will try and either
// write to the file (if it's empty) or read from it (if it's not).
void Test(Windows::Storage::StorageFolder^ folder, const wchar_t* filename, HANDLE_CREATION_OPTIONS options)
{
using namespace Microsoft::WRL;
using namespace Microsoft::WRL::Wrappers;
// Get an IUnknown from the ref class, and then QI for IStorageFolderHandleAccess
ComPtr<IUnknown> abiPointer(reinterpret_cast<IUnknown*>(folder));
ComPtr<IStorageFolderHandleAccess> handleAccess;
HRESULT hr = abiPointer.As(&handleAccess);
if (FAILED(hr))
ThrowWithHRESULT(hr, L"Can't QI");
// Standard RAII wrapper for HANDLEs that represent files
HandleT<HandleTraits::FileHandleTraits>win32fileHandle;
// This is roughly equivalent of calling CreateFile2
hr = handleAccess->Create(filename, options,
HANDLE_ACCESS_OPTIONS::HAO_WRITE | HANDLE_ACCESS_OPTIONS::HAO_READ,
HANDLE_SHARING_OPTIONS::HSO_SHARE_NONE, HANDLE_OPTIONS::HO_NONE, nullptr,
win32fileHandle.GetAddressOf());
if (FAILED(hr))
ThrowWithHRESULT(hr, L"Can't access file");
// From here, it's standard Win32 code - nothing WinRT specific at all
LARGE_INTEGER size{ 0 };
if (FALSE == GetFileSizeEx(win32fileHandle.Get(), &size))
ThrowWithGetLastError(L"Can't get file size");
static const DWORD BUFFER_SIZE = 500;
char buffer[BUFFER_SIZE];
DWORD bytesUsed{ 0 };
if (size.QuadPart == 0)
{
const static auto str = "Hello, world\r\n";
if (FALSE == WriteFile(win32fileHandle.Get(), str, strlen(str), &bytesUsed, nullptr))
ThrowWithGetLastError(L"Can't write to file");
sprintf_s(buffer, ARRAYSIZE(buffer), "Wrote %d bytes to file\r\n", bytesUsed);
OutputDebugStringA(buffer);
}
else
{
if (FALSE == ReadFile(win32fileHandle.Get(), buffer, ARRAYSIZE(buffer) - 1, &bytesUsed, nullptr))
ThrowWithGetLastError(L"Can't read from file");
buffer[bytesUsed] = 0;
OutputDebugStringA(buffer);
}
}
// Trivial driver that gets a StorageFolder and then creates a file
// inside it, writes some text, then re-opens it to read text.
void TestWrapper()
{
using namespace Windows::Storage;
using namespace Windows::Storage::Pickers;
auto picker = ref new FolderPicker();
picker->FileTypeFilter->Append(L".txt");
picker->SuggestedStartLocation = PickerLocationId::Desktop;
concurrency::create_task(picker->PickSingleFolderAsync()).then([]
(StorageFolder^ folder)
{
if (folder != nullptr)
{
// Create and then read back a simple file
Test(folder, L"win32handletest.txt", HANDLE_CREATION_OPTIONS::HCO_CREATE_ALWAYS);
Test(folder, L"win32handletest.txt", HANDLE_CREATION_OPTIONS::HCO_OPEN_ALWAYS);
}
}
);
}
MainPage::MainPage()
{
InitializeComponent();
TestWrapper();
}

NtQueryInformationFile for FileStreamInformation succeeds in 32-bit fails in 64-bit

Edit: this question was originally about behavioural difference between code in C++ and C# but that proved to be a red herring. Question has been rewritten to better reflect the problem I'm having.
I'm trying to list the alternate streams of a file hosted on an SMB server using the NtQueryInformationFile function. The code I've written so far works correctly with most servers but fails sometimes when run against non-samba Mac OS X SMB server.
I've reduced the code form my application to the following bit of code that reproduces the issue reliably:
using System;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
namespace Streams
{
class Program
{
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public class NETRESOURCE
{
public uint dwScope;
public uint dwType;
public uint dwDisplayType;
public uint dwUsage;
public string lpLocalName;
public string lpRemoteName;
public string lpComment;
public string lpProvider;
}
[DllImport("ntdll.dll", SetLastError = false, CharSet = CharSet.Unicode)]
public static extern uint NtQueryInformationFile(
SafeFileHandle handle,
IntPtr IoStatusBlock,
IntPtr pInfoBlock,
uint length,
uint fileInformationClass);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern SafeFileHandle CreateFile(
string fileName,
uint desiredAccessMask,
uint shareMode,
IntPtr lpSecurityAttributes,
uint creationDisposition,
uint flagsAndAttributes,
IntPtr hTemplateFile);
[DllImport("mpr.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern uint WNetAddConnection2(NETRESOURCE netResource, [MarshalAs(UnmanagedType.LPTStr)] string password, [MarshalAs(UnmanagedType.LPTStr)] string username, uint flags);
static void Main(string[] args)
{
var server = args[0];
var username = args[1];
var password = args[2];
var uncPath = args[3];
NETRESOURCE netResource = new NETRESOURCE();
netResource.dwType = 0x1 /* DISK */;
netResource.lpRemoteName = server;
WNetAddConnection2(netResource, password, username, 0x00000004 /* CONNECT_TEMPORARY */);
var fh = CreateFile(
uncPath,
0x80000000 /* GENERIC_READ */,
(uint)(FileShare.Read | FileShare.Write | FileShare.Delete),
IntPtr.Zero,
3 /* OPEN_EXISTING */,
0x08000000 /* SequentialScan */ | 0x02000000 /* BackupSemantics */,
IntPtr.Zero
);
IntPtr status = Marshal.AllocHGlobal(1024);
uint bufferSize = 64*1024;
IntPtr buffer = Marshal.AllocHGlobal((int)bufferSize);
uint ntStatus = NtQueryInformationFile(fh, status, buffer, bufferSize, 22 /* FileStreamInformation */);
Console.WriteLine($"NtQueryFileInformation returned {ntStatus}");
Console.ReadKey();
}
}
}
In most cases the value of ntStatus is STATUS_OK as is expected. When I try to use this on a file that has alternate data streams with a Mac OS X SMB server I get STATUS_INVALID_NETWORK_RESPONSE instead. That error code seems to indicate that the response from the server is incorrect, but when I inspect this with Wireshark there are no differences compared to when STATUS_OK is returned.
To make things even stranger, this code works when I run it in 32-bit mode (set the 'Prefer 32-bit' in the Visual Studio project settings). When run in 64-bit mode I always get the error code.
The obvious error then would be that the code in question is not 64-bit clean, but AFAICT the code above is.
I've also tried replacing the NtQueryInformationFile call with the call to GetFileInformationByHandleEx, but that gives me the same result (with a Win32 error code instead of an NT status code of course).
What could explain this difference in behaviour between 32-bit and 64-bit mode?

c# PInvoke w_char_t**

I have the following c++ function which I cannot alter (3rd-Party):
[c++]
int __stdcall TEST(wchar_t **xml, int &result_size)
{
// xml is instantiated here!
}
[c#]
class native
{
[DllImport("somedll.dll")]
public static extern int TEST(StringBuilder a, ref int size);
{
}
}
Example:
StringBuilder b = new StringBuilder();
int size = 0;
native.Test(b,ref size)
The stringbuilder object only contains first character . If I resize the object:
b.Length = size; The data is incorrect except first character.
Is this the correct way to pass wchar_t** from c++ to c#?
Regards,
John
The function would be p/invoked like this:
[DllImport(#"mylib.dll")]
static extern int TEST(out IntPtr xml);
I removed the size paramter since it is not needed since you can use a null-terminated string.
Call the function like this:
IntPtr xmlptr;
int retval = TEST(out xmlptr);
string xml = Marshal.PtrToStringUni(xmlptr);
// deallocate xmlptr somehow
The tricky bit is to deallocate the memory allocated on the native side. Either use a shared allocator, e.g. the COM allocator. Or export a deallocator from the native code.
Personally I'd re-design the interface to use COM BSTR. I'd have the C++ return a BSTR and on the managed side use [MarshalAs(UnmanagedType.BStr)]. Then the framework handles all the deallocation and marshalling for you.

Resources