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

半城伤御伤魂 提交于 2019-11-30 03:17:52

问题


#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;
}

回答1:


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 :(




回答2:


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.



回答3:


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.



来源:https://stackoverflow.com/questions/3225124/is-it-possible-to-make-a-function-execute-code-from-a-string-on-the-stack

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