是否可以使函数从堆栈中的字符串执行代码?

use*_*094 9 c shellcode

#include <stdio.h>

int main(int argc, char** argv)
{
    void (*p) (void);
    /* this obviously won't work, but what string could I put in 
       here (if anything) to make this execute something meaningful?
       Does any OS allow instructions to be read from
       the stack rather than text area of the process image? */
    char *c = "void f() { printf(\"Hello, world!\"); }";
    p = ( void (*)() )c;
    p();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*hen 9

eval()在许多脚本语言中,有一种,但不是真的,在c中没有.

但是,您所描述的有点像缓冲区溢出漏洞.

在哪里,您使用字符串将"代码"(不是c语法,但机器代码)写入缓冲区后的地址空间.这是一个很好的小主题教程.

不要使用此信息写病毒:(

  • 有一个`eval()`:写一个C编译器,将字符串编译成机器码,然后运行它. (2认同)

dre*_*lax 6

您可以使用libtcc编译和运行C源代码:

const char *code = "int main(int argc, char**argv) { printf(\"Hello, world!\"); return 0; }";
TCCState *tcc = tcc_new();

if (tcc_compile_string(tcc, code))
{
    // an error occurred compiling the string (syntax errors perhaps?)
}

int argc = 1;
char *argv[] = { "test" };

int result = tcc_run (tcc, argc, argv);

// result should be the return value of the compiled "main" function.
// be sure to delete the memory used by libtcc

tcc_delete(tcc);
Run Code Online (Sandbox Code Playgroud)

一系列问题:

  1. 您只能libtcc在受支持的体系结构上进行编译.
  2. 你需要有一个main功能.


小智 3

当然有可能。缓冲区溢出漏洞利用它。

请参阅Shellcode以了解可以放置哪种类型的字符串。

基本上你可以做的就是将机器代码放入堆栈并跳转到地址。这将导致执行(如果操作系统/机器允许,请参阅NX 位)。

您甚至可以尝试从某个函数地址执行 m​​emcpy 到堆栈上的字符串,然后尝试跳转到堆栈上的地址。