示例#1
0
def edit_entry(no):
    if not session.get('logged_in'):
        #abort(401)
        return redirect(url_for('login'))
    if request.method == 'GET':
        entries = dbsession.query(Backdata).filter_by(slno=no)
        return render_template('edit_entries.html', entries=entries)
    else:
        server = dbsession.query(Backdata).filter_by(slno=no).first()
        server.serv_name = request.form['serv_name']
        server.remote_user = request.form['remote_user']
        server.remote_port = request.form['remote_port']
        server.dir_bkp = request.form['dir_bkp']
        server.bkp_hour = request.form['bkp_hour']
        server.rt_hour = request.form['rt_hour']
        server.bkp_day = request.form['bkp_day']
        server.rt_day = request.form['rt_day']
        server.bkp_week = request.form['bkp_week']
        server.rt_week = request.form['rt_week']
        server.bkp_month = request.form['bkp_month']
        server.rt_month = request.form['rt_month']
        server.aws_profile = request.form['aws_profile']
        #         db.session.merge(server)
        dbsession.commit()
        flash('Edit was successfull')
        return redirect(url_for('show_entries'))
示例#2
0
def create_team():
    team = Team()
    team.name = "TestTeam"
    team.motto = "TestMotto"
    dbsession.add(team)
    dbsession.commit()
    return team
示例#3
0
 def setUp(self):
     self.box, self.corp = create_box()
     self.static_flag = Flag.create_flag(
         _type=FLAG_STATIC,
         box=self.box,
         name="Static Flag",
         raw_token="statictoken",
         description="A static test token",
         value=100,
     )
     self.regex_flag = Flag.create_flag(
         _type=FLAG_REGEX,
         box=self.box,
         name="Regex Flag",
         raw_token="(f|F)oobar",
         description="A regex test token",
         value=200,
     )
     self.file_flag = Flag.create_flag(
         _type=FLAG_FILE,
         box=self.box,
         name="File Flag",
         raw_token="fdata",
         description="A file test token",
         value=300,
     )
     dbsession.add(self.static_flag)
     dbsession.add(self.regex_flag)
     dbsession.add(self.file_flag)
     dbsession.commit()
示例#4
0
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()
示例#5
0
def score_bots():
    ''' Award money for botnets '''
    logging.info("Scoring botnets, please wait ...")
    bot_manager = BotManager.instance()
    for team in Team.all():
        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()
示例#6
0
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()
示例#7
0
def create_team():
    team = Team()
    team.name = "TestTeam"
    team.motto = "TestMotto"
    dbsession.add(team)
    dbsession.commit()
    return team
示例#8
0
 def validate_email(self, token):
     emailtoken = EmailToken.by_user_id(self.id)
     if emailtoken and emailtoken.value == token:
         emailtoken.valid = True
         dbsession.add(emailtoken)
         dbsession.commit()
     return self.is_email_valid()
示例#9
0
 def setUp(self):
     self.box, self.corp = create_box()
     self.static_flag = Flag.create_flag(
         _type=FLAG_STATIC,
         box=self.box,
         name="Static Flag",
         raw_token="statictoken",
         description="A static test token",
         value=100,
     )
     self.regex_flag = Flag.create_flag(
         _type=FLAG_REGEX,
         box=self.box,
         name="Regex Flag",
         raw_token="(f|F)oobar",
         description="A regex test token",
         value=200,
     )
     self.file_flag = Flag.create_flag(
         _type=FLAG_FILE,
         box=self.box,
         name="File Flag",
         raw_token="fdata",
         description="A file test token",
         value=300,
     )
     dbsession.add(self.static_flag)
     dbsession.add(self.regex_flag)
     dbsession.add(self.file_flag)
     dbsession.commit()
示例#10
0
 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.commit()
示例#11
0
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()
示例#12
0
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()
示例#13
0
 def create_broadcast(cls, team, title, message, icon=None):
     if not options.global_notification and team:
         cls.create_team(team, title, message, icon)
     else:
         for user in User.all_users():
             notification = cls._create(user, title, message, icon)
             dbsession.add(notification)
         dbsession.commit()
示例#14
0
 def create_broadcast(cls, team, title, message, icon=None):
     if not options.global_notification and team:
         cls.create_team(team, title, message, icon)
     else:
         for user in User.all_users():
             notification = cls._create(user, title, message, icon)
             dbsession.add(notification)
         dbsession.commit()
示例#15
0
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()
示例#16
0
 def create_choice(cls, flag=None, item=None):
     ''' Create a choice and save it to the database '''
     if not flag:
         flag = cls.flag
     if not item:
         item = cls.item
     choice = cls._create(flag, unicode(item)[:256])
     dbsession.add(choice)
     dbsession.commit()
示例#17
0
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()
示例#18
0
 def create_choice(cls, flag=None, item=None):
     ''' Create a choice and save it to the database '''
     if not flag:
         flag = cls.flag
     if not item:
         item = cls.item
     choice = cls._create(flag, unicode(item)[:256])
     dbsession.add(choice)
     dbsession.commit()
示例#19
0
 def create_choice(cls, flag=None, item=None):
     """ Create a choice and save it to the database """
     if not flag:
         flag = cls.flag
     if not item:
         return
     choice = cls._create(flag, str(item)[:256])
     dbsession.add(choice)
     dbsession.commit()
示例#20
0
 def avatar(self):
     if self._avatar is not None:
         return self._avatar
     else:
         avatar = get_new_avatar('box')
         if not avatar.startswith("default_"):
             self._avatar = avatar
             dbsession.add(self)
             dbsession.commit()
         return avatar
示例#21
0
文件: Box.py 项目: x0xr00t/RootTheBox
 def avatar(self):
     if self._avatar is not None:
         return self._avatar
     else:
         avatar = get_new_avatar("box")
         if not avatar.startswith("default_"):
             self._avatar = avatar
             dbsession.add(self)
             dbsession.commit()
         return avatar
示例#22
0
def create_user():
    user = User.by_handle("HacKer")
    if user is None:
        user = User()
        user.handle = "HacKer"
        user.password = "******"
        user.bank_password = "******"
        dbsession.add(user)
        dbsession.commit()
    return user
示例#23
0
def create_user():
    user = User.by_handle("HacKer")
    if user is None:
        user = User()
        user.handle = "HacKer"
        user.password = "******"
        user.bank_password = "******"
        dbsession.add(user)
        dbsession.commit()
    return user
示例#24
0
def register():
        data = request.get_json(force=True)
        print('data:',data, type(data))
        query = dbsession.query(models.User).filter_by(email=data['email'], password=data['password']).all()
        if len(query) != 0:
                return jsonify({'status':'error', 'error':'The user is already registered!'})
        else:
                newUser=models.User(email=data['email'], password=data['password'])
                dbsession.add(newUser)
                dbsession.commit()
                return jsonify({'status': 'welcome!'})
示例#25
0
def deleteUser():
        data = request.get_json(force=True)
        print('data:',data, type(data))
        query = None
        try:
                query = dbsession.query(models.User).filter_by(email=data['email'], password=data['password']).one()
        except:
                return jsonify({'status':'error', 'error':'The user is not registered!'})
        dbsession.delete(query)
        dbsession.commit()
        return jsonify({'status': 'success'})
示例#26
0
def create_categories(categories):
    """ Create Category objects based on XML data """
    logging.info("Found %s categories" % categories.get("count"))
    for index, cat_elem in enumerate(categories.getchildren()):
        try:
            category = Category()
            category.category = get_child_text(cat_elem, "category")
            dbsession.add(category)
        except:
            logging.exception("Failed to import category #%d" % (index + 1))
    dbsession.flush()
    dbsession.commit()
示例#27
0
def create_categories(categories):
    ''' Create Category objects based on XML data '''
    logging.info("Found %s categories" % categories.get('count'))
    for index, cat_elem in enumerate(categories.getchildren()):
        try:
            category = Category()
            category.category = get_child_text(cat_elem, 'category')
            dbsession.add(category)
        except:
            logging.exception("Failed to import category #%d" % (index + 1))
    dbsession.flush()
    dbsession.commit()
示例#28
0
 def push_user(self, team_id, user_id):
     ''' Push all unread notifications to open user websockets '''
     connections = self.get_user_connections(team_id, user_id)
     notifications = Notification.unread_by_user_id(user_id)
     logging.debug("User #%s has %d unread notification(s)" %
                   (user_id, len(notifications)))
     for notification in notifications:
         for connection in connections:
             self.safe_write_message(connection, notification.to_dict())
         notification.viewed = True
         dbsession.add(notification)
     dbsession.commit()
示例#29
0
def create_box(corp=None):
    if corp is None:
        corp = create_corp()
    game_level = GameLevel.all()[0]
    box = Box(corporation_id=corp.id, game_level_id=game_level.id)
    box.name = "TestBox"
    box.description = "Some description"
    box.difficuly = "Easy"
    corp.boxes.append(box)
    dbsession.add(box)
    dbsession.commit()
    return box, corp
示例#30
0
def create_box(corp=None):
    if corp is None:
        corp = create_corp()
    game_level = GameLevel.all()[0]
    box = Box(corporation_id=corp.id, game_level_id=game_level.id)
    box.name = "TestBox"
    box.description = "Some description"
    box.difficuly = "Easy"
    corp.boxes.append(box)
    dbsession.add(box)
    dbsession.commit()
    return box, corp
示例#31
0
 def change_password(self):
     ''' Change a password '''
     user = self.get_current_user()
     old_password = self.get_argument('old_password', '')
     new_password = self.get_password()
     if user.validate_password(old_password):
         user.password = new_password
         dbsession.add(user)
         dbsession.commit()
         self.clear_all_cookies()
         self.redirect('/login')
     else:
         raise ValidationError("Old password is invalid")
示例#32
0
 def __create__(cls, user, title, message, category, event_uuid, icon=None):
     ''' Create a notification and save it to the database '''
     notification = Notification(
         user_id=user.id,
         event_uuid=event_uuid,
         title=unicode(title),
         message=unicode(message),
         category=category,
     )
     if icon is not None:
         notification.icon = icon
     dbsession.add(notification)
     dbsession.commit()
 def change_password(self):
     ''' Change a password '''
     user = self.get_current_user()
     old_password = self.get_argument('old_password', '')
     new_password = self.get_password()
     if user.validate_password(old_password):
         user.password = new_password
         dbsession.add(user)
         dbsession.commit()
         self.clear_all_cookies()
         self.redirect('/login')
     else:
         raise ValidationError("Old password is invalid")
示例#34
0
 def avatar(self):
     if self._avatar is not None:
         return self._avatar
     else:
         if options.teams:
             avatar = get_new_avatar("team")
         else:
             avatar = get_new_avatar("user", True)
         if not avatar.startswith("default_"):
             self._avatar = avatar
             dbsession.add(self)
             dbsession.commit()
         return avatar
示例#35
0
 def __anonymous__(cls, title, message, category, event_uuid, icon=None):
     ''' Creates anonysmous notification where user_id = NULL '''
     notification = Notification(
         user_id=None,
         event_uuid=event_uuid,
         title=unicode(title),
         message=unicode(message),
         category=category,
     )
     if icon is not None:
         notification.icon = icon
     dbsession.add(notification)
     dbsession.commit()
示例#36
0
 def avatar(self):
     if self._avatar is not None:
         return self._avatar
     else:
         if options.teams:
             avatar = get_new_avatar('team')
         else:
             avatar = get_new_avatar('user', True)
         if not avatar.startswith("default_"):
             self._avatar = avatar
             dbsession.add(self)
             dbsession.commit()
         return avatar
示例#37
0
 def __create__(cls, user, title, message, category, event_uuid, icon=None):
     ''' Create a notification and save it to the database '''
     notification = Notification(
         user_id=user.id,
         event_uuid=event_uuid,
         title=unicode(title),
         message=unicode(message),
         category=category,
     )
     if icon is not None:
         notification.icon = icon
     dbsession.add(notification)
     dbsession.commit()
示例#38
0
def add_wordlist():
    if options.name is None:
        logging.critical("You must provide a name with --name")
        os._exit(1)
    if options.path is None:
        logging.critical("You must provide a path with --path")
        os._exit(1)
    try:
        wordlist = Wordlist(name=options.name, path=options.path)
        dbsession.add(wordlist)
        dbsession.commit()
    except ValidationError as error:
        logging.error("Failed to add wordlist: %s" % error)
示例#39
0
 def __anonymous__(cls, title, message, category, event_uuid, icon=None):
     ''' Creates anonysmous notification where user_id = NULL '''
     notification = Notification(
         user_id=None,
         event_uuid=event_uuid,
         title=unicode(title),
         message=unicode(message),
         category=category,
     )
     if icon is not None:
         notification.icon = icon
     dbsession.add(notification)
     dbsession.commit()
def add_wordlist():
    if options.name is None:
        logging.critical("You must provide a name with --name")
        os._exit(1)
    if options.path is None:
        logging.critical("You must provide a path with --path")
        os._exit(1)
    try:
        wordlist = Wordlist(name=options.name, path=options.path)
        dbsession.add(wordlist)
        dbsession.commit()
    except ValidationError as error:
        logging.error("Failed to add wordlist: %s" % error)
示例#41
0
 def setUp(self):
     self.box, self.corp = create_box()
     self.static_flag = Flag.create_flag(
         _type=FLAG_STATIC,
         box=self.box,
         name="Static Flag",
         raw_token="statictoken",
         description="A static test token",
         value=100,
     )
     self.regex_flag = Flag.create_flag(
         _type=FLAG_REGEX,
         box=self.box,
         name="Regex Flag",
         raw_token="(f|F)oobar",
         description="A regex test token",
         value=200,
     )
     self.file_flag = Flag.create_flag(
         _type=FLAG_FILE,
         box=self.box,
         name="File Flag",
         raw_token="fdata",
         description="A file test token",
         value=300,
     )
     self.choice_flag = Flag.create_flag(
         _type=FLAG_CHOICE,
         box=self.box,
         name="Choice Flag",
         raw_token="fdata",
         description="A choice test token",
         value=400,
     )
     self.datetime_flag = Flag.create_flag(
         _type=FLAG_DATETIME,
         box=self.box,
         name="Datetime Flag",
         raw_token="2018-06-22 18:00:00",
         description="A datetime test token",
         value=500,
     )
     
     dbsession.add(self.static_flag)
     dbsession.add(self.regex_flag)
     dbsession.add(self.file_flag)
     dbsession.add(self.choice_flag)
     dbsession.add(self.datetime_flag)
     dbsession.commit()
示例#42
0
 def do_chpass(self, username):
     """
     Change a user's password
     Usage: reset <handle>
     """
     user = User.by_handle(username)
     if user is None:
         print(WARN + "'%s' user not found in database." % username)
     else:
         sys.stdout.write(PROMPT + "New ")
         sys.stdout.flush()
         user.password = getpass.getpass()
         dbsession.add(user)
         dbsession.commit()
         print(INFO + "Updated %s password successfully." % user.handle)
示例#43
0
 def do_grant(self, username):
     '''
     Add user permissions
     Usage: grant <handle>
     '''
     user = User.by_handle(username)
     if user is None:
         print(WARN + "'%s' user not found in database." % username)
     else:
         name = raw_input(PROMPT + "Add permission: ")
         permission = Permission(name=unicode(name), user_id=user.id)
         dbsession.add(permission)
         dbsession.add(user)
         dbsession.commit()
         print(INFO + "Successfully granted %s permissions to %s." % (name, user.handle,))
示例#44
0
 def do_mkteam(self, nop):
     '''
     Make a new team.
     Usage: mkteam
     '''
     try:
         team = Team(
             name=unicode(raw_input(PROMPT + "Team name: ")),
             motto=unicode(raw_input(PROMPT + "Team motto: ")),
         )
         dbsession.add(team)
         dbsession.commit()
         print(INFO + "Successfully created new team.")
     except:
         print(WARN + "Failed to create new team.")
示例#45
0
 def do_mkteam(self, nop):
     """
     Make a new team.
     Usage: mkteam
     """
     try:
         team = Team(
             name=unicode(raw_input(PROMPT + "Team name: ")),
             motto=unicode(raw_input(PROMPT + "Team motto: ")),
         )
         dbsession.add(team)
         dbsession.commit()
         print(INFO + "Successfully created new team.")
     except:
         print(WARN + "Failed to create new team.")
示例#46
0
 def do_chpass(self, username):
     '''
     Change a user's password
     Usage: reset <handle>
     '''
     user = User.by_handle(username)
     if user is None:
         print(WARN + "'%s' user not found in database." % username)
     else:
         sys.stdout.write(PROMPT + "New ")
         sys.stdout.flush()
         user.password = getpass.getpass()
         dbsession.add(user)
         dbsession.commit()
         print(INFO + "Updated %s password successfully." % user.handle)
示例#47
0
 def push_user(self, team_id, user_id):
     ''' Push all unread notifications to open user websockets '''
     connections = self.get_user_connections(team_id, user_id)
     notifications = Notification.unread_by_user_id(user_id)
     logging.debug("User #%s has %d unread notification(s)" % (
         user_id, len(notifications)
     ))
     for notification in notifications:
         for connection in connections:
             self.safe_write_message(connection,
                                     notification.to_dict()
                                     )
         notification.viewed = True
         dbsession.add(notification)
     dbsession.commit()
示例#48
0
 def avatar(self):
     if self._avatar is not None:
         return self._avatar
     else:
         if not options.teams:
             avatar = default_avatar('user')
         elif self.has_permission(ADMIN_PERMISSION):
             avatar = default_avatar('user')
         else:
             avatar = get_new_avatar('user')
             if not avatar.startswith("default_"):
                 self._avatar = avatar
                 dbsession.add(self)
                 dbsession.commit()
         return avatar
示例#49
0
 def avatar(self):
     if self._avatar is not None:
         return self._avatar
     else:
         if not options.teams:
             avatar = default_avatar('user')
         elif self.is_admin():
             avatar = default_avatar('user')
         else:
             avatar = get_new_avatar('user')
             if not avatar.startswith("default_"):
                 self._avatar = avatar
                 dbsession.add(self)
                 dbsession.commit()
         return avatar
示例#50
0
def create_categories(categories):
    """ Create Category objects based on XML data """
    if categories is None:
        return
    logging.info("Found %s categories" % categories.get("count"))
    for index, cat_elem in enumerate(categories):
        cat = get_child_text(cat_elem, "category")
        if Category.by_category(cat) is None:
            try:
                category = Category()
                category.category = cat
                dbsession.add(category)
            except:
                logging.exception("Failed to import category #%d" %
                                  (index + 1))
    dbsession.commit()
示例#51
0
def _xml_file_import(filename):
    ''' Parse and import a single XML file '''
    logging.debug("Processing: %s" % filename)
    try:
        tree = ET.parse(filename)
        xml_root = tree.getroot()
        levels = get_child_by_tag(xml_root, "gamelevels")
        create_levels(levels)
        corporations = get_child_by_tag(xml_root, "corporations")
        create_corps(corporations)
        logging.debug("Done processing: %s" % filename)
        dbsession.commit()
        return True
    except:
        dbsession.rollback()
        logging.exception("Exception raised while parsing %s, rolling back changes" % filename)
        return False
def __create_index(path):
    ''' Adds a given index to the database '''
    try:
        wordlist = Wordlist.by_name(options.name)
        if wordlist is None:
            raise ValidationError("Wordlist with name '%s' does not exist" % (
                options.name
            ))
        algorithm_key = options.algorithm
        if algorithm_key is None:
            algorithm_key = __determine_algorithm(wordlist.path, path)
        if algorithm_key is not None:
            idx = WordlistIndex(wordlist_id=wordlist.id,
                                algorithm=algorithm_key,
                                path=path)
            dbsession.add(idx)
            dbsession.commit()
    except ValidationError as error:
        logging.error("Failed to add index '%s', %s" % (path, error))
示例#53
0
 def do_mkuser(self, nop):
     '''
     Make a new user account
     Usage: mkuser
     '''
     try:
         user = User(
             handle=unicode(raw_input(PROMPT + "Handle: ")),
         )
         dbsession.add(user)
         dbsession.flush()
         sys.stdout.write(PROMPT + "New ")
         sys.stdout.flush()
         user.password = getpass.getpass()
         dbsession.add(user)
         dbsession.commit()
         print(INFO + "Successfully created new account.")
     except:
         print(WARN + "Failed to create new account.")
示例#54
0
 def do_strip(self, username):
     '''
     Strip a user of all permissions
     Usage: strip <handle>
     '''
     user = User.by_handle(username)
     if user is None:
         print(WARN + "'%s' user not found in database." % username)
     else:
         username = user.handle
         permissions = Permission.by_user_id(user.id)
         if len(permissions) == 0:
             print(WARN + "%s has no permissions." % user.handle)
         else:
             for perm in permissions:
                 print(INFO + "Removing permission: " + perm.name)
                 dbsession.delete(perm)
         dbsession.commit()
         print(INFO + "Successfully removed %s's permissions." % user.handle)
示例#55
0
 def do_rmuser(self, username):
     '''
     Delete a user from the database
     Usage: delete <handle>
     '''
     user = User.by_handle(username)
     if user is None:
         print(WARN + "'%s' user not found in database." % username)
     else:
         username = user.handle
         print(WARN + str("Are you sure you want to delete %s?" % username))
         if raw_input(PROMPT + "Delete [y/n]: ").lower() == 'y':
             permissions = Permission.by_user_id(user.id)
             for perm in permissions:
                 print(INFO + "Removing permission: " + perm.name)
                 dbsession.delete(perm)
             dbsession.flush()
             dbsession.delete(user)
             dbsession.commit()
             print(INFO + "Successfully deleted %s from database." % username)
示例#56
0
 def do_chteam(self, username):
     '''
     Change a user's team
     Usage: chteam <handle>
     '''
     user = User.by_handle(username)
     if user is None:
         print(WARN + "'%s' user not found in database." % username)
     else:
         print(INFO + "Available teams:")
         for team in Team.all():
             print(" %d. %s" % (team.id, team.name))
         team_id = raw_input(PROMPT + "Set user's team to: ")
         team = Team.by_id(team_id)
         if team is not None:
             user.team_id = team.id
             dbsession.add(user)
             dbsession.commit()
             print(INFO + "Successfully changed %s's team to %s." % (user.handle, team.name))
         else:
             print(WARN + "Team does not exist.")
示例#57
0
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.info("%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()
    dbsession.commit()
def boot_strapper():
    # Fills the database with some startup data.
    _password = ""

    if options.setup.startswith('dev'):
        admin_user = u'admin'
        _password = '******'
    else:
        admin_user = unicode(raw_input(PROMPT + "Admin username: "******"New Admin ")
        sys.stdout.flush()
        _password1 = getpass.getpass()
        sys.stdout.write(PROMPT + "Confirm New Admin ")
        sys.stdout.flush()
        _password2 = getpass.getpass()
        if _password1 == _password2 and 12 <= len(_password1):
            _password = _password1
        else:
            print(WARN +
                  'Error: Passwords did not match, or were less than 12 chars')
            os._exit(1)

    user = User(name=admin_user, password=_password)
    dbsession.add(user)
    dbsession.flush()
    admin_permission = Permission(name=ADMIN_PERMISSION, user_id=user.id)
    user.permissions.append(admin_permission)
    dbsession.add(admin_permission)
    dbsession.add(user)
    dbsession.commit()

    # Display Details
    if options.setup.startswith('dev'):
        environ = bold + R + "Developement boot strap" + W
        details = ", default admin password is '%s'." % _password
    else:
        environ = bold + "Production boot strap" + W
        details = '.'
    print INFO + '%s completed successfully%s' % (environ, details)
示例#59
0
item = MarketItem(
    name=u"SWAT",
    price=3000,
    image=u"swat.png",
    description=u"Gain access to the internal police computer system, allowing you to insert fraudlent arrest warrents for other players.",
)
dbsession.add(item)
dbsession.flush()

# Game Levels
game_level = GameLevel(
    number=0,
    buyout=0,
)
dbsession.add(game_level)
dbsession.flush()

# Admin User Account
admin_user = User(handle=admin_handle)
admin_user.password = password
dbsession.add(admin_user)
dbsession.flush()

admin_permission = Permission(
    name=ADMIN_PERMISSION,
    user_id=admin_user.id
)
dbsession.add(admin_permission)
dbsession.commit()