예제 #1
0
 def challenges():
     if not is_admin() and not ctftime() and not view_after_ctf():
         return redirect('/')
     if can_view_challenges():
         return render_template('chals.html', ctftime=ctftime())
     else:
         return redirect(url_for('login', next="challenges"))
예제 #2
0
파일: challenges.py 프로젝트: scr34m0/CTFd
def challenges_view():
    if not is_admin():
        if not ctftime():
            if view_after_ctf():
                pass
            else:
                return redirect('/')
    if can_view_challenges():
        return render_template('chals.html', ctftime=ctftime())
    else:
        return redirect(url_for('auth.login', next='challenges'))
예제 #3
0
파일: challenges.py 프로젝트: Evil404/CTFd
def challenges_view():
    if not is_admin():
        if not ctftime():
            if view_after_ctf():
                pass
            else:
                return redirect(url_for('views.static_html'))
        if get_config('verify_emails') and not is_verified():
            return redirect(url_for('auth.confirm_user'))
    if can_view_challenges():
        return render_template('chals.html', ctftime=ctftime())
    else:
        return redirect(url_for('auth.login', next='challenges'))
예제 #4
0
def removeconnection():
    if not ctftime():
        if view_after_ctf():
            pass
        else:
            return redirect('/')
    error = {}
    if 'evidence-name1' in request.form.keys() and 'evidence-name1' in request.form.keys():
        evidence_name1 = str(request.form['evidence-name1'])
        evidence_name2 = str(request.form['evidence-name2'])

        has_evidence_name1 = TeamEvidence.query.filter_by(teamid=session['id'], name=evidence_name1).first()
        has_evidence_name2 = TeamEvidence.query.filter_by(teamid=session['id'], name=evidence_name2).first()

        if has_evidence_name1 == None or has_evidence_name2 == None:
            if has_evidence_name1 == None:
                error["error"] = "Evidence name 1 does not exist"
            elif has_evidence_name2 == None:
                error["error"] = "Evidence name 2 does not exist"
        else:
            submitted_connections = TeamEvidenceConnection.query.filter_by(teamid=session['id'], \
                had=has_evidence_name1.id, found=has_evidence_name2.id).first()

            if submitted_connections == None:
                error["error"] = "Connection does not exist"
            else:
                db.session.delete(submitted_connections)
                db.session.commit()

    else:
        error["error"] = "No evidence given"

    return json.dumps(error)
예제 #5
0
def addevidence():
    if not ctftime():
        if view_after_ctf():
            pass
        else:
            return redirect('/')

    error = {}
    if 'flag' in request.form.keys():
        flag = str(request.form['flag'])
        try:
            print flag
        except:
            pass
        submitted_flags = TeamEvidence.query.filter_by(teamid=session['id'], name=flag).first()
        actual_flags = Evidence.query.filter_by(flag=flag).first()

        if submitted_flags != None:
            error["error"] = "Already submitted flag"
        elif actual_flags == None:
            error["error"] = "Incorrect flag given"
            error["confirm"] = "confirm"
        else:
            new_evidence = TeamEvidence(session["id"], actual_flags.name, 1)
            db.session.add(new_evidence)
            db.session.commit()
    else:
        error["error"] = "No name or flag given"

    return json.dumps(error)
예제 #6
0
def challenges_view():
    errors = []
    start = utils.get_config('start') or 0
    end = utils.get_config('end') or 0
    if not utils.is_admin():  # User is not an admin
        if not utils.ctftime():
            # It is not CTF time
            if utils.view_after_ctf():  # But we are allowed to view after the CTF ends
                pass
            else:  # We are NOT allowed to view after the CTF ends
                if utils.get_config('start') and not utils.ctf_started():
                    errors.append('{} has not started yet'.format(utils.ctf_name()))
                if (utils.get_config('end') and utils.ctf_ended()) and not utils.view_after_ctf():
                    errors.append('{} has ended'.format(utils.ctf_name()))
                return render_template('chals.html', errors=errors, start=int(start), end=int(end))
        if utils.get_config('verify_emails') and not utils.is_verified():  # User is not confirmed
            return redirect(url_for('auth.confirm_user'))
    if utils.user_can_view_challenges():  # Do we allow unauthenticated users?
        if utils.get_config('start') and not utils.ctf_started():
            errors.append('{} has not started yet'.format(utils.ctf_name()))
        if (utils.get_config('end') and utils.ctf_ended()) and not utils.view_after_ctf():
            errors.append('{} has ended'.format(utils.ctf_name()))
        return render_template('chals.html', errors=errors, start=int(start), end=int(end))
    else:
        return redirect(url_for('auth.login', next='challenges'))
예제 #7
0
파일: challenges.py 프로젝트: MaiPhuoc/CTFd
 def challenges():
     if not ctftime():
         return redirect("/")
     if can_view_challenges():
         return render_template("chals.html")
     else:
         return redirect(url_for("login", next="challenges"))
예제 #8
0
def removeevidence():
    if not ctftime():
        if view_after_ctf():
            pass
        else:
            return redirect('/')
    error = {}
    if 'evidence-name' in request.form.keys():
        evidence_name = str(request.form['evidence-name'])
        submitted_flags = TeamEvidence.query.filter_by(teamid=session['id'], name=evidence_name).first()
        submitted_connections = TeamEvidenceConnection.query.filter(and_(\
            or_(TeamEvidenceConnection.had == evidence_name, TeamEvidenceConnection.found == evidence_name \
                ), TeamEvidenceConnection.teamid == session['id'])).all()

        if submitted_flags == None:
            error["error"] = "Evidence does not exist"
        else:
            db.session.delete(submitted_flags)
            for c in submitted_connections:
                db.session.delete(c)
            db.session.commit()

    else:
        error["error"] = "No name or flag given"

    return json.dumps(error)
예제 #9
0
파일: views.py 프로젝트: semprix/CTFIgniter
def file_handler(path):
    f = Files.query.filter_by(location=path).first_or_404()
    if f.chal:
        if not utils.is_admin():
            if not utils.ctftime():
                if utils.view_after_ctf() and utils.ctf_started():
                    pass
                else:
                    abort(403)
    upload_folder = os.path.join(app.root_path, app.config['UPLOAD_FOLDER'])
    return send_file(safe_join(upload_folder, f.location))
예제 #10
0
파일: challenges.py 프로젝트: MaiPhuoc/CTFd
    def chal(chalid):
        if not ctftime():
            return redirect("/")
        if authed():
            logger = logging.getLogger("keys")
            data = (
                time.strftime("%m/%d/%Y %X"),
                session["username"].encode("utf-8"),
                request.form["key"].encode("utf-8"),
                get_kpm(session["id"]),
            )
            print "[{0}] {1} submitted {2} with kpm {3}".format(*data)
            if get_kpm(session["id"]) > 10:
                wrong = WrongKeys(session["id"], chalid, request.form["key"])
                db.session.add(wrong)
                db.session.commit()
                db.session.close()
                logger.warn("[{0}] {1} submitted {2} with kpm {3} [TOO FAST]".format(*data))
                return "3"  # Submitting too fast
            solves = Solves.query.filter_by(teamid=session["id"], chalid=chalid).first()
            if not solves:
                keys = Keys.query.filter_by(chal=chalid).all()
                key = request.form["key"].strip().lower()
                for x in keys:
                    if x.key_type == 0:  # static key
                        if x.flag.strip().lower() == key:
                            solve = Solves(chalid=chalid, teamid=session["id"], ip=request.remote_addr)
                            db.session.add(solve)
                            db.session.commit()
                            db.session.close()
                            logger.info("[{0}] {1} submitted {2} with kpm {3} [CORRECT]".format(*data))
                            return "1"  # key was correct
                    elif x.key_type == 1:  # regex
                        res = re.match(str(x), key, re.IGNORECASE)
                        if res and res.group() == key:
                            solve = Solves(chalid=chalid, teamid=session["id"], ip=request.remote_addr)
                            db.session.add(solve)
                            db.session.commit()
                            db.session.close()
                            logger.info("[{0}] {1} submitted {2} with kpm {3} [CORRECT]".format(*data))
                            return "1"  # key was correct

                wrong = WrongKeys(session["id"], chalid, request.form["key"])
                db.session.add(wrong)
                db.session.commit()
                db.session.close()
                logger.info("[{0}] {1} submitted {2} with kpm {3} [WRONG]".format(*data))
                return "0"  # key was wrong
            else:
                logger.info("{0} submitted {1} with kpm {2} [ALREADY SOLVED]".format(*data))
                return "2"  # challenge was already solved
        else:
            return "-1"
예제 #11
0
파일: challenges.py 프로젝트: remasis/CTFd
def chal(chalid):
    if not ctftime():
        return redirect('/challenges')
    if authed():
        fails = WrongKeys.query.filter_by(team=session['id'],chal=chalid).count()
        logger = logging.getLogger('keys')
        data = (time.strftime("%m/%d/%Y %X"), session['username'].encode('utf-8'), request.form['key'].encode('utf-8'), get_kpm(session['id']))
        print "[{0}] {1} submitted {2} with kpm {3}".format(*data)
        if fails >= int(get_config("max_tries")) and int(get_config("max_tries")) > 0:
            return "4" #too many tries on this challenge
        if get_kpm(session['id']) > 10:
            wrong = WrongKeys(session['id'], chalid, request.form['key'])
            db.session.add(wrong)
            db.session.commit()
            db.session.close()
            logger.warn("[{0}] {1} submitted {2} with kpm {3} [TOO FAST]".format(*data))
            return "3" # Submitting too fast
        solves = Solves.query.filter_by(teamid=session['id'], chalid=chalid).first()
        if not solves:
            keys = Keys.query.filter_by(chal=chalid).all()
            key = request.form['key'].strip().lower()
            for x in keys:
                if x.key_type == 0: #static key
                    if x.flag.strip().lower() == key:
                        solve = Solves(chalid=chalid, teamid=session['id'], ip=request.remote_addr, flag=key)
                        db.session.add(solve)
                        db.session.commit()
                        db.session.close()
                        logger.info("[{0}] {1} submitted {2} with kpm {3} [CORRECT]".format(*data))
                        return "1" # key was correct
                elif x.key_type == 1: #regex
                    res = re.match(str(x), key, re.IGNORECASE)
                    if res and res.group() == key:
                        solve = Solves(chalid=chalid, teamid=session['id'], ip=request.remote_addr, flag=key)
                        db.session.add(solve)
                        db.session.commit()
                        db.session.close()
                        logger.info("[{0}] {1} submitted {2} with kpm {3} [CORRECT]".format(*data))
                        return "1" # key was correct

            wrong = WrongKeys(session['id'], chalid, request.form['key'])
            db.session.add(wrong)
            db.session.commit()
            db.session.close()
            logger.info("[{0}] {1} submitted {2} with kpm {3} [WRONG]".format(*data))
            return '0' # key was wrong
        else:
            logger.info("{0} submitted {1} with kpm {2} [ALREADY SOLVED]".format(*data))
            return "2" # challenge was already solved
    else:
        return "-1"
예제 #12
0
def hints_view(hintid):
    if not utils.ctf_started():
        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():
            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))
            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():
            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)
예제 #13
0
    def chals():
        if not is_admin() and not ctftime() and not view_after_ctf():
            return redirect('/')
        if can_view_challenges():
            chals = Challenges.query.add_columns('id', 'name', 'value', 'description', 'category').order_by(Challenges.value).all()
            
            json = {'game':[]}
            for x in chals:
                files = [ str(f.location) for f in Files.query.filter_by(chal=x.id).all() ]
                json['game'].append({'id':x[1], 'name':x[2], 'value':x[3], 'description':x[4], 'category':x[5], 'files':files})

            db.session.close()
            return jsonify(json)
        else:
            db.session.close()
            return redirect('/login')
예제 #14
0
def submit_flag():
    result = {}
    cur_round = get_current_round()

    if not ctftime():
        return redirect('/challenges')

    if authed():
        submitkey = str(request.form['flag'].strip().lower())
        teamid = session['id']
        request_ip = request.remote_addr
        querykey = Keys.query.filter_by(flag=submitkey, round=cur_round).first()
        if querykey:
            # Right flag
            if Gameboxs.query.filter_by(id=querykey.gameboxid).first().teamid == teamid:
                # Self flag
                result['status'] = 2
                result['msg'] = 'Self flag'
            else:
                querysolve = Solves.query.filter_by(keyid=querykey.id, teamid=teamid).first()
                if querysolve:
                    # Already submitted
                    result['status'] = 2
                    result['msg'] = 'Already submitted'
                else:
                    # Right flag
                    newsolve = Solves(querykey.id, teamid, querykey.chalid ,querykey.round, request_ip)
                    db.session.add(newsolve)
                    db.session.commit()
                    result['status'] = 1
                    result['msg'] = 'Right Flag'
        else:
            # Wrong flag
            result['status'] = 0
            result['msg'] = 'Wrong Flag'
    else:
        result['status'] = -1
        result['msg'] = 'Login First'

    db.session.close()
    return jsonify(result)
예제 #15
0
파일: challenges.py 프로젝트: Evil404/CTFd
def chals():
    if not is_admin():
        if not ctftime():
            if view_after_ctf():
                pass
            else:
                return redirect(url_for('views.static_html'))
    if can_view_challenges():
        chals = Challenges.query.filter(or_(Challenges.hidden != True, Challenges.hidden == None)).add_columns('id', 'name', 'value', 'description', 'category').order_by(Challenges.value).all()

        json = {'game':[]}
        for x in chals:
            tags = [tag.tag for tag in Tags.query.add_columns('tag').filter_by(chal=x[1]).all()]
            files = [ str(f.location) for f in Files.query.filter_by(chal=x.id).all() ]
            json['game'].append({'id':x[1], 'name':x[2], 'value':x[3], 'description':x[4], 'category':x[5], 'files':files, 'tags':tags})

        db.session.close()
        return jsonify(json)
    else:
        db.session.close()
        return redirect(url_for('auth.login', next='chals'))
예제 #16
0
def confirmevidence():
    if not ctftime():
        if view_after_ctf():
            pass
        else:
            return redirect('/')

    error = {}
    if 'flag' in request.form.keys():
        flag = str(request.form['flag'])
        submitted_flags = TeamEvidence.query.filter_by(teamid=session['id'], name=flag).first()

        if submitted_flags != None:
            error["error"] = "Already submitted evidence"
        else:
            db.session.add(TeamEvidence(session["id"], flag, 2))
            db.session.commit()
    else:
        error["error"] = "No name or flag given"

    return json.dumps(error)
예제 #17
0
def chals():
    if not utils.is_admin():
        if not utils.ctftime():
            if utils.view_after_ctf():
                pass
            else:
                return redirect(url_for('views.static_html'))
    if utils.user_can_view_challenges() and (utils.ctf_started() or utils.is_admin()):
        chals = Challenges.query.filter(or_(Challenges.hidden != True, Challenges.hidden == None)).order_by(Challenges.value).all()
        json = {'game': []}
        for x in chals:
            tags = [tag.tag for tag in Tags.query.add_columns('tag').filter_by(chal=x.id).all()]
            files = [str(f.location) for f in Files.query.filter_by(chal=x.id).all()]
            unlocked_hints = set([u.itemid for u in Unlocks.query.filter_by(model='hints', teamid=session['id'])])
            hints = []
            for hint in Hints.query.filter_by(chal=x.id).all():
                if hint.id in unlocked_hints or utils.ctf_ended():
                    hints.append({'id': hint.id, 'cost': hint.cost, 'hint': hint.hint})
                else:
                    hints.append({'id': hint.id, 'cost': hint.cost})
            # hints = [{'id':hint.id, 'cost':hint.cost} for hint in Hints.query.filter_by(chal=x.id).all()]
            chal_type = get_chal_class(x.type)
            json['game'].append({
                'id': x.id,
                'type': chal_type.name,
                'name': x.name,
                'value': x.value,
                'description': x.description,
                'category': x.category,
                'files': files,
                'tags': tags,
                'hints': hints
            })

        db.session.close()
        return jsonify(json)
    else:
        db.session.close()
        return redirect(url_for('auth.login', next='chals'))
예제 #18
0
파일: challenges.py 프로젝트: MaiPhuoc/CTFd
    def chals():
        if not ctftime():
            return redirect("/")
        if can_view_challenges():
            chals = (
                Challenges.query.add_columns("id", "name", "value", "description", "category")
                .order_by(Challenges.value)
                .all()
            )

            json = {"game": []}
            for x in chals:
                files = [str(f.location) for f in Files.query.filter_by(chal=x.id).all()]
                json["game"].append(
                    {"id": x[1], "name": x[2], "value": x[3], "description": x[4], "category": x[5], "files": files}
                )

            db.session.close()
            return jsonify(json)
        else:
            db.session.close()
            return redirect("/login")
예제 #19
0
def chal(chalid):
    if utils.ctf_ended() and not utils.view_after_ctf():
        return redirect(url_for('challenges.challenges_view'))
    if not utils.user_can_view_challenges():
        return redirect(url_for('auth.login', next=request.path))
    if utils.authed() and utils.is_verified() and (utils.ctf_started()
                                                   or utils.view_after_ctf()):
        fails = WrongKeys.query.filter_by(teamid=session['id'],
                                          chalid=chalid).count()
        logger = logging.getLogger('keys')
        data = (time.strftime("%m/%d/%Y %X"),
                session['username'].encode('utf-8'),
                request.form['key'].encode('utf-8'),
                utils.get_kpm(session['id']))
        print("[{0}] {1} submitted {2} with kpm {3}".format(*data))

        # Anti-bruteforce / submitting keys too quickly
        if utils.get_kpm(session['id']) > 10:
            if utils.ctftime():
                wrong = WrongKeys(teamid=session['id'],
                                  chalid=chalid,
                                  ip=utils.get_ip(),
                                  flag=request.form['key'].strip())
                db.session.add(wrong)
                db.session.commit()
                db.session.close()
            logger.warn(
                "[{0}] {1} submitted {2} with kpm {3} [TOO FAST]".format(
                    *data))
            # return '3' # Submitting too fast
            return jsonify({
                'status':
                3,
                'message':
                "You're submitting keys too fast. Slow down."
            })

        solves = Solves.query.filter_by(teamid=session['id'],
                                        chalid=chalid).first()

        # Challange not solved yet
        if not solves:
            chal = Challenges.query.filter_by(id=chalid).first_or_404()
            provided_key = request.form['key'].strip()
            saved_keys = Keys.query.filter_by(chal=chal.id).all()

            # Hit max attempts
            max_tries = chal.max_attempts
            if max_tries and fails >= max_tries > 0:
                return jsonify({
                    'status': 0,
                    'message': "You have 0 tries remaining"
                })

            chal_class = get_chal_class(chal.type)
            status, message = chal_class.solve(chal, provided_key)
            if status:  # The challenge plugin says the input is right
                # TODO: if auth flag success, add gamble point
                if utils.ctftime():
                    score = chal.value
                    original_score = chal.original_value

                    solved_problem = Solves.query.filter_by(
                        chalid=chalid).count()
                    solved_team = Solves.query.filter_by(chalid=chalid).all()

                    challenge = Challenges.query.filter_by(id=chalid).first()

                    solve = Solves(teamid=session['id'],
                                   chalid=chalid,
                                   ip=utils.get_ip(),
                                   flag=provided_key)
                    gamble = Gamble(teamid=session['id'],
                                    chalid=chalid,
                                    value=original_score)
                    gamble.name = "gamble point"

                    # result = (original_score * ((solved_problem * 10) / 100))
                    result = (original_score * (1 / 10))

                    failed = False
                    try:
                        if solved_problem == 0:
                            challenge.original_value = score

                        if solved_problem >= 1:
                            challenge.value -= result
                            db.session.add(challenge)
                            db.session.commit()

                        db.session.add(solve)
                        db.session.commit()

                        db.session.add(gamble)
                        db.session.commit()

                        db.session.close()

                    except Exception as e:
                        db.session.rollback()
                        db.session.flush()
                        failed = True

                logger.info(
                    "[{0}] {1} submitted {2} with kpm {3} [CORRECT]".format(
                        *data))
                return jsonify({'status': 1, 'message': message})
            else:  # The challenge plugin says the input is wrong
                if utils.ctftime():
                    wrong = WrongKeys(teamid=session['id'],
                                      chalid=chalid,
                                      ip=utils.get_ip(),
                                      flag=provided_key)
                    db.session.add(wrong)
                    db.session.commit()
                    db.session.close()
                logger.info(
                    "[{0}] {1} submitted {2} with kpm {3} [WRONG]".format(
                        *data))
                # return '0' # key was wrong
                if max_tries:
                    attempts_left = max_tries - fails - 1  # Off by one since fails has changed since it was gotten
                    tries_str = 'tries'
                    if attempts_left == 1:
                        tries_str = 'try'
                    if message[
                            -1] not in '!().;?[]\{\}':  # Add a punctuation mark if there isn't one
                        message = message + '.'
                    return jsonify({
                        'status':
                        0,
                        'message':
                        '{} You have {} {} remaining.'.format(
                            message, attempts_left, tries_str)
                    })
                else:
                    return jsonify({'status': 0, 'message': message})

        # Challenge already solved
        else:
            logger.info(
                "{0} submitted {1} with kpm {2} [ALREADY SOLVED]".format(
                    *data))
            # return '2' # challenge was already solved
            return jsonify({'status': 2, 'message': 'You already solved this'})
    else:
        return jsonify({
            'status': -1,
            'message': "You must be logged in to solve a challenge"
        })
예제 #20
0
파일: challenges.py 프로젝트: Evil404/CTFd
def chal(chalid):
    if not ctftime():
        return redirect(url_for('challenges.challenges_view'))
    if authed():
        fails = WrongKeys.query.filter_by(teamid=session['id'], chalid=chalid).count()
        logger = logging.getLogger('keys')
        data = (time.strftime("%m/%d/%Y %X"), session['username'].encode('utf-8'), request.form['key'].encode('utf-8'), get_kpm(session['id']))
        print("[{0}] {1} submitted {2} with kpm {3}".format(*data))

        # Hit max attempts
        if fails >= int(get_config("max_tries")) and int(get_config("max_tries")) > 0:
            return "4" #too many tries on this challenge

        # Anti-bruteforce / submitting keys too quickly
        if get_kpm(session['id']) > 10:
            wrong = WrongKeys(session['id'], chalid, request.form['key'])
            db.session.add(wrong)
            db.session.commit()
            db.session.close()
            logger.warn("[{0}] {1} submitted {2} with kpm {3} [TOO FAST]".format(*data))
            return "3" # Submitting too fast

        solves = Solves.query.filter_by(teamid=session['id'], chalid=chalid).first()

        # Challange not solved yet
        if not solves:
            chal = Challenges.query.filter_by(id=chalid).first()
            key = str(request.form['key'].strip().lower())
            keys = json.loads(chal.flags)
            for x in keys:
                if x['type'] == 0: #static key
                    print(x['flag'], key.strip().lower())
                    if x['flag'] and x['flag'].strip().lower() == key.strip().lower():
                        solve = Solves(chalid=chalid, teamid=session['id'], ip=get_ip(), flag=key)
                        db.session.add(solve)
                        db.session.commit()
                        db.session.close()
                        logger.info("[{0}] {1} submitted {2} with kpm {3} [CORRECT]".format(*data))
                        return "1" # key was correct
                elif x['type'] == 1: #regex
                    res = re.match(str(x['flag']), key, re.IGNORECASE)
                    if res and res.group() == key:
                        solve = Solves(chalid=chalid, teamid=session['id'], ip=get_ip(), flag=key)
                        db.session.add(solve)
                        db.session.commit()
                        db.session.close()
                        logger.info("[{0}] {1} submitted {2} with kpm {3} [CORRECT]".format(*data))
                        return "1" # key was correct

            wrong = WrongKeys(session['id'], chalid, request.form['key'])
            db.session.add(wrong)
            db.session.commit()
            db.session.close()
            logger.info("[{0}] {1} submitted {2} with kpm {3} [WRONG]".format(*data))
            return '0' # key was wrong

        # Challenge already solved
        else:
            logger.info("{0} submitted {1} with kpm {2} [ALREADY SOLVED]".format(*data))
            return "2" # challenge was already solved
    else:
        return "-1"
예제 #21
0
    def chal(chalid):
        if not ctftime():
            return redirect('/')
        if authed():
            logger = logging.getLogger('keys')
            data = (time.strftime("%m/%d/%Y %X"),
                    session['username'].encode('utf-8'),
                    request.form['key'].encode('utf-8'),
                    get_kpm(session['id']))
            print "[{0}] {1} submitted {2} with kpm {3}".format(*data)
            if get_kpm(session['id']) > 10:
                wrong = WrongKeys(session['id'], chalid, request.form['key'])
                db.session.add(wrong)
                db.session.commit()
                db.session.close()
                logger.warn(
                    "[{0}] {1} submitted {2} with kpm {3} [TOO FAST]".format(
                        *data))
                return "3"  # Submitting too fast
            solves = Solves.query.filter_by(teamid=session['id'],
                                            chalid=chalid).first()
            if not solves:
                keys = Keys.query.filter_by(chal=chalid).all()
                key = request.form['key'].strip().lower()
                for x in keys:
                    if x.key_type == 0:  #static key
                        if x.flag.strip().lower() == key:
                            solve = Solves(chalid=chalid,
                                           teamid=session['id'],
                                           ip=request.remote_addr)
                            db.session.add(solve)
                            db.session.commit()
                            db.session.close()
                            logger.info(
                                "[{0}] {1} submitted {2} with kpm {3} [CORRECT]"
                                .format(*data))
                            return "1"  # key was correct
                    elif x.key_type == 1:  #regex
                        res = re.match(str(x), key, re.IGNORECASE)
                        if res and res.group() == key:
                            solve = Solves(chalid=chalid,
                                           teamid=session['id'],
                                           ip=request.remote_addr)
                            db.session.add(solve)
                            db.session.commit()
                            db.session.close()
                            logger.info(
                                "[{0}] {1} submitted {2} with kpm {3} [CORRECT]"
                                .format(*data))
                            return "1"  # key was correct

                wrong = WrongKeys(session['id'], chalid, request.form['key'])
                db.session.add(wrong)
                db.session.commit()
                db.session.close()
                logger.info(
                    "[{0}] {1} submitted {2} with kpm {3} [WRONG]".format(
                        *data))
                return '0'  # key was wrong
            else:
                logger.info(
                    "{0} submitted {1} with kpm {2} [ALREADY SOLVED]".format(
                        *data))
                return "2"  # challenge was already solved
        else:
            return "-1"
예제 #22
0
def chal(chalid):
    if utils.ctf_ended() and not utils.view_after_ctf():
        return redirect(url_for('challenges.challenges_view'))
    if not utils.user_can_view_challenges():
        return redirect(url_for('auth.login', next=request.path))
    if utils.authed() and utils.is_verified() and (utils.ctf_started()
                                                   or utils.view_after_ctf()):
        fails = WrongKeys.query.filter_by(teamid=session['id'],
                                          chalid=chalid).count()
        logger = logging.getLogger('keys')
        data = (time.strftime("%m/%d/%Y %X"),
                session['username'].encode('utf-8'),
                request.form['key'].encode('utf-8'),
                utils.get_kpm(session['id']))
        print("[{0}] {1} submitted {2} with kpm {3}".format(*data))

        # Anti-bruteforce / submitting keys too quickly
        if utils.get_kpm(session['id']) > 10:
            if utils.ctftime():
                wrong = WrongKeys(teamid=session['id'],
                                  chalid=chalid,
                                  ip=utils.get_ip(),
                                  flag=request.form['key'].strip())
                db.session.add(wrong)
                db.session.commit()
                db.session.close()
            logger.warn(
                "[{0}] {1} submitted {2} with kpm {3} [TOO FAST]".format(
                    *data))
            # return '3' # Submitting too fast
            return jsonify({
                'status':
                3,
                'message':
                "You're submitting keys too fast. Slow down."
            })

        solves = Solves.query.filter_by(teamid=session['id'],
                                        chalid=chalid).first()

        # Challange not solved yet
        if not solves:
            chal = Challenges.query.filter_by(id=chalid).first_or_404()
            provided_key = request.form['key'].strip()
            saved_keys = Keys.query.filter_by(chal=chal.id).all()

            # Hit max attempts
            max_tries = chal.max_attempts
            if max_tries and fails >= max_tries > 0:
                return jsonify({
                    'status': 0,
                    'message': "You have 0 tries remaining"
                })

            chal_class = get_chal_class(chal.type)
            if chal_class.solve(chal, provided_key):
                if utils.ctftime():
                    solve = Solves(teamid=session['id'],
                                   chalid=chalid,
                                   ip=utils.get_ip(),
                                   flag=provided_key)
                    db.session.add(solve)
                    db.session.commit()
                    db.session.close()
                logger.info(
                    "[{0}] {1} submitted {2} with kpm {3} [CORRECT]".format(
                        *data))
                return jsonify({'status': 1, 'message': 'Correct'})

            if utils.ctftime():
                wrong = WrongKeys(teamid=session['id'],
                                  chalid=chalid,
                                  ip=utils.get_ip(),
                                  flag=provided_key)
                db.session.add(wrong)
                db.session.commit()
                db.session.close()
            logger.info(
                "[{0}] {1} submitted {2} with kpm {3} [WRONG]".format(*data))
            # return '0' # key was wrong
            if max_tries:
                attempts_left = max_tries - fails - 1  # Off by one since fails has changed since it was gotten
                tries_str = 'tries'
                if attempts_left == 1:
                    tries_str = 'try'
                return jsonify({
                    'status':
                    0,
                    'message':
                    'Incorrect. You have {} {} remaining.'.format(
                        attempts_left, tries_str)
                })
            else:
                return jsonify({'status': 0, 'message': 'Incorrect'})

        # Challenge already solved
        else:
            logger.info(
                "{0} submitted {1} with kpm {2} [ALREADY SOLVED]".format(
                    *data))
            # return '2' # challenge was already solved
            return jsonify({'status': 2, 'message': 'You already solved this'})
    else:
        return jsonify({
            'status': -1,
            'message': "You must be logged in to solve a challenge"
        })
예제 #23
0
def chal(chalid):
    if utils.ctf_paused():
        return jsonify({
            'status': 3,
            'message': '{} is paused'.format(utils.ctf_name())
        })
    if utils.ctf_ended() and not utils.view_after_ctf():
        abort(403)
    if not utils.user_can_view_challenges():
        return redirect(url_for('auth.login', next=request.path))
    if (utils.authed() and utils.is_verified() and
        (utils.ctf_started() or utils.view_after_ctf())) or utils.is_admin():
        team = Teams.query.filter_by(id=session['id']).first()
        fails = WrongKeys.query.filter_by(teamid=session['id'],
                                          chalid=chalid).count()
        logger = logging.getLogger('keys')
        data = (time.strftime("%m/%d/%Y %X"),
                session['username'].encode('utf-8'),
                request.form['key'].encode('utf-8'),
                utils.get_kpm(session['id']))
        print("[{0}] {1} submitted {2} with kpm {3}".format(*data))

        chal = Challenges.query.filter_by(id=chalid).first_or_404()
        if chal.hidden:
            abort(404)
        chal_class = get_chal_class(chal.type)

        # Anti-bruteforce / submitting keys too quickly
        if utils.get_kpm(session['id']) > 10:
            if utils.ctftime():
                chal_class.fail(team=team, chal=chal, request=request)
            logger.warn(
                "[{0}] {1} submitted {2} with kpm {3} [TOO FAST]".format(
                    *data))
            # return '3' # Submitting too fast
            return jsonify({
                'status':
                3,
                'message':
                "You're submitting keys too fast. Slow down."
            })

        solves = Solves.query.filter_by(teamid=session['id'],
                                        chalid=chalid).first()

        # Challange not solved yet
        if not solves:
            provided_key = request.form['key'].strip()
            saved_keys = Keys.query.filter_by(chal=chal.id).all()

            # Hit max attempts
            max_tries = chal.max_attempts
            if max_tries and fails >= max_tries > 0:
                return jsonify({
                    'status': 0,
                    'message': "You have 0 tries remaining"
                })

            status, message = chal_class.attempt(chal, request)
            if status:  # The challenge plugin says the input is right
                if utils.ctftime() or utils.is_admin():
                    chal_class.solve(team=team, chal=chal, request=request)
                logger.info(
                    "[{0}] {1} submitted {2} with kpm {3} [CORRECT]".format(
                        *data))
                return jsonify({'status': 1, 'message': message})
            else:  # The challenge plugin says the input is wrong
                if isinstance(
                        message,
                        int):  # This means someone submitted others' flag
                    if utils.ctftime() or utils.is_admin():
                        chal_class.penalty(
                            team1=team,
                            team2=Teams.query.filter_by(id=message).first(),
                            chal=chal,
                            request=request)
                    logger.info(
                        "[{0}] {1} submitted {2} with kpm {3} [CHEAT]".format(
                            *data))
                    message = "Incorrect(Warning!You are trying to submit other team's flag)"
                else:
                    if utils.ctftime() or utils.is_admin():
                        chal_class.fail(team=team, chal=chal, request=request)
                    logger.info(
                        "[{0}] {1} submitted {2} with kpm {3} [WRONG]".format(
                            *data))
                # return '0' # key was wrong
                if max_tries:
                    attempts_left = max_tries - fails - 1  # Off by one since fails has changed since it was gotten
                    tries_str = 'tries'
                    if attempts_left == 1:
                        tries_str = 'try'
                    if message[
                            -1] not in '!().;?[]\{\}':  # Add a punctuation mark if there isn't one
                        message = message + '.'
                    return jsonify({
                        'status':
                        0,
                        'message':
                        '{} You have {} {} remaining.'.format(
                            message, attempts_left, tries_str)
                    })
                else:
                    return jsonify({'status': 0, 'message': message})

        # Challenge already solved
        else:
            logger.info(
                "{0} submitted {1} with kpm {2} [ALREADY SOLVED]".format(
                    *data))
            # return '2' # challenge was already solved
            return jsonify({'status': 2, 'message': 'You already solved this'})
    else:
        return jsonify({
            'status': -1,
            'message': "You must be logged in to solve a challenge"
        })
예제 #24
0
def chal(chalid):
    if utils.ctf_ended() and not utils.view_after_ctf():
        return redirect(url_for('challenges.challenges_view'))
    if not utils.user_can_view_challenges():
        return redirect(url_for('auth.login', next=request.path))
    if utils.authed() and utils.is_verified() and (utils.ctf_started() or utils.view_after_ctf()):
        fails = WrongKeys.query.filter_by(teamid=session['id'], chalid=chalid).count()
        logger = logging.getLogger('keys')
        data = (time.strftime("%m/%d/%Y %X"), session['username'].encode('utf-8'), request.form['key'].encode('utf-8'), utils.get_kpm(session['id']))
        print("[{0}] {1} submitted {2} with kpm {3}".format(*data))

        # Anti-bruteforce / submitting keys too quickly
        if utils.get_kpm(session['id']) > 10:
            if utils.ctftime():
                wrong = WrongKeys(session['id'], chalid, request.form['key'])
                db.session.add(wrong)
                db.session.commit()
                db.session.close()
            logger.warn("[{0}] {1} submitted {2} with kpm {3} [TOO FAST]".format(*data))
            # return '3' # Submitting too fast
            return jsonify({'status': 3, 'message': "You're submitting keys too fast. Slow down."})

        solves = Solves.query.filter_by(teamid=session['id'], chalid=chalid).first()

        # Challange not solved yet
        if not solves:
            chal = Challenges.query.filter_by(id=chalid).first_or_404()
            provided_key = request.form['key'].strip()
            saved_keys = Keys.query.filter_by(chal=chal.id).all()

            # Hit max attempts
            max_tries = chal.max_attempts
            if max_tries and fails >= max_tries > 0:
                return jsonify({
                    'status': 0,
                    'message': "You have 0 tries remaining"
                })

            chal_class = get_chal_class(chal.type)
            if chal_class.solve(chal, provided_key):
                if utils.ctftime():
                    solve = Solves(chalid=chalid, teamid=session['id'], ip=utils.get_ip(), flag=provided_key)
                    db.session.add(solve)
                    db.session.commit()
                    db.session.close()
                logger.info("[{0}] {1} submitted {2} with kpm {3} [CORRECT]".format(*data))
                return jsonify({'status': 1, 'message': 'Correct'})

            if utils.ctftime():
                wrong = WrongKeys(teamid=session['id'], chalid=chalid, flag=provided_key)
                db.session.add(wrong)
                db.session.commit()
                db.session.close()
            logger.info("[{0}] {1} submitted {2} with kpm {3} [WRONG]".format(*data))
            # return '0' # key was wrong
            if max_tries:
                attempts_left = max_tries - fails - 1  # Off by one since fails has changed since it was gotten
                tries_str = 'tries'
                if attempts_left == 1:
                    tries_str = 'try'
                return jsonify({'status': 0, 'message': 'Incorrect. You have {} {} remaining.'.format(attempts_left, tries_str)})
            else:
                return jsonify({'status': 0, 'message': 'Incorrect'})

        # Challenge already solved
        else:
            logger.info("{0} submitted {1} with kpm {2} [ALREADY SOLVED]".format(*data))
            # return '2' # challenge was already solved
            return jsonify({'status': 2, 'message': 'You already solved this'})
    else:
        return jsonify({
            'status': -1,
            'message': "You must be logged in to solve a challenge"
        })
예제 #25
0
파일: challenges.py 프로젝트: nliplace/CTFd
def chal(chalid):
    if not ctftime():
        return redirect(url_for('challenges.challenges_view'))
    if authed():
        fails = WrongKeys.query.filter_by(teamid=session['id'], chalid=chalid).count()
        logger = logging.getLogger('keys')
        data = (time.strftime("%m/%d/%Y %X"), session['username'].encode('utf-8'), request.form['key'].encode('utf-8'), get_kpm(session['id']))
        print("[{0}] {1} submitted {2} with kpm {3}".format(*data))

        # Anti-bruteforce / submitting keys too quickly
        if get_kpm(session['id']) > 10:
            wrong = WrongKeys(session['id'], chalid, request.form['key'])
            db.session.add(wrong)
            db.session.commit()
            db.session.close()
            logger.warn("[{0}] {1} submitted {2} with kpm {3} [TOO FAST]".format(*data))
            # return "3" # Submitting too fast
            return jsonify({'status': '3', 'message': "You're submitting keys too fast. Slow down."})

        solves = Solves.query.filter_by(teamid=session['id'], chalid=chalid).first()

        # Challange not solved yet
        if not solves:
            chal = Challenges.query.filter_by(id=chalid).first()
            key = str(request.form['key'].strip().lower())
            keys = json.loads(chal.flags)

            # Hit max attempts
            max_tries = int(get_config("max_tries"))
            if fails >= max_tries > 0:
                return jsonify({
                    'status': '0',
                    'message': "You have 0 tries remaining"
                })

            for x in keys:
                if x['type'] == 0: #static key
                    print(x['flag'], key.strip().lower())
                    if x['flag'] and x['flag'].strip().lower() == key.strip().lower():
                        solve = Solves(chalid=chalid, teamid=session['id'], ip=get_ip(), flag=key)
                        db.session.add(solve)
                        db.session.commit()
                        db.session.close()
                        logger.info("[{0}] {1} submitted {2} with kpm {3} [CORRECT]".format(*data))
                        # return "1" # key was correct
                        return jsonify({'status':'1', 'message':'Correct'})
                elif x['type'] == 1: #regex
                    res = re.match(str(x['flag']), key, re.IGNORECASE)
                    if res and res.group() == key:
                        solve = Solves(chalid=chalid, teamid=session['id'], ip=get_ip(), flag=key)
                        db.session.add(solve)
                        db.session.commit()
                        db.session.close()
                        logger.info("[{0}] {1} submitted {2} with kpm {3} [CORRECT]".format(*data))
                        # return "1" # key was correct
                        return jsonify({'status': '1', 'message': 'Correct'})

            wrong = WrongKeys(session['id'], chalid, request.form['key'])
            db.session.add(wrong)
            db.session.commit()
            db.session.close()
            logger.info("[{0}] {1} submitted {2} with kpm {3} [WRONG]".format(*data))
            # return '0' # key was wrong
            if max_tries:
                attempts_left = max_tries - fails
                tries_str = 'tries'
                if attempts_left == 1:
                    tries_str = 'try'
                return jsonify({'status': '0', 'message': 'Incorrect. You have {} {} remaining.'.format(attempts_left, tries_str)})
            else:
                return jsonify({'status': '0', 'message': 'Incorrect'})


        # Challenge already solved
        else:
            logger.info("{0} submitted {1} with kpm {2} [ALREADY SOLVED]".format(*data))
            # return "2" # challenge was already solved
            return jsonify({'status': '2', 'message': 'You already solved this'})
    else:
        return "-1"
예제 #26
0
def chal(chalid):
    if utils.ctf_paused():
        return jsonify({
            'status': 3,
            'message': '{} is paused'.format(utils.ctf_name())
        })
    if (utils.authed() and utils.is_verified() and (utils.ctf_started() or utils.view_after_ctf())) or utils.is_admin():
        team = Teams.query.filter_by(id=session['id']).first()
        fails = WrongKeys.query.filter_by(teamid=session['id'], chalid=chalid).count()
        logger = logging.getLogger('keys')
        data = (time.strftime("%m/%d/%Y %X"), session['username'].encode('utf-8'), request.form['key'].encode('utf-8'), utils.get_kpm(session['id']))
        print("[{0}] {1} submitted {2} with kpm {3}".format(*data))

        chal = Challenges.query.filter_by(id=chalid).first_or_404()
        if chal.hidden:
            abort(404)
        chal_class = get_chal_class(chal.type)

        # Anti-bruteforce / submitting keys too quickly
        if utils.get_kpm(session['id']) > 10:
            if utils.ctftime():
                chal_class.fail(team=team, chal=chal, request=request)
            logger.warn("[{0}] {1} submitted {2} with kpm {3} [TOO FAST]".format(*data))
            # return '3' # Submitting too fast
            return jsonify({'status': 3, 'message': "你提交答案过快,请稍后再试"})

        solves = Solves.query.filter_by(teamid=session['id'], chalid=chalid).first()

        # Challange not solved yet
        if not solves:
            provided_key = request.form['key'].strip()
            saved_keys = Keys.query.filter_by(chal=chal.id).all()

            # Hit max attempts
            max_tries = chal.max_attempts
            if max_tries and fails >= max_tries > 0:
                return jsonify({
                    'status': 0,
                    'message': "你已经没有机会再试了"
                })

            status, message = chal_class.attempt(chal, request)
            if status:  # The challenge plugin says the input is right
                if utils.ctftime() or utils.is_admin():
                    chal_class.solve(team=team, chal=chal, request=request)
                logger.info("[{0}] {1} submitted {2} with kpm {3} [CORRECT]".format(*data))
                return jsonify({'status': 1, 'message': message})
            else:  # The challenge plugin says the input is wrong
                if utils.ctftime() or utils.is_admin():
                    chal_class.fail(team=team, chal=chal, request=request)
                logger.info("[{0}] {1} submitted {2} with kpm {3} [WRONG]".format(*data))
                # return '0' # key was wrong
                if max_tries:
                    attempts_left = max_tries - fails - 1  # Off by one since fails has changed since it was gotten
                    tries_str = 'tries'
                    if attempts_left == 1:
                        tries_str = 'try'
                    if message[-1] not in '!().;?[]\{\}':  # Add a punctuation mark if there isn't one
                        message = message + '.'
                    return jsonify({'status': 0, 'message': '{} You have {} {} remaining.'.format(message, attempts_left, tries_str)})
                else:
                    return jsonify({'status': 0, 'message': message})

        # Challenge already solved
        else:
            logger.info("{0} submitted {1} with kpm {2} [ALREADY SOLVED]".format(*data))
            # return '2' # challenge was already solved
            return jsonify({'status': 2, 'message': '你已经做过本题了'})
    else:
        return jsonify({
            'status': -1,
            'message': "必须先登陆才能解题"
        })
예제 #27
0
def chals():
    if not utils.is_admin():
        if not utils.ctftime():
            if utils.view_after_ctf():
                pass
            else:
                abort(403)

    if utils.get_config('verify_emails'):
        if utils.authed():
            if utils.is_admin() is False and utils.is_verified(
            ) is False:  # User is not confirmed
                abort(403)

    if utils.user_can_view_challenges() and (utils.ctf_started()
                                             or utils.is_admin()):
        teamid = session.get('id')
        chals = Challenges.query.filter(
            or_(Challenges.hidden != True,
                Challenges.hidden == None)).order_by(Challenges.value).all()
        json = {'game': []}
        for x in chals:
            tags = [
                tag.tag for tag in Tags.query.add_columns('tag').filter_by(
                    chal=x.id).all()
            ]
            files = [
                str(f.location)
                for f in Files.query.filter_by(chal=x.id).all()
            ]
            unlocked_hints = set([
                u.itemid
                for u in Unlocks.query.filter_by(model='hints', teamid=teamid)
            ])
            hints = []
            for hint in Hints.query.filter_by(chal=x.id).all():
                if hint.id in unlocked_hints or utils.ctf_ended():
                    hints.append({
                        'id': hint.id,
                        'cost': hint.cost,
                        'hint': hint.hint
                    })
                else:
                    hints.append({'id': hint.id, 'cost': hint.cost})
            chal_type = get_chal_class(x.type)
            json['game'].append({
                'id': x.id,
                'type': chal_type.name,
                'name': x.name,
                'value': x.value,
                'description': x.description,
                'category': x.category,
                'files': files,
                'tags': tags,
                'hints': hints,
                'template': chal_type.templates['modal'],
                'script': chal_type.scripts['modal'],
            })
            json['column_mode'] = utils.get_config('column_mode')

        db.session.close()
        return jsonify(json)
    else:
        db.session.close()
        abort(403)
예제 #28
0
파일: challenges.py 프로젝트: noraj/CTFd
def chal(chalid):
    if ctf_ended() and not view_after_ctf():
        return redirect(url_for('challenges.challenges_view'))
    if not user_can_view_challenges():
        return redirect(url_for('auth.login', next=request.path))
    if authed() and is_verified() and (ctf_started() or view_after_ctf()):
        fails = WrongKeys.query.filter_by(teamid=session['id'],
                                          chalid=chalid).count()
        logger = logging.getLogger('keys')
        data = (time.strftime("%m/%d/%Y %X"),
                session['username'].encode('utf-8'),
                request.form['key'].encode('utf-8'), get_kpm(session['id']))
        print("[{0}] {1} submitted {2} with kpm {3}".format(*data))

        # Anti-bruteforce / submitting keys too quickly
        if get_kpm(session['id']) > 10:
            if ctftime():
                wrong = WrongKeys(session['id'], chalid, request.form['key'])
                db.session.add(wrong)
                db.session.commit()
                db.session.close()
            logger.warn(
                "[{0}] {1} submitted {2} with kpm {3} [TOO FAST]".format(
                    *data))
            # return '3' # Submitting too fast
            return jsonify({
                'status':
                '3',
                'message':
                "You're submitting keys too fast. Slow down."
            })

        solves = Solves.query.filter_by(teamid=session['id'],
                                        chalid=chalid).first()

        # Challange not solved yet
        if not solves:
            chal = Challenges.query.filter_by(id=chalid).first_or_404()
            key = unicode(request.form['key'].strip().lower())
            keys = json.loads(chal.flags)

            # Hit max attempts
            max_tries = int(get_config("max_tries"))
            if fails >= max_tries > 0:
                return jsonify({
                    'status': '0',
                    'message': "You have 0 tries remaining"
                })

            for x in keys:
                if x['type'] == 0:  # static key
                    print(x['flag'], key.strip().lower())
                    if x['flag'] and x['flag'].strip().lower() == key.strip(
                    ).lower():
                        if ctftime():
                            solve = Solves(chalid=chalid,
                                           teamid=session['id'],
                                           ip=get_ip(),
                                           flag=key)
                            db.session.add(solve)
                            db.session.commit()
                            db.session.close()
                        logger.info(
                            "[{0}] {1} submitted {2} with kpm {3} [CORRECT]".
                            format(*data))
                        # return '1' # key was correct
                        return jsonify({'status': '1', 'message': 'Correct'})
                elif x['type'] == 1:  # regex
                    res = re.match(x['flag'], key, re.IGNORECASE)
                    if res and res.group() == key:
                        if ctftime():
                            solve = Solves(chalid=chalid,
                                           teamid=session['id'],
                                           ip=get_ip(),
                                           flag=key)
                            db.session.add(solve)
                            db.session.commit()
                            db.session.close()
                        logger.info(
                            "[{0}] {1} submitted {2} with kpm {3} [CORRECT]".
                            format(*data))
                        # return '1' # key was correct
                        return jsonify({'status': '1', 'message': 'Correct'})

            if ctftime():
                wrong = WrongKeys(session['id'], chalid, request.form['key'])
                db.session.add(wrong)
                db.session.commit()
                db.session.close()
            logger.info(
                "[{0}] {1} submitted {2} with kpm {3} [WRONG]".format(*data))
            # return '0' # key was wrong
            if max_tries:
                attempts_left = max_tries - fails
                tries_str = 'tries'
                if attempts_left == 1:
                    tries_str = 'try'
                return jsonify({
                    'status':
                    '0',
                    'message':
                    'Incorrect. You have {} {} remaining.'.format(
                        attempts_left, tries_str)
                })
            else:
                return jsonify({'status': '0', 'message': 'Incorrect'})

        # Challenge already solved
        else:
            logger.info(
                "{0} submitted {1} with kpm {2} [ALREADY SOLVED]".format(
                    *data))
            # return '2' # challenge was already solved
            return jsonify({
                'status': '2',
                'message': 'You already solved this'
            })
    else:
        return '-1'
예제 #29
0
def chal_custom(chalid):
    if utils.ctf_paused():
        return jsonify({
            'status': 3,
            'message': '{} is paused'.format(utils.ctf_name())
        })
    if (utils.authed() and utils.is_verified() and
        (utils.ctf_started() or utils.view_after_ctf())) or utils.is_admin():
        team = Teams.query.filter_by(id=session['id']).first()
        fails = WrongKeys.query.filter_by(teamid=session['id'],
                                          chalid=chalid).count()
        logger = logging.getLogger('keys')
        data = (time.strftime("%m/%d/%Y %X"),
                session['username'].encode('utf-8'),
                request.form['key'].encode('utf-8'),
                utils.get_kpm(session['id']))
        print("[{0}] {1} submitted {2} with kpm {3}".format(*data))

        chal = Challenges.query.filter_by(id=chalid).first_or_404()
        if chal.hidden:
            abort(404)
        chal_class = get_chal_class(chal.type)

        # Anti-bruteforce / submitting keys too quickly
        if utils.get_kpm(session['id']) > 10:
            if utils.ctftime():
                chal_class.fail(team=team, chal=chal, request=request)
            logger.warn(
                "[{0}] {1} submitted {2} with kpm {3} [TOO FAST]".format(
                    *data))
            # return '3' # Submitting too fast
            return jsonify({
                'status':
                3,
                'message':
                "You're submitting keys too fast. Slow down."
            })

        solves = Solves.query.filter_by(teamid=session['id'],
                                        chalid=chalid).first()

        # Challange not solved yet
        if not solves:
            provided_key = request.form['key'].strip()
            saved_keys = Keys.query.filter_by(chal=chal.id).all()

            # Hit max attempts
            max_tries = chal.max_attempts
            if max_tries and fails >= max_tries > 0:
                return jsonify({
                    'status': 0,
                    'message': "You have 0 tries remaining"
                })

            status, message = chal_class.attempt(chal, request)
            if status:  # The challenge plugin says the input is right
                if utils.ctftime() or utils.is_admin():
                    chal_class.solve(team=team, chal=chal, request=request)
                logger.info(
                    "[{0}] {1} submitted {2} with kpm {3} [CORRECT]".format(
                        *data))

                if "SmartCity" in str(chal_class):
                    print(session['id'])
                    smart_color = SmartCityTeam.query.filter_by(
                        teamId=session['id']).first().color
                    smart_buildingId = SmartCityChallenge.query.filter_by(
                        id=chalid).first().buildingId
                    smart_soundId = SmartCityChallenge.query.filter_by(
                        id=chalid).first().soundId
                    smart_image = SmartCityTeam.query.filter_by(
                        teamId=session['id']).first().image
                    b = smart_buildingId.split('\', \'')
                    b[0] = b[0][2:]
                    b[-1] = b[-1][:-2]
                    print("Team with color " + str(smart_color) +
                          " and image " + str(smart_image) +
                          " solved challenege with buildingId " + str(b) +
                          "and sound " + smart_soundId)
                    smartSession = SmartTable(b, smart_color, smart_image,
                                              smart_soundId)
                    createSmartCityTableSession2(smartSession)

                return jsonify({'status': 1, 'message': message})
            else:  # The challenge plugin says the input is wrong
                if utils.ctftime() or utils.is_admin():
                    chal_class.fail(team=team, chal=chal, request=request)
                logger.info(
                    "[{0}] {1} submitted {2} with kpm {3} [WRONG]".format(
                        *data))
                # return '0' # key was wrong
                if max_tries:
                    attempts_left = max_tries - fails - 1  # Off by one since fails has changed since it was gotten
                    tries_str = 'tries'
                    if attempts_left == 1:
                        tries_str = 'try'
                    if message[
                            -1] not in '!().;?[]\{\}':  # Add a punctuation mark if there isn't one
                        message = message + '.'
                    return jsonify({
                        'status':
                        0,
                        'message':
                        '{} You have {} {} remaining.'.format(
                            message, attempts_left, tries_str)
                    })
                else:
                    return jsonify({'status': 0, 'message': message})

        # Challenge already solved
        else:
            logger.info(
                "{0} submitted {1} with kpm {2} [ALREADY SOLVED]".format(
                    *data))
            # return '2' # challenge was already solved
            return jsonify({'status': 2, 'message': 'You already solved this'})
    else:
        return jsonify({
            'status': -1,
            'message': "You must be logged in to solve a challenge"
        })
예제 #30
0
def chal_contest(contestid, chalid):
    contest = Contests.query.filter_by(id=contestid).first()

    if utils.ctf_ended(
            contest=contest) and not utils.view_after_ctf(contest=contest):
        return redirect(url_for('challenges.challenges_view'))
    if not utils.user_can_view_challenges(contest=contest):
        return redirect(url_for('contests.contests_view'))
    if utils.authed() and utils.is_verified() and utils.is_participated(
            contest=contest) and (utils.ctf_started(contest=contest)
                                  or utils.view_after_ctf(contest=contest)):
        fails = WrongKeys.query.filter_by(teamid=session['id'],
                                          chalid=chalid).count()
        logger = logging.getLogger('keys')
        data = (time.strftime("%m/%d/%Y %X"),
                session['username'].encode('utf-8'),
                request.form['key'].encode('utf-8'),
                utils.get_kpm(session['id']))
        print("[{0}] {1} submitted {2} with kpm {3}".format(*data))

        # Anti-bruteforce / submitting keys too quickly
        if utils.get_kpm(session['id']) > 10:
            if utils.ctftime():
                wrong = WrongKeys(teamid=session['id'],
                                  chalid=chalid,
                                  ip=utils.get_ip(),
                                  flag=request.form['key'].strip())
                db.session.add(wrong)
                db.session.commit()
                db.session.close()
            logger.warn(
                "[{0}] {1} submitted {2} with kpm {3} [TOO FAST]".format(
                    *data))
            # return '3' # Submitting too fast
            return jsonify({
                'status':
                3,
                'message':
                "You're submitting keys too fast. Slow down."
            })

        solves = Solves.query.filter_by(teamid=session['id'],
                                        chalid=chalid).first()

        chal = Challenges.query.filter_by(id=chalid).first_or_404()
        provided_key = request.form['key'].strip()
        saved_keys = Keys.query.filter_by(chal=chal.id).all()

        # Hit max attempts
        max_tries = chal.max_attempts
        if max_tries and fails >= max_tries > 0:
            return jsonify({
                'status': 0,
                'message': "You have 0 tries remaining"
            })

        chal_class = get_chal_class(chal.type)
        status, message = chal_class.solve(chal, provided_key)
        if status:  # The challenge plugin says the input is right
            if utils.ctftime(contest=contest):
                solve = Solves(teamid=session['id'],
                               chalid=chalid,
                               ip=utils.get_ip(),
                               flag=provided_key,
                               contestid=contestid)
                db.session.add(solve)
                db.session.commit()
                db.session.close()
            else:
                message += '. But time is up'

            if solves:
                message += ". You already solved this"
                logger.info(
                    "{0} submitted {1} with kpm {2} [ALREADY SOLVED]".format(
                        *data))
                # return '2' # challenge was already solved
                return jsonify({'status': 2, 'message': message})

            logger.info(
                "[{0}] {1} submitted {2} with kpm {3} [CORRECT]".format(*data))
            return jsonify({'status': 1, 'message': message})
        else:  # The challenge plugin says the input is wrong
            if utils.ctftime(contest=contest):
                wrong = WrongKeys(teamid=session['id'],
                                  chalid=chalid,
                                  ip=utils.get_ip(),
                                  flag=provided_key,
                                  contestid=contestid)
                db.session.add(wrong)
                db.session.commit()
                db.session.close()
            else:
                message += '. But time is up'

            if solves:
                message += ". You already solved this"
                logger.info(
                    "{0} submitted {1} with kpm {2} [ALREADY SOLVED]".format(
                        *data))
                # return '2' # challenge was already solved
                return jsonify({'status': 2, 'message': message})

            logger.info(
                "[{0}] {1} submitted {2} with kpm {3} [WRONG]".format(*data))
            # return '0' # key was wrong
            if max_tries:
                attempts_left = max_tries - fails - 1  # Off by one since fails has changed since it was gotten
                tries_str = 'tries'
                if attempts_left == 1:
                    tries_str = 'try'
                if message[
                        -1] not in '!().;?[]\{\}':  # Add a punctuation mark if there isn't one
                    message = message + '.'
                return jsonify({
                    'status':
                    0,
                    'message':
                    '{} You have {} {} remaining.'.format(
                        message, attempts_left, tries_str)
                })
            else:
                return jsonify({'status': 0, 'message': message})

    else:
        return jsonify({
            'status': -1,
            'message': "You must be logged in to solve a challenge"
        })
예제 #31
0
def chal(chalid):
    if not ctftime():
        return redirect(url_for('challenges.challenges_view'))
    if authed():
        fails = WrongKeys.query.filter_by(team=session['id'],
                                          chalid=chalid).count()
        logger = logging.getLogger('keys')
        data = (time.strftime("%m/%d/%Y %X"),
                session['username'].encode('utf-8'),
                request.form['key'].encode('utf-8'), get_kpm(session['id']))
        print("[{0}] {1} submitted {2} with kpm {3}".format(*data))

        # Hit max attempts
        if fails >= int(get_config("max_tries")) and int(
                get_config("max_tries")) > 0:
            return "4"  #too many tries on this challenge

        # Anti-bruteforce / submitting keys too quickly
        if get_kpm(session['id']) > 10:
            wrong = WrongKeys(session['id'], chalid, request.form['key'])
            db.session.add(wrong)
            db.session.commit()
            db.session.close()
            logger.warn(
                "[{0}] {1} submitted {2} with kpm {3} [TOO FAST]".format(
                    *data))
            return "3"  # Submitting too fast

        solves = Solves.query.filter_by(teamid=session['id'],
                                        chalid=chalid).first()

        # Challange not solved yet
        if not solves:
            chal = Challenges.query.filter_by(id=chalid).first()
            key = str(request.form['key'].strip().lower())
            keys = json.loads(chal.flags)
            for x in keys:
                if x['type'] == 0:  #static key
                    print(x['flag'], key.strip().lower())
                    if x['flag'] == key.strip().lower():
                        solve = Solves(chalid=chalid,
                                       teamid=session['id'],
                                       ip=request.remote_addr,
                                       flag=key)
                        db.session.add(solve)
                        db.session.commit()
                        db.session.close()
                        logger.info(
                            "[{0}] {1} submitted {2} with kpm {3} [CORRECT]".
                            format(*data))
                        return "1"  # key was correct
                elif x['type'] == 1:  #regex
                    res = re.match(str(x['flag']), key, re.IGNORECASE)
                    if res and res.group() == key:
                        solve = Solves(chalid=chalid,
                                       teamid=session['id'],
                                       ip=request.remote_addr,
                                       flag=key)
                        db.session.add(solve)
                        db.session.commit()
                        db.session.close()
                        logger.info(
                            "[{0}] {1} submitted {2} with kpm {3} [CORRECT]".
                            format(*data))
                        return "1"  # key was correct

            wrong = WrongKeys(session['id'], chalid, request.form['key'])
            db.session.add(wrong)
            db.session.commit()
            db.session.close()
            logger.info(
                "[{0}] {1} submitted {2} with kpm {3} [WRONG]".format(*data))
            return '0'  # key was wrong

        # Challenge already solved
        else:
            logger.info(
                "{0} submitted {1} with kpm {2} [ALREADY SOLVED]".format(
                    *data))
            return "2"  # challenge was already solved
    else:
        return "-1"