# Switches
from re import S
import sys
import argparse

# pretty print
import pprint
pp = pprint.PrettyPrinter(indent=4)

# pwn
from pwn import *
from pwnlib.rop import gadgets


# ::::::::::::::::::::::::: CONFIG :::::::::::::::::::::::::
PATH = 'Chals'
BINARY = '_binary_'
HOST = '_domain_:_port_'

LIBC_REMOTE = f'{PATH}/libc/libc-2.23.so'
LIBC_LOCAL = '/usr/lib/i386-linux-gnu/libc-2.33.so'
# :::::::::::::::::::::::::::::::::::::::::::::::::::::::::

# ::::::::::::::::::::::: CHECK SEC ::::::::::::::::::::::::

'''

'''

# ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::


def pwn(args):
    binary = f'./{PATH}/{BINARY}'
    proc = process(binary)
    rop = ROP(binary)

    if (args.remote):
        host = HOST.split(':')
        proc = remote(host[0], int(host[1]))
        libc = ELF(LIBC_REMOTE, checksec=False)
    elif (args.local):
        libc = ELF(LIBC_LOCAL, checksec=False)
    if (args.debug):
        gdb.attach(proc)
    elif (args.gadgets):
        gadgets = rop.gadgets
        pp.pprint(gadgets)

    ## get da banner
    log.info('Receiving banner ...')
    proc.recvuntil('> ')

    # shellit
    proc.interactive()


def print_banner():
    print('''
  __                              
  \ \   _ ____      ___ __       
   \ \ | '_ \ \ /\ / / '_ \       
   / / | |_) \ V  V /| | | |     
  /_/  | .__/ \_/\_/ |_| |_|     
       |_|                       
                              
    ''')

if __name__ == "__main__":

    parser = argparse.ArgumentParser(description=print_banner())

    parser.add_argument('-l', '--local',
                        help = 'run against local binary',
                        action = 'store_true',
                        )
    parser.add_argument('-d', '--debug',
                        help = 'run with debugger attached',
                        action ='store_true'
                        )
    parser.add_argument('-r', '--remote',
                        help = 'run against remote binary',
                        action ='store_true'
                        )
    parser.add_argument('-g', '--gadgets',
                        help = 'dump binary gadgets',
                        action ='store_true'
                        )

    args = parser.parse_args()

    if (len(sys.argv) == 1): parser.print_help()
    else: pwn(args)
