# Pwn class1 - Stack exploit ###### tags: note ## Pwn(Binary exploitation): 透過一或多個漏洞,最終取得程式的掌控權 * 取得 shell * 讀取、竄改程式 * linux 為基礎 ## Pwngdb instruction * code : codebase * checksec : 簡要查看此程式保護機制 * objdump : 可查看 function location * tls : 取得 TLS address (可查看 Canary : -=0x28) * canary : 取得 canary * got : 查看 GOT * readelf * ctx : back to exec ## Tools * ROPgadget : 可 pass 出各種 不同 offset 的 instruction,可能能 pass 出可以使用的 ROPgadget ```= # example ROPgadget --multibr --binary filename > rop vim rop # "/": find ``` * ldd : 可查找若執行當前 binary 程式,會 link 的 library ```= # example ldd ./filename ``` * one_gadget : 可查看 one_gadget ```= # example one_gadget /libname ``` * seccomp-tools : 可分析程式執行中所使用到的 seccomp rules ## Python pwntool * flat() : 將指令打包,ex: in context.arch='amd64' 則會將 instruction 打包成 8個bytes 為單位(符合記憶體單位) ## Executable and Linkable Format(ELF) * Windows 中的 exe 檔 or Linux 中的可執行檔格式 * 用 section 來區分不同功能的資料 * 不同功能會需要不同的權限、大小 * 程式碼屬於 .text section,會需要執行權限 * 常數字串屬於 .rodata section,需要讀取權限 * section v.s. segment * section: 告訴 linker 動態連接時需要的資料 * 名稱表功能 ex: .text 為程式碼 * 是否需被載入記憶體 ex: .text or .data * metadata section * segment: 告訴作業系統此程式載入時的資訊 * 相同權限的資料會載入到相同的區塊 * 被載入到哪塊 virtual memory * Memory layout ![](https://i.imgur.com/ccZYFfS.png) * ELF-protection * Position-Independent Executable(PIE) * 程式碼以相對位置儲存,非絕對位置 * No-eXecute(NX) * .text 以外的 section 不會有執行權限 * stack protector(Canary) * 在 stack 結尾處插入一個隨機數,return 前檢查此數是否有被修改來判斷執行是否有問題 * RELocation Read-Only(REALO) * 分成 Full / Partial / No 三種型態,分別代表在 runtime 解析外部 function 時使用的不同機制 * secure computing mode(Seccomp) * 制定規則來禁止/允許呼叫特定的 syscall * Address Space Layout Randomization(ASLR) * 程式載入時,stack、heap 等記憶體區塊會使用隨機的位址作為 base address * 在一定的範圍中隨機 * 末 12 bits 是固定的,每次載入時都不會更動 * x86 v.s. x64 ![](https://i.imgur.com/SDgamkM.png) ![](https://i.imgur.com/Hvzevbv.png) * Buffer OverFlow(BOF) * 當程式使用固定大小的空間來儲存使用者的資料時,由於設計不良,導致資料超出此空間而覆蓋到其他資料 * 執行 syscall 時需對其 0x10(?)(alignment) * 保護方式 * Canary(stack guard) * 在 offset `0x28` 的位置放置一隨機數,該值稱之 * Canary 第一個 Byte 必為 `00`,可透過 leak canary 繞過此保護機制。 * Canary 在 epilogue 比對失敗則會呼叫 `__stack_chk_fail` ![](https://i.imgur.com/gaIEGkw.png) * 破解方法 : leak canary * memory randomization ![](https://i.imgur.com/ifLtAGM.png) * Global Offset Table(GOT) * Exploit * GOT hijacking * Ret2plt * Leak libc * Ret2libc * Procedure Linkage Table(PLT) * Lazy binding : 動態載入 * Return Oriented Programming(ROP) * 前提是要有 BOF 漏洞才可控制程式流程。 * (Advanced) csu_init : __libc_csu_init 擁有能大量控制 register 的 gadget,並且能夠 dereference function pointer 來呼叫 function * (Advanced) Stack pivoting * Format String Bug(FSB) *