Skip to content

Commit 4f4ee86

Browse files
committed
Revert "addressed DarthTon#341: HandleGuard refactoring"
This reverts commit 13f9261.
1 parent dd6531b commit 4f4ee86

File tree

13 files changed

+72
-35
lines changed

13 files changed

+72
-35
lines changed

src/BlackBone/DriverControl/DriverControl.cpp

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -793,20 +793,23 @@ NTSTATUS DriverControl::UnloadDriver( const std::wstring& svcName )
793793
/// <returns>Status code</returns>
794794
LSTATUS DriverControl::PrepareDriverRegEntry( const std::wstring& svcName, const std::wstring& path )
795795
{
796-
RegHandle key1, key2;
796+
HKEY key1, key2;
797797
DWORD dwType = 1;
798798
LSTATUS status = 0;
799799
WCHAR wszLocalPath[MAX_PATH] = { 0 };
800800

801-
swprintf_s( wszLocalPath, std::size( wszLocalPath ), L"\\??\\%s", path.c_str() );
801+
swprintf_s( wszLocalPath, ARRAYSIZE( wszLocalPath ), L"\\??\\%s", path.c_str() );
802802

803803
status = RegOpenKeyW( HKEY_LOCAL_MACHINE, L"system\\CurrentControlSet\\Services", &key1 );
804804
if (status)
805805
return status;
806806

807807
status = RegCreateKeyW( key1, svcName.c_str(), &key2 );
808808
if (status)
809+
{
810+
RegCloseKey( key1 );
809811
return status;
812+
}
810813

811814
status = RegSetValueExW(
812815
key2, L"ImagePath", 0, REG_SZ,
@@ -815,9 +818,24 @@ LSTATUS DriverControl::PrepareDriverRegEntry( const std::wstring& svcName, const
815818
);
816819

817820
if (status)
821+
{
822+
RegCloseKey( key2 );
823+
RegCloseKey( key1 );
818824
return status;
825+
}
819826

820-
return RegSetValueExW( key2, L"Type", 0, REG_DWORD, reinterpret_cast<const BYTE*>(&dwType), sizeof( dwType ) );
827+
status = RegSetValueExW( key2, L"Type", 0, REG_DWORD, reinterpret_cast<const BYTE*>(&dwType), sizeof( dwType ) );
828+
if (status)
829+
{
830+
RegCloseKey( key2 );
831+
RegCloseKey( key1 );
832+
return status;
833+
}
834+
835+
RegCloseKey( key2 );
836+
RegCloseKey( key1 );
837+
838+
return status;
821839
}
822840

823841

src/BlackBone/DriverControl/DriverControl.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -312,7 +312,7 @@ class DriverControl
312312
/// <returns>Status code</returns>
313313
LSTATUS PrepareDriverRegEntry( const std::wstring& svcName, const std::wstring& path );
314314
private:
315-
Handle _hDriver;
315+
FileHandle _hDriver;
316316
NTSTATUS _loadStatus = STATUS_NOT_FOUND;
317317
};
318318

src/BlackBone/Include/HandleGuard.h

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ namespace blackbone
77
/// <summary>
88
/// Strong exception guarantee
99
/// </summary>
10-
template<typename handle_t, auto close_fn>
10+
template<typename handle_t, auto close_fn, handle_t zero_handle>
1111
class HandleGuard
1212
{
1313
public:
@@ -24,7 +24,7 @@ class HandleGuard
2424

2525
~HandleGuard()
2626
{
27-
if (valid())
27+
if (_handle != zero_handle)
2828
close_fn( _handle );
2929
}
3030

@@ -53,7 +53,7 @@ class HandleGuard
5353
if (handle == _handle)
5454
return;
5555

56-
if (valid())
56+
if (_handle != zero_handle)
5757
close_fn( _handle );
5858

5959
_handle = handle;
@@ -66,24 +66,25 @@ class HandleGuard
6666
return tmp;
6767
}
6868

69-
handle_t get() const noexcept { return _handle; }
70-
bool valid() const noexcept { return reinterpret_cast<intptr_t>(_handle) > reinterpret_cast<intptr_t>(zero_handle); }
69+
inline handle_t get() const noexcept { return _handle; }
7170

72-
operator handle_t() const noexcept { return _handle; }
73-
explicit operator bool() const noexcept { return valid(); }
71+
inline operator handle_t() const noexcept { return _handle; }
72+
inline explicit operator bool() const noexcept { return _handle != zero_handle; }
7473

75-
handle_t* operator &() noexcept { return &_handle; }
74+
inline handle_t* operator &() noexcept { return &_handle; }
7675

77-
bool operator ==( const HandleGuard& rhs ) const noexcept { return _handle == rhs._handle; }
78-
bool operator <( const HandleGuard& rhs ) const noexcept { return _handle < rhs._handle; }
76+
inline bool operator ==( const HandleGuard& rhs ) const noexcept { return _handle == rhs._handle; }
77+
inline bool operator <( const HandleGuard& rhs ) const noexcept { return _handle < rhs._handle; }
7978

8079
private:
81-
static constexpr handle_t zero_handle = handle_t( 0 );
8280
handle_t _handle;
8381
};
8482

85-
using Handle = HandleGuard<HANDLE, &CloseHandle>;
86-
using ACtxHandle = HandleGuard<HANDLE, &ReleaseActCtx>;
87-
using RegHandle = HandleGuard<HKEY, &RegCloseKey>;
83+
using Handle = HandleGuard<HANDLE, &CloseHandle, nullptr>;
84+
using FileHandle = HandleGuard<HANDLE, &CloseHandle, INVALID_HANDLE_VALUE>;
85+
using ACtxHandle = HandleGuard<HANDLE, &ReleaseActCtx, INVALID_HANDLE_VALUE>;
86+
using FileMapHandle = HandleGuard<void*, &UnmapViewOfFile, nullptr>;
87+
using SnapHandle = FileHandle;
88+
using RegHandle = HandleGuard<HKEY, &RegCloseKey, nullptr>;
8889

8990
}

src/BlackBone/Misc/NameResolve.cpp

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,7 @@ NTSTATUS NameResolve::ResolvePath(
167167
// Perform search accordingly to Windows Image loader search order
168168
// 1. KnownDlls
169169
//
170-
RegHandle hKey;
170+
HKEY hKey = NULL;
171171
LRESULT res = 0;
172172
res = RegOpenKeyW( HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Control\\Session Manager\\KnownDLLs", &hKey );
173173

@@ -197,10 +197,14 @@ NTSTATUS NameResolve::ResolvePath(
197197
if (res == ERROR_SUCCESS)
198198
{
199199
path = std::wstring( sys_path ) + L"\\" + value_data;
200+
201+
RegCloseKey( hKey );
200202
return STATUS_SUCCESS;
201203
}
202204
}
203205
}
206+
207+
RegCloseKey( hKey );
204208
}
205209

206210

@@ -355,7 +359,7 @@ NTSTATUS NameResolve::ProbeSxSRedirect( std::wstring& path, Process& proc, HANDL
355359
/// <returns>Process executable directory</returns>
356360
std::wstring NameResolve::GetProcessDirectory( DWORD pid )
357361
{
358-
Handle snapshot;
362+
SnapHandle snapshot;
359363
MODULEENTRY32W mod = { sizeof(MODULEENTRY32W), 0 };
360364
std::wstring path = L"";
361365

src/BlackBone/PE/PEImage.cpp

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -497,7 +497,7 @@ NTSTATUS PEImage::PrepareACTX( const wchar_t* filepath /*= nullptr*/ )
497497
if (GetTempFileNameW( tempDir, L"ImageManifest", 0, tempPath ) == 0)
498498
return STATUS_SXS_CANT_GEN_ACTCTX;
499499

500-
auto hTmpFile = Handle( CreateFileW( tempPath, FILE_GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, 0, NULL ) );
500+
auto hTmpFile = FileHandle( CreateFileW( tempPath, FILE_GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, 0, NULL ) );
501501
if (hTmpFile != INVALID_HANDLE_VALUE)
502502
{
503503
DWORD bytes = 0;
@@ -521,7 +521,8 @@ NTSTATUS PEImage::PrepareACTX( const wchar_t* filepath /*= nullptr*/ )
521521

522522
// Create ACTX
523523
_hctx = CreateActCtxW( &act );
524-
if (_hctx)
524+
525+
if (_hctx != INVALID_HANDLE_VALUE)
525526
return STATUS_SUCCESS;
526527

527528
// Return success if current process is protected

src/BlackBone/PE/PEImage.h

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -310,7 +310,7 @@ class PEImage
310310
void* GetManifest( uint32_t& size, int32_t& manifestID );
311311

312312
private:
313-
Handle _hFile; // Target file HANDLE
313+
FileHandle _hFile; // Target file HANDLE
314314
Handle _hMapping; // Memory mapping object
315315
void* _pFileBase = nullptr; // Mapping base
316316
bool _isPlainData = false; // File mapped as plain data file
@@ -324,7 +324,7 @@ class PEImage
324324
uint32_t _imgSize = 0; // Image size
325325
uint32_t _epRVA = 0; // Entry point RVA
326326
uint32_t _hdrSize = 0; // Size of headers
327-
ACtxHandle _hctx; // Activation context
327+
ACtxHandle _hctx; // Activation context
328328
int32_t _manifestIdx = 0; // Manifest resource ID
329329
uint32_t _subsystem = 0; // Image subsystem
330330
int32_t _ILFlagOffset = 0; // Offset of pure IL flag

src/BlackBone/Process/Process.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -323,7 +323,7 @@ call_result_t<std::vector<HandleInfo>> Process::EnumHandles()
323323
std::vector<DWORD> Process::EnumByName( const std::wstring& name )
324324
{
325325
std::vector<DWORD> found;
326-
auto hProcSnap = Handle( CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 ) );
326+
auto hProcSnap = SnapHandle( CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 ) );
327327
if (!hProcSnap)
328328
return found;
329329

src/BlackBone/Process/Threads/Threads.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ call_result_t<ThreadPtr> ProcessThreads::CreateNew( ptr_t threadProc, ptr_t arg,
5353
std::vector<ThreadPtr> ProcessThreads::getAll() const
5454
{
5555
std::vector<ThreadPtr> result;
56-
auto hThreadSnapshot = Handle( CreateToolhelp32Snapshot( TH32CS_SNAPTHREAD, 0 ) );
56+
auto hThreadSnapshot = SnapHandle( CreateToolhelp32Snapshot( TH32CS_SNAPTHREAD, 0 ) );
5757
if (!hThreadSnapshot)
5858
return result;
5959

src/BlackBone/Syscalls/Syscall.h

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@
66

77
extern "C" void* syscall_stub();
88

9-
namespace blackbone::syscall
9+
namespace blackbone
10+
{
11+
namespace syscall
1012
{
1113
template<typename T>
1214
using to_int64 = std::conditional_t<sizeof( T ) < sizeof( int64_t ), int64_t, T>;
@@ -66,3 +68,4 @@ namespace blackbone::syscall
6668

6769
#pragma warning(pop)
6870
}
71+
}

src/BlackBoneTest/TestAsmJit.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ namespace Testing
7878
AssertEx::IsTrue( b );
7979

8080
// Check locally
81-
auto hFile = Handle( CreateFileW( filePath, GENERIC_READ, 0x7, nullptr, OPEN_EXISTING, FILE_DELETE_ON_CLOSE, nullptr ) );
81+
FileHandle hFile = FileHandle( CreateFileW( filePath, GENERIC_READ, 0x7, nullptr, OPEN_EXISTING, FILE_DELETE_ON_CLOSE, nullptr ) );
8282
AssertEx::IsTrue( hFile );
8383

8484
uint8_t readBuf[sizeof( writeBuf )] = { };

src/BlackBoneTest/TestManualMap.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ namespace Testing
131131

132132
std::pair<std::unique_ptr<uint8_t[]>, uint32_t> GetFileData( const std::wstring& path )
133133
{
134-
auto hFile = Handle( CreateFileW( path.c_str(), FILE_GENERIC_READ, 0x7, nullptr, OPEN_EXISTING, 0, nullptr ) );
134+
auto hFile = FileHandle( CreateFileW( path.c_str(), FILE_GENERIC_READ, 0x7, nullptr, OPEN_EXISTING, 0, nullptr ) );
135135
if (hFile)
136136
{
137137
uint32_t size = GetFileSize( hFile, nullptr );

src/BlackBoneTest/TestRemoteCall.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,7 @@ namespace Testing
195195
AssertEx::AreEqual( static_cast<DWORD>(sizeof( writeBuf )), bytes );
196196

197197
// Check locally
198-
auto hFile = Handle( CreateFileW( filePath, GENERIC_READ, 0x7, nullptr, OPEN_EXISTING, FILE_DELETE_ON_CLOSE, nullptr ) );
198+
FileHandle hFile = FileHandle( CreateFileW( filePath, GENERIC_READ, 0x7, nullptr, OPEN_EXISTING, FILE_DELETE_ON_CLOSE, nullptr ) );
199199
AssertEx::IsTrue( hFile );
200200

201201
uint8_t readBuf[sizeof( writeBuf )] = { };

src/Samples/Main.cpp

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,16 @@ void MapCmdFromMem();
1111

1212
int main( int /*argc*/, char* /*argv[]*/ )
1313
{
14+
Process pc;
15+
pc.Attach( GetCurrentProcess() );
16+
17+
bool prot = pc.core().isProtected();
18+
19+
Driver().EnsureLoaded();
20+
Driver().ProtectProcess( GetCurrentProcessId(), PolicyOpt::Policy_Enable );
21+
22+
bool prot2 = pc.core().isProtected();
23+
1424
// List all process PIDs matching name
1525
auto pids = Process::EnumByName( L"explorer.exe" );
1626

@@ -44,7 +54,7 @@ int main( int /*argc*/, char* /*argv[]*/ )
4454
}
4555

4656
// Start new suspended process and attach immediately
47-
Process notepad;
57+
Process notepad;
4858
notepad.CreateAndAttach( L"C:\\windows\\system32\\notepad.exe", true );
4959
{
5060
// do stuff...
@@ -93,7 +103,7 @@ int main( int /*argc*/, char* /*argv[]*/ )
93103
memory.Read( mainMod->baseAddress, sizeof( dosHeader ), &dosHeader );
94104

95105
// Method 3
96-
auto [status, dosHeader2] = memory.Read<IMAGE_DOS_HEADER>( mainMod->baseAddress );
106+
auto[status, dosHeader2] = memory.Read<IMAGE_DOS_HEADER>( mainMod->baseAddress );
97107

98108
// Change memory protection
99109
if (NT_SUCCESS( memory.Protect( mainMod->baseAddress, sizeof( dosHeader ), PAGE_READWRITE ) ))
@@ -110,7 +120,7 @@ int main( int /*argc*/, char* /*argv[]*/ )
110120
}
111121

112122
// Allocate memory
113-
if (auto [status2, block] = memory.Allocate( 0x1000, PAGE_EXECUTE_READWRITE ); NT_SUCCESS( status2 ))
123+
if (auto[status2, block] = memory.Allocate( 0x1000, PAGE_EXECUTE_READWRITE ); NT_SUCCESS( status2 ))
114124
{
115125
// Write into memory block
116126
block->Write( 0x10, 12.0 );
@@ -164,7 +174,7 @@ int main( int /*argc*/, char* /*argv[]*/ )
164174
{
165175
auto& remote = notepad.remote();
166176
remote.CreateRPCEnvironment( Worker_None, true );
167-
177+
168178
auto GetModuleHandleWPtr = notepad.modules().GetExport( L"kernel32.dll", "GetModuleHandleW" );
169179
if (GetModuleHandleWPtr)
170180
{
@@ -256,7 +266,7 @@ int main( int /*argc*/, char* /*argv[]*/ )
256266
GetCurrentProcess(),
257267
GetModuleHandle( nullptr ),
258268
buf,
259-
sizeof( buf ),
269+
sizeof(buf),
260270
&bytes
261271
);
262272

0 commit comments

Comments
 (0)