is it possible to make a function execute code from a string on the stack?

拥有回忆 提交于 2019-11-30 18:47:39

Sort of, but not really, there is no eval() in c, like in many scripting languages.

However, what you are describing is sort of like a Buffer Overflow exploit.

Where, you use a string to write "code" (not c syntax, but machine code) into the address space after the buffer. Here's a nice little tutorial of the topic.

Don't use this information to write a virus :(

You could use libtcc to compile and run C source code:

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);

A coouple of issues:

  1. You can only compile libtcc on a supported architecture.
  2. You need to have a main function.

Sure it is possible. Buffer Overflow exploits use it.

See Shellcode for what kind of strings you can place.

Basically what you can do it put machine code on the stack and jump to the address. This will cause execution (if the OS/machine allows it, see NX bit).

You could perhaps even try to do a memcpy from some function address onto a string on the stack and then try jumping to the address on the stack.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!