Exemplo n.º 1
0
def main(argv):
	parser = argparse.ArgumentParser(description='CryptoKnight - Generation & Extraction')
	parser.add_argument('-d', '--dist', type=int, nargs='?', const=10, default=None, metavar='N', help='define distribution scale (default: 10)')
	parser.add_argument('--tune', dest='tune', type=int, nargs='?', const=10, default=None, metavar='N', help='tuning epochs (default: 10)', required=False)
	parser.add_argument('--setup', action='store_true', help='install dependencies')
	args = parser.parse_args()

	signal.signal(signal.SIGINT, signal_handler)
	title()

	if (not args.setup and not alive()):
		print("[!] Environment not setup.")
		parser.print_help()
		sys.exit(0)
	elif (args.setup): 
		if (not setup()): 
			print("[!] Setup could not complete.")
			sys.exit(0)
	print("[+] Environment ready.")

	# allocate distribution from args
	sets = []
	sets.append(["training", 0])
	sets.append(["testing", 0])

	# check for existing data
	create = False
	for dist in sets:
		prev = os.path.join(DIST, dist[0])
		try: open(prev)
		except IOError: open(prev, 'w+').close
		dist[1] = sum(1 for line in open(os.path.join(DIST, dist[0])))

	dsize = sets[0][1] + sets[1][1]
	if (args.dist):
		sets[0][1] = int(math.ceil((float(args.dist)/100)*75))
		sets[1][1] = int(math.ceil((float(args.dist)/100)*25))
		if (dsize>0):
			choice = raw_input("[!] Data found, recreate? (y/N)\n")
			if ("y" in choice or dsize==0):
				create = True
				sys.stdout.write("\033[F")
			else:
				sys.stdout.write("\033[F")
				print("[+] Skipping.")
		else: create = True
	elif (dsize==0):
		print("[!] No data found, specify new distribution scale (i.e. -d 50).\n")
		parser.print_help()
		sys.exit(0)

	os.system('stty -echo; setterm -cursor off;')	# disable user input

	# no data / overwrite == draw
	if (create):
		print("[!] Caution: This process can incur significant overhead.\n")

		for dist in sets:
			# create directories for code and executables
			if (os.path.isdir(os.path.join(HEAD, dist[0])) == True):
				shutil.rmtree(os.path.join(HEAD, dist[0]))
				os.mkdir(os.path.join(HEAD, dist[0]))
			# clear any previous distributions	
			open(os.path.join(DIST, dist[0]), 'w').close()

		# read preset labels
		with open(LABELS, 'rb') as labels:
			reader = csv.reader(labels)
			classes = list(reader)
			for dist in sets:
				samples = []
				instances = []
				for l, c in enumerate(classes):
					gen = Generate(int(dist[1]), c, dist[0])
					makefiles, obfuscations = gen.create()
					samples.append([l, makefiles])
					instances.append([c, obfuscations])

				# list samples and selected obfuscations
				print("[+] Generated: " + str(len(samples)*int(dist[1])))
				for i in instances:
					print("\t[-] " + '%10s' % ', '.join(i[0]) + " -- " + ', '.join("%s=%r" % (key,val) for (key,val) in i[1].iteritems()))
				print("")
				try:
					run_analysis(samples, os.path.join(DIST, dist[0]))
				except ZeroDivisionError:
					print("[!] Incorrect distribution scale.")

	# pass distribution to model
	train_model(sets, args.tune)

	# cleanup
	os.system('stty echo; setterm -cursor on;')
	if os.path.isdir("tmp"): shutil.rmtree("tmp")
Exemplo n.º 2
0
def get_calendar_service():
    # needed for calendar authorization
    return setup()
Exemplo n.º 3
0
def main():
    menu = (
        "Select a menu option. "
        "\n 0. Quit \n 1. Create calendar entries. \n 2. View calendar entries. \n 3. View upcoming due dates."
        "\n ")

    while True:
        setup.setup()
        selection = input(menu)

        if selection == "0":
            print("Goodbye!")
            quit()

        if selection == "1":
            all_classes = list()
            class_name = (input("Enter the class name or press (Q) to quit. \n"
                                ).upper().replace(" ", ""))

            while class_name.upper() != "Q":
                all_classes.append(
                    School.CollegeClass.new_school_class(class_name))
                class_name = (
                    input("Enter the class name or press (Q) to quit.\n"
                          ).upper().replace(" ", ""))

            try:
                if all_classes[0].all_exams:
                    calendar_id = Calendar.new_calendar()
                    for school_class in all_classes:
                        # creates a new event for each exam date
                        Calendar.set_events(school_class, calendar_id)

                elif not all_classes[0].all_exams:
                    print("No exams to enter. \n")

            except IndexError:
                print("No classes were entered.\n")

        elif selection == "2":
            try:
                events = int(input("How many events to list?"))
                Calendar.view_events(events, Calendar.return_calendar_id())
            except ValueError:
                print("Invalid input.")

        elif selection == "3":
            #try:
            search_class = (input(
                "Enter a class to find a certain class's events, or don't").
                            upper().replace(" ", ""))
            dates = int(input("How many days to view due dates."))
            Calendar.weekly_events(Calendar.return_calendar_id(), dates,
                                   search_class)

        # dates input must be an integer
        #except ValueError:
        #  print("Invalid input.")

        else:
            print("Invalid input. Try again.")
Exemplo n.º 4
0
import os

from src.download import get_mincraft_versions, download_new_version
from src.update import get_current_version, backup_settings, backup_world, swapin_new_server, restore_user_settings
from src.setup import setup
from src.run import launch_game, game_loop
if True:
    dirs = setup()
    versions = get_mincraft_versions(dirs)
    recent_version = list(versions)[0]
    last_version = list(versions)[1]
    current_version = get_current_version(dirs)
    print(f"Current Minecraft Version: {current_version}")
    print(f"Most Recent Version: {recent_version}")
    need_update = False
    if current_version not in str(recent_version):
        print(f'Minecraft needs update to {recent_version}')
        need_update = True
        if 'None' in current_version:
            need_update = False
    if need_update:
        ver = versions[recent_version]
        print('Starting Backup and Update.')
        backup_settings(dirs)
        print('Backed up User Settings')
        world_name = backup_world(dirs)
        print(f'Backed up World: {world_name}')
        print(f'Downloading New Version: {recent_version}')
        rollback_server_filepath = download_new_version(versions[last_version])
        ver['file_path'] = download_new_version(ver)
        swapin_new_server(ver)
Exemplo n.º 5
0
def main(argv):
    parser = argparse.ArgumentParser(description='CryptoKnight - Assessment')
    parser.add_argument('-p', '--predict', type=str, metavar='args', \
     help='specify arguments as string literal')
    parser.add_argument('-e', '--evaluate', type=str, metavar='distribution', \
     help='specify set to evaluate')
    parser.add_argument('--setup',
                        action='store_true',
                        help='install dependencies')
    args = parser.parse_args()

    signal.signal(signal.SIGINT, signal_handler)
    title()

    if (not args.setup and not alive()):
        print("[!] Environment not setup.")
        parser.print_help()
        sys.exit(0)
    elif (args.setup):
        if (not setup()):
            print("[!] Setup could not complete.")
            sys.exit(0)
    print("[+] Environment ready.")
    if (not args.predict and not args.evaluate):
        parser.print_help()
        sys.exit(0)

    arguments = args.evaluate if args.evaluate else args.predict.split(" ")[0]

    if not os.path.isfile(arguments):
        print("[!] " + str(arguments) + " is not a file.")
        sys.exit(0)

    # prevent user input during analysis
    os.system('stty -echo; setterm -cursor off;')

    # evaluate model on specified set
    if args.evaluate:
        print("[!] Evaluating: " + str(args.evaluate) + "\n")
        print("[+] x = predicted, y = actual")
        os.system("python ./src/Model/dcnn.py --evaluate " + args.evaluate)
        os.system('stty echo; setterm -cursor on;')
        sys.exit(0)

    arguments = args.predict.split(" ")  # collect exe specific args
    open(SAMPLE, 'w').close()  # clean previous sample

    begin = False

    def animate():
        for c in itertools.cycle(['|', '/', '-', '\\']):
            if begin: break
            sys.stdout.write('\r[*] Tracing ' + c)
            sys.stdout.flush()
            time.sleep(0.2)

    # start timing
    start = datetime.datetime.now()
    print("[+] Start Time: " + str(start) + "\n")

    try:
        # trace animation
        t = threading.Thread(target=animate)
        t.daemon = True
        t.start()
    except (KeyboardInterrupt, SystemExit):
        begin = True
        print("\n[!] Exiting.")
        sys.exit(0)

    # run pintool in killable subprocess
    cmd = [PIN + "/pin", "-t", PIN + \
     "/source/tools/CryptoKnight/obj-intel64/CryptoTrace.so", \
     "-v", "3", "-o", SAMPLE, "--"]
    cmd.extend(arguments)
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE)

    try:
        while True:
            # read from stdout
            line = p.stdout.readline()
            if line:
                if not begin:
                    print("\r[+] Execution finished.\n")
                    print("[=====]\n")
                begin = True
            else:
                break
            print(line),
    except KeyboardInterrupt:
        try:
            # user defined closure, terminate subprocess
            p.terminate()
        except OSError:
            pass
    p.wait()

    # collect timing information
    end = datetime.datetime.now()
    print("\n[+] End Time: " + str(end))
    mins, secs = divmod(((end - start).total_seconds()), 60)
    hours, mins = divmod(mins, 60)
    total = '%02d:%02d:%02d' % (hours, mins, secs)
    print("[+] Analysis Time: " + total)

    # evaluate model with custom sample
    os.system("python ./src/Model/dcnn.py --predict " + SAMPLE)

    # cleanup
    os.system('stty echo; setterm -cursor on;')
    if os.path.isdir("tmp"): shutil.rmtree("tmp")
Exemplo n.º 6
0
import colorama

from src.game import Game
from src.setup import setup

if __name__ == '__main__':
    colorama.init()
    config = setup()

    # get parameters config...
    hardcode_mode = config.get('hardcode_mode')
    dimensions = config.get('dimensions')

    game = Game(dimensions.get('columns'),
                dimensions.get('rows'),
                speed=0.10,
                hardocode_mode=False)
    game.run()
Exemplo n.º 7
0
from flask import Flask
from src.setup import setup

application = app = Flask(__name__)
setup(app)

if (__name__ == "__main__"):
    from flask_debugtoolbar import DebugToolbarExtension
    toolbar = DebugToolbarExtension()
    toolbar.init_app(app)
    app.run(debug=True)