Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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;
}
like image 200
user389094 Avatar asked Jul 11 '10 23:07

user389094


People also ask

How do you make a string function?

Use the Function() Constructor to create a function from the string. It accepts any number of arguments(in form of string). Last one should be the body of the function. In this example, Only the body of the function is passed which is returning a value.

How do you execute a string?

Given few lines of code inside a string variable and execute the code inside the string. Examples: Input: code = """ a = 6+5 print(a)""" Output: 11 Explanation: Mind it that "code" is a variable and not python code.

Which function will run JavaScript code stored in str?

Conclusion. We can run JavaScript code that's stored in a string with JavaScript by creating a function from it with the Function constructor or pass it into the setTimeout function.

How do you write code inside a string in Python?

If you want to execute Python statements, you can use exec(string). For example, >>> my_code = 'print "Hello World!"' >>> exec(my_code) Hello World!


1 Answers

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.
like image 78
dreamlax Avatar answered Oct 21 '22 16:10

dreamlax