title: Read and Execute Shellcode from a .txt File
body: <p><a href="https://stackoverflow.com/questions/17822771/testing-shellcode-from-c-bus-error-10?noredirect=1#comment26044536_17822771">Testing Shellcode From C Bus Error 10</a></p>
  
  <p>Above was my previous question which involved excuting shellcode from within a c program, when the shell code is inside the source. It was solved by Carl Norum and was due to memory protection. I have a different problem but is similar. Instead of having the shell code in the same file, I want to read the shell code from a .txt file and execute it. Below I tried marking a section of memory as PROT_EXEC and read the contents of the .txt file into it and execute. But it won't work, I'm getting the same error, KERN_PROTECTION_FAILURE, I tried using mprotect and mmap to mark a section of memory as PROT_EXEC.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;sys/mman.h&gt;
  #include &lt;string.h&gt;
  #include &lt;stdlib.h&gt;
  
  int (*ret)();
  
  unsigned char* buf;
  
  int main()
  {
      FILE* file;
      file = fopen("text.txt", "rb");
  
      fseek(file, 0, SEEK_END);
      unsigned int len = ftell(file);
      fseek(file, 0, SEEK_SET);
  
      buf = valloc(len);
      fread(buf, 1, len, file);
  
      fclose(file);
  
      mprotect(buf, len, PROT_EXEC);
  
     // I also tried mmap, but same error.
     /* void *ptr = mmap(0, 1024, PROT_EXEC, MAP_ANON | MAP_PRIVATE, -1, 0);
  
      if (ptr == MAP_FAILED)
      {
          perror("mmap");
          exit(-1);
      }
  
      memcpy(ptr, buf, 1024);*/
  
      ret = buf;
  
      ret();
  
      return 0;
  }
  </code></pre>
  
  <p>This is the text.txt file I'm reading in, its the same hello world code, from my previous question:</p>
  
  <pre><code>\x55\x48\x89\xe5\xeb\x33\x48\x31\xff\x66\xbf\x01\x00\x5e\x48\x31\xd2\xb2\x0e\x41\xb0\x02\x49\xc1\xe0\x18\x49\x83\xc8\x04\x4c\x89\xc0\x0f\x05\x31\xff\x41\xb0\x02\x49\xc1\xe0\x18\x49\x83\xc8\x01\x4c\x89\xc0\x0f\x05\x48\x89\xec\x5d\xe8\xc8\xff\xff\xff\x48\x65\x6c\x6c\x6f\x2c\x20\x57\x6f\x72\x6c\x64\x21\x0a
  </code></pre>
  
  <p>Since I'm copying the contents of the txt file into PROC_EXEC memory, I don't understand why I'm getting KERN_PROTECTION_FAILURE.</p>