Пример #1
0
    def tracker():
        if request.endpoint == "views.themes":
            return

        if authed():
            user_ips = get_current_user_recent_ips()
            ip = get_ip()

            track = None
            if (ip not in user_ips) or (request.method != "GET"):
                track = Tracking.query.filter_by(
                    ip=get_ip(), user_id=session["id"]).first()

                if track:
                    track.date = datetime.datetime.utcnow()
                else:
                    track = Tracking(ip=get_ip(), user_id=session["id"])
                    db.session.add(track)

            if track:
                try:
                    db.session.commit()
                except (InvalidRequestError, IntegrityError):
                    db.session.rollback()
                    db.session.close()
                    logout_user()
                else:
                    clear_user_recent_ips(user_id=session["id"])
Пример #2
0
    def tracker():
        # TODO: This function shouldn't cause a DB hit for lookups if possible
        if authed():
            track = Tracking.query.filter_by(ip=get_ip(),
                                             user_id=session['id']).first()
            if not track:
                visit = Tracking(ip=get_ip(), user_id=session['id'])
                db.session.add(visit)
            else:
                track.date = datetime.datetime.utcnow()

            try:
                db.session.commit()
            except (InvalidRequestError, IntegrityError) as e:
                print(e.message)
                db.session.rollback()
                session.clear()

            if authed():
                user = get_current_user()
                team = get_current_team()

                if request.path.startswith('/themes') is False:
                    if user and user.banned:
                        return render_template(
                            'errors/403.html',
                            error='You have been banned from this CTF'), 403

                    if team and team.banned:
                        return render_template(
                            'errors/403.html',
                            error='Your team has been banned from this CTF'
                        ), 403

            db.session.close()
Пример #3
0
    def fail(user, team, challenge, request, share):
        """
        This method is used to insert Fails into the database in order to mark an answer incorrect.

        :param team: The Team object from the database
        :param challenge: The Challenge object from the database
        :param request: The request the user submitted
        :return:
        """
        data = request.form or request.get_json()
        submission = data['submission'].strip()
        if share:
            wrong = ShareFlags(user_id=user.id,
                               team_id=team.id if team else None,
                               challenge_id=challenge.id,
                               ip=get_ip(request),
                               provided=submission)
        else:
            wrong = Fails(user_id=user.id,
                          team_id=team.id if team else None,
                          challenge_id=challenge.id,
                          ip=get_ip(request),
                          provided=submission)
        db.session.add(wrong)
        db.session.commit()
        db.session.close()
Пример #4
0
	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:
		"""		
		data = request.form or request.get_json()
		submission = data["submission"].strip()
		docker = DockerConfig.query.filter_by(id=1).first()
		try:
			if is_teams_mode():
				docker_containers = DockerChallengeTracker.query.filter_by(docker_image=challenge.docker_image).filter_by(team_id=team.id).first()
			else:
				docker_containers = DockerChallengeTracker.query.filter_by(docker_image=challenge.docker_image).filter_by(user_id=user.id).first()
			delete_container(docker, docker_containers.instance_id)
			DockerChallengeTracker.query.filter_by(instance_id=docker_containers.instance_id).delete()
		except:
			pass
		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,
		)
		db.session.add(solve)
		db.session.commit()
		db.session.close()
Пример #5
0
    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:
        """
        chal = LahChallenge.query.filter_by(id=challenge.id).first()
        if not chal.is_unlocked:
            raise RuntimeError("Attempted to solve a locked lah challenge.")

        # check if this is the selected solve
        unlock = get_unlock_state()
        if unlock.selected == challenge.id:
            with db.session.no_autoflush:
                unlock.selected = None
                unlock.unlocker_id = user.id
                unlock.expiration = datetime.datetime.now() + datetime.timedelta(minutes = 1)
            scheduler.add_job(unlock_timeout_callback, DateTrigger(unlock.expiration), id=UNLOCK_TIMEOUT_JOB_ID, replace_existing=True, misfire_grace_time=999999999)
            db.session.commit()

        data = request.form or request.get_json()
        submission = data['submission'].strip()
        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
        )
        db.session.add(solve)
        db.session.commit()
        db.session.close()
Пример #6
0
    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:
        """
        chal = multiChallenge.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,
        )
        db.session.add(solve)

        solve_count = (Solves.query.join(
            Model, Solves.account_id == Model.id).filter(
                Solves.challenge_id == challenge.id,
                Model.hidden == False,
                Model.banned == False,
            ).count())

        db.session.commit()
        db.session.close()
    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:
        """
        data = request.form or request.get_json()
        submission = data["submission"].strip()

        disbot("<@" + str(user.oauth_id) + "> just solved " +
               str(challenge.name) + "!!")  # <--- LHC DISCORD SOLVE NOTIFIER

        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,
        )
        db.session.add(solve)
        db.session.commit()
        db.session.close()
    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 = WriteupDynamicChallenge.query.filter_by(
            id=challenge.id).first()
        data = request.form or request.get_json()
        submission = data["submission"].strip()

        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,
        )
        db.session.add(solve)
        db.session.commit()

        WriteupDynamicValueChallenge.calculate_value(challenge)
Пример #9
0
    def solve(user, team, challenge, request):
        chal = DynICPCModel.query.filter_by(id=challenge.id).first()
        Model = get_model()
        solve = Solves(user_id=user.id,
                       team_id=team.id if team else None,
                       challenge_id=challenge.id,
                       ip=get_ip(request),
                       provided=request.judge_result['submission_id'])
        db.session.add(solve)
        solve_count = (Solves.query.join(
            Model, Solves.account_id == Model.id).filter(
                Solves.challenge_id == challenge.id,
                not Model.hidden,
                not Model.banned,
            ).count())

        # We subtract -1 to allow the first solver to get max point value
        solve_count -= 1

        # It is important that this calculation takes into account floats.
        # Hence this file uses from __future__ import division
        value = (((chal.minimum - chal.initial) / (chal.decay**2)) *
                 (solve_count**2)) + chal.initial

        value = math.ceil(value)
        if value < chal.minimum:
            value = chal.minimum

        chal.value = value
        db.session.commit()
        db.session.close()
Пример #10
0
 def fail(user, team, challenge, request):
     db.session.add(
         Fails(user_id=user.id,
               team_id=team.id if team else None,
               challenge_id=challenge.id,
               ip=get_ip(request),
               provided=request.judge_result['submission_id']))
     db.session.commit()
     db.session.close()
Пример #11
0
    def tracker():
        if request.endpoint == "views.themes":
            return

        if authed():
            track = Tracking.query.filter_by(ip=get_ip(),
                                             user_id=session["id"]).first()
            if not track:
                visit = Tracking(ip=get_ip(), user_id=session["id"])
                db.session.add(visit)
            else:
                track.date = datetime.datetime.utcnow()

            try:
                db.session.commit()
            except (InvalidRequestError, IntegrityError):
                db.session.rollback()
                logout_user()

            if authed():
                user = get_current_user()
                team = get_current_team()
                #level = get_level()

                if request.path.startswith("/themes") is False:
                    if user and user.banned:
                        return (
                            render_template(
                                "errors/403.html",
                                error="You have been banned from this CTF",
                            ),
                            403,
                        )

                    if team and team.banned:
                        return (
                            render_template(
                                "errors/403.html",
                                error="Your team has been banned from this CTF",
                            ),
                            403,
                        )

            db.session.close()
Пример #12
0
def log(logger, format, **kwargs):
    logger = logging.getLogger(logger)
    props = {
        "id": session.get("id"),
        "date": time.strftime("%m/%d/%Y %X"),
        "ip": get_ip(),
    }
    props.update(kwargs)
    msg = format.format(**props)
    logger.info(msg)
Пример #13
0
    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:
        """
        chal = DynamicChallenge.query.filter_by(id=challenge.id).first()
        data = request.form or request.get_json()
        submission = data['submission'].strip()

        Model = get_model()

        solve_count = Solves.query \
            .join(Model, Solves.account_id == Model.id) \
            .filter(Solves.challenge_id == challenge.id, Model.hidden == False, Model.banned == False) \
            .count()

        # It is important that this calculation takes into account floats.
        # Hence this file uses from __future__ import division
        # value = (
        #     (
        #         (chal.minimum - chal.initial) / (chal.decay**2)
        #     ) * (solve_count**2)
        # ) + chal.initial

        if (team and team.hidden == True) or (not team
                                              and user.hidden == True):
            pass
        else:

            value = chal.initial * 0.03 + (
                (chal.initial * 0.97) /
                (1 + (max(0, solve_count) / 4.92201)**3.206069))

            value = math.ceil(value)

            if value < chal.minimum:
                value = chal.minimum

            if chal.decay != 0 and solve_count >= chal.decay:
                value = chal.minimum

            chal.value = value

        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)
        db.session.add(solve)
        db.session.commit()
        db.session.close()
Пример #14
0
 def fail(user, team, challenge, request):
     data = request.form or request.get_json()
     submission = data['submission'].strip()
     wrong = Fails(user_id=user.id,
                   team_id=team.id if team else None,
                   challenge_id=challenge.id,
                   ip=get_ip(request),
                   provided=submission)
     db.session.add(wrong)
     db.session.commit()
     db.session.close()
    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()
Пример #16
0
    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:
        """
        chal = AliyunChallenge.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,
        )
        db.session.add(solve)

        solve_count = (
            Solves.query.join(Model, Solves.account_id == Model.id)
                .filter(
                Solves.challenge_id == challenge.id,
                Model.hidden == False,
                Model.banned == False,
            )
                .count()
        )

        # We subtract -1 to allow the first solver to get max point value
        solve_count -= 1

        # It is important that this calculation takes into account floats.
        # Hence this file uses from __future__ import division
        value = (
                        ((chal.minimum - chal.initial) / (chal.decay ** 2)) * (solve_count ** 2)
                ) + chal.initial

        value = math.ceil(value)

        if value < chal.minimum:
            value = chal.minimum

        chal.value = value

        db.session.commit()
        db.session.close()
Пример #17
0
    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:
        """
        chal = ADAChallenge.query.filter_by(id=challenge.id).first()
        data = request.form or request.get_json()
        submission = data["submission"].strip()

        Model = get_model()
        if Model == Users:
            attacker = GlowwormContainers.query.filter_by(user_id=user.id, challenge_id=challenge.id).first()
            attacker_name = user.name
            victim = GlowwormContainers.query.filter_by(flag=submission).first()
            victim_name = Users.query.filter_by(id=victim.user_id).first()
            team_id = None
        else:
            attacker = GlowwormContainers.query.filter_by(user_id=team.id, challenge_id=challenge.id).first()
            attacker_name = team.name
            victim = GlowwormContainers.query.filter_by(flag=submission).first()
            victim_name = Teams.query.filter_by(id=victim.user_id).first()
            team_id = victim_name.team_id

        attack = GlowwormAttacks(
            attack_id = attacker.user_id,
            attack_name = attacker_name,
            victim_id = victim.user_id,
            victim_name = victim_name.name,
            docker_id = victim.docker_id,
            envname = victim.docker_id.split("_",1)[1],
            flag = submission,
            round = get_round()
        )
        attack_log = GlowwormAttackLog(
            user_id=user.id,
            team_id=team.id if team else None,
            victim_user_id=victim_name.id,
            victim_team_id=team_id,
            challenge_id=challenge.id,
            ip=get_ip(req=request),
            provided=submission,
        )
        db.session.add(attack)
        db.session.add(attack_log)

        db.session.commit()
        db.session.close()
Пример #18
0
def log(logger, format, **kwargs):
    logger = logging.getLogger(logger)
    props = {
        'id': session.get('id'),
        'name': session.get('name'),
        'email': session.get('email'),
        'type': session.get('type'),
        'date': time.strftime("%m/%d/%Y %X"),
        'ip': get_ip()
    }
    props.update(kwargs)
    msg = format.format(**props)
    print(msg)
    logger.info(msg)
Пример #19
0
 def solve(cls, user, team, challenge, request):
     data = request.form or request.get_json()
     provided = ",".join(
         map(lambda x: x.split("_")[-1].upper(),
             filter(lambda x: data[x] is True, data)))
     solve = Solves(
         user_id=user.id,
         team_id=team.id if team else None,
         challenge_id=challenge.id,
         ip=get_ip(req=request),
         provided=provided,
     )
     db.session.add(solve)
     db.session.commit()
Пример #20
0
    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:
        """
        data = request.form or request.get_json()
        submission = data['submission'].strip()

        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)
Пример #21
0
    def solve(cls, user, team, challenge, request):
        print(f"Arward: {user} {team}")
        #super().solve(user, team, challenge, request)  // Do not Solve for MultiAnswser

        data = request.form or request.get_json()
        submission = data["submission"].strip()
        solve = Fails(
            user_id=user.id,
            team_id=team.id if team else None,
            challenge_id=challenge.id,
            ip=get_ip(req=request),
            type="correct",
            provided=submission,
        )

        db.session.add(solve)
        db.session.commit()
Пример #22
0
    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:
        """
        chal = DynamicChallenge.query.filter_by(id=challenge.id).first()
        data = request.form or request.get_json()
        submission = data['submission'].strip()

        solve_count = Solves.query\
            .join(Teams, Solves.team_id == Teams.id)\
            .filter(Solves.challenge_id == chal.id, Teams.banned == False)\
            .count()

        # It is important that this calculation takes into account floats.
        # Hence this file uses from __future__ import division
        value = (
            (
                (chal.minimum - chal.initial) / (chal.decay**2)
            ) * (solve_count**2)
        ) + chal.initial

        value = math.ceil(value)

        if value < chal.minimum:
            value = chal.minimum

        chal.value = value

        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
        )
        db.session.add(solve)
        db.session.commit()
        db.session.close()
Пример #23
0
    def solve(user, team, challenge, request):
        chal = KeyedChallenge.query.filter_by(id=challenge.id).first()
        data = request.form or request.get_json()
        submission = data['submission'].strip()

        Model = get_model()

        solve_count = Solves.query \
            .join(Model, Solves.account_id == Model.id) \
            .filter(Solves.challenge_id == challenge.id, Model.hidden == False, Model.banned == False) \
            .count()

        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)
        db.session.add(solve)
        db.session.commit()
        db.session.close()
Пример #24
0
    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:
        """
        data = request.form or request.get_json()
        submission = "No flags for this challenge"
        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,
        )
        db.session.add(solve)
        db.session.commit()
        db.session.close()
Пример #25
0
        def ratelimit_function(*args, **kwargs):
            ip_address = current_user.get_ip()
            key = "{}:{}:{}".format(key_prefix, ip_address, request.endpoint)
            current = cache.get(key)

            if request.method == method:
                if (
                    current and int(current) > limit - 1
                ):  # -1 in order to align expected limit with the real value
                    resp = jsonify(
                        {
                            "code": 429,
                            "message": "Too many requests."
                        }
                    )
                    resp.status_code = 429
                    return resp
                else:
                    if current is None:
                        cache.set(key, 1, timeout=interval)
                    else:
                        cache.set(key, int(current) + 1, timeout=interval)
            return f(*args, **kwargs)
Пример #26
0
    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:
        """
        chal = IntegratedChallenge.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)
        db.session.add(solve)

        db.session.commit()
        db.session.close()
Пример #27
0
    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:
        """
        chal = DynamicCheckChallenge.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,
        )
        db.session.add(solve)

        solve_count = (Solves.query.join(
            Model, Solves.account_id == Model.id).filter(
                Solves.challenge_id == challenge.id,
                Model.hidden == False,
                Model.banned == False,
            ).count())

        # We subtract -1 to allow the first solver to get max point value
        solve_count -= 1

        # add coolq send msg
        try:
            from .coolq import init_bot
            bot = init_bot()
            if solve_count == 0:
                msg = "[Msg] First Blood of {} by {}-{}".format(
                    challenge.name, team.name, user.name)
                bot.send_group_msg(group_id=793235129, message=msg)
            elif solve_count == 1:
                msg = "[Msg] Double Kill of {} by {}-{}".format(
                    challenge.name, team.name, user.name)
                bot.send_group_msg(group_id=793235129, message=msg)
            elif solve_count == 2:
                msg = "[Msg] Triple Kill of {} by {}-{}".format(
                    challenge.name, team.name, user.name)
                bot.send_group_msg(group_id=793235129, message=msg)
            else:
                msg = "[Msg] Rampage of {} by {}-{}".format(
                    challenge.name, team.name, user.name)
        except Exceptions as e:
            log("submissions",
                "[{date}] {name} bot error {error}",
                error=str(e))

        # It is important that this calculation takes into account floats.
        # Hence this file uses from __future__ import division
        value = (((chal.minimum - chal.initial) / (chal.decay**2)) *
                 (solve_count**2)) + chal.initial

        value = math.ceil(value)

        if value < chal.minimum:
            value = chal.minimum

        chal.value = value

        db.session.commit()
        db.session.close()
Пример #28
0
    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:
        """
        bonus = BonusChallenges.query.filter_by(id=chal.id).first()

        account_id = team.id
        provided_key = request.form['key'].strip()
        # solve = Solves(team_id=account_id, user_id=account_id, challenge_id=chal.id, ip=user.get_ip(req=request), flag=provided_key)
        try:
            solve = Solves(team_id=account_id, user_id=account_id, challenge_id=chal.id, ip=user.get_ip(req=request))
        
            db.session.add(solve)
            
            db.session.commit()
            # db.session.close() # don't close too soon. There is a parent query above this in /bonus route handler; ctrl-f for 'bhk3'
        except:
            db.session.rollback()