Execute PE file on virtual memory

Hi everyone. I've been reversing some malware like ramnit and I noticed that they contain most of their codes in embedded executable programs and proceed to execute the program as if it's part of the parent program. This is different from process forking method since that creates a new process while this one just calls into the embedded program as if it's one of it's own function (well almost ). So here is a code I came up with that does just that. What it basically does is, it first maps the executable's different sections on to an executable memory region, it then imports and builds the IAT of the executable and finally performs relocation fix-ups and transfers control to the entry point of the executable after setting up ebx to point to PEB and eax to the EP. Since you can't always allocate on the preferred base address of the executable, relocation table is a MUST. This won't work on executables without relocation tables but that shouldn't matter if you are trying to obfuscate your own code since you can tell the compiler to include relocation tables when you recompile it. You can use this method as another layer of protection from AVs.

#include <Windows.h>
#include <string.h>
#include <stdio.h>
#include <tchar.h>
#include "mem_map.h"
 
HMODULE load_dll(const char *dll_name)
{
    HMODULE module;
 
    module = GetModuleHandle(dll_name);
    if (!module)
        module = LoadLibrary(dll_name);
    return module;
}
 
void *get_proc_address(HMODULE module, const char *proc_name)
{
    char *modb = (char *)module;
 
    IMAGE_DOS_HEADER *dos_header = (IMAGE_DOS_HEADER *)modb;
    IMAGE_NT_HEADERS *nt_headers = (IMAGE_NT_HEADERS *)(modb + dos_header->e_lfanew);
    IMAGE_OPTIONAL_HEADER *opt_header = &nt_headers->OptionalHeader;
    IMAGE_DATA_DIRECTORY *exp_entry = (IMAGE_DATA_DIRECTORY *)
        (&opt_header->DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]);
    IMAGE_EXPORT_DIRECTORY *exp_dir = (IMAGE_EXPORT_DIRECTORY *)(modb + exp_entry->VirtualAddress);
 
    void **func_table = (void **)(modb + exp_dir->AddressOfFunctions);
    WORD *ord_table = (WORD *)(modb + exp_dir->AddressOfNameOrdinals);
    char **name_table = (char **)(modb + exp_dir->AddressOfNames);
    void *address = NULL;
 
    DWORD i;
 
    /* is ordinal? */
    if (((DWORD)proc_name >> 16) == 0) {
        WORD ordinal = LOWORD(proc_name);
        DWORD ord_base = exp_dir->Base;
        /* is valid ordinal? */
        if (ordinal < ord_base || ordinal > ord_base + exp_dir->NumberOfFunctions)
            return NULL;
         
        /* taking ordinal base into consideration */
        address = (void *)(modb + (DWORD)func_table[ordinal - ord_base]);
    } else {
        /* import by name */
        for (i = 0; i < exp_dir->NumberOfNames; i++) {
            /* name table pointers are rvas */
            if (strcmp(proc_name, modb + (DWORD)name_table[i]) == 0)
                address = (void *)(modb + (DWORD)func_table[ord_table[i]]);
        }
    }
 
    /* is forwarded? */
    if ((char *)address >= (char *)exp_dir &&
        (char *)address < (char *)exp_dir + exp_entry->Size) {
        char *dll_name, *func_name;
        HMODULE frwd_module;
 
        dll_name = strdup((char *)address);
        if (!dll_name)
            return NULL;
        address = NULL;
        func_name = strchr(dll_name, '.');
        *func_name++ = 0;
 
        if (frwd_module = load_dll(dll_name))
            address = get_proc_address(frwd_module, func_name);
 
        free(dll_name);
    }
 
    return address;
}
 
#define MAKE_ORDINAL(val) (val & 0xffff)
int load_imports(IMAGE_IMPORT_DESCRIPTOR *imp_desc, void *load_address)
{
    while (imp_desc->Name || imp_desc->TimeDateStamp) {
        IMAGE_THUNK_DATA *name_table, *address_table, *thunk;
        char *dll_name = (char *)load_address + imp_desc->Name;
        HMODULE module;
 
        module = load_dll(dll_name);
        if (!module) {
            printf("error loading %s\n", dll_name);
            return 0;
        }
 
        name_table = (IMAGE_THUNK_DATA *)((char *)load_address + imp_desc->OriginalFirstThunk);
        address_table = (IMAGE_THUNK_DATA *)((char *)load_address + imp_desc->FirstThunk);
 
        /* if there is no name table, use address table */
        thunk = name_table == load_address ? address_table : name_table;
        if (thunk == load_address)
            return 0;
 
        while (thunk->u1.AddressOfData) {
            unsigned char *func_name;
            /* is ordinal? */
            if (thunk->u1.Ordinal & IMAGE_ORDINAL_FLAG)
                func_name = (unsigned char *)MAKE_ORDINAL(thunk->u1.Ordinal);
            else
                func_name = ((IMAGE_IMPORT_BY_NAME *)((char *)load_address + thunk->u1.AddressOfData))->Name;
 
            /* address_table->u1.Function = (DWORD)GetProcAddress(module, (char *)func_name); */
            address_table->u1.Function = (DWORD)get_proc_address(module, (char *)func_name);
 
            thunk++;
            address_table++;
        }
        imp_desc++;
    }
    return 1;
}
 
void fix_relocations(IMAGE_BASE_RELOCATION *base_reloc, DWORD dir_size,
        DWORD new_imgbase, DWORD old_imgbase)
{
    IMAGE_BASE_RELOCATION *cur_reloc = base_reloc, *reloc_end;
    DWORD delta = new_imgbase - old_imgbase;    
 
    reloc_end = (IMAGE_BASE_RELOCATION *)((char *)base_reloc + dir_size);
    while (cur_reloc < reloc_end && cur_reloc->VirtualAddress) {
        int count = (cur_reloc->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / sizeof(WORD);
        WORD *cur_entry = (WORD *)(cur_reloc + 1);
        void *page_va = (void *)((char *)new_imgbase + cur_reloc->VirtualAddress);
 
        while (count--) {
            /* is valid x86 relocation? */
            if (*cur_entry >> 12 == IMAGE_REL_BASED_HIGHLOW)
                *(DWORD *)((char *)page_va + (*cur_entry & 0x0fff)) += delta;
            cur_entry++;
        }
        /* advance to the next one */
        cur_reloc = (IMAGE_BASE_RELOCATION *)((char *)cur_reloc + cur_reloc->SizeOfBlock);
    }
}
 
IMAGE_NT_HEADERS *get_nthdrs(void *map)
{
    IMAGE_DOS_HEADER *dos_hdr;
    dos_hdr = (IMAGE_DOS_HEADER *)map;
    return (IMAGE_NT_HEADERS *)((char *)map + dos_hdr->e_lfanew);
}
 
/* returns EP mem address on success
* NULL on failure
*/
void *load_pe(void *fmap)
{
    IMAGE_NT_HEADERS *nthdrs;
    IMAGE_DATA_DIRECTORY *reloc_entry, *imp_entry;
    void *vmap;
    WORD nsections, i;
    IMAGE_SECTION_HEADER *sec_hdr;
    size_t hdrs_size;
    IMAGE_BASE_RELOCATION *base_reloc;
 
    nthdrs = get_nthdrs(fmap);
    reloc_entry = &nthdrs->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
    /* no reloc info? */
    if (!reloc_entry->VirtualAddress)
        return NULL;
    /* allocate executable mem (.SizeOfImage) */
    vmap = VirtualAlloc(NULL, nthdrs->OptionalHeader.SizeOfImage,
        MEM_COMMIT, PAGE_EXECUTE_READWRITE);
    if (!vmap)
        return NULL;
 
    /* copy the Image + Sec hdrs */
    nsections = nthdrs->FileHeader.NumberOfSections;
    sec_hdr = IMAGE_FIRST_SECTION(nthdrs);
    hdrs_size = (char *)(sec_hdr + nsections) - (char *)fmap;
    memcpy(vmap, fmap, hdrs_size);
    /* copy the sections */
    for (i = 0; i < nsections; i++) {
        size_t sec_size;
        sec_size = sec_hdr[i].SizeOfRawData;
        memcpy((char *)vmap + sec_hdr[i].VirtualAddress,
            (char *)fmap + sec_hdr[i].PointerToRawData, sec_size);
    }
 
    /* load dlls */
    imp_entry = &nthdrs->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
    if (!load_imports((IMAGE_IMPORT_DESCRIPTOR *)
        ((char *)vmap + imp_entry->VirtualAddress), vmap))
        goto cleanup;
    /* fix relocations */
    base_reloc = (IMAGE_BASE_RELOCATION *)((char *)vmap + reloc_entry->VirtualAddress);
    fix_relocations(base_reloc, reloc_entry->Size,
        (DWORD)vmap, nthdrs->OptionalHeader.ImageBase);
    return (void *)((char *)vmap + nthdrs->OptionalHeader.AddressOfEntryPoint);
cleanup:
    VirtualFree(vmap, 0, MEM_RELEASE);
    return NULL;
}
 
int vmem_exec(void *fmap)
{
    void *ep;
 
    ep = load_pe(fmap);
    if (!ep)
        return 0;
 
    __asm {
    mov ebx, fs:[0x30]
    mov eax, ep
    call    eax
    }
 
    return 1;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市啃奴,隨后出現(xiàn)的幾起案子销凑,更是在濱河造成了極大的恐慌根悼,老刑警劉巖唆貌,帶你破解...
    沈念sama閱讀 212,884評(píng)論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異抖所,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)晴埂,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,755評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)寻定,“玉大人儒洛,你說(shuō)我怎么就攤上這事±撬伲” “怎么了琅锻?”我有些...
    開封第一講書人閱讀 158,369評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)向胡。 經(jīng)常有香客問(wèn)我恼蓬,道長(zhǎng),這世上最難降的妖魔是什么僵芹? 我笑而不...
    開封第一講書人閱讀 56,799評(píng)論 1 285
  • 正文 為了忘掉前任处硬,我火速辦了婚禮,結(jié)果婚禮上拇派,老公的妹妹穿的比我還像新娘荷辕。我一直安慰自己,他們只是感情好件豌,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,910評(píng)論 6 386
  • 文/花漫 我一把揭開白布疮方。 她就那樣靜靜地躺著,像睡著了一般苟径。 火紅的嫁衣襯著肌膚如雪案站。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 50,096評(píng)論 1 291
  • 那天棘街,我揣著相機(jī)與錄音蟆盐,去河邊找鬼。 笑死遭殉,一個(gè)胖子當(dāng)著我的面吹牛石挂,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播险污,決...
    沈念sama閱讀 39,159評(píng)論 3 411
  • 文/蒼蘭香墨 我猛地睜開眼痹愚,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了蛔糯?” 一聲冷哼從身側(cè)響起拯腮,我...
    開封第一講書人閱讀 37,917評(píng)論 0 268
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎蚁飒,沒(méi)想到半個(gè)月后动壤,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,360評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡淮逻,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,673評(píng)論 2 327
  • 正文 我和宋清朗相戀三年琼懊,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了阁簸。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,814評(píng)論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡哼丈,死狀恐怖启妹,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情醉旦,我是刑警寧澤饶米,帶...
    沈念sama閱讀 34,509評(píng)論 4 334
  • 正文 年R本政府宣布,位于F島的核電站车胡,受9級(jí)特大地震影響咙崎,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜吨拍,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,156評(píng)論 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望网杆。 院中可真熱鬧羹饰,春花似錦、人聲如沸碳却。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,882評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)昼浦。三九已至馍资,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間关噪,已是汗流浹背鸟蟹。 一陣腳步聲響...
    開封第一講書人閱讀 32,123評(píng)論 1 267
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留使兔,地道東北人建钥。 一個(gè)月前我還...
    沈念sama閱讀 46,641評(píng)論 2 362
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像虐沥,于是被迫代替她去往敵國(guó)和親熊经。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,728評(píng)論 2 351

推薦閱讀更多精彩內(nèi)容