Skip to content →

提取机器码并运行

构造shellcode,一般是使用高级语言编写一段程序然后编译,反汇编得到十六进制的操作码,或者直接写汇编然后从二进制文件中提取操作码,它们都需要借助反汇编工具或十六进制编辑工具。本文将介绍两段C++代码,其一用于提取机器码,其二用于运行机器码。

  • 提取机器码

以下代码用于自动化提取机器码,只需将汇编代码嵌入TODO位置,然后编译运行即可。代码下载地址:getMachinecode.cpp

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

ULONG get_shellcode_addr() {
    ULONG beginning_addr = 0;

    __asm {
        call    beginning // will push the address of beginning

beginning:
        pop     eax       // will pop the address of beginning to eax
        mov     beginning_addr,eax
        jmp     end_of_shellcode
    }

    __asm {
begin_of_shellcode:
        // TODO, insert your ASM shellcode here, it must not contain NOP!
    }

    // TODO, insert your C++ shellcode here

    __asm {
end_of_shellcode:
        nop
    }

    return (beginning_addr + 1 + 3 + 5); // the address of begin_of_shellcode
}

int main() {
    ULONG shellcode_addr = get_shellcode_addr();

    int count = 0;
    unsigned char shellcode[1024];
    while(true) {
        BYTE db = *((BYTE *)(shellcode_addr + count));
        if(db == 0x90) {
            shellcode[count] = '\0';
            break;
        }
        else {
            shellcode[count++] = db;
        }
    }

    printf("%d bytes of shellcode:\n", count);
    for(int i = 0; i < count; i++) {
        if(i % 16 == 0) printf("\"\n\"");
        printf("\\x%02X", shellcode[i]);
    }

    return 0;
}
  • 运行机器码

以下代码用于运行机器码,代码中的机器码功能是弹出一个MessageBox窗口,只需将它替换成你自己的机器码,然后编译运行即可。

/*
In Visual Studio:
Project/Property/Linker/Advanced/Data Execution Prevention(DEP) -> NO
*/

#include <windows.h>

void main() {
    unsigned char shellcode[] =
        "\x40\x40\x40\x40\x40\xEB\x65\x55\x8B\xEC\x64\xA1\x30\x00\x00\x00"
        "\x8B\x40\x0C\x8B\x40\x14\x8B\x00\x8B\x70\x28\x80\x7E\x0C\x33\x75"
        "\xF5\x8B\x40\x10\x8B\xF8\x03\x7F\x3C\x8B\x7F\x78\x03\xF8\x8B\xDF"
        "\x8B\x7B\x20\x03\xF8\x33\xC9\x8B\x34\x8F\x03\xF0\x41\x8B\x54\x24"
        "\x08\x39\x16\x75\xF2\x8B\x54\x24\x0C\x39\x56\x04\x75\xE9\x8B\x7B"
        "\x24\x03\xF8\x8B\x0C\x4F\x81\xE1\xFF\xFF\x00\x00\x8B\x7B\x1C\x03"
        "\xF8\x49\xC1\xE1\x02\x8B\x3C\x0F\x03\xC7\x5D\xC3\x68\x72\x6F\x63"
        "\x41\x68\x47\x65\x74\x50\xE8\x8C\xFF\xFF\xFF\x83\xC4\x08\x50\x68"
        "\x4C\x69\x62\x72\x68\x4C\x6F\x61\x64\xE8\x79\xFF\xFF\xFF\x83\xC4"
        "\x08\x50\x68\x33\x32\x00\x00\x68\x75\x73\x65\x72\x54\xFF\xD0\x83"
        "\xC4\x08\x68\x6F\x78\x41\x00\x68\x61\x67\x65\x42\x68\x4D\x65\x73"
        "\x73\x54\x50\xFF\x54\x24\x18\x83\xC4\x0C\x33\xFF\x57\x68\x34\x33"
        "\x32\x31\x8B\xCC\x57\x51\x51\x57\xFF\xD0\x83\xC4\x08\x83\xC4\x08"
        "\x68\x50\x72\x6F\x63\x68\x45\x78\x69\x74\xE8\x28\xFF\xFF\xFF\x83"
        "\xC4\x08\x33\xFF\x57\xFF\xD0";

    __asm {
        lea     eax,shellcode
        push    eax
        ret
    }
}

Published in 未分类