title: Example of a buffer overflow leading to a security leak
body: <p>I read many articles about unsafe functions like strcpy, memcpy, etc. which may lead to security problems when processing external data, like the content of a file or data coming from sockets. This may sound stupid, but I wrote a vulnerable program but I did not manage to "hack" it.</p>
  
  <p>I understand the problem of buffer overflow. Take this example code:</p>
  
  <pre><code>int main() {
     char buffer[1];
     int var = 0;
  
     scan("%s", &amp;buffer);
     printf("var = 0x%x\n", var);
     return 0;
  }
  </code></pre>
  
  <p>When I execute the program and type "abcde", the program outputs 0x65646362 which is "edcb" in hexadecimal + little-endian. However I read that you could modify the eip value that was pushed on the stack in order to make the program execute some unwanted code (eg. right before a call to the system() function).</p>
  
  <p>However the function's assembly starts like this:</p>
  
  <pre><code>push %ebp
  mov %ebp, %esp
  and $0xfffffff0, %esp
  sub $0x20, %esp
  </code></pre>
  
  <p>Since the value of %esp is random at the start of the function and because of this "and", there seems to be no reliable way to write a precise value into the pushed eip value.</p>
  
  <p>Moreover, I read that it was possible to execute the code you wrote in the buffer (here the buffer is only 1 byte long, but in reality it would be large enough to store some code) but what value would you give to eip in order to do so (considering the location of the buffer is random)?</p>
  
  <p>So why are developpers so worried about security problems (except that the program could crash) ? Do you have an example of a vulnerable program and how to "hack" it to execute unwanted code? I tried this on linux, is Windows less safe?</p>