import requests
import imp
import os
import re
import datetime
import sys
import threading
import subprocess
from CustomUtils import *

VERBOSE = False

# Carica modulo per database
database = imp.load_source('*', 'CTF-Flag-Submitter/database.py')
DB = database.connect_to_db( 'instance/InsHack@ti.sqlite' )

BASE_PATH = os.path.dirname(os.path.abspath(__file__)) + '/'

if len( sys.argv ) >= 2:
    VERBOSE = (sys.argv[1].lower() == 'verbose')


def LaunchSingleExploit( ip, porta, exploit, THREAD_ID ):
    """
    Ritorna l'oggetto
    {
        'flag': [
            'FLAGUWNYXIYSHCDDSURMWMWEWUJQJIY=',
            'FLAGDLHGMGZCHXBAHQNWCBABEHNJUDU=',
            'FLAGBMDQPTQDSEQGMQPCKUXATKSMOVB=',
            ....
        ],
        'errors': errors,                 # COME ARRAY
        'output': result,                 # COME ARRAY
        'important_messages': messages,   # COME ARRAY
        'exploit': exploit
    }

    """



    FLAGS_LEAKED = []

    errors = []
    messages = []

    BASE_DIR = BASE_PATH + exploit['base_dir']
    # os.chdir( exploit['base_dir'] )

    cmd = exploit['cmd']
    # print "BASE_DIR"
    # print "{}".format(BASE_DIR)
    # print "BASE_DIR"

    COMMAND = '{} "{}" "{}"'.format( cmd, ip, porta )
    print "[--ID:{}] Launching command:    {}".format( THREAD_ID, COMMAND )

    try:
        pr = subprocess.Popen( COMMAND, shell=True, cwd=BASE_DIR, stdout=subprocess.PIPE ) #.read()
        PROCESS_OUTPUT = pr.stdout.read()
    except Exception as e:
        return {
            'flag': FLAGS_LEAKED,   # = []
            'errors': [ "ERROR PROCESS." ],
            'output': '',
            'important_messages': ''
            #, 'exploit': ''
        }



    # FLAG FOUND
    results = re.findall(r'[A-Z0-9]{31}=', PROCESS_OUTPUT)
    if len(results) > 0:
        # Remove duplicate flags
        results__ = set(results)
        results = list(results__)
        FLAGS_LEAKED = results

    else:
        # Flag not found
        errors.append( 'Flag not found in response.' )
        FLAGS_LEAKED = [ ]

    # # FLAG FOUND
    # if "ccit{" in result:
    #     results = re.findall(r'ccit{.*}', result)
    #     if len(results) > 0:
    #         flag = results[0]
    #     else:
    #         errors.append( 'ccit{ is in result but regex can\'t find ( ccit{.*} )' )
    #         flag = ''
    #
    # else:
    #     errors.append( 'Flag not found in response.' )
    #     # Flag not found



    data = {
        'flag': FLAGS_LEAKED,
        'errors': errors,
        'output': PROCESS_OUTPUT,
        'important_messages': messages
        #, 'exploit': exploit
    }

    return data

def LaunchExploits( exploits, team, THREAD_ID ):

    IP = team['ip']
    PORTA = exploits['porta_challenge']
    # t = threading.currentThread()

    # print exploits
    DATA_RETURN = []        # Dati da ritornare
    FLAGS_LEAKED = []       # Lista dei flag trovati

    rets = []

    for exploit in exploits['exploits']:
        print '[--ID:{}] Provo exploit v.{} di {}'.format( THREAD_ID, exploit['versione_exploit'], exploit['proprietario'] )
        # print exploit

        ret = LaunchSingleExploit( IP, PORTA, exploit, THREAD_ID )
        # if getattr(t, "do_run", False):
        #     return rets

        if len(ret['important_messages']) > 0:
            print '+'*100
            for msg in ret['important_messages']:
                print '+ {}'.format( msg )
            print '+'*100

        FLAGS_LEAKED = ret['flag']

        # print ret
        if len( FLAGS_LEAKED ) > 0:

            # DATA_RETURN = [ ]
            for FLAG_LEAKED in FLAGS_LEAKED:
                data = {
                    'flag': FLAG_LEAKED,
                    'errors': ret['errors'],
                    'output': ret['output'],
                    'important_messages': ret['important_messages'],
                    'exploit': exploit
                }

                DATA_RETURN.append( data )

                print '[ OK ID:{} ] Successo! Nuovo flag: "{}"'.format( THREAD_ID, FLAG_LEAKED )


            # print F_DATA
            if len( FLAGS_LEAKED ) == 1:
                print "Trovato 1 flag da THREAD {}".format( THREAD_ID )
            else:
                print "Trovati {} flags da THREAD {}".format( len( FLAGS_LEAKED ), THREAD_ID )

            # FLAG TROVATO/I
            # CONTINUA CON IL PROSSIMO EXPLOIT


        # NESSUN FLAG TROVATO CON L'EXPLOIT CORRENTE.
        # RITENTO CON IL PROSSIMO EXPLOIT



    return DATA_RETURN

def StoreFlag( FLAG, team, datetime__, exploit ):
    # print "FLAG: {}".format( FLAG )
    # print "exploit: {}".format( exploit )
    # print "team: {}".format( team['id'] )

    id_team = team['id']
    id_exploit = exploit['id']
    created_at = datetime__
    flag_is_not_found = True

    # print "{} : {} : {} : {}".format( id_team, id_exploit, FLAG, created_at )

    # print ''.join( FLAG )

    res = DB.execute(
        'SELECT id FROM flags WHERE flag = ? ', ( FLAG, )
    ).fetchone()

    if res is not None:
        print '[~OK~] FLAG {} gia\' inserito.'.format( FLAG )
    else:
        DB.execute(
            'INSERT INTO flags ( id_team_rivale, id_exploit, flag, created_at ) VALUES ( ?, ?, ?, ? )',
            ( id_team, id_exploit, FLAG, created_at )
        )
        DB.commit()
        print '[ OK ] FLAG {} appena inserito.'.format( FLAG )


TEAMS = []
EXPLOITS = []
GLOBAL_FLAGS = []


def ThreadLaunchExploitsWrapper( challenge, team, THREAD_ID ):

    t = threading.currentThread()

    # getattr(t, "ID", None)
    #
    # ID
    # TEAM
    # CHALLENGE

    print "[ID:{}] Lancio exploits per challenge \"{}\" verso il team \"{}\" ({}:{}).".format( THREAD_ID, challenge['nome_challenge'], team['name'].encode('utf-8'), team['ip'], challenge['porta_challenge'] )
    DATA_OUTPUT = LaunchExploits( challenge, team, THREAD_ID )

    # Formato di DATA_OUTPUT
    #
    # [
    #     {
    #         'flag': FLAG_LEAKED,
    #         'errors': ret['errors'],
    #         'output': ret['output'],
    #         'important_messages': ret['important_messages'],
    #         'exploit': exploit
    #     }, ...
    # ]

    for FLAG_DATA in DATA_OUTPUT:
        FLAG_LEAKED = FLAG_DATA['flag']
        EXPLOIT = FLAG_DATA['exploit']
        if len( FLAG_LEAKED ) > 0:
            GLOBAL_FLAGS.append( { 'flag':FLAG_LEAKED, 'team':team, 'created_at': datetime.datetime.now(), 'exploit': EXPLOIT  } )

    if len( DATA_OUTPUT ) == 0:
        print "[---] Errore... Nessun flag trovato per {} dal THREAD {}".format( challenge['nome_challenge'], THREAD_ID )
        # if VERBOSE:
        #     err = []
        #     for ret in rets:
        #         err.append( ret['output'] )
        #     print "ERROR: # " + '\nERROR: # '.join(err)
        return []

    # if len( DATA_OUTPUT ) > 0:
    #     flag = rets[0]['flag']
    #     exploit__ = rets[0]['exploit']
    #     if len(flag) > 0:
    #         # StoreFlag( flag, team, datetime.datetime.now(), exploit__ )
    #
    #         # if getattr(t, "do_run", False):
    #         #     return rets
    #
    #     else:
    #         print "[---] Errore... Nessun flag trovato per {} dal THREAD {}".format( challenge['nome_challenge'], THREAD_ID )
    #         if VERBOSE:
    #             err = []
    #             for ret in rets:
    #                 err.append( ret['output'] )
    #             print "ERROR: # " + '\nERROR: # '.join(err)


    # if getattr(t, "do_run", False):
    #     return rets

    return DATA_OUTPUT  # InsHack@ti


import time

def main():
    global GLOBAL_FLAGS
    # exit()

    # Il TICK e' 120 secondi, ma lancia gli exploit ogni 30 secondi per sicurezza di latenza
    # 120 SECONDI
    REAL_TICK = 120
    WARNING_TICK = 40
    LOOP_TICK = 30
    init_time = time.time()

    i = 0
    while True:
        # Clear screen
        os.system('clear')
        print "Exploit launcher - Loop n. {}".format(i)

        TEAMS = ReadTeams()
        CHALLENGES_EXPLOITS = ReadChallengesAndActiveExploits()

        CoolPrintTeams(TEAMS)
        CoolPrintChallenges(CHALLENGES_EXPLOITS)
        # print TEAMS
        # print EXPLOITS
        thread_list = []

        i = 0
        # with open('flags.txt', 'w') as f:
        #     f.write('\n')

        ActiveTeams = GetActiveTeams( TEAMS )

        print TEAMS
        print ActiveTeams

        # PER OGNI TEAM ESEGUI UN THREAD?
        for team in ActiveTeams:
            for challenge in CHALLENGES_EXPLOITS:

                if len( challenge['exploits'] ) > 0:

                    THREAD_ID = i

                    current_thread = threading.Thread(target=ThreadLaunchExploitsWrapper, args=(challenge, team, THREAD_ID))
                    # current_thread.start()
                    thread_list.append( {
                    'id': THREAD_ID,
                    'thread': current_thread,
                    'team': team,
                    'challenge': challenge['nome_challenge']
                    } )
                    i += 1

                    # ThreadLaunchExploitsWrapper( challenge, team )


                else:
                    print "[ x_x ] Nessun exploit disponibile per {}".format( challenge['nome_challenge'] )

        # print thread_list
        print "N_THREADS: {}...".format( len(thread_list) )

        for t in thread_list:
            t['thread'].start()
            print "THREAD STARTED... {}".format( t['id'] )

        # print "SLEEPING..."
        # time.sleep(10)
        # print "END SLEEPING..."


        for t in thread_list:
            t['thread'].join()
            print "THREAD {} QUITTED...".format( t['id'] )



        # print "JOINING_THREADS..."
        # i = 0
        # for t in thread_list:
        #     t['thread'].do_run = False
        #
        #     # print "WAITING THREAD... {}".format( t['id'] )
        #     #
        #     # if not t['thread'].isAlive():
        #     #     print "THREADS EXITED... {}".format( t['id'] )
        #     #     continue
        #     #     t['thread'].do_run = False
        #     #
        #     #
        #     # t['thread'].join()
        #     print "THREADS EXITED... {}".format( t['id'] )
        #
        # print "THREADS JOINED..."

        # print GLOBAL_FLAGS
        for flag_data in GLOBAL_FLAGS:
            flag = flag_data['flag']
            team = flag_data['team']
            created_at = flag_data['created_at']
            exploit__ = flag_data['exploit']
            StoreFlag( flag, team, datetime.datetime.now(), exploit__ )

        GLOBAL_FLAGS = []

        end_time = time.time()
        if (end_time - init_time > WARNING_TICK):
            print "!!!!!!!! WARNING !!!!!!!! WARNING !!!!!!!! WARNING !!!!!!!! WARNING !!!!!!!!"
            print "EXPLOIT TROPPO LENTI ({} s). SUPERANO I {} SECONDI".format(end_time - init_time, WARNING_TICK)
            print "!!!!!!!! WARNING !!!!!!!! WARNING !!!!!!!! WARNING !!!!!!!! WARNING !!!!!!!!"

        while (end_time - init_time < LOOP_TICK):
            # end_time = time.time()
            # print "Fanculo lo sleep... Runna tutto."
            # break
            end_time = time.time()
            print "Waiting until {} s... Delta: {}... ".format( LOOP_TICK, str(end_time - init_time)[:10],  )
            time.sleep(1)
        i += 1
        init_time = time.time()# init_time + LOOP_TICK


if __name__ == '__main__':
    # test()
    main()

import requests
import imp
import os
import re
import datetime
import sys
import threading
import subprocess
from CustomUtils import *

VERBOSE = False

# Carica modulo per database
database = imp.load_source('*', 'CTF-Flag-Submitter/database.py')
DB = database.connect_to_db( 'instance/InsHack@ti.sqlite' )

BASE_PATH = os.path.dirname(os.path.abspath(__file__)) + '/'

if len( sys.argv ) >= 2:
    VERBOSE = (sys.argv[1].lower() == 'verbose')


def LaunchSingleExploit( ip, porta, exploit, THREAD_ID ):
    """
    Ritorna l'oggetto
    {
        'flag': [
            'FLAGUWNYXIYSHCDDSURMWMWEWUJQJIY=',
            'FLAGDLHGMGZCHXBAHQNWCBABEHNJUDU=',
            'FLAGBMDQPTQDSEQGMQPCKUXATKSMOVB=',
            ....
        ],
        'errors': errors,                 # COME ARRAY
        'output': result,                 # COME ARRAY
        'important_messages': messages,   # COME ARRAY
        'exploit': exploit
    }

    """



    FLAGS_LEAKED = []

    errors = []
    messages = []

    BASE_DIR = BASE_PATH + exploit['base_dir']
    # os.chdir( exploit['base_dir'] )

    cmd = exploit['cmd']
    # print "BASE_DIR"
    # print "{}".format(BASE_DIR)
    # print "BASE_DIR"

    COMMAND = '{} "{}" "{}"'.format( cmd, ip, porta )
    print "[--ID:{}] Launching command:    {}".format( THREAD_ID, COMMAND )

    try:
        pr = subprocess.Popen( COMMAND, shell=True, cwd=BASE_DIR, stdout=subprocess.PIPE ) #.read()
        PROCESS_OUTPUT = pr.stdout.read()
    except Exception as e:
        return {
            'flag': FLAGS_LEAKED,   # = []
            'errors': [ "ERROR PROCESS." ],
            'output': '',
            'important_messages': ''
            #, 'exploit': ''
        }



    # FLAG FOUND
    results = re.findall(r'[A-Z0-9]{31}=', PROCESS_OUTPUT)
    if len(results) > 0:
        # Remove duplicate flags
        results__ = set(results)
        results = list(results__)
        FLAGS_LEAKED = results

    else:
        # Flag not found
        errors.append( 'Flag not found in response.' )
        FLAGS_LEAKED = [ ]

    # # FLAG FOUND
    # if "ccit{" in result:
    #     results = re.findall(r'ccit{.*}', result)
    #     if len(results) > 0:
    #         flag = results[0]
    #     else:
    #         errors.append( 'ccit{ is in result but regex can\'t find ( ccit{.*} )' )
    #         flag = ''
    #
    # else:
    #     errors.append( 'Flag not found in response.' )
    #     # Flag not found



    data = {
        'flag': FLAGS_LEAKED,
        'errors': errors,
        'output': PROCESS_OUTPUT,
        'important_messages': messages
        #, 'exploit': exploit
    }

    return data

def LaunchExploits( exploits, team, THREAD_ID ):

    IP = team['ip']
    PORTA = exploits['porta_challenge']
    # t = threading.currentThread()

    # print exploits
    DATA_RETURN = []        # Dati da ritornare
    FLAGS_LEAKED = []       # Lista dei flag trovati

    rets = []

    for exploit in exploits['exploits']:
        print '[--ID:{}] Provo exploit v.{} di {}'.format( THREAD_ID, exploit['versione_exploit'], exploit['proprietario'] )
        # print exploit

        ret = LaunchSingleExploit( IP, PORTA, exploit, THREAD_ID )
        # if getattr(t, "do_run", False):
        #     return rets

        if len(ret['important_messages']) > 0:
            print '+'*100
            for msg in ret['important_messages']:
                print '+ {}'.format( msg )
            print '+'*100

        FLAGS_LEAKED = ret['flag']

        # print ret
        if len( FLAGS_LEAKED ) > 0:

            # DATA_RETURN = [ ]
            for FLAG_LEAKED in FLAGS_LEAKED:
                data = {
                    'flag': FLAG_LEAKED,
                    'errors': ret['errors'],
                    'output': ret['output'],
                    'important_messages': ret['important_messages'],
                    'exploit': exploit
                }

                DATA_RETURN.append( data )

                print '[ OK ID:{} ] Successo! Nuovo flag: "{}"'.format( THREAD_ID, FLAG_LEAKED )


            # print F_DATA
            if len( FLAGS_LEAKED ) == 1:
                print "Trovato 1 flag da THREAD {}".format( THREAD_ID )
            else:
                print "Trovati {} flags da THREAD {}".format( len( FLAGS_LEAKED ), THREAD_ID )

            # FLAG TROVATO/I
            # CONTINUA CON IL PROSSIMO EXPLOIT


        # NESSUN FLAG TROVATO CON L'EXPLOIT CORRENTE.
        # RITENTO CON IL PROSSIMO EXPLOIT



    return DATA_RETURN

def StoreFlag( FLAG, team, datetime__, exploit ):
    # print "FLAG: {}".format( FLAG )
    # print "exploit: {}".format( exploit )
    # print "team: {}".format( team['id'] )

    id_team = team['id']
    id_exploit = exploit['id']
    created_at = datetime__
    flag_is_not_found = True

    # print "{} : {} : {} : {}".format( id_team, id_exploit, FLAG, created_at )

    # print ''.join( FLAG )

    res = DB.execute(
        'SELECT id FROM flags WHERE flag = ? ', ( FLAG, )
    ).fetchone()

    if res is not None:
        print '[~OK~] FLAG {} gia\' inserito.'.format( FLAG )
    else:
        DB.execute(
            'INSERT INTO flags ( id_team_rivale, id_exploit, flag, created_at ) VALUES ( ?, ?, ?, ? )',
            ( id_team, id_exploit, FLAG, created_at )
        )
        DB.commit()
        print '[ OK ] FLAG {} appena inserito.'.format( FLAG )


TEAMS = []
EXPLOITS = []
GLOBAL_FLAGS = []


def ThreadLaunchExploitsWrapper( challenge, team, THREAD_ID ):

    t = threading.currentThread()

    # getattr(t, "ID", None)
    #
    # ID
    # TEAM
    # CHALLENGE

    print "[ID:{}] Lancio exploits per challenge \"{}\" verso il team \"{}\" ({}:{}).".format( THREAD_ID, challenge['nome_challenge'], team['name'].encode('utf-8'), team['ip'], challenge['porta_challenge'] )
    DATA_OUTPUT = LaunchExploits( challenge, team, THREAD_ID )

    # Formato di DATA_OUTPUT
    #
    # [
    #     {
    #         'flag': FLAG_LEAKED,
    #         'errors': ret['errors'],
    #         'output': ret['output'],
    #         'important_messages': ret['important_messages'],
    #         'exploit': exploit
    #     }, ...
    # ]

    for FLAG_DATA in DATA_OUTPUT:
        FLAG_LEAKED = FLAG_DATA['flag']
        EXPLOIT = FLAG_DATA['exploit']
        if len( FLAG_LEAKED ) > 0:
            GLOBAL_FLAGS.append( { 'flag':FLAG_LEAKED, 'team':team, 'created_at': datetime.datetime.now(), 'exploit': EXPLOIT  } )

    if len( DATA_OUTPUT ) == 0:
        print "[---] Errore... Nessun flag trovato per {} dal THREAD {}".format( challenge['nome_challenge'], THREAD_ID )
        # if VERBOSE:
        #     err = []
        #     for ret in rets:
        #         err.append( ret['output'] )
        #     print "ERROR: # " + '\nERROR: # '.join(err)
        return []

    # if len( DATA_OUTPUT ) > 0:
    #     flag = rets[0]['flag']
    #     exploit__ = rets[0]['exploit']
    #     if len(flag) > 0:
    #         # StoreFlag( flag, team, datetime.datetime.now(), exploit__ )
    #
    #         # if getattr(t, "do_run", False):
    #         #     return rets
    #
    #     else:
    #         print "[---] Errore... Nessun flag trovato per {} dal THREAD {}".format( challenge['nome_challenge'], THREAD_ID )
    #         if VERBOSE:
    #             err = []
    #             for ret in rets:
    #                 err.append( ret['output'] )
    #             print "ERROR: # " + '\nERROR: # '.join(err)


    # if getattr(t, "do_run", False):
    #     return rets

    return DATA_OUTPUT  # InsHack@ti


import time

def main():
    global GLOBAL_FLAGS
    # exit()

    # Il TICK e' 120 secondi, ma lancia gli exploit ogni 30 secondi per sicurezza di latenza
    # 120 SECONDI
    REAL_TICK = 120
    WARNING_TICK = 40
    LOOP_TICK = 30
    init_time = time.time()

    i = 0
    while True:
        # Clear screen
        os.system('clear')
        print "Exploit launcher - Loop n. {}".format(i)

        TEAMS = ReadTeams()
        CHALLENGES_EXPLOITS = ReadChallengesAndActiveExploits()

        CoolPrintTeams(TEAMS)
        CoolPrintChallenges(CHALLENGES_EXPLOITS)
        # print TEAMS
        # print EXPLOITS
        thread_list = []

        i = 0
        # with open('flags.txt', 'w') as f:
        #     f.write('\n')

        ActiveTeams = GetActiveTeams( TEAMS )

        print TEAMS
        print ActiveTeams

        # PER OGNI TEAM ESEGUI UN THREAD?
        for team in ActiveTeams:
            for challenge in CHALLENGES_EXPLOITS:

                if len( challenge['exploits'] ) > 0:

                    THREAD_ID = i

                    current_thread = threading.Thread(target=ThreadLaunchExploitsWrapper, args=(challenge, team, THREAD_ID))
                    # current_thread.start()
                    thread_list.append( {
                    'id': THREAD_ID,
                    'thread': current_thread,
                    'team': team,
                    'challenge': challenge['nome_challenge']
                    } )
                    i += 1

                    # ThreadLaunchExploitsWrapper( challenge, team )


                else:
                    print "[ x_x ] Nessun exploit disponibile per {}".format( challenge['nome_challenge'] )

        # print thread_list
        print "N_THREADS: {}...".format( len(thread_list) )

        for t in thread_list:
            t['thread'].start()
            print "THREAD STARTED... {}".format( t['id'] )

        # print "SLEEPING..."
        # time.sleep(10)
        # print "END SLEEPING..."


        for t in thread_list:
            t['thread'].join()
            print "THREAD {} QUITTED...".format( t['id'] )



        # print "JOINING_THREADS..."
        # i = 0
        # for t in thread_list:
        #     t['thread'].do_run = False
        #
        #     # print "WAITING THREAD... {}".format( t['id'] )
        #     #
        #     # if not t['thread'].isAlive():
        #     #     print "THREADS EXITED... {}".format( t['id'] )
        #     #     continue
        #     #     t['thread'].do_run = False
        #     #
        #     #
        #     # t['thread'].join()
        #     print "THREADS EXITED... {}".format( t['id'] )
        #
        # print "THREADS JOINED..."

        # print GLOBAL_FLAGS
        for flag_data in GLOBAL_FLAGS:
            flag = flag_data['flag']
            team = flag_data['team']
            created_at = flag_data['created_at']
            exploit__ = flag_data['exploit']
            StoreFlag( flag, team, datetime.datetime.now(), exploit__ )

        GLOBAL_FLAGS = []

        end_time = time.time()
        if (end_time - init_time > WARNING_TICK):
            print "!!!!!!!! WARNING !!!!!!!! WARNING !!!!!!!! WARNING !!!!!!!! WARNING !!!!!!!!"
            print "EXPLOIT TROPPO LENTI ({} s). SUPERANO I {} SECONDI".format(end_time - init_time, WARNING_TICK)
            print "!!!!!!!! WARNING !!!!!!!! WARNING !!!!!!!! WARNING !!!!!!!! WARNING !!!!!!!!"

        while (end_time - init_time < LOOP_TICK):
            # end_time = time.time()
            # print "Fanculo lo sleep... Runna tutto."
            # break
            end_time = time.time()
            print "Waiting until {} s... Delta: {}... ".format( LOOP_TICK, str(end_time - init_time)[:10],  )
            time.sleep(1)
        i += 1
        init_time = time.time()# init_time + LOOP_TICK


if __name__ == '__main__':
    # test()
    main()

# Carica modulo per database Ritorna l'oggetto     {         'flag': [             'FLAGUWNYXIYSHCDDSURMWMWEWUJQJIY=',             'FLAGDLHGMGZCHXBAHQNWCBABEHNJUDU=',             'FLAGBMDQPTQDSEQGMQPCKUXATKSMOVB=',             ....         ],         'errors': errors,                 # COME ARRAY         'output': result,                 # COME ARRAY         'important_messages': messages,   # COME ARRAY         'exploit': exploit     } # os.chdir( exploit['base_dir'] ) # print "BASE_DIR" # print "{}".format(BASE_DIR) # print "BASE_DIR" #.read() # = [] #, 'exploit': '' # FLAG FOUND # Remove duplicate flags # Flag not found # # FLAG FOUND # if "ccit{" in result: #     results = re.findall(r'ccit{.*}', result) #     if len(results) > 0: #         flag = results[0] #     else: #         errors.append( 'ccit{ is in result but regex can\'t find ( ccit{.*} )' ) #         flag = '' # # else: #     errors.append( 'Flag not found in response.' ) #     # Flag not found #, 'exploit': exploit # t = threading.currentThread() # print exploits # Dati da ritornare # Lista dei flag trovati # print exploit # if getattr(t, "do_run", False): #     return rets # print ret # DATA_RETURN = [ ] # print F_DATA # FLAG TROVATO/I # CONTINUA CON IL PROSSIMO EXPLOIT # NESSUN FLAG TROVATO CON L'EXPLOIT CORRENTE. # RITENTO CON IL PROSSIMO EXPLOIT # print "FLAG: {}".format( FLAG ) # print "exploit: {}".format( exploit ) # print "team: {}".format( team['id'] ) # print "{} : {} : {} : {}".format( id_team, id_exploit, FLAG, created_at ) # print ''.join( FLAG ) # getattr(t, "ID", None) # # ID # TEAM # CHALLENGE # Formato di DATA_OUTPUT # # [ #     { #         'flag': FLAG_LEAKED, #         'errors': ret['errors'], #         'output': ret['output'], #         'important_messages': ret['important_messages'], #         'exploit': exploit #     }, ... # ] # if VERBOSE: #     err = [] #     for ret in rets: #         err.append( ret['output'] ) #     print "ERROR: # " + '\nERROR: # '.join(err) # if len( DATA_OUTPUT ) > 0: #     flag = rets[0]['flag'] #     exploit__ = rets[0]['exploit'] #     if len(flag) > 0: #         # StoreFlag( flag, team, datetime.datetime.now(), exploit__ ) # #         # if getattr(t, "do_run", False): #         #     return rets # #     else: #         print "[---] Errore... Nessun flag trovato per {} dal THREAD {}".format( challenge['nome_challenge'], THREAD_ID ) #         if VERBOSE: #             err = [] #             for ret in rets: #                 err.append( ret['output'] ) #             print "ERROR: # " + '\nERROR: # '.join(err) # if getattr(t, "do_run", False): #     return rets # InsHack@ti # exit() # Il TICK e' 120 secondi, ma lancia gli exploit ogni 30 secondi per sicurezza di latenza # 120 SECONDI # Clear screen # print TEAMS # print EXPLOITS # with open('flags.txt', 'w') as f: #     f.write('\n') # PER OGNI TEAM ESEGUI UN THREAD? # current_thread.start() # ThreadLaunchExploitsWrapper( challenge, team ) # print thread_list # print "SLEEPING..." # time.sleep(10) # print "END SLEEPING..." # print "JOINING_THREADS..." # i = 0 # for t in thread_list: #     t['thread'].do_run = False # #     # print "WAITING THREAD... {}".format( t['id'] ) #     # #     # if not t['thread'].isAlive(): #     #     print "THREADS EXITED... {}".format( t['id'] ) #     #     continue #     #     t['thread'].do_run = False #     # #     # #     # t['thread'].join() #     print "THREADS EXITED... {}".format( t['id'] ) # # print "THREADS JOINED..." # print GLOBAL_FLAGS # end_time = time.time() # print "Fanculo lo sleep... Runna tutto." # break # init_time + LOOP_TICK # test()