def edit_ipv6(self): ''' Add ipv6 addresses to a box (sorta edits the box object) ''' form = Form(box_uuid="Select a box", ipv6="Please provide a list of IPv6 addresses") if form.validate(self.request.arguments): errors = [] box = Box.by_uuid(self.get_argument('box_uuid')) if box is not None: ips_string = self.get_argument('ipv6').replace('\n', ',').lower() ips = filter(lambda char: char in "1234567890abcdef:,", ips_string).split(",") for ip in filter(lambda ip: 0 < len(ip), ips): try: box = Box.by_ip_address(ip) if box is None: addr = IpAddress(box_id=box.id, v6=ip) dbsession.add(addr) else: errors.append( "%s has already been assigned to %s." % ( ip, box.name, )) except ValueError: errors.append("'%s' is not a valid IPv6 address" % str(ip[:39])) dbsession.flush() else: errors.append("Box does not exist") self.render("admin/view/game_objects.html", errors=errors) else: self.render("admin/view/game_objects.html", errors=form.errors)
def score_bots(): ''' Award money for botnets ''' logging.info("Scoring botnets, please wait ...") bot_manager = BotManager.instance() for team in Team.all(): if len(team.members) > 0: bots = bot_manager.by_team(team.name) reward = 0 for bot in bots: try: reward += options.bot_reward bot.write_message({ 'opcode': 'status', 'message': 'Collected $%d reward' % options.bot_reward }) except: logging.info("Bot at %s failed to respond to score ping" % bot.remote_ip) if 0 < len(bots): logging.info("%s was awarded $%d for controlling %s bot(s)" % ( team.name, reward, len(bots), )) bot_manager.add_rewards(team.name, options.bot_reward) bot_manager.notify_monitors(team.name) team.money += reward dbsession.add(team) dbsession.flush() dbsession.commit()
def edit_corporations(self): ''' Updates corporation object in the database ''' form = Form( uuid="Object not selected", name="Missing corporation name", description="Missing description", ) if form.validate(self.request.arguments): corp = Corporation.by_uuid(self.get_argument('uuid')) if corp is not None: if self.get_argument('name') != corp.name: logging.info("Updated corporation name %s -> %s" % ( corp.name, self.get_argument('name'), )) corp.name = unicode(self.get_argument('name')) if self.get_argument('description') != corp.description: logging.info("Updated corporation description %s -> %s" % ( corp.description, self.get_argument('description'), )) corp.description = unicode( self.get_argument('description')) dbsession.add(corp) dbsession.flush() self.redirect('/admin/view/game_objects') else: self.render("admin/view/game_objects.html", errors=["Corporation does not exist"]) else: self.render("admin/view/game_objects.html", errors=form.errors)
def stats_complexity(self): ''' Returns stats on solved hash's plain text complexity ''' if self.cached_complexity_analysis == None: complexity = [] if 0 < len(self.lower_case_passwords): complexity.append( {'Lower Case': len(self.lower_case_passwords)}) if 0 < len(self.upper_case_passwords): complexity.append( {'Upper Case': len(self.upper_case_passwords)}) if 0 < len(self.numeric_passwords): complexity.append({'Numeric': len(self.numeric_passwords)}) if 0 < len(self.mixed_case_passwords): complexity.append( {'Mixed Case': len(self.mixed_case_passwords)}) if 0 < len(self.lower_alpha_numeric_passwords): complexity.append({'Lower Case Alpha-numeric': len(self.lower_alpha_numeric_passwords)}) if 0 < len(self.upper_alpha_numeric_passwords): complexity.append({'Upper Case Alpha-numeric': len(self.upper_alpha_numeric_passwords)}) if 0 < len(self.mixed_alpha_numeric_passwords): complexity.append({'Mixed Case Alpha-numeric': len(self.mixed_alpha_numeric_passwords)}) self.cached_complexity_analysis = json.dumps(complexity) dbsession.add(self) dbsession.flush() return self.cached_complexity_analysis
def create_flags(parent, box): ''' Create flag objects for a box ''' logging.info("Found %s flag(s)" % parent.get('count')) flag_dependency = [] for index, flag_elem in enumerate(parent.getchildren()): try: name = get_child_text(flag_elem, 'name') flag = Flag(box_id=box.id) flag.name = name flag.token = get_child_text(flag_elem, 'token') flag.value = get_child_text(flag_elem, 'value') flag.case_sensitive = get_child_text(flag_elem, 'case_sensitive') flag.description = get_child_text(flag_elem, 'description') flag.capture_message = get_child_text(flag_elem, 'capture_message') flag.type = flag_elem.get('type') dbsession.add(flag) dbsession.flush() depend = get_child_text(flag_elem, 'depends_on') if depend: flag_dependency.append({"flag": flag, "name": depend}) if flag.type == "choice": create_choices(get_child_by_tag(flag_elem, 'flag_choices'), flag) create_hints(get_child_by_tag(flag_elem, 'hints'), box, flag) except: logging.exception("Failed to import flag #%d" % (index + 1)) if len(flag_dependency) > 0: for item in flag_dependency: for flag in box.flags: if item["name"] == flag.name: item["flag"].lock_id = flag.id continue
def create_game_level(number, buyout): ''' Creates a GameLevel object ''' if GameLevel.by_number(number) is not None: logging.info("Game level #%s already exists, skipping" % number) return GameLevel.by_number(number) logging.info("Create Game Level #%s with a buyout of $%s" % ( number, buyout )) new_level = GameLevel( number=abs(int(number)), buyout=abs(int(buyout)), ) game_levels = GameLevel.all() game_levels.append(new_level) logging.debug("Updating game level linked list ...") game_levels = sorted(game_levels) index = 0 for level in game_levels[:-1]: level.next_level_id = game_levels[index + 1].id dbsession.add(level) index += 1 game_levels[0].number = 0 dbsession.add(game_levels[0]) game_levels[-1].next_level_id = None dbsession.add(game_levels[-1]) dbsession.flush() return new_level
def create_file(self, user): ''' Saves uploaded file ''' file_name = os.path.basename( self.request.files['file_data'][0]['filename'] ) char_white_list = ascii_letters + digits + "-._" file_name = filter(lambda char: char in char_white_list, file_name) content = guess_type(file_name) if content[0] is None: self.render("share_upload/share_files.html", errors=["Unknown file content, please zip and upload"], shares=user.team.files ) elif len(file_name) < 1: self.render("share_upload/share_files.html", errors=["Invalid file name"] ) else: uuid = unicode(uuid4()) filePath = self.application.settings['shares_dir'] + '/' + uuid save = open(filePath, 'w') data = b64encode(self.request.files['file_data'][0]['body']) save.write(data) save.close() file_upload = FileUpload( file_name=unicode(file_name), content=unicode(str(content[0])), uuid=uuid, description=unicode(self.get_argument('description', 'No description.')), byte_size=len(self.request.files['file_data'][0]['body']), team_id=user.team.id ) dbsession.add(file_upload) dbsession.flush() return file_upload
def score_bots(): ''' Award money for botnets ''' logging.info("Scoring botnets, please wait ...") bot_manager = BotManager.instance() event_manager = EventManager.instance() for team in Team.all(): if len(team.members) > 0: bots = bot_manager.by_team(team.name) if 0 < len(bots): reward = 0 for bot in bots: try: reward += options.bot_reward bot.write_message({ 'opcode': 'status', 'message': 'Collected $%d reward' % options.bot_reward }) except: logging.info( "Bot at %s failed to respond to score ping" % bot.remote_ip ) message = "%s was awarded $%d for controlling %s bot(s)" % ( team.name, reward, len(bots), ) bot_manager.add_rewards(team.name, options.bot_reward) bot_manager.notify_monitors(team.name) team.money += reward dbsession.add(team) dbsession.flush() event_manager.bot_scored(team, message) dbsession.commit()
def create_flag(name, token, value, box, description="No description", is_file=False): if Flag.by_name(name) is not None: logging.info("Flag with name '%s' already exists, skipping" % (name)) return Flag.by_name(name) if Flag.by_token(token) is not None: logging.info("Flag with token '%s' already exists, skipping" % (token)) return Flag.by_token(token) if is_file and os.path.exists(token): with open(token) as favatar: _token = Flag.digest(favatar.read()) elif is_file and 40 == len(token): _token = unicode(token) # Just assume it's a SHA1 elif is_file: raise ValueError("Flag token file does not exist, and is not a hash.") else: _token = unicode(token[:256]) logging.info("Create Flag: %s" % name) flag = Flag( name=unicode(name[:32]), token=_token, is_file=is_file, description=unicode(description[:256]), value=abs(int(value)), box_id=box.id, ) dbsession.add(flag) dbsession.flush() return flag
def query_plugins(self, weapon_system, rpc): if 0 < len(weapon_system.plugins): self.output += "[-] Clearing old plugin(s) ...\n" for old_plugin in weapon_system.plugins: dbsession.delete(old_plugin) dbsession.flush() self.output += "[*] Attempting to detect remote plugin(s) ...\n" for algo in Algorithm.all(): self.output += "[+] Looking for %s plugins ..." % algo plugin_names = rpc.root.exposed_get_category_plugins(algo.name) self.output += " found %d\n" % len(plugin_names) for plugin_name in plugin_names: self.output += "[+] Query info from remote plugin '%s'\n" % plugin_name details = rpc.root.exposed_get_plugin_details( algo.name, plugin_name) plugin = PluginDetails( name=unicode(plugin_name), author=unicode(details['author']), website=unicode(details['website']), version=unicode(details['version']), description=unicode(details['description']), copyright=unicode(details['copyright']), ) plugin.precomputation = details['precomputation'] plugin.algorithm_id = algo.id weapon_system.plugins.append(plugin)
def post(self, *args, **kwargs): user_uuid = self.get_argument('uuid', '') user = User.by_uuid(user_uuid) if user is not None: errors = [] username = self.get_argument('username', None) password = self.get_argument('password', None) if password is not None: if 12 <= len(password) <= 100: self.change_user_password(user) else: errors.append("Password invalid length (12-100)") if username is not None and username != user.username: if 3 <= len(username) <= 15: if User.by_username(username) is None: user.username = username dbsession.add(user) dbsession.flush() else: errors.append("Username already exists") else: errors.append("Username is an invalid length (3-15)") self.render("admin/manage_users.html", errors=errors) else: self.render("admin/manage_users.html", errors=["User does not exist"])
def create_levels(levels): ''' Create GameLevel objects based on XML data ''' logging.info("Found %s game level(s)" % levels.get('count')) for index, level_elem in enumerate(levels.getchildren()): # GameLevel 0 is created automatically by the bootstrap if get_child_text(level_elem, 'number') != '0': try: number = get_child_text(level_elem, 'number') if GameLevel.by_number(number) is None: game_level = GameLevel() game_level.number = number game_level.buyout = get_child_text(level_elem, 'buyout') dbsession.add(game_level) else: logging.info("GameLevel %d already exists, skipping" % number) except: logging.exception("Failed to import game level #%d" % (index + 1)) dbsession.flush() game_levels = GameLevel.all() for index, game_level in enumerate(game_levels): if index + 1 < len(game_levels): game_level.next_level_id = game_levels[index + 1].id logging.info("%r -> %r" % (game_level, game_levels[index + 1])) dbsession.add(game_level) dbsession.commit()
def create_boxes(parent, corporation): ''' Create boxes for a corporation ''' logging.info("Found %s boxes" % parent.get('count')) for index, box_elem in enumerate(parent.getchildren()): try: name = get_child_text(box_elem, 'name') game_level = GameLevel.by_number(box_elem.get('gamelevel')) if game_level is None: logging.warning( "GameLevel does not exist for box %s, skipping" % name) elif Box.by_name(name) is None: box = Box(corporation_id=corporation.id) box.name = name box.game_level_id = game_level.id box.difficulty = get_child_text(box_elem, 'difficulty') box.description = get_child_text(box_elem, 'description') box.operating_system = get_child_text(box_elem, 'operatingsystem') box.avatar = get_child_text(box_elem, 'avatar').decode('base64') box.garbage = get_child_text(box_elem, 'garbage') category = get_child_text(box_elem, 'category') if category: box.category_id = Category.by_category(category).id dbsession.add(box) dbsession.flush() create_flags(get_child_by_tag(box_elem, 'flags'), box) create_hints(get_child_by_tag(box_elem, 'hints'), box) else: logging.info("Box with name %s already exists, skipping" % name) except: logging.exception("Failed to import box %d" % (index + 1))
def edit_corporations(self): ''' Updates corporation object in the database ''' form = Form( uuid="Object not selected", name="Missing corporation name", description="Missing description", ) if form.validate(self.request.arguments): corp = Corporation.by_uuid(self.get_argument('uuid')) if corp is not None: if self.get_argument('name') != corp.name: logging.info("Updated corporation name %s -> %s" % (corp.name, self.get_argument('name'),) ) corp.name = unicode(self.get_argument('name')) if self.get_argument('description') != corp.description: logging.info("Updated corporation description %s -> %s" % (corp.description, self.get_argument('description'),) ) corp.description = unicode(self.get_argument('description')) dbsession.add(corp) dbsession.flush() self.redirect('/admin/view/game_objects') else: self.render("admin/view/game_objects.html", errors=["Corporation does not exist"] ) else: self.render("admin/view/game_objects.html", errors=form.errors)
def post_avatar(self, *args, **kwargs): ''' Saves avatar - Reads file header an only allows approved formats ''' user = User.by_id(self.session['user_id']) if 'avatar' in self.request.files: if len(self.request.files['avatar'][0]['body']) < (1024 * 1024): if user.avatar == "default_avatar.jpeg": user.avatar = unicode(uuid4()) + u".jpeg" ext = imghdr.what("", h=self.request.files['avatar'][0]['body']) avatar_path = str(self.application.settings['avatar_dir'] + '/' + user.avatar) if ext in ['png', 'jpeg', 'gif', 'bmp']: if os.path.exists(avatar_path): os.unlink(avatar_path) user.avatar = unicode( user.avatar[:user.avatar.rfind('.')] + "." + ext) file_path = str(self.application.settings['avatar_dir'] + '/' + user.avatar) avatar = open(file_path, 'wb') avatar.write(self.request.files['avatar'][0]['body']) avatar.close() dbsession.add(user) dbsession.flush() self.render_page(success=["Successfully changed avatar"]) else: self.render_page(errors=[ str("Invalid image format, avatar must be:" + ".png .jpeg .gif or .bmp") ]) else: self.render_page(errors=["The image is too large"]) else: self.render_page(errors=["Please provide and image"])
def edit_users(self): ''' Update user objects in the database ''' form = Form( uuid="User not selected", account="Please enter an account name", handle="Please enter a handle name", hash_algorithm="Please select a hash algorithm", team_uuid="Please select a team", ) if form.validate(self.request.arguments): errors = [] user = User.by_uuid(self.get_argument('uuid')) if user is not None: # Update user account name if user.account != self.get_argument('account'): if User.by_account(self.get_argument('account')) is None: logging.info("Updated user account %s -> %s" % (user.account, self.get_argument('account'),)) user.account = unicode(self.get_argument('account')) else: errors.append("Account name is already in use") # Update user handle if user.handle != self.get_argument('handle'): if User.by_handle(self.get_argument('handle')) is None: logging.info("Updated user handle %s -> %s" % (user.handle, self.get_argument('handle'),)) user.handle = unicode(self.get_argument('handle')) else: errors.append("Handle is already in use") # Update hashing algoritm if self.get_argument('hash_algorithm') in user.algorithms: if user.algorithm != self.get_argument('hash_algorithm'): if 0 < len(self.get_argument('password', '')): logging.info("Updated %s's hashing algorithm %s -> %s" % (user.handle, user.algorithm, self.get_argument('hash_algorithm'),) ) user.algorithm = self.get_argument('hash_algorithm') else: errors.append("You must provide a password when updating the hashing algorithm") else: errors.append("Not a valid hash algorithm") # Update password if 0 < len(self.get_argument('password', '')): user.password = self.get_argument('password') # Update team team = Team.by_uuid(self.get_argument('team_uuid')) if team is not None: if user.team_id != team.id: logging.info("Updated %s's team %s -> %s" % (user.handle, user.team_id, team.name)) user.team_id = team.id else: errors.append("Team does not exist in database") dbsession.add(user) dbsession.flush() else: errors.append("User does not exist") self.render("admin/view/user_objects.html", errors=errors) else: self.render("admin/view/user_objects.html", errors=form.errors)
def edit_ipv6(self): ''' Add ipv6 addresses to a box (sorta edits the box object) ''' form = Form(box_uuid="Select a box", ipv6="Please provide a list of IPv6 addresses") if form.validate(self.request.arguments): errors = [] box = Box.by_uuid(self.get_argument('box_uuid')) if box is not None: ips_string = self.get_argument('ipv6').replace('\n', ',').lower() ips = filter(lambda char: char in "1234567890abcdef:,", ips_string).split(",") for ip in filter(lambda ip: 0 < len(ip), ips): try: box = Box.by_ip_address(ip) if box is None: addr = IpAddress(box_id=box.id, v6=ip) dbsession.add(addr) else: errors.append( "%s has already been assigned to %s." % (ip, box.name,) ) except ValueError: errors.append( "'%s' is not a valid IPv6 address" % str(ip[:39]) ) dbsession.flush() else: errors.append("Box does not exist") self.render("admin/view/game_objects.html", errors=errors) else: self.render("admin/view/game_objects.html", errors=form.errors)
def post(self, *args, **kwargs): ''' Attempt to upgrade hash algo ''' form = Form( old_password="******", new_password1="Enter a new password", new_password2="Confirm your new password", ) if form.validate(self.request.arguments): user = self.get_current_user() passwd = self.get_argument('new_password1') old_passwd = self.get_argument('old_password') if not user.validate_password(old_passwd): self.render_page(["Invalid password"]) elif not passwd == self.get_argument('new_password2'): self.render_page(["New passwords do not match"]) elif user.team.money < self.config.password_upgrade: self.render_page(["You cannot afford to upgrade your hash"]) elif len(passwd) <= self.config.max_password_length: user.team.money -= self.config.password_upgrade dbsession.add(user.team) dbsession.flush() self.update_password(passwd) self.render_page() else: self.render_page(["New password is too long"]) else: self.render_page(form.errors)
def create_boxes(parent, corporation): ''' Create boxes for a corporation ''' logging.info("Found %s boxes" % parent.get('count')) for index, box_elem in enumerate(parent.getchildren()): try: name = get_child_text(box_elem, 'name') game_level = GameLevel.by_number(box_elem.get('gamelevel')) if game_level is None: logging.warning("GameLevel does not exist for box %s, skipping" % name) elif Box.by_name(name) is None: box = Box(corporation_id=corporation.id) box.name = name box.game_level_id = game_level.id box.difficulty = get_child_text(box_elem, 'difficulty') box.description = get_child_text(box_elem, 'description') box.operating_system = get_child_text(box_elem, 'operatingsystem') box.avatar = get_child_text(box_elem, 'avatar').decode('base64') box.garbage = get_child_text(box_elem, 'garbage') dbsession.add(box) dbsession.flush() create_flags(get_child_by_tag(box_elem, 'flags'), box) create_hints(get_child_by_tag(box_elem, 'hints'), box) else: logging.info("Box with name %s already exists, skipping" % name) except: logging.exception("Failed to import box %d" % (index + 1))
def create_file(self, user): """ Saves uploaded file """ file_name = os.path.basename(self.request.files["file_data"][0]["filename"]) char_white_list = ascii_letters + digits + "-._" file_name = filter(lambda char: char in char_white_list, file_name) content = guess_type(file_name) if content[0] is None: self.render( "share_upload/share_files.html", errors=["Unknown file content, please zip and upload"], shares=user.team.files, ) elif len(file_name) < 1: self.render("share_upload/share_files.html", errors=["Invalid file name"]) else: uuid = unicode(uuid4()) filePath = self.application.settings["shares_dir"] + "/" + uuid save = open(filePath, "w") data = b64encode(self.request.files["file_data"][0]["body"]) save.write(data) save.close() file_upload = FileUpload( file_name=unicode(file_name), content=unicode(str(content[0])), uuid=uuid, description=unicode(self.get_argument("description")), byte_size=len(self.request.files["file_data"][0]["body"]), team_id=user.team.id, ) dbsession.add(file_upload) dbsession.flush() self.event_manager.team_file_share(user, file_upload)
def initialize(self, *args): ''' One time initialization, gathers system information ''' success = False logging.info( "Preforming weapon system initialization, please wait ... ") ssh_keyfile = NamedTemporaryFile() ssh_keyfile.write(self.ssh_key) ssh_keyfile.seek(0) try: logging.info("Connectiong to remote ssh server at %s:%s" % (self.ip_address, self.ssh_port)) ssh_context = SshContext(self.ip_address, user=self.ssh_user, keyfile=ssh_keyfile.name) rpc_connection = rpyc.ssh_connect(ssh_context, self.service_port) capabilities = rpc_connection.root.exposed_get_capabilities() self.lm_capable = 'LM' in capabilities self.ntlm_capable = 'NTLM' in capabilities self.md5_capable = 'MD5' in capabilities self.cpu_count = rpc_connection.root.exposed_cpu_count() self.initialized = True dbsession.add(self) dbsession.flush() success = True except ValueError: logging.exception( "Failed to initialize weapon system, check parameters") except EOFError: logging.exception( "Failed to initialize weapon system, check parameters") finally: ssh_keyfile.close() return success
def post(self, *args, **kwargs): ''' Attempt to upgrade hash algo ''' form = Form( old_password="******", new_password1="Enter a new password", new_password2="Confirm your new password", ) if form.validate(self.request.arguments): user = self.get_current_user() passwd = self.get_argument('new_password1') old_passwd = self.get_argument('old_password') if not user.validate_bank_password(old_passwd): self.render_page(["Invalid password"]) elif not passwd == self.get_argument('new_password2'): self.render_page(["New passwords do not match"]) elif user.team.money < self.config.password_upgrade_cost: self.render_page(["You cannot afford to upgrade your hash"]) elif len(passwd) <= self.config.max_password_length: user.team.money -= self.config.password_upgrade_cost dbsession.add(user.team) dbsession.flush() self.update_password(passwd) self.render_page() else: self.render_page(["New password is too long"]) else: self.render_page(form.errors)
def post_avatar(self, *args, **kwargs): ''' Saves avatar - Reads file header an only allows approved formats ''' user = User.by_id(self.session['user_id']) if 'avatar' in self.request.files: if len(self.request.files['avatar'][0]['body']) < (1024 * 1024): if user.avatar == "default_avatar.jpeg": user.avatar = unicode(uuid4()) + u".jpeg" ext = imghdr.what( "", h=self.request.files['avatar'][0]['body'] ) avatar_path = str(self.application.settings['avatar_dir'] + '/' + user.avatar) if ext in ['png', 'jpeg', 'gif', 'bmp']: if os.path.exists(avatar_path): os.unlink(avatar_path) user.avatar = unicode(user.avatar[:user.avatar.rfind('.')] + "." + ext) file_path = str(self.application.settings['avatar_dir'] + '/' + user.avatar) avatar = open(file_path, 'wb') avatar.write(self.request.files['avatar'][0]['body']) avatar.close() dbsession.add(user) dbsession.flush() self.render_page(success=["Successfully changed avatar"]) else: self.render_page( errors=["Invalid image format, avatar must be: .png .jpeg .gif or .bmp"] ) else: self.render_page(errors=["The image is too large"]) else: self.render_page(errors=["Please provide an image"])
def __queue__(self): ''' Starts a job or leaves it in the queue (thread safe) ''' logging.debug("Attempting to acquire queue mutex ...") self.mutex.acquire() logging.debug("Successfully acquired queue mutex.") queue = list(Job.queue()) # Create a copy of the queue for job in queue: logging.info("Dispatching job: %s" % job.job_name) if len(job) == 0: job.status = u"COMPLETED" dbsession.add(job) dbsession.flush() else: algo = Algorithm.by_id(job.algorithm_id) weapon_systems = WeaponSystem.system_ready(algo) if weapon_systems is not None and 0 < len(weapon_systems): logging.info("Weapon systems available: %d" % (len(weapon_systems), )) thread.start_new_thread(self.__crack__, ( job, weapon_systems[0], )) else: logging.info("No available weapon systems at this time.") self.mutex.release()
def create_file(self, user): ''' Saves uploaded file ''' file_name = os.path.basename( self.request.files['file_data'][0]['filename']) char_white_list = ascii_letters + digits + "-._" file_name = filter(lambda char: char in char_white_list, file_name) content = guess_type(file_name) if content[0] is None: self.render("share_upload/share_files.html", errors=["Unknown file content, please zip and upload"], shares=user.team.files) elif len(file_name) < 1: self.render("share_upload/share_files.html", errors=["Invalid file name"]) else: uuid = unicode(uuid4()) filePath = self.application.settings['shares_dir'] + '/' + uuid save = open(filePath, 'w') data = b64encode(self.request.files['file_data'][0]['body']) save.write(data) save.close() file_upload = FileUpload( file_name=unicode(file_name), content=unicode(str(content[0])), uuid=uuid, description=unicode( self.get_argument('description', 'No description.')), byte_size=len(self.request.files['file_data'][0]['body']), team_id=user.team.id) dbsession.add(file_upload) dbsession.flush() return file_upload
def __queue__(self): ''' Starts a job or leaves it in the queue (thread safe) ''' logging.debug("Attempting to acquire queue mutex ...") self.mutex.acquire() logging.debug("Successfully acquired queue mutex.") queue = list(Job.queue()) # Create a copy of the queue for job in queue: logging.info("Dispatching job: %s" % job.job_name) if len(job) == 0: job.status = u"COMPLETED" dbsession.add(job) dbsession.flush() else: algo = Algorithm.by_id(job.algorithm_id) weapon_systems = WeaponSystem.system_ready(algo) if weapon_systems is not None and 0 < len(weapon_systems): logging.info("Weapon systems available: %d" % ( len(weapon_systems), )) thread.start_new_thread( self.__crack__, (job, weapon_systems[0],) ) else: logging.info("No available weapon systems at this time.") self.mutex.release()
def delivered(cls, user_id, uuid): notify = dbsession.query(cls).filter( and_(cls.event_uuid == uuid, cls.user_id == user_id) ).first() notify.viewed = True dbsession.add(notify) dbsession.flush()
def query_plugins(self, weapon_system, rpc): if 0 < len(weapon_system.plugins): self.output += "[-] Clearing old plugin(s) ...\n" for old_plugin in weapon_system.plugins: dbsession.delete(old_plugin) dbsession.flush() self.output += "[*] Attempting to detect remote plugin(s) ...\n" for algo in Algorithm.all(): self.output += "[+] Looking for %s plugins ..." % algo plugin_names = rpc.root.exposed_get_category_plugins(algo.name) self.output += " found %d\n" % len(plugin_names) for plugin_name in plugin_names: self.output += "[+] Query info from remote plugin '%s'\n" % plugin_name details = rpc.root.exposed_get_plugin_details(algo.name, plugin_name) plugin = PluginDetails( name=unicode(plugin_name), author=unicode(details['author']), website=unicode(details['website']), version=unicode(details['version']), description=unicode(details['description']), copyright=unicode(details['copyright']), ) plugin.precomputation = details['precomputation'] plugin.algorithm_id = algo.id weapon_system.plugins.append(plugin)
def create_flags(parent, box): """ Create flag objects for a box """ if parent: logging.info("Found %s flag(s)" % parent.get("count")) flag_dependency = [] for index, flag_elem in enumerate(parent.getchildren()): try: flag = Flag(box_id=box.id) flag.name = get_child_text(flag_elem, "name") flag.token = get_child_text(flag_elem, "token") flag.value = get_child_text(flag_elem, "value", 10) flag.case_sensitive = get_child_text(flag_elem, "case_sensitive", 0) flag.description = get_child_text(flag_elem, "description") flag.capture_message = get_child_text(flag_elem, "capture_message") flag.type = get_child_text(flag_elem, "type", "static") flag.order = get_child_text(flag_elem, "order", None) dbsession.add(flag) dbsession.flush() depend = get_child_text(flag_elem, "depends_on", None) if depend: flag_dependency.append({"flag": flag, "name": depend}) if flag.type == "choice": create_choices(get_child_by_tag(flag_elem, "flag_choices"), flag) create_hints(get_child_by_tag(flag_elem, "hints"), box, flag) except: logging.exception("Failed to import flag #%d" % (index + 1)) if len(flag_dependency) > 0: for item in flag_dependency: for flag in box.flags: if item["name"] == flag.name: item["flag"].lock_id = flag.id continue
def post(self, *args, **kwargs): user_uuid = self.get_argument('uuid', '') user = User.by_uuid(user_uuid) if user is not None: errors = [] username = self.get_argument('username', None) password = self.get_argument('password', None) if password is not None: if 12 <= len(password) <= 100: self.change_user_password(user) else: errors.append("Password invalid length (12-100)") if username is not None and username != user.username: if 3 <= len(username) <= 15: if User.by_username(username) is None: user.username = username dbsession.add(user) dbsession.flush() else: errors.append("Username already exists") else: errors.append("Username is an invalid length (3-15)") self.render("admin/manage_users.html", errors=errors) else: self.render("admin/manage_users.html", errors=["User does not exist"] )
def create_levels(levels): """ Create GameLevel objects based on XML data """ logging.info("Found %s game level(s)" % levels.get("count")) for index, level_elem in enumerate(levels.getchildren()): # GameLevel 0 is created automatically by the bootstrap try: number = get_child_text(level_elem, "number") if number == "0" or GameLevel.by_number(number) is None: if number != "0": game_level = GameLevel() else: game_level = GameLevel.by_id(0) if game_level is None: game_level = GameLevel() game_level.number = number game_level.name = get_child_text(level_elem, "name") game_level.type = get_child_text(level_elem, "type") game_level.reward = get_child_text(level_elem, "reward", 0) game_level.buyout = get_child_text(level_elem, "buyout", 0) dbsession.add(game_level) else: logging.info("GameLevel %d already exists, skipping" % int(number)) except: logging.exception("Failed to import game level #%d" % (index + 1)) dbsession.flush() game_levels = GameLevel.all() for index, game_level in enumerate(game_levels): if index + 1 < len(game_levels): game_level.next_level_id = game_levels[index + 1].id logging.info("%r -> %r" % (game_level, game_levels[index + 1])) dbsession.add(game_level) dbsession.commit()
def post(self, *args, **kwargs): ''' Change user password ''' user = self.get_current_user() old_password = self.get_argument('old_password', None) pass1 = self.get_argument('pass1', None) pass2 = self.get_argument('pass2', None) if old_password is None or pass1 is None or pass2 is None: self.render('veil/settings.html', errors=['Fill in all the forms'] ) elif len(pass1) < 12 or len(pass2) < 12: self.render('veil/settings.html', errors=['New password too short (min. 12)'] ) elif pass1 != pass2: self.render('veil/settings.html', errors=['New passwords do not match'] ) elif user.validate_password(old_password): user.password = pass1 dbsession.add(user) dbsession.flush() self.render('veil/settings.html', errors=[]) else: self.render('veil/settings.html', errors=['Old password incorrect'] )
def score_bots(): ''' Award money for botnets ''' logging.info("Scoring botnets, please wait ...") bot_manager = BotManager.Instance() config = ConfigManager.Instance() for team in Team.all(): bots = bot_manager.by_team(team.name) reward = 0 for bot in bots: try: reward += config.bot_reward bot.write_message({ 'opcode': 'status', 'message': 'Collected $%d reward' % config.bot_reward }) except: logging.info( "Bot at %s failed to respond to score ping" % bot.remote_ip ) if 0 < len(bots): logging.debug("%s was awarded $%d for controlling %s bot(s)" % ( team.name, reward, len(bots), )) bot_manager.add_rewards(team.name, config.bot_reward) bot_manager.notify_monitors(team.name) team.money += reward dbsession.add(team) dbsession.flush()
def change_user_password(user): ''' Update user password and salt ''' user.salt = bcrypt.salt(16) dbsession.add(user) dbsession.flush() user.password = password dbsession.add(user) dbsession.flush()
def create_dork(self, user): new_dork = Dork(title=self.get_argument('title'), description=self.get_argument('description'), query=self.get_argument('query'), author=self.get_argument('author'), submitted_user_id=user.id) dbsession.add(new_dork) dbsession.flush()
def post(self, *args, **kwargs): uuid = self.get_argument('uuid', '') payload = Payload.by_uuid(uuid) user = self.get_current_user() if payload is not None and payload in user.history: dbsession.delete(payload) dbsession.flush() self.redirect('/history')
def create_blog_entry(self, title, paragraph, pic_name): entry = BlogEntry( title=unicode(title), paragraph=unicode(paragraph), image_uri=unicode('/static/images/' + pic_name), ) dbsession.add(entry) dbsession.flush()
def __crack__(self, job, weapon_system): ''' Does the actual password cracking, before calling this function you should ensure the weapon system is online and not busy ''' results = None user = User.by_id(job.user_id) if user is None: logging.error( "Invalid job passed to dispatcher (no user with id %d)." % (job.user_id, )) elif job == None: logging.error("Invalid job passed to dispatcher (job is None).") else: job.started = datetime.now() algorithm = Algorithm.by_id(job.algorithm_id) try: ssh_keyfile = NamedTemporaryFile() ssh_keyfile.write(weapon_system.ssh_key) ssh_keyfile.seek(0) ssh_context = SshContext( weapon_system.ip_address, user=weapon_system.ssh_user, keyfile=ssh_keyfile.name, ) rpc_connection = rpyc.ssh_connect( ssh_context, weapon_system.service_port, ) hashes = job.to_list() logging.info("Sending %s job to %s for cracking." % ( job.job_name, weapon_system.weapon_system_name, )) job.status = u"IN_PROGRESS" dbsession.add(job) dbsession.flush() results = rpc_connection.root.exposed_crack_list( job.id, job.to_list(), algorithm.algorithm_name, ) except: logging.exception( "Connection to remote weapon system failed, check parameters." ) finally: ssh_keyfile.close() if results is not None: job.save_results(results) else: logging.warn("No results returned from weapon system.") job.status = u"COMPLETED" job.finished = datetime.now() dbsession.add(job) dbsession.flush() self.__next__()
def generate_teams(num_teams): """ Generates teams by number """ from models import Team, dbsession for i in range(0, num_teams): team = Team() team.name = 'Team ' + str(i + 1) dbsession.add(team) dbsession.flush() dbsession.commit()
def post(self, *args, **kwargs): ''' Toggle account lock ''' uuid = self.get_argument('uuid', '') user = User.by_uuid(uuid) if user is not None: user.locked = False if user.locked else True dbsession.add(user) dbsession.flush() self.redirect('/admin')
def generate_teams_by_name(team_names): """ Generates teams by their names """ from models import Team, dbsession for i in range(0, len(team_names)): team = Team() team.name = team_names[i] dbsession.add(team) dbsession.flush() dbsession.commit()
def create_user(self, username, password): ''' Add user to the database ''' user = User(name=username) dbsession.add(user) dbsession.flush() user.password = password dbsession.add(user) dbsession.flush() return user
def create_hint(box, price, description): print(INFO + "Create Hint: %s has a new hint for $%s" % (box.name, price,)) hint = Hint( box_id=box.id, price=int(abs(price)), description=unicode(description) ) dbsession.add(hint) dbsession.flush()
def create_corporation(name, description="No description"): print(INFO + "Create corporation: " + bold + name + W) corp = Corporation( name=unicode(name), description=unicode(description), ) dbsession.add(corp) dbsession.flush() return corp
def award_money(box, team, auth): ''' Awards money if everything authenticated properly ''' team = Team.by_id(team.id) # Refresh object if auth.confirmed_access == 'root': team.money += box.root_award else: team.money += box.user_award dbsession.add(team) dbsession.flush()
def score(self): ''' Returns user's current score from cache, or re-calculates if expired ''' if self.dirty: actions = dbsession.query(Action).filter_by(user_id=self.id).all() #@UndefinedVariable self.score_cache = sum(actions) self.dirty = False dbsession.add(self) dbsession.flush() return self.score_cache
def post(self, *args, **kwargs): ''' AJAX // Delete a paste object from the database ''' paste_uuid = self.get_argument("uuid", "") paste = PasteBin.by_uuid(paste_uuid) user = self.get_current_user() if paste is not None and paste.team_id == user.team.id: dbsession.delete(paste) dbsession.flush() self.redirect("/user/share/pastebin")
def __mkipv4__(box, address): print(INFO + "IPv4 address '%s' now belongs to %s" % (address, box.name,)) ip = IpAddress( v4=unicode(address), ) box.ip_addresses.append(ip) dbsession.add(ip) dbsession.add(box) dbsession.flush() return ip
def edit_boxes(self): ''' Edit existing boxes in the database ''' form = Form( uuid="Object not selected", name="Missing box name", corporation_uuid="Please select a corporation", description="Please enter a description", difficulty="Please enter a difficulty", ) if form.validate(self.request.arguments): box = Box.by_uuid(self.get_argument('uuid')) if box is not None: errors = [] if self.get_argument('name') != box.name: if Box.by_name(self.get_argument('name')) is None: logging.info("Updated box name %s -> %s" % ( box.name, self.get_argument('name'), )) box.name = unicode(self.get_argument('name')) else: errors.append("Box name already exists") corp = Corporation.by_uuid( self.get_argument('corporation_uuid')) if corp is not None and corp.id != box.corporation_id: logging.info("Updated %s's corporation %s -> %s" % ( box.name, box.corporation_id, corp.id, )) box.corporation_id = corp.id elif corp is None: errors.append("Corporation does not exist") if self.get_argument('description') != box.description: logging.info("Updated %s's description %s -> %s" % ( box.name, box.description, self.get_argument('description'), )) box.description = unicode(self.get_argument('description')) if self.get_argument('difficulty') != box.difficulty: logging.info("Updated %s's difficulty %s -> %s" % ( box.name, box.difficulty, self.get_argument('difficulty'), )) box.difficulty = unicode(self.get_argument('difficulty')) dbsession.add(box) dbsession.flush() self.render("admin/view/game_objects.html", errors=errors) else: self.render("admin/view/game_objects.html", errors=["Box does not exist"]) else: self.render("admin/view/game_objects.html", errors=form.errors)