title: Segmentation fault by jumping to a user-defined machine code
body: <p>I have the following program (in C):</p>
  
  <pre><code>char shellcode[] = "\xb8\x01\x00\x00\x00\xbb\x00\x00\x00\x00\xcd\x80";
  
      void run_shellcode() {
          int* ret;
          ret = (int*)(&amp;ret) + 2;
          *ret = (int)shellcode;
      }
      int main() { 
          run_shellcode(); 
      }
  </code></pre>
  
  <p>The basis is an example from a lecture about network security available here:</p>
  
  <p><a href="https://hhunetsec.de/2015/02-BufferOverflows.pdf" rel="nofollow">https://hhunetsec.de/2015/02-BufferOverflows.pdf</a></p>
  
  <p>What the program does is the following. <code>int* ret</code> is a pointer variable on the stack of the function <code>run_shellcode</code>. From the variable its own address is taken, added two (pointer arithmetic) and written in the address itself. The resulting address is two addresses above the original address of <code>ret</code> and is the return address of the function. Then the variable is dereferenced and the address of the string overwrites the return address of the function. In this way the code is supposed to execute the machine code in <code>shellcode</code>.</p>
  
  <p>I tried to reproduce this example, but am failing constantly with segmentation fault. The machine code in the string is just a call of the exit system call (despite the name "shellcode") and looks pretty good in disassembler:</p>
  
  <pre><code>(gdb) disass /r shellcode
  Dump of assembler code for function shellcode:
  0x080495ec &lt;shellcode+0&gt;:        b8 01 00 00 00 mov    $0x1,%eax
  0x080495f1 &lt;shellcode+5&gt;:        bb 00 00 00 00 mov    $0x0,%ebx
  0x080495f6 &lt;shellcode+10&gt;:       cd 80  int    $0x80
  0x080495f8 &lt;shellcode+12&gt;:       00 00  add    %al,(%eax)
  </code></pre>
  
  <p>It is compiled in the following way: </p>
  
  <pre><code>gcc -g -m32 -fno-stack-protector -o hello_5 hello_5.c 
  </code></pre>
  
  <p>The debugger also shows that it actually jumps to <code>shellcode</code>, but then segmentation fault follows. I tried different machine code that actually works otherwise, but always failed in this example. </p>
  
  <p>I suppose there is some protection mechanism that prevents executing? Did I make a mistake somewhere? Can I get it run somehow?</p>
  
  <p>I'm not a student of that university where the lecture comes from, so I can't ask for help there.</p>