Exemple #1
0
def handleUseCmd(cmd, modulename):
    if cmd[:3] == "set" and len(cmd) > 3:
        cmdUseSet(cmd)
        cmdUseShell(modulename)
    elif (cmd[:4] == "exit" or cmd[:4] == "quit") and len(cmd) == 4:
        global moduleAttributes
        moduleAttributes = []
    elif cmd[:4] == "info" and len(cmd) == 4:
        cmdinfo(modulename)
        cmdUseShell(modulename)
    elif cmd[:10] == "attributes" and len(cmd) == 10:
        cmdUseAttributes()
        cmdUseShell(modulename)
    elif (cmd[:3] == "gen" and len(cmd) == 3) or (cmd[:8] == "generate"
                                                  and len(cmd) == 8):
        print(
            "This will delete and recreate the needed folders/files and replace inject.bin"
        )
        sure = input("Are you sure? (y/n): ")
        if sure.lower() == 'y':
            cmdUseGenerate(modulename)
        else:
            cmdUseShell(modulename)
    elif cmd[:4] == "help" and len(cmd) == 4:
        cmdHelp(True)
        cmdUseShell(modulename)
    elif cmd[:3] == "cls" and len(cmd) == 3:
        output.cls()
        cmdUseShell(modulename)
    elif cmd[:5] == "clear" and len(cmd) == 5:
        output.cls()
        cmdUseShell(modulename)
    else:
        output.error('Unknown Command => ' + cmd)
        cmdUseShell(modulename)
Exemple #2
0
def p_program_tokenstring(p):
    ''' program : defs NEWLINE
    '''
    try:
        tmp = [str(x()) if isinstance(x, MacroCall) else x for x in p[1]]
    except PreprocError as v:
        error(v.lineno, v.message)
        
    p[0] = tmp + [p[2]]
Exemple #3
0
def p_program_newline(p):
    ''' program : program defs NEWLINE
    '''
    try:
        tmp = [str(x()) if isinstance(x, MacroCall) else x for x in p[2]]
    except PreprocError as v:
        error(v.lineno, v.message)

    p[0] = p[1] # + tmp # + [p[3]]
    p[0].extend(tmp)
    p[0].append(p[3])
Exemple #4
0
def checkdupes(index, field):
    if field not in fields.PERSONFIELDS and \
       field not in fields.TEAMFIELDS:
        raise ValueError(f"checking unrecognized field '{field}'")

    dupes = set()
    for key, value in index[field].items():
        if len(value) > 1:
            dupes.add(key)
    if dupes:
        error(index['_NAME'],
              f"duplicate {field}(s) found: {', '.join(sorted(dupes))}")
Exemple #5
0
def authorize():
    """
    Create the config for the user. This will ask the user to visit a webpage and paste the api key encountered.
    :return: Nothing
    """

    if output.mode() == output.JSON:
        output.error("Not logged in.")
        sys.exit(1)

    api_key = input(
        "Please go to {} to obtain an api_key, and paste here: ".format(
            URI_WEB_API_KEY))
    Config(api_key)
    print("Successfully set up user account")
Exemple #6
0
def search_filename(fname, lineno):
    ''' Search a filename into the list of the include path
    '''
    for i in INCLUDEPATH:
        if not os.path.isabs(i):
            for j in os.environ['PATH'].split(os.pathsep) + [CURRENT_DIR]:
                path = os.path.join(j, i, fname)
                if os.path.exists(path):
                    return path
        else:
            path = os.path.join(i, fname)
            if os.path.exists(path):
                return path

    error(lineno, "file '%s' not found" % fname)
Exemple #7
0
def p_define_params_paramlist(p):
    ''' params : LP paramlist RP
    '''
    for i in p[2]:
        if not isinstance(i, ID):
            error(p.lineno(3), '"%s" might not appear in a macro parameter list', str(i))
            p[0] = None
            return

    names = [x.name for x in p[2]]
    for i in range(len(names)):
        if names[i] in names[i + 1:]:
            error(p.lineno(3), 'Duplicated name parameter "%s"' % (names[i]))
            p[0] = None
            return

    p[0] = p[2]
Exemple #8
0
def main():
    """
    Main function gets the args input and determines which method to call to handle. Handles exceptions from
    malformed input.
    :return: Nothing
    """
    try:
        args = _parse_arguments()

        if args.json:
            output.set_mode('json')

        if args.mode == AUTH_MODE:
            if args.key:
                Config(args.key)
                output.output("Saved API key.")
                return

            if not (args.metadata and Config.auth_exists()):
                authorize()
            if args.metadata:
                output.output(Config())
        elif args.mode == BOT_MODE:
            if args.bot_mode == BOT_UPLOAD_MODE:
                upload_bot.upload(args.bot_path, args.dry_run,
                                  args.include_extensions)
            else:
                upload_bot.download(args.bot_path)
        elif args.mode == REPLAY_MODE:
            if not args.replay_mode:
                raise ValueError("Provide a download mode (date or user)")
            download_game.download(
                args.replay_mode, args.destination,
                getattr(args, 'date', None), getattr(args, 'all', None),
                Config().user_id if Config.auth_exists() else None,
                getattr(args, 'user_id', None), getattr(args, 'limit', None))
        elif args.mode == PLAY_MODE:
            compare_bots.play_games(args.halite_binary, args.game_output_dir,
                                    args.map_width, args.map_height,
                                    args.run_commands, args.iterations, [])
        elif args.mode == GYM_MODE:
            gym.main(args)
    except (IndexError, TypeError, ValueError, IOError) as err:
        output.error(str(err))
        sys.exit(-1)
Exemple #9
0
def cmdUseSet(cmd):
    params = cmd.split(" ")
    if len(params) < 3:
        output.error('Command Syntax => set <attribute> <value>')
    else:
        global moduleAttributes
        if params[1] in moduleAttributes:
            joined = params[2]
            if len(params) > 3:
                #add other after a space eg set text Hello World
                # so we add the World at the end
                for p in range(3, len(params)):
                    joined += " " + params[p]

            moduleAttributes[params[1]] = joined
            output.success(params[1] + '=>' + joined)
        else:
            output.error("Attribute '" + params[1] + "' is unknown")
Exemple #10
0
def initialise():
    command = get_command(sys.argv)

    if command.args:
        source_path = command.args[0]

        try:
            with open(source_path) as sourcef:
                lines = list(line.strip("\n") for line in sourcef)
                return SourceFile(source_path, lines, command.flags)

        except FileNotFoundError:
            output.error("Init",
                         "Could not find source file \"" + source_path + "\"")
            raise output.Abort()
    else:
        output.error("Init", "Please specify a source file.")
        raise output.Abort()
Exemple #11
0
def cmdinfo(cmd):
    modulename = cmd
    module_content = ''
    if os.path.isfile('modules/' + modulename + '/module.json'):
        with open('modules/' + modulename + '/module.json', 'r') as module:
            module_content = module.read().replace('\n', '')
        loadedModule = json.loads(module_content)
        print('\n=> Module Info\n--------------------------------------')
        name = ['Name', loadedModule['title']]
        desc = ['Description', loadedModule['description']]
        firmware = ['Firmware', loadedModule['requirements']['firmware']]
        uacbypass = [
            'Bypass UAC', loadedModule['requirements']['has_uac_bypass']
        ]
        print(
            tabulate([name, desc, firmware, uacbypass],
                     headers=['Attribute', 'Value']))
    else:
        output.error("Module '" + modulename + "' does not exist")
Exemple #12
0
def allpresentin(index, field, targetindex, targetfield):
    if field not in fields.PERSONFIELDS and \
       field not in fields.TEAMFIELDS:
        raise ValueError(f"checking unrecognized field '{field}'")
    if targetfield not in fields.PERSONFIELDS and \
       targetfield not in fields.TEAMFIELDS:
        raise ValueError(f"checking unrecognized targetfield '{targetfield}'")

    tracker = {}
    for key in index[field]:
        tracker[key] = 1
    for key in targetindex[targetfield]:
        tracker[key] = tracker.get(key, 0) - 1
    notfound = list(filter(lambda key: tracker[key] > 0, tracker))
    if notfound:
        error(
            None, "{0}[{1}(s)] not found in {2}[{3}]: {4}".format(
                index['_NAME'], field, targetindex['_NAME'], targetfield,
                ', '.join(sorted(notfound))))
Exemple #13
0
def run_matches(db_path, hlt_path, output_dir, map_dimensions, iterations):
    flags = []

    if output_dir:
        abs_output_dir = os.path.abspath(output_dir)
        os.makedirs(abs_output_dir, exist_ok=True)
        flags = ['-i', abs_output_dir]

    for i in range(iterations):
        map_size = random.choice(map_dimensions)
        with connect(db_path) as conn:
            all_bots = list_bots(conn)
            num_players = random.choice((2, 4))
            if len(all_bots) < MIN_PLAYERS:
                output.error('Need at least {} bots registered to play.'.format(MIN_PLAYERS))
                sys.exit(1)
            elif len(all_bots) < num_players:
                num_players = MIN_PLAYERS

            random.shuffle(all_bots)
            bots = all_bots[:num_players]

        overrides = []
        for bot in bots:
            overrides.append('-o')
            overrides.append(bot['name'])
        raw_results = compare_bots._play_game(hlt_path,
                                              map_size[0], map_size[1],
                                              [bot['path'] for bot in bots],
                                              flags + overrides)
        results = json.loads(raw_results)
        with connect(db_path) as conn:
            add_match(conn, bots, results)

        output.output('Played {}/{} matches...'.format(i + 1, iterations),
                      progress=i + 1,
                      iterations=iterations,
                      results=results,
                      participants=bots)
    output.output('Done playing games.', progress=iterations, iterations=iterations)
Exemple #14
0
def cmdUse(cmd):
    global loadedModule
    global moduleAttributes
    modulename = cmd
    module_content = ''
    if os.path.isfile('modules/' + modulename + '/module.json'):
        with open('modules/' + modulename + '/module.json', 'r') as module:
            module_content = module.read().replace('\n', '')
        loadedModule = json.loads(module_content)
        moduleAttributes = loadedModule['attributes']
        #add default attributes: lang,drive
        moduleAttributes['language'] = 'us'
        if os.name == 'nt':
            moduleAttributes['sdcard_mount'] = 'H:\\'
        else:
            moduleAttributes['sdcard_mount'] = '/mnt/ducky/'
        #check for uac bypass and add attribute
        if loadedModule['requirements']['has_uac_bypass'].lower() == "true":
            moduleAttributes['uac_bypass_key'] = 'y'

        cmdUseShell(modulename)
    else:
        output.error("Module '" + modulename + "' does not exist")
Exemple #15
0
def handleCommand(cmd):
    global loadedModule
    #output.info cmd
    if cmd[:4] == "info":
        cmdinfo(cmd)
    #list modules
    elif cmd[:7] == "modules" and len(cmd) == 7:
        cmdList()
    elif (cmd[:4] == "exit" or cmd[:4] == "quit") and len(cmd) == 4:
        output.success('KTHXBYE')
        sys.exit()
    elif cmd[:4] == "help" and len(cmd) == 4:
        cmdHelp(False)
    elif cmd[:3] == "cls" and len(cmd) == 3:
        output.cls()
    elif cmd[:5] == "clear" and len(cmd) == 5:
        output.cls()
    else:
        if cmd in modules:
            cmdUse(cmd)
        else:
            output.error('Unknown Command => ' + cmd)

    startShell()
Exemple #16
0
def main_quick():
    "Fast payload generation using command line arguments"
    init(autoreset=True)
    javaCheck()
    output.cls()
    output.banner()
    loadModules()
    #
    #   format: ./PyDuck.py <module> <duck_drive> [list of attributes in format]
    #   format of attributes: attribute=value
    #
    global loadedModule
    global moduleAttributes
    modulename = sys.argv[1]
    if modulename in modules:
        if os.path.isfile('modules/' + modulename + '/module.json'):
            with open('modules/' + modulename + '/module.json', 'r') as module:
                module_content = module.read().replace('\n', '')
            loadedModule = json.loads(module_content)

            moduleAttributes = loadedModule['attributes']
            # add default attributes: lang,drive
            moduleAttributes['language'] = 'us'
            moduleAttributes['sdcard_mount'] = sys.argv[2]
            attr_args = []
            if len(sys.argv) > 3:
                for i in range(3, len(sys.argv)):
                    attr_args.append(sys.argv[i])
            # check for uac bypass and add attribute
            if loadedModule['requirements']['has_uac_bypass'].lower(
            ) == "true":
                moduleAttributes['uac_bypass_key'] = 'y'

            for a in attr_args:
                sep = a.split('=')
                if sep[0] in moduleAttributes:
                    output.success("Setting " + sep[0] + " to " + sep[1])
                    moduleAttributes[sep[0]] = sep[1]
                else:
                    output.error("Attribute " + sep[0] + " not found..exiting")
                    sys.exit(1)

            cmdUseGenerate(modulename)

        else:
            output.error("Module '" + modulename + "' does not exist")
    else:
        output.error("Module '" + modulename + "' does not exist")
Exemple #17
0
 def _print_message(message, file=None, _out=out):
  if file == sys.stdout:
   _out += [output.normal(message)]
  else:
   _out += [output.error(message)]
Exemple #18
0
#!/usr/bin/env python

import json
from pathlib import Path
import output
from protonmail_api import Api, ApiRequestError, ApiResponseError

DIR = Path(__file__).resolve().parent
AUTH_PATH = Path(DIR, 'auth.json')

try:
    if not AUTH_PATH.is_file():
        output.error('auth.json not found')
        exit()

    with open(AUTH_PATH, 'r') as f:
        auth = json.load(f)

    api = Api(auth['UID'], auth['AccessToken'])
    session, unread = None, None
    SESSION_PATH = Path(DIR, 'session.json')
    if SESSION_PATH.is_file():
        with open(SESSION_PATH, 'r') as f:
            session = json.load(f)
            event_id = session['event_id']
            unread = session['unread']
    else:
        event_id = api.event_id()['EventID']

    resp = api.events(event_id)
    messages = resp.get('Messages', [])
Exemple #19
0
 def error(self, msg):
     ''' Prints an error msg, and exits.
     '''
     error(self.lex.lineno, msg)
     sys.exit(1)
Exemple #20
0
degree_path = results_folder + '/degree'
nodes_betweenness_path = results_folder + '/betweenness.nodes'
edges_betweenness_path = results_folder + '/betweenness.edges'
eigenvector_path = results_folder + '/eigenvector'
graph_path = graphs_folder + '/graph'

# Add results folder
data.make_folder(results_folder)
data.make_folder(graphs_folder)

# Import the data file
filename = 'tgraph_real_wikiedithyperlinks.txt'

# If no file was selected, exit
if filename == '':
    output.error('No data file selected, exiting...')
    exit()

if TEST:
    # Create a random graph
    output.important('Creating a random connected graph with 100 nodes')
    graph = random_graph()
else:
    # Read the graph
    output.important('Reading graph data from "' + filename + '"...')
    graph = datafile_to_graph(filename)

# Output graph info
output.success('\nSuccessfully read graph. Info:')
output.dim(str(graph.num_edges()) + "  edges")
output.dim(str(graph.num_vertices()) + "  vertices")
Exemple #21
0
def fail(*s, bad_key=False):
    if s:
        output.error(" ".join(map(str, s)))
    output.error("{} attack failed".format(name))
    sys.exit(1 if not bad_key else 2)
Exemple #22
0
def p_error(p):
    if p is not None:
        error(p.lineno, "syntax error. Unexpected token '%s' [%s]" % (p.value, p.type))
    else:
        OPTIONS.stderr.value.write("General syntax error at preprocessor (unexpected End of File?)")
        sys.exit(1)
Exemple #23
0
 def error(self, msg):
     ''' Prints an error msg, and exits.
     '''
     error(self.lex.lineno, msg)
     sys.exit(1)
Exemple #24
0
def main(args):
    if args.gym_mode == BOTS_MODE:

        def _prettyprint_bot(bot):
            return "\n".join([
                'Bot "{}" (ID {}, version {})'.format(bot['name'], bot['id'], bot['version']),
                'Rank {} (score={:.02f}, μ={:.02f}, σ={:.02f})'.format(bot['rank'], bot['mu'] - 3*bot['sigma'], bot['mu'], bot['sigma']),
                'Path: {}'.format(bot['path']),
                'Games Played: {}'.format(bot['games_played']),
            ])

        if args.bot_name:
            with connect(args.db_path) as conn:
                bots = list_bots(conn)
                for bot in bots:
                    if bot['name'] == args.bot_name:
                        output.output(_prettyprint_bot(bot),
                                      bot=bot,
                                      history=get_rank_history(conn, bot['id']))
                        break
                else:
                    output.error('Bot not found.')
                    sys.exit(1)
            return

        with connect(args.db_path) as conn:
            bots = list_bots(conn)
            output.print_list("Registered Bots:", bots, formatter=_prettyprint_bot)
    elif args.gym_mode == STATS_MODE:
        if args.query:
            with connect(args.db_path) as conn:
                results = list(conn.execute(args.query).fetchall())
                if not results:
                    output.output("No results.", results=results)
                    return

                # TODO: table output func
                keys = list(results[0].keys())
                for key in keys:
                    print('{:>20}'.format(key), end='|')
                print()
                for key in keys:
                    print('-' * 20, end='+')
                print()
                for index, row in enumerate(results):
                    for key in keys:
                        print('{:>20}'.format(row[key]), end='|')
                    print()
            return

        def _prettyprint_match(match):
            winner = [p for p in match['participants'] if p['id'] == match['winner']][0]
            return 'Match #{}: "{}" beat {}\nMap Size: {}x{}\nReplay: {}'.format(
                match['id'],
                winner['name'],
                ' '.join([ '"{}"'.format(bot['name'])
                           for bot in match['participants']
                           if bot['id'] != winner['id'] ]),
                match['results']['map_width'],
                match['results']['map_height'],
                match['results']['replay'],
            )

        with connect(args.db_path) as conn:
            matches = list_matches(conn)
            output.print_list("Games Played:", matches, formatter=_prettyprint_match)
    elif args.gym_mode == REGISTER_MODE:
        with connect(args.db_path) as conn:
            register_bot(conn, args.name, args.path)
    elif args.gym_mode == DEREGISTER_MODE:
        with connect(args.db_path) as conn:
            deregister_bot(conn, args.name)
    elif args.gym_mode == EVALUATE_MODE:
        hlt_path = args.halite_binary
        output_dir = args.game_output_dir
        map_dimensions = [(32, 32), (48, 48), (64, 64), (80, 80)]
        iterations = args.iterations

        run_matches(args.db_path, hlt_path, output_dir, map_dimensions, iterations)
Exemple #25
0
def javaCheck():
    ret = os.system("java -version")
    if ret > 0:
        output.error("Java not installed or Java not in PATH Variable")
        sys.exit(1)
Exemple #26
0
 def log_error(self, stage, row_number, col_number, message):
     output.error(stage, message)
     output.raw_info("\n".join(self.get_traceback(row_number, col_number)))
     raise output.Abort()