Reputation: 5149
I have some code that has the following function in:
//some code before
// buf is a char[] containing shellcode
((void(*)( ))buf)( ); //Not sure how this works
Can anyone describe what the above function actually does and how?
Syntactically it is also rather confusing!
The full code executes a shellcode and is part of a well known and widely used Security module*, should you wish to view the full source. If it makes any difference gcc -z execstack
is used during it's compilation.
Thanks.
*(Source on page 3)
Upvotes: 1
Views: 1532
Reputation: 25695
It is casting buf
into a function and running it as if it was a function that returns void
and takes no arguments. Essentially running the shellcode.
From the source code in the article:
#include <stdlib.h>
#include <stdio.h>
const char code[] =
"\x31\xc0" /* Line 1: xorl %eax,%eax */
"\x50" /* Line 2: pushl %eax */
"\x68""//sh" /* Line 3: pushl $0x68732f2f */
"\x68""/bin" /* Line 4: pushl $0x6e69622f */
"\x89\xe3" /* Line 5: movl %esp,%ebx */
"\x50" /* Line 6: pushl %eax */
"\x53" /* Line 7: pushl %ebx */
"\x89\xe1" /* Line 8: movl %esp,%ecx */
"\x99" /* Line 9: cdql */
"\xb0\x0b" /* Line 10: movb $0x0b,%al */
"\xcd\x80" /* Line 11: int $0x80 */
;
int main(int argc, char **argv)
{
char buf[sizeof(code)];
strcpy(buf, code);
((void(*)( ))buf)( );
}
It copies the contents of code
into buf
, laying it out sequentially. The first few lines set up the function prologue(setting up the stack etc). It looks to the machine as if, that the code laid out in buf
is same it would look if it was actually a function. When casted, the compiler allows you to actually call the function starting at buf
. Pretty amazing isn't it? But it is conceptually simple.
Upvotes: 5
Reputation: 40613
That statement casts buf
to a pointer to a function (with type void(*)()
), and then calls that function.
buf // `buf` decays to a pointer to the first element of `buf`
(void(*)())buf // this pointer has its type changed to `void(*)()`
// (a pointer to a function taking no arguments and returning void)
((void(*)())buf)(); // this function is called
Upvotes: 1
Reputation: 48076
buf
is being cast to a function pointer and then that function is being invoked. void
is the return type. The last set of parens is where the arg's would go if there were any.
Upvotes: 0