开发者

Call assembly in buffer in C

Is this possible?

I want to place intel assembly code into a char buffer, and then execute that code from within a C program

If I placed the assembly code into a buffer, could I cast it in开发者_C百科to a function pointer and call that?

I am using GCC and linux


Do you want to execute Intel assembly code or machine code? If you want to execute machine code, then yes, you can, provided that the memory page the character buffer is on is not marked NX (no execute).

If you're talking about assembly code, then no, you would first need to run the code through an assembler (on Un*x systems the standard one is typically called as; on Linux, this should be the same as gas) and then run the resulting machine code.


Yes you could. Infact that is how a buffer overflow attack could work. For more information google buffer overflow attacks. Breaking execution into direct assembly will always work (so long as the assembly is correct).


Perhaps Google can help you write a buffer overflow exploit?


Maybe -- the syntax is:

char buff[/* enough space */];
/* fill in buff with the right opcodes that conform to the Linux ABI */
((void (*)()) buff) ();

The problem is the modern x64's have a mode called "W^X" or "NX bit" which prevents the above code from executing from data pointers. There are APIs for dealing with this, but I am not familiar with the Linux one; a little googling seems to indicate that you actually mark your .o files at link time wanting to disable the NX bit. That seems like a bad idea to me (it seems instead that you should be able to, at run time, promote a data region to be executable, or allocate a writable region from a runnable region of memory; but hey, that's just my opinion -- maybe its really hard to do that.)

Assuming you don't have a NX bit or W^X issue, then just do that cast above and have a ball.


This actually works about the way you'd expect, as long as you get the function pointer syntax right. Other than security exploits, you can use this technique for performance optimization.

I should know better than to type code in with my phone, but...

unsigned char buffer[]={blah, blah, blah ...};
void (*p)() = (void (*))buffer;
p();


If you want to execute something like "pop %[register] push %[register]" as you write in your comment, yes, this is possible, but it isn't easy.

You need to either write an assembler or embed an open source assembler in your application. You feed your assembler with your char array, create the machine code (preferably PIC code, so you can omit the linking and relocating) in an other buffer and execute code in this buffer via a function pointer.

If you can guarantee there is an "as" or "gas" on the platform you run the code, you might get away with a quick and dirty hack to call "as" with your code piped in and the object code piped out.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜