def create_award(): try: teamid = request.form['teamid'] name = request.form.get('name', 'Award') value = request.form.get('value', 0) award = Awards(teamid, name, value) award.description = request.form.get('description') award.category = request.form.get('category') db.session.add(award) db.session.commit() return "1" except Exception as e: print e return "0"
def create_award(): try: teamid = request.form['teamid'] name = request.form.get('name', 'Award') value = request.form.get('value', 0) award = Awards(teamid, name, value) award.description = request.form.get('description') award.category = request.form.get('category') db.session.add(award) db.session.commit() db.session.close() return '1' except Exception as e: print(e) return '0'
def attempt(chal, request): # print(f"Essai ::: {chal.id} {chal.type}") data = request.form or request.get_json() submission = data["submission"].strip() flags = Flags.query.filter_by(challenge_id=chal.id).all() user = Users.query.filter_by(id=session['id']).first() sub = Submissions.query.filter_by( challenge_id=chal.id, provided=submission, team_id=user.team_id if user else None).all() if (len(sub) > 0): return False, "Pas de doublons ici" # print(f"{session['id']}") # print(f"Keys {chal.value}") for flag in flags: try: # print(f">> {flag.data} {flag.content}") if (flag.content == submission): award = Awards(user_id=session['id'], team_id=user.team_id if user else None, name=chal.name, description=flag.comments, value=chal.value, category=chal.category, icon="crosshairs") db.session.add(award) db.session.commit() return True, "Bingo" except: e = sys.exc_info()[0] print(e) return False, 'Error' award = Awards(user_id=session['id'], team_id=user.team_id if user else None, name=chal.name, description="Echec", value=chal.value * -1, icon="ban", category=chal.category) db.session.add(award) db.session.commit() return False, f"Incorrect ( -{chal.value})"
def solve(team, chal, request): """ This method is used to insert Solves into the database in order to mark a challenge as solved. :param team: The Team object from the database :param chal: The Challenge object from the database :param request: The request the user submitted :return: """ chal = FirstBloodChallenges.query.filter_by(id=chal.id).first() solve_count = Solves.query.join(Teams, Solves.teamid == Teams.id).filter( Solves.chalid == chal.id, Teams.banned == False).count() if solve_count == 0: name = 'First Blood ({})'.format(chal.name) db.session.add(Awards(team.id, name, chal.bonus)) provided_key = request.form['key'].strip() solve = Solves(teamid=team.id, chalid=chal.id, ip=utils.get_ip(req=request), flag=provided_key) db.session.add(solve) db.session.commit() db.session.close()
def solve(team, chal, request): """ This method is used to insert Solves into the database in order to mark a challenge as solved. :param team: The Team object from the database :param chal: The Challenge object from the database :param request: The request the user submitted :return: """ chal = CommunityChallengeModel.query.filter_by(id=chal.id).first() solve_count = Solves.query.join(Teams, Solves.teamid == Teams.id).filter( Solves.chalid == chal.id, Teams.banned == False).count() # if this is the first validation, we give the bonus points to the chal's owner if solve_count == 0: award = Awards( teamid=chal.owner, name=text_type( 'Bonus points for submitting challenge {}'.format( chal.name)), value=chal.value) db.session.add(award) provided_key = request.form['key'].strip() solve = Solves(teamid=team.id, chalid=chal.id, ip=utils.get_ip(req=request), flag=provided_key) db.session.add(solve) db.session.commit() db.session.close()
def patch(self, submission_id): submission = Submissions.query.filter_by( id=submission_id).first_or_404() challenges = Challenges.query.filter_by( id=submission.challenge_id).first_or_404() #challenges.value = challenges.value - 1 #Need to award points awards = Awards( user_id=submission.user_id, team_id=submission.team_id, description=submission.provided, value=1, category=submission.challenge_id, ) submission.type = 'correct' log('submission', "[{date}] {name} submitted {submission} with TYPE {kpm}, Challeng ID {tpm} ", submission=submission.id, kpm=submission.type, tpm=submission.challenge_id) solve = Solves(user_id=submission.user_id, team_id=submission.team_id, challenge_id=submission.challenge_id, ip=submission.ip, provided=submission.provided) db.session.add(awards) db.session.add(solve) db.session.delete(submission) db.session.commit() db.session.close() return { 'success': True, }
def attempt(chal, request): """ This method is used to check whether a given input is right or wrong. It does not make any changes and should return a boolean for correctness and a string to be shown to the user. It is also in charge of parsing the user's input from the request itself. :param chal: The Challenge object from the database :param request: The request the user submitted :return: (boolean, string) """ provided_key = request.form['key'].strip() # Compare our hash with the hash of their provided key if chal.current_hash == get_hash(provided_key): # TODO? add the key to a publicly available list of previous keys/solves # TODO? allow [REGEX] to be replaced in a hint by the current key creation rules solves = Awards.query.filter_by( teamid=session['id'], name=chal.id, description=request.form['key'].strip()).first() chal.king = session['id'] king_name = _team_name(chal.king) # TODO check if it is time to advance to the next difficulty level/regex key = generate_key(chal.regex, chal.id) logger.debug("Generated key '{}' for challenge '{}'".format( key, chal.name)) chal.current_hash = get_hash(key) # Challenge not solved yet, give the team first capture points if not solves: solve = Awards(teamid=session['id'], name=chal.id, value=chal.value) solve.description = provided_key db.session.add(solve) logger.debug( 'First capture, {} points awarded. "{}" will receive {} points every {} minutes"' .format(chal.value, king_name, chal.hold, chal.cycles)) logger.debug( 'Another capture, "{}" is now King of the hill and will receive {} points every {} minutes' .format(king_name, chal.hold, chal.cycles)) db.session.commit() db.session.close() return True, 'Correct, "{}" is now king of the hill!'.format( king_name) db.session.close() return False, 'Incorrect, "{}" remains the king'.format( _team_name(chal.king))
def hints_view_contest(contestid, hintid): contest = Contests.query.filter_by(id=contestid).first() if not utils.ctf_started(contest=contest): abort(403) hint = Hints.query.filter_by(id=hintid).first_or_404() chal = Challenges.query.filter_by(id=hint.chal).first() unlock = Unlocks.query.filter_by(model='hints', itemid=hintid, teamid=session['id']).first() if request.method == 'GET': if unlock: return jsonify({ 'hint': hint.hint, 'chal': hint.chal, 'cost': hint.cost }) else: return jsonify({'chal': hint.chal, 'cost': hint.cost}) elif request.method == 'POST': if not unlock and utils.ctftime(contest=contest): team = Teams.query.filter_by(id=session['id']).first() if team.score() < hint.cost: return jsonify({'errors': 'Not enough points'}) unlock = Unlocks(model='hints', teamid=session['id'], itemid=hint.id) award = Awards(teamid=session['id'], name='Hint for {}'.format(chal.name), value=(-hint.cost), contestid=contestid) db.session.add(unlock) db.session.add(award) db.session.commit() json_data = { 'hint': hint.hint, 'chal': hint.chal, 'cost': hint.cost } db.session.close() return jsonify(json_data) elif utils.ctf_ended(contest=contest): json_data = { 'hint': hint.hint, 'chal': hint.chal, 'cost': hint.cost } db.session.close() return jsonify(json_data) else: json_data = { 'hint': hint.hint, 'chal': hint.chal, 'cost': hint.cost } db.session.close() return jsonify(json_data)
def add(self, chal_key): """ Adds an award, corresponding to the chal_key in parameters. Does not check if an award for this chal_key and this team has already been given. It has to be done before. :chal_key: an object returned by a query on the Keys Model. :return: award_score. The points associated to the interm-award. (Can be negative). """ # REC FUTURE : check if the key in param is a key of the challenge. key_infos = json.loads(chal_key.data) award_score = key_infos['award'] award_name = 'plugin_intermflag_%s_%s' % (self.chal_id, chal_key.id) award = Awards(teamid=self.team_id, name=award_name, value=award_score) award.description = "Plug-in intermediate flag. TODO fill that later." db.session.add(award) db.session.commit() return award_score
def hints_view(hintid): if utils.ctf_started() is False: if utils.is_admin() is False: abort(403) hint = Hints.query.filter_by(id=hintid).first_or_404() chal = Challenges.query.filter_by(id=hint.chal).first() unlock = Unlocks.query.filter_by(model='hints', itemid=hintid, teamid=session['id']).first() if request.method == 'GET': if unlock: return jsonify({ 'hint': hint.hint, 'chal': hint.chal, 'cost': hint.cost }) else: return jsonify({'chal': hint.chal, 'cost': hint.cost}) elif request.method == 'POST': if unlock is None: # The user does not have an unlock. if utils.ctftime() or ( utils.ctf_ended() and utils.view_after_ctf()) or utils.is_admin() is True: # It's ctftime or the CTF has ended (but we allow views after) team = Teams.query.filter_by(id=session['id']).first() if team.score() < hint.cost: return jsonify({'errors': get_tip('NOT_ENOUGH_POINT')}) unlock = Unlocks(model='hints', teamid=session['id'], itemid=hint.id) award = Awards(teamid=session['id'], name=text_type( get_tip('HIT_FOR').format(chal.name)), value=(-hint.cost)) db.session.add(unlock) db.session.add(award) db.session.commit() json_data = { 'hint': hint.hint, 'chal': hint.chal, 'cost': hint.cost } db.session.close() return jsonify(json_data) elif utils.ctf_ended(): # The CTF has ended. No views after. abort(403) else: # The user does have an unlock, we should give them their hint. json_data = { 'hint': hint.hint, 'chal': hint.chal, 'cost': hint.cost } db.session.close() return jsonify(json_data)
def solve(user, team, challenge, request): """ This method is used to insert Solves into the database in order to mark a challenge as solved. :param team: The Team object from the database :param chal: The Challenge object from the database :param request: The request the user submitted :return: """ challenge = GuessPenaltyChallenge.query.filter_by( id=challenge.id).first() data = request.form or request.get_json() submission = data["submission"].strip() Model = get_model() solve = Solves( user_id=user.id, team_id=team.id if team else None, challenge_id=challenge.id, ip=get_ip(req=request), provided=submission, ) # Issue penalty award fail_count = (Fails.query.join(Model, Fails.account_id == Model.id).filter( Fails.challenge_id == challenge.id, Model.hidden == False, Model.banned == False, ).count()) value = (((challenge.minimum - challenge.initial) / (challenge.decay**2)) * (fail_count**2)) + challenge.initial value = math.ceil(value) if value < challenge.minimum: value = challenge.minimum value = value - challenge.initial penalty = Awards(user_id=user.id, team_id=team.id if team else None, name="FAIL Penalty: %s" % challenge.name, description="Penalty for incorrect attempts", value=value, category=challenge.category, icon="") # Commit to database db.session.add(solve) db.session.add(penalty) db.session.commit()
def attempt(chal, request): """ This method is used to check whether a given input is right or wrong. It does not make any changes and should return a boolean for correctness and a string to be shown to the user. It is also in charge of parsing the user's input from the request itself. :param chal: The Challenge object from the database :param request: The request the user submitted :return: (boolean, string) """ provided_key = request.form['key'].strip() chal_keys = Keys.query.filter_by(chal=chal.id).all() for chal_key in chal_keys: if get_key_class(chal_key.type).compare(chal_key.flag, provided_key): if chal_key.type == "correct": solves = Awards.query.filter_by(teamid=session['id'], name=chal.id, description=request.form['key'].strip()).first() try: flag_value = solves.description except AttributeError: flag_value = "" # Challenge not solved yet if provided_key != flag_value or not solves: solve = Awards(teamid=session['id'], name=chal.id, value=chal.value) solve.description = provided_key db.session.add(solve) db.session.commit() db.session.close() return True, 'Correct' # TODO Add description function call to the end of "Correct" in return elif chal_key.type == "wrong": solves = Awards.query.filter_by(teamid=session['id'], name=chal.id, description=request.form['key'].strip()).first() try: flag_value = solves.description except AttributeError: flag_value = "" # Challenge not solved yet if provided_key != flag_value or not solves: wrong_value = 0 wrong_value -= chal.value wrong = WrongKeys(teamid=session['id'], chalid=chal.id, ip=utils.get_ip(request), flag=provided_key) solve = Awards(teamid=session['id'], name=chal.id, value=wrong_value) solve.description = provided_key db.session.add(wrong) db.session.add(solve) db.session.commit() db.session.close() return False, 'Error' # TODO Add description function call to the end of "Error" in return return False, 'Incorrect'
def attempt(chal, request): """Attempt the user answer to see if it's right""" provided_key = request.form['key'].strip() chal_keys = Keys.query.filter_by(chal=chal.id).all() yara_results = yara_rule_tester(provided_key) result_type = {} for result in yara_results: solves = Awards.query.filter_by( teamid=session['id'], name=chal.id, description=result.strip()).first() try: flag_value = str(solves.description) except AttributeError: flag_value = "" if result != flag_value and not solves: for chal_key in chal_keys: if result == chal_key.flag: result_type[result] = chal_key.type # Challenge not solved yet if result_type[result] == "correct": solve = Awards(teamid=session['id'], name=chal.id, value=chal.value) solve.description = result db.session.add(solve) db.session.commit() elif result_type[result] == "wrong": wrong_value = 0 wrong_value -= chal.value wrong = WrongKeys(teamid=session['id'], chalid=chal.id, ip=utils.get_ip(request), flag=result) solve = Awards(teamid=session['id'], name=chal.id, value=wrong_value) solve.description = result db.session.add(wrong) db.session.add(solve) db.session.commit() db.session.close() return False, "Nothing"
def gen_award(db, user_id, team_id=None, name="award_name", value=100): award = Awards(user_id=user_id, team_id=team_id, name=name, value=value) award.date = datetime.datetime.utcnow() db.session.add(award) db.session.commit() return award
solve = Solves(x + 1, chalid, '127.0.0.1', gen_word()) new_base = random_date(base_time, base_time + datetime.timedelta(minutes=random.randint(30, 60))) solve.date = new_base base_time = new_base db.session.add(solve) db.session.commit() # Generating Awards print("GENERATING AWARDS") for x in range(USER_AMOUNT): base_time = datetime.datetime.utcnow() + datetime.timedelta(minutes=-10000) for _ in range(random.randint(0, AWARDS_AMOUNT)): award = Awards(x + 1, gen_word(), random.randint(-10, 10)) new_base = random_date(base_time, base_time + datetime.timedelta(minutes=random.randint(30, 60))) award.date = new_base base_time = new_base db.session.add(award) db.session.commit() # Generating Wrong Keys print("GENERATING WRONG KEYS") for x in range(USER_AMOUNT): used = [] base_time = datetime.datetime.utcnow() + datetime.timedelta(minutes=-10000) for y in range(random.randint(1, CHAL_AMOUNT * 20)): chalid = random.randint(1, CHAL_AMOUNT)
used_teams.append((chalid, team.id)) used_users.append((chalid, user_id)) db.session.commit() # Generating Awards print("GENERATING AWARDS") for x in range(USER_AMOUNT): base_time = datetime.datetime.utcnow() + datetime.timedelta( minutes=-10000) for _ in range(random.randint(0, AWARDS_AMOUNT)): user = Users.query.filter_by(id=x + 1).first() award = Awards( user_id=user.id, team_id=user.team_id, name=gen_word(), value=random.randint(-10, 10), icon=gen_icon(), ) new_base = random_date( base_time, base_time + datetime.timedelta(minutes=random.randint(30, 60)), ) award.date = new_base base_time = new_base db.session.add(award) db.session.commit()
def attempt(cls, chal, request): """ This method is used to check whether a given input is right or wrong. It does not make any changes and should return a boolean for correctness and a string to be shown to the user. It is also in charge of parsing the user's input from the request itself. :param chal: The Challenge object from the database :param request: The request the user submitted :return: (boolean, string) """ data = request.form or request.get_json() submission = data["submission"].strip() flags = Flags.query.filter_by(challenge_id=challenge.id).all() for flag in flags: try: if get_flag_class(flag.type).compare(flag, submission): if flag.type == "correct": solves = Awards.query.filter_by( teamid=session['id'], name=chal.id, description=submission).first() try: flag_value = solves.description except AttributeError: flag_value = "" # Challenge not solved yet if submission != flag_value or not solves: solve = Awards(teamid=session['id'], name=chal.id, value=chal.value) solve.description = submission db.session.add(solve) db.session.commit() db.session.close() return True, 'Correct' # TODO Add description function call to the end of "Correct" in return elif flag.type == "wrong": solves = Awards.query.filter_by( teamid=session['id'], name=chal.id, description=submission).first() try: flag_value = solves.description except AttributeError: flag_value = "" # Challenge not solved yet if submission != flag_value or not solves: fail_value = 0 fail_value -= chal.value fail = Fails(teamid=session['id'], chalid=chal.id, ip=utils.get_ip(request), flag=submission) solve = Awards(teamid=session['id'], name=chal.id, value=fail_value) solve.description = submission db.session.add(fail) db.session.add(solve) db.session.commit() db.session.close() return False, 'Error' # TODO Add description function call to the end of "Error" in return except FlagException as e: return False, e.message return False, 'Incorrect'
solve = Solves(chalid, x + 1, '127.0.0.1', gen_word()) new_base = random_date(base_time, base_time + datetime.timedelta(minutes=random.randint(30, 60))) solve.date = new_base base_time = new_base db.session.add(solve) db.session.commit() # Generating Awards print("GENERATING AWARDS") for x in range(USER_AMOUNT): base_time = datetime.datetime.utcnow() + datetime.timedelta(minutes=-10000) for _ in range(random.randint(0, AWARDS_AMOUNT)): award = Awards(x + 1, gen_word(), random.randint(-10, 10)) new_base = random_date(base_time, base_time + datetime.timedelta(minutes=random.randint(30, 60))) award.date = new_base base_time = new_base db.session.add(award) db.session.commit() # Generating Wrong Keys print("GENERATING WRONG KEYS") for x in range(USER_AMOUNT): used = [] base_time = datetime.datetime.utcnow() + datetime.timedelta(minutes=-10000) for y in range(random.randint(1, CHAL_AMOUNT * 20)): chalid = random.randint(1, CHAL_AMOUNT)