2

I have a piece of code like this:

#include <stdio.h>

int main()
{
   char z[100] = "Hello world";

   printf("%s", z); 

   getchar(); 
}

I then compiled it using gcc -S file.c

Then I turned into a object file using: gcc -c file.S -o file.o

Then I turned into a exe to make sure it worked and it did using this: gcc file.o -o file

Next I moved on to dumping the object file to find the opcode using this: objdump -d file.o

I extracted the opcode and I got this:

\x55\x48\x89\xe5\x48\x81\xec\x90
\x00\x00\x00\xe8\x00\x00\x00\x00
\x48\xb8\x49\x20\x61\x6d\x20\x6c
\x65\x61\x48\xba\x72\x6e\x69\x6e
\x67\x20\x43\x20\x48\x89\x45\x90
\x48\x89\x55\x98\x48\xb8\x70\x72
\x6f\x67\x72\x61\x6d\x6d\x48\xba
\x69\x6e\x67\x20\x6c\x61\x6e\x67
\x48\x89\x45\xa0\x48\x89\x55\xa8
\x48\xb8\x75\x61\x67\x65\x2e\x00
\x00\x00\xba\x00\x00\x00\x00\x48
\x89\x45\xb0\x48\x89\x55\xb8\x48
\xc7\x45\xc0\x00\x00\x00\x00\x48
\xc7\x45\xc8\x00\x00\x00\x00\x48
\xc7\x45\xd0\x00\x00\x00\x00\x48
\xc7\x45\xd8\x00\x00\x00\x00\x48
\xc7\x45\xe0\x00\x00\x00\x00\x48
\xc7\x45\xe8\x00\x00\x00\x00\xc7
\x45\xf0\x00\x00\x00\x00\x48\x8d
\x45\x90\x48\x89\xc2\x48\x8d\x0d
\x00\x00\x00\x00\xe8\x00\x00\x00
\x00\xe8\x00\x00\x00\x00\xb8\x00
\x00\x00\x00\x48\x81\xc4\x90\x00
\x00\x00\x5d\xc3\x90\x90\x90\x90

Then I executed it using this

#include <stdio.h>

unsigned char code[] = "\x55\x48\x89\xe5\x48\x81\xec\x90\x00\x00\x00\xe8\x00\x00\x00\x00\x48\xb8\x49\x20\x61\x6d\x20\x6c\x65\x61\x48\xba\x72\x6e\x69\x6e\x67\x20\x43\x20\x48\x89\x45\x90\x48\x89\x55\x98\x48\xb8\x70\x72\x6f\x67\x72\x61\x6d\x6d\x48\xba\x69\x6e\x67\x20\x6c\x61\x6e\x67\x48\x89\x45\xa0\x48\x89\x55\xa8\x48\xb8\x75\x61\x67\x65\x2e\x00\x00\x00\xba\x00\x00\x00\x00\x48\x89\x45\xb0\x48\x89\x55\xb8\x48\xc7\x45\xc0\x00\x00\x00\x00\x48\xc7\x45\xc8\x00\x00\x00\x00\x48\xc7\x45\xd0\x00\x00\x00\x00\x48\xc7\x45\xd8\x00\x00\x00\x00\x48\xc7\x45\xe0\x00\x00\x00\x00\x48\xc7\x45\xe8\x00\x00\x00\x00\xc7\x45\xf0\x00\x00\x00\x00\x48\x8d\x45\x90\x48\x89\xc2\x48\x8d\x0d\x00\x00\x00\x00\xe8\x00\x00\x00\x00\xe8\x00\x00\x00\x00\xb8\x00\x00\x00\x00\x48\x81\xc4\x90\x00\x00\x00\x5d\xc3\x90\x90\x90\x90";

int main(int argc, char **argv) {
  int foo_value = 0;

  int (*foo)() = (int(*)())code;
  foo_value = foo();

  printf("%d\n", foo_value);
}

Compiled that using gcc shell.c Then I ran a.exe and it says:

1 [main] a 106 cygwin_exception::open_stackdumpfile: Dumping stack trace to a.exe.stackdump
1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56
Agent Magma
  • 41
  • 1
  • 7

1 Answers1

3

The machine code for file is not position-independent, and tries to call library functions. This does not "just work" when turned into shellcode.

Single-step your a.exe in a debugger and see how it fails.

Also, you need to use gcc -zexecstack shell.c so the shellcode is in an executable page.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847