首页 > 解决方案 > 将操作码打印为 asm 格式

问题描述

我有一个在我的程序中被更改的 shellcode,

然后我希望能够打印它,以检查一切是否正确。

我将如何打印它,以便以我设置矢量的方式读取它。

std::vector<unsigned char> shellcode  = {
    0xB8, 0x00 ,0x00, 0x00, 0x00,   //mov eax, 0
    0xFF, 0x30,                     //push [eax]
    0xFF, 0x70, 0x04,               //push [eax+4]
    0xFF, 0x70, 0x08,               //push [eax+8]
};

printf("Opcode generated:");
for (int i = 0; i < shellcode.size(); i++) {
    printf(" 0x%02x", (unsigned char)(shellcode[i] & 0xFF));
}

应该是一个更短的方式然后这个

printf("Opcode generated:\n");
for (int i = 0; i <= 4; i++) {
    printf(" 0x%02X", shellcode[i]);
}
printf("\n");
for (int i = 5; i <= 6; i++) {
    printf(" 0x%02X", shellcode[i]);
}
printf("\n");
for (int i = 7; i <= 9; i++) {
    printf(" 0x%02X", shellcode[i]);
}
printf("\n");
for (int i = 10; i <= 12; i++) {
    printf(" 0x%02X", shellcode[i]);
}
printf("\n");

标签: c++

解决方案


一个解决方案可能是创建一个std::vector<std::vector<unsigned char>>并使用 range-for 循环来打印值。

这是一个工作示例(live):

#include <cstdio>
#include <vector>

int main()
{
    std::vector<std::vector<unsigned char>> shellcode  = {
        { 0xB8, 0x00 ,0x00, 0x00, 0x00 },   //mov eax, 0
        { 0xFF, 0x30 },                     //push [eax]
        { 0xFF, 0x70, 0x04 },               //push [eax+4]
        { 0xFF, 0x70, 0x08 },               //push [eax+8]
    };

    printf("Opcode generated:\n");
    for (  const auto& row : shellcode )
    {
        for ( const auto& byte : row )
        {
            printf(" 0x%02X", byte);
        }
        printf("\n");
    }

    return 0;
}

输出:

Opcode generated:
 0xB8 0x00 0x00 0x00 0x00
 0xFF 0x30
 0xFF 0x70 0x04
 0xFF 0x70 0x08

另一种解决方案可能是保持这样的行长(live):

#include <cstdio>
#include <vector>

int main()
{
    const std::vector<unsigned char> shellcode
    {
        0xB8, 0x00 ,0x00, 0x00, 0x00,   //mov eax, 0
        0xFF, 0x30,                     //push [eax]
        0xFF, 0x70, 0x04,               //push [eax+4]
        0xFF, 0x70, 0x08,               //push [eax+8]
    };

    const auto lineLengths = { 5, 2, 3, 3 };

    printf("Opcode generated:\n");
    auto index {0u};
    for ( auto lineLength : lineLengths )
    {
        while ( lineLength-- )
        {
            printf(" 0x%02X", shellcode[index++]);
        }
        printf("\n");
    }

    return 0;
}

您可以在进入循环打印之前添加一个断言,即 of 的大小shellcode必须等于 of 的总和lineLengths。像这样的东西:

#include <numeric>
#include <cassert>
assert( std::accumulate(lineLengths.begin(), lineLengths.end(), 0) == shellcode.size() );

这是带有断言的实时示例:https ://godbolt.org/z/n5B-42


推荐阅读