Shellcode in C program

时光怂恿深爱的人放手 提交于 2019-11-27 03:58:16

问题


In Demystifying the Execve Shellcode is explained a way to write an execve shellcode:

#include<stdio.h>
#include<string.h>

unsigned char code[] = 
"\x31\xc0\x50\x68\x6e\x2f\x73\x68\x68\x2f\x2f\x62\x69\x89\xe3\x50\x89\xe2\x53\x89\xe1\xb0\x0b\xcd\x80";

main()
{

    printf("Shellcode Length: %d\n", strlen(code));

    int (*ret)() = (int(*)())code;

    ret();
}

What does the line int (*ret)() = (int(*)())code; do?


回答1:


  int (*ret)() = (int(*)())code;
  ~~~~~~~~~~~~   ~~~~~~~~~~~~~~
        1              2

  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
               3
  1. It defines ret as a pointer to a function which has no parameter () and returns int. So, Those () indicates the definition of parameters of a function.

  2. It's for casting code to a pointer to a function which has no parameter () and returns int.

  3. Casts code as a function and assigns it to ret. After that you can call ret();.

 

unsigned char code[] =  "\x31\xc0\x50\x68\x6e\x2f\...

It is a sequence of machine instructions represented by hex values. It will be injected to the code as a function.




回答2:


    (*(void(*)())shellcode)()

==

    p = (void(*)()) shellcode;
    (*p)();



回答3:


The int line declares the ret() function, by pointing to the code[] array; in other words, the function is mapped to the code[] binary instructions.

The \x construct is a safe way to embed hexadecimal characters in a string. You could for instance replace “\x31” by “1” as the character code of “1” is 49, or hexadecimal 31.




回答4:


Can this function pointer part be re-written in a simpler form?

I don't know if you think this is simpler, but maybe:

#include <stdio.h>
#include <string.h>

unsigned char code[] = 
"\x31\xc0\x50\x68\x6e\x2f\x73\x68\x68\x2f\x2f\x62\x69\x89\xe3\x50\x89\xe2\x53\x89\xe1\xb0\x0b\xcd\x80";

typedef int(*shellcode_t)();

int main(int argc, char ** argv) {
    printf("Shellcode Length: %ld\n", strlen(code));

    shellcode_t ret = (shellcode_t)code;

    ret();
}


来源:https://stackoverflow.com/questions/16626857/shellcode-in-c-program

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