Esempio n. 1
0
def team_accept_invite():
	params = utils.flat_multi(request.form)
	_user = user.get_user().first()
	if user.in_team(_user):
		raise WebException("You're already in a team!")

	tid = params.get("tid")
	_team = get_team(tid=tid).first()
	if _team is None:
		raise WebException("Team not found.")

	if len(_team.get_members()) >= utils.get_config("team_size"):
		raise WebException("This team is full.")

	invitation = TeamInvitations.query.filter_by(rtype=0, frid=tid, toid=_user.uid).first()
	if invitation is None:
		raise WebException("Invitation doesn't exist.")

	with app.app_context():
		_user = Users.query.filter_by(uid=_user.uid).first()
		_user.tid = tid
		db.session.delete(invitation)
		invitation2 = TeamInvitations.query.filter_by(rtype=1, frid=_user.uid, toid=tid).first()
		if invitation2 is not None:
			db.session.delete(invitation2)
		db.session.add(Activity(_user.uid, 6, _team.tid, -1))
		db.session.commit()
		db.session.close()

	return { "success": 1, "message": "Success!" }
Esempio n. 2
0
def team_remove_member():
	username = session.get("username")
	tid = session.get("tid")
	team = Teams.query.filter_by(tid=tid).first()
	usr = Users.query.filter_by(username=username).first()
	owner = team.owner
	if team.finalized:
		raise WebException("This team is finalized.")
	if usr.uid == owner or usr.admin:
		params = utils.flat_multi(request.form)
		to_remove = params.get("username")
		if to_remove is None:
			return { "success": 0, "message": "ur high" }
		user_to_remove = Users.query.filter_by(username_lower=to_remove.lower()).first()
		if user_to_remove is None:
			return { "success": 0, "message": "User not found." }
		if user_to_remove.tid != tid:
			return { "success": 0, "message": "This user is not on your team!" }
		with app.app_context():
			Users.query.filter_by(uid=user_to_remove.uid).update({ "tid": -1 })
			db.session.commit()
			db.session.close()
		return { "success": 1, "message": "Success!" }
	else:
		raise WebException("Not authorized.")
Esempio n. 3
0
def user_twofactor_verify():
    _user = get_user().first()
    if _user is None:
        raise WebException("User not found.")

    params = utils.flat_multi(request.form)

    pwd = params.get("password")
    if pwd is None:
        raise WebException("Please enter your password.")
    if not utils.check_password(_user.password, pwd):
        raise WebException("Incorrect password.")

    if "token" not in params:
        raise WebException("Invalid token.")
    token = params.get("token")

    if not (_user.verify_totp(int(token))):
        raise WebException("Invalid token. Current server time: " +
                           time.strftime("%Y-%m-%d %H:%M:%S"))
    with app.app_context():
        Users.query.filter_by(uid=_user.uid).update({"otp_confirmed": True})
        db.session.commit()

    print "CONFIRMED"

    return {"success": 1, "message": "Confirmed!"}
Esempio n. 4
0
def team_invite():
	params = utils.flat_multi(request.form)
	_user = user.get_user().first()
	_team = get_team(tid=_user.tid).first()
	if _user.uid != _team.owner:
		raise WebException("You must be the captain of your team to invite members!")
	if _team.finalized:
		raise WebException("This team is finalized.")

	new_member = params.get("new_member")
	if new_member is None:
		raise WebException("Please provide a username!")
	_user2 = user.get_user(username_lower=new_member.lower()).first()
	if _user2 is None:
		raise WebException("User doesn't exist!")
	if _user2.tid > 0:
		raise WebException("This user is already a part of a team!")

	if _team.get_pending_invitations(toid=_user2.uid) is not None:
		raise WebException("You've already invited this member!")

	req = TeamInvitations(0, _team.tid, _user2.uid)
	with app.app_context():
		db.session.add(req)
		db.session.commit()
		db.session.close()

	return { "success": 1, "message": "Success!" }
Esempio n. 5
0
def user_twofactor_verify():
	_user = get_user().first()
	if _user is None:
		raise WebException("User not found.")

	params = utils.flat_multi(request.form)

	pwd = params.get("password")
	if pwd is None:
		raise WebException("Please enter your password.")
	if not utils.check_password(_user.password, pwd):
		raise WebException("Incorrect password.")

	if "token" not in params:
		raise WebException("Invalid token.")
	token = params.get("token")

	if not(_user.verify_totp(int(token))):
		raise WebException("Invalid token. Current server time: " + time.strftime("%Y-%m-%d %H:%M:%S"))
	with app.app_context():
		Users.query.filter_by(uid=_user.uid).update({ "otp_confirmed": True })
		db.session.commit()

	print "CONFIRMED"

	return { "success": 1, "message": "Confirmed!" }
Esempio n. 6
0
def team_delete():
	params = utils.flat_multi(request.form)
	if "tid" in params:
		tid = params.get("tid")
	else:
		tid = session.get("tid")

	username = session["username"]
	team = Teams.query.filter_by(tid=tid).first()
	usr = Users.query.filter_by(username=username).first()
	owner = team.owner
	if usr.uid == owner or usr.admin:
		with app.app_context():
			for member in Users.query.filter_by(tid=tid).all():
				member.tid = -1
				db.session.add(member)
			UserActivity.query.filter_by(tid=tid).delete()
			Solves.query.filter_by(tid=tid).delete()
			ProgrammingSubmissions.query.filter_by(tid=tid).delete()
			db.session.delete(team)
			db.session.commit()
			db.session.close()
			session.pop("tid")
		return { "success": 1, "message": "Success!" }
	else:
		raise WebException("Not authorized.")
Esempio n. 7
0
def team_accept_invite_request():
	params = utils.flat_multi(request.form)
	_user = user.get_user().first()
	if not user.in_team(_user):
		raise WebException("You must be in a team!")
	_team = get_team(tid=_user.tid).first()
	tid = _team.tid
	if _user.uid != _team.owner:
		raise WebException("You must be the captain of your team to rescind invitations!")
	if _team.finalized:
		raise WebException("This team is finalized.")

	if len(_team.get_members()) >= utils.get_config("team_size"):
		raise WebException("Your team is full.")

	uid = params.get("uid")
	_user2 = user.get_user(uid=uid).first()
	if user.in_team(_user2):
		raise WebException("This user is already in a team!")

	invitation = TeamInvitations.query.filter_by(rtype=1, frid=_user2.uid, toid=tid).first()
	if invitation is None:
		raise WebException("Invitation doesn't exist.")

	with app.app_context():
		_user2 = Users.query.filter_by(uid=_user2.uid).first()
		_user2.tid = tid
		db.session.delete(invitation)
		invitation2 = TeamInvitations.query.filter_by(rtype=0, frid=tid, toid=_user2.uid).first()
		if invitation2 is not None:
			db.session.delete(invitation2)
		db.session.commit()
		db.session.close()

	return { "success": 1, "message": "Success!" }
Esempio n. 8
0
def team_invite_rescind():
    params = utils.flat_multi(request.form)
    _user = user.get_user().first()
    _team = get_team(tid=_user.tid).first()
    if _user.uid != _team.owner:
        raise WebException(
            "You must be the captain of your team to rescind invitations!")
    if _team.finalized:
        raise WebException("This team is finalized.")

    uid = params.get("uid")
    if uid is None:
        raise WebException("Please provide a user.")
    invitation = TeamInvitations.query.filter_by(rtype=0,
                                                 frid=_team.tid,
                                                 toid=uid).first()
    if invitation is None:
        raise WebException("Invitation doesn't exist.")

    with app.app_context():
        db.session.delete(invitation)
        db.session.commit()
        db.session.close()

    return {"success": 1, "message": "Success!"}
Esempio n. 9
0
def team_invite():
    params = utils.flat_multi(request.form)
    _user = user.get_user().first()
    _team = get_team(tid=_user.tid).first()
    if _user.uid != _team.owner:
        raise WebException(
            "You must be the captain of your team to invite members!")
    if _team.finalized:
        raise WebException("This team is finalized.")

    new_member = params.get("new_member")
    if new_member is None:
        raise WebException("Please provide a username!")
    _user2 = user.get_user(username_lower=new_member.lower()).first()
    if _user2 is None:
        raise WebException("User doesn't exist!")
    if _user2.tid > 0:
        raise WebException("This user is already a part of a team!")

    if _team.get_pending_invitations(toid=_user2.uid) is not None:
        raise WebException("You've already invited this member!")

    req = TeamInvitations(0, _team.tid, _user2.uid)
    with app.app_context():
        db.session.add(req)
        db.session.commit()
        db.session.close()

    return {"success": 1, "message": "Success!"}
Esempio n. 10
0
def team_remove_member():
    username = session.get("username")
    tid = session.get("tid")
    team = Teams.query.filter_by(tid=tid).first()
    usr = Users.query.filter_by(username=username).first()
    owner = team.owner
    if team.finalized:
        raise WebException("This team is finalized.")
    if usr.uid == owner or usr.admin:
        params = utils.flat_multi(request.form)
        to_remove = params.get("username")
        if to_remove is None:
            return {"success": 0, "message": "ur high"}
        user_to_remove = Users.query.filter_by(
            username_lower=to_remove.lower()).first()
        if user_to_remove is None:
            return {"success": 0, "message": "User not found."}
        if user_to_remove.tid != tid:
            return {"success": 0, "message": "This user is not on your team!"}
        with app.app_context():
            Users.query.filter_by(uid=user_to_remove.uid).update({"tid": -1})
            db.session.commit()
            db.session.close()
        return {"success": 1, "message": "Success!"}
    else:
        raise WebException("Not authorized.")
Esempio n. 11
0
def team_delete():
    params = utils.flat_multi(request.form)
    if "tid" in params:
        tid = params.get("tid")
    else:
        tid = session.get("tid")

    username = session["username"]
    team = Teams.query.filter_by(tid=tid).first()
    usr = Users.query.filter_by(username=username).first()
    owner = team.owner
    if usr.uid == owner or usr.admin:
        with app.app_context():
            for member in Users.query.filter_by(tid=tid).all():
                member.tid = -1
                db.session.add(member)
            UserActivity.query.filter_by(tid=tid).delete()
            Solves.query.filter_by(tid=tid).delete()
            ProgrammingSubmissions.query.filter_by(tid=tid).delete()
            db.session.delete(team)
            db.session.commit()
            db.session.close()
            session.pop("tid")
        return {"success": 1, "message": "Success!"}
    else:
        raise WebException("Not authorized.")
Esempio n. 12
0
def user_register():
    params = utils.flat_multi(request.form)

    if params.get("password") != params.get("password_confirm"):
        raise WebException("Passwords do not match.")
    verify_to_schema(UserSchema, params)

    name = params.get("name")
    email = params.get("email")
    username = params.get("username")
    password = params.get("password")
    password_confirm = params.get("password_confirm")
    utype = int(params.get("type"))

    register_user(name, username, email, password, utype, admin=False)
    login_user(username, password)
    logger.log(
        __name__, "%s registered with %s" %
        (name.encode("utf-8"), email.encode("utf-8")))

    try:
        send_verification(username, email, token)
    except:
        return {
            "success": 1,
            "message": "Verification email sent to %s" % email
        }
    return {"success": 0, "message": "Failed."}
Esempio n. 13
0
def user_update_profile():
    params = utils.flat_multi(request.form)
    password = params.get("current_password")
    new_password = params.get("new_password")
    new_password_confirm = params.get("new_password_confirm")
    email = params.get("email")

    if new_password != new_password_confirm:
        raise WebException("Passwords do not match.")

    user = get_user(username=session["username"]).first()
    correct = utils.check_password(user.password, password)

    if not correct:
        raise WebException("Incorrect password.")
    if new_password != "":
        user.password = utils.hash_password(new_password)

    if email != user.email:
        if get_user(email=email.lower()).count() > 0:
            raise WebException("This email is taken!")
        user.email = email.lower()
        user.email_verified = False

    current_session = db.session.object_session(user)
    current_session.add(user)
    current_session.commit()
    return {"success": 1, "message": "Profile updated."}
Esempio n. 14
0
def user_update_profile():
	params = utils.flat_multi(request.form)
	password = params.get("current_password")
	new_password = params.get("new_password")
	new_password_confirm = params.get("new_password_confirm")
	email = params.get("email")

	if new_password != new_password_confirm:
		raise WebException("Passwords do not match.")

	user = get_user(username=session["username"]).first()
	correct = utils.check_password(user.password, password)

	if not correct:
		raise WebException("Incorrect password.")
	if new_password != "":
		user.password = utils.hash_password(new_password)

	if email != user.email:
		if get_user(email=email.lower()).count() > 0:
			raise WebException("This email is taken!")
		user.email = email.lower()
		user.email_verified = False

	current_session = db.session.object_session(user)
	current_session.add(user)
	current_session.commit()
	return { "success": 1, "message": "Profile updated." }
Esempio n. 15
0
def team_accept_invite():
    params = utils.flat_multi(request.form)
    _user = user.get_user().first()
    if user.in_team(_user):
        raise WebException("You're already in a team!")

    tid = params.get("tid")
    _team = get_team(tid=tid).first()
    if _team is None:
        raise WebException("Team not found.")
    if _team.finalized:
        raise WebException("This team is finalized.")

    if len(_team.get_members()) >= utils.get_config("team_size"):
        raise WebException("This team is full.")

    invitation = TeamInvitations.query.filter_by(rtype=0,
                                                 frid=tid,
                                                 toid=_user.uid).first()
    if invitation is None:
        raise WebException("Invitation doesn't exist.")

    with app.app_context():
        _user = Users.query.filter_by(uid=_user.uid).first()
        _user.tid = tid
        db.session.delete(invitation)
        invitation2 = TeamInvitations.query.filter_by(rtype=1,
                                                      frid=_user.uid,
                                                      toid=tid).first()
        if invitation2 is not None:
            db.session.delete(invitation2)
        db.session.commit()
        db.session.close()

    return {"success": 1, "message": "Success!"}
Esempio n. 16
0
def problem_submit():
    params = utils.flat_multi(request.form)
    pid = params.get("pid")
    flag = params.get("flag")
    tid = session.get("tid")
    _user = user.get_user().first()
    username = _user.username

    problem = Problems.query.filter_by(pid=pid).first()
    team = Teams.query.filter_by(tid=tid).first()
    solved = Solves.query.filter_by(pid=pid, tid=tid, correct=1).first()
    if solved:
        raise WebException("You already solved this problem.")

    flag_tried = Solves.query.filter_by(pid=pid, flag=flag).first()
    if flag_tried:
        raise WebException("Your team has already tried this solution.")

    if problem:
        if problem.category == "Programming":
            raise WebException(
                "Please submit programming problems using the Programming interface."
            )
        grader = imp.load_source("grader", problem.grader)
        random = None
        if problem.autogen:
            random = autogen.get_random(pid, tid)
        correct, response = grader.grade(random, flag)

        solve = Solves(pid, _user.uid, tid, flag, correct)
        db.session.add(solve)
        db.session.commit()

        if correct:
            # Wait until after the solve has been added to the database before adding bonus
            solves = get_solves(pid)
            solve.bonus = [-1, solves][solves < 4]

            cache.invalidate_memoization(get_solves, pid)

            if _user:
                activity = UserActivity(_user.uid, 3, tid=tid, pid=pid)
                db.session.add(activity)

            db.session.commit()
            logger.log(__name__,
                       "%s has solved %s by submitting %s" %
                       (team.teamname, problem.title, flag),
                       level=logger.WARNING)
            return {"success": 1, "message": response}
        else:
            logger.log(__name__,
                       "%s has incorrectly submitted %s to %s" %
                       (team.teamname, flag, problem.title),
                       level=logger.WARNING)
            raise WebException(response)

    else:
        raise WebException("Problem does not exist!")
Esempio n. 17
0
def activity_team():
	params = utils.flat_multi(request.args)
	if "team" not in params:
		raise WebException("Please specify a team.")
	_team = get_team(teamname_lower=params.get("team").lower()).first()
	if _team is None:
		raise WebException("Team not found.")
	return _team.get_activity()
Esempio n. 18
0
def activity_user():
	params = utils.flat_multi(request.args)
	if "user" not in params:
		raise WebException("Please specify a user.")
	_user = get_user(username_lower=params.get("user").lower()).first()
	if _user is None:
		raise WebException("User not found.")
	return _user.get_activity()
Esempio n. 19
0
def clear_solves():
    params = utils.flat_multi(request.form)

    pid = params.get("pid")
    Solves.query.filter_by(pid=pid).delete()
    ProgrammingSubmissions.query.filter_by(pid=pid).delete()
    cache.invalidate_memoization(get_solves, pid)
    db.session.commit()

    return {"success": 1, "message": "Submissions cleared."}
Esempio n. 20
0
def clear_solves():
	params = utils.flat_multi(request.form)

	pid = params.get("pid")
	Solves.query.filter_by(pid=pid).delete()
	ProgrammingSubmissions.query.filter_by(pid=pid).delete()
	cache.invalidate_memoization(get_solves, pid)
	db.session.commit()

	return { "success": 1, "message": "Submissions cleared." }
Esempio n. 21
0
def problem_solves():
	params = utils.flat_multi(request.form)
	pid = params.get("pid")
	solves_return = []
	solves = Solves.query.filter_by(pid=pid,correct=True).order_by("date asc").all()
	for solve in solves:
		data = {
			"teamname": Teams.query.filter_by(tid=solve.tid).first().teamname,
			"date": utils.isoformat(float(solve.date))
		}
		solves_return.append(data)
	return { "success": 1, "solves": solves_return }
Esempio n. 22
0
def user_info():
	logged_in = is_logged_in()
	username = utils.flat_multi(request.args).get("username")
	if username is None:
		if logged_in:
			username = session["username"]
	if username is None:
		raise WebException("No user specified.")
	me = False if not("username" in session) else username.lower() == session["username"].lower()
	user = get_user(username_lower=username.lower()).first()
	if user is None:
		raise WebException("User not found.")

	show_email = me if logged_in else False
	user_in_team = in_team(user)
	userdata = {
		"user_found": True,
		"name": user.name,
		"username": user.username,
		"type": ["Student", "Instructor", "Observer"][user.utype - 1],
		"admin": user.admin,
		"registertime": datetime.datetime.fromtimestamp(user.registertime).isoformat() + "Z",
		"me": me,
		"show_email": show_email,
		"in_team": user_in_team,
		"uid": user.uid,
		"activity": user.get_activity(),
		"tfa_enabled": user.tfa_enabled(),
		"stats": user.get_stats()
	}
	if show_email:
		userdata["email"] = user.email
	if user_in_team:
		userdata["team"] = team.get_team_info(tid=user.tid)
	if me:
		userdata["tfa_enabled"] = user.tfa_enabled()
		userdata["email_verified"] = user.email_verified == True
		if not(user_in_team):
			invitations = user.get_invitations()
			userdata["invitations"] = invitations
		session_data = []
		sessions = LoginTokens.query.filter_by(username=user.username, active=True).all()
		for _session in sessions:
			session_data.append({
				"sid": _session.sid,
				"me": _session.sid == session["sid"],
				"ip": _session.ip,
				"location": _session.location,
				"since": datetime.datetime.fromtimestamp(_session.issued).isoformat() + "Z"
			})
		userdata["sessions"] = session_data
	return { "success": 1, "user": userdata }
Esempio n. 23
0
def problem_submit():
	params = utils.flat_multi(request.form)
	pid = params.get("pid")
	flag = params.get("flag")
	tid = session.get("tid")
	_user = user.get_user().first()
	username = _user.username

	problem = Problems.query.filter_by(pid=pid).first()
	team = Teams.query.filter_by(tid=tid).first()
	solved = Solves.query.filter_by(pid=pid, tid=tid, correct=1).first()
	if solved:
		raise WebException("You already solved this problem.")

	flag_tried = Solves.query.filter_by(pid=pid, flag=flag).first()
	if flag_tried:
		raise WebException("Your team has already tried this solution.")

	if problem:
		if problem.category == "Programming":
			raise WebException("Please submit programming problems using the Programming interface.")
		grader = imp.load_source("grader", problem.grader)
		random = None
		if problem.autogen:
			random = autogen.get_random(pid, tid)
		correct, response = grader.grade(random, flag)

		solve = Solves(pid, _user.uid, tid, flag, correct)
		db.session.add(solve)
		db.session.commit()

		if correct:
			# Wait until after the solve has been added to the database before adding bonus
			solves = get_solves(pid)
			solve.bonus = [-1, solves][solves < 4]

			cache.invalidate_memoization(get_solves, pid)

			if _user:
				activity = UserActivity(_user.uid, 3, tid=tid, pid=pid)
				db.session.add(activity)

			db.session.commit()
			logger.log(__name__, "%s has solved %s by submitting %s" % (team.teamname, problem.title, flag), level=logger.WARNING)
			return { "success": 1, "message": response }
		else:
			logger.log(__name__, "%s has incorrectly submitted %s to %s" % (team.teamname, flag, problem.title), level=logger.WARNING)
			raise WebException(response)

	else:
		raise WebException("Problem does not exist!")
Esempio n. 24
0
def problem_delete():
    params = utils.flat_multi(request.form)
    pid = params.get("pid")
    problem = Problems.query.filter_by(pid=pid).first()
    if problem:
        ProgrammingSubmissions.query.filter_by(pid=pid).delete()
        Solves.query.filter_by(pid=pid).delete()
        UserActivity.query.filter_by(pid=pid).delete()
        Problems.query.filter_by(pid=pid).delete()
        grader_folder = os.path.dirname(problem.grader)
        shutil.rmtree(grader_folder)
        db.session.commit()
        return {"success": 1, "message": "Success!"}
    raise WebException("Problem does not exist!")
Esempio n. 25
0
def user_forgot_password(token=None):
    params = utils.flat_multi(request.form)
    if token is not None:
        user = get_user(reset_token=token).first()
        if user is None:
            raise WebException("Invalid reset token.")

        # We are viewing the actual reset form
        if request.method == "GET":
            return {"success": 1, "message": ""}

        # Submission of actual reset form
        if request.method == "POST":
            password = params.get("password")
            confirm_password = params.get("confirm_password")
            if password != confirm_password:
                raise WebException("Passwords do not match.")
            else:
                user.password = utils.hash_password(password)
                user.reset_token = None
                current_session = db.session.object_session(user)
                current_session.add(user)
                current_session.commit()
                return {"success": 1, "message": "Success!"}
    else:
        email = params.get("email").lower()

        user = get_user(email=email).first()
        if user is None:
            raise WebException("User with that email does not exist.")

        token = utils.generate_string(length=64)
        user.reset_token = token
        current_session = db.session.object_session(user)
        current_session.add(user)
        current_session.commit()

        reset_link = "%s/forgot/%s" % ("127.0.0.1:8000", token)
        subject = "OpenCTF password reset"
        body = """%s,\n\nA request to reset your OpenCTF password has been made. If you did not request this password reset, you may safely ignore this email and delete it.\n\nYou may reset your password by clicking this link or pasting it to your browser.\n\n%s\n\nThis link can only be used once, and will lead you to a page where you can reset your password.\n\nGood luck!\n\n- OpenCTF Administrator""" % (
            user.username, reset_link)
        response = utils.send_email(email, subject, body)
        if response.status_code != 200:
            raise WebException("Could not send email")

        response = response.json()
        if "Queued" in response["message"]:
            return {"success": 1, "message": "Email sent to %s" % email}
        else:
            raise WebException(response["message"])
Esempio n. 26
0
def delete_submission():
    params = utils.flat_multi(request.form)
    psid = params.get("psid")
    tid = session.get("tid")
    result = ProgrammingSubmissions.query.filter_by(psid=psid, tid=tid)

    if result.first() is None:
        raise WebException("Submission does not exist.")

    with app.app_context():
        result.delete()
        db.session.commit()

    return {"success": 1, "message": "Success!"}
Esempio n. 27
0
def delete_submission():
	params = utils.flat_multi(request.form)
	psid = params.get("psid")
	tid = session.get("tid")
	result = ProgrammingSubmissions.query.filter_by(psid=psid, tid=tid)

	if result.first() is None:
		raise WebException("Submission does not exist.")

	with app.app_context():
		result.delete()
		db.session.commit()

	return { "success": 1, "message": "Success!" }
Esempio n. 28
0
def problem_delete():
	params = utils.flat_multi(request.form)
	pid = params.get("pid")
	problem = Problems.query.filter_by(pid=pid).first()
	if problem:
		ProgrammingSubmissions.query.filter_by(pid=pid).delete()
		Solves.query.filter_by(pid=pid).delete()
		UserActivity.query.filter_by(pid=pid).delete()
		Problems.query.filter_by(pid=pid).delete()
		grader_folder = os.path.dirname(problem.grader)
		shutil.rmtree(grader_folder)
		db.session.commit()
		return { "success": 1, "message": "Success!" }
	raise WebException("Problem does not exist!")
Esempio n. 29
0
def user_forgot_password(token=None):
	params = utils.flat_multi(request.form)
	if token is not None:
		user = get_user(reset_token=token).first()
		if user is None:
			raise WebException("Invalid reset token.")

		# We are viewing the actual reset form
		if request.method == "GET":
			return { "success": 1, "message": ""}

		# Submission of actual reset form
		if request.method == "POST":
			password = params.get("password")
			confirm_password = params.get("confirm_password")
			if password != confirm_password:
				raise WebException("Passwords do not match.")
			else:
				user.password = utils.hash_password(password)
				user.reset_token = None
				current_session = db.session.object_session(user)
				current_session.add(user)
				current_session.commit()
				return { "success": 1, "message": "Success!" }
	else:
		email = params.get("email").lower()

		user = get_user(email=email).first()
		if user is None:
			raise WebException("User with that email does not exist.")

		token = utils.generate_string(length=64)
		user.reset_token = token
		current_session = db.session.object_session(user)
		current_session.add(user)
		current_session.commit()

		reset_link = "%s/forgot/%s" % ("127.0.0.1:8000", token)
		subject = "OpenCTF password reset"
		body = """%s,\n\nA request to reset your OpenCTF password has been made. If you did not request this password reset, you may safely ignore this email and delete it.\n\nYou may reset your password by clicking this link or pasting it to your browser.\n\n%s\n\nThis link can only be used once, and will lead you to a page where you can reset your password.\n\nGood luck!\n\n- OpenCTF Administrator""" % (user.username, reset_link)
		response = utils.send_email(email, subject, body)
		if response.status_code != 200:
			raise WebException("Could not send email")

		response = response.json()
		if "Queued" in response["message"]:
			return { "success": 1, "message": "Email sent to %s" % email }
		else:
			raise WebException(response["message"])
Esempio n. 30
0
def open_ticket():
    params = utils.flat_multi(request.form)

    htid = params.get("htid")

    ticket = get_ticket(htid=htid).first()
    if ticket is None:
        raise WebException("Ticket does not exist.")

    ticket.opened = True
    with app.app_context():
        db.session.add(ticket)
        db.session.commit()

    return {"success": 1, "message": "Ticket opened."}
Esempio n. 31
0
def open_ticket():
	params = utils.flat_multi(request.form)

	htid = params.get("htid")

	ticket = get_ticket(htid=htid).first()
	if ticket is None:
		raise WebException("Ticket does not exist.")

	ticket.opened = True
	with app.app_context():
		db.session.add(ticket)
		db.session.commit()

	return { "success": 1, "message": "Ticket opened." }
Esempio n. 32
0
def problem_add():
	params = utils.flat_multi(request.form)
	title = params.get("title")
	category = params.get("category")
	description = params.get("description")
	hint = params.get("hint")
	value = params.get("value")
	grader_contents = params.get("grader_contents")
	bonus = params.get("bonus")
	autogen = params.get("autogen")
	try:
		add_problem(title, category, description, value, grader_contents, hint=hint, bonus=bonus, autogen=autogen)
	except e:
		raise WebException(str(e))
	return { "success": 1, "message": "Success!" }
Esempio n. 33
0
def team_info():
    logged_in = user.is_logged_in()
    my_team = -1
    in_team = False
    owner = False
    _user = None
    teamdata = {}
    search = {}
    teamname = utils.flat_multi(request.args).get("teamname")
    if teamname:
        search.update({"teamname_lower": teamname.lower()})
    if logged_in:
        _user = user.get_user().first()
        if user.in_team(_user):
            my_team = _user.tid
            if "teamname_lower" not in search:
                search.update({"tid": _user.tid})
                in_team = True
    if bool(search) != False:
        team = get_team(**search).first()
        teamdata = get_team_info(**search)
        if logged_in:
            in_team = teamdata["tid"] == _user.tid
            owner = teamdata["captain"] == _user.uid
        teamdata["in_team"] = in_team
        teamdata["my_team"] = my_team
        if in_team:
            teamdata["is_owner"] = owner
            if owner:
                teamdata["pending_invitations"] = team.get_pending_invitations(
                )
                teamdata["invitation_requests"] = team.get_invitation_requests(
                )
        else:
            if logged_in:
                teamdata["invited"] = team.get_pending_invitations(
                    toid=_user.uid) is not None
                teamdata["requested"] = team.get_invitation_requests(
                    frid=_user.uid) is not None
    else:
        if logged_in:
            teamdata["invitations"] = _user.get_invitations()
            teamdata["my_team"] = my_team
            teamdata["tid"] = -1
        else:
            # Non-logged-in user viewing /team page
            raise WebException()
    return {"success": 1, "team": teamdata}
Esempio n. 34
0
def reply_to_ticket():
	params = utils.flat_multi(request.form)

	htid = params.get("htid")
	body = params.get("body")

	_user = user.get_user().first()
	if _user is None:
		raise WebException("User does not exist.")

	reply = TicketReplies(htid, body, _user.uid)
	with app.app_context():
		db.session.add(reply)
		db.session.commit()

	return { "success": 1, "message": "" }
Esempio n. 35
0
def admin_settings_update():
	params = utils.flat_multi(request.form)
	params.pop("csrf_token")
	with app.app_context():
		for key in params:
			config = Config.query.filter_by(key=key).first()
			if config is None:
				config = Config(key, params[key])
			else:
				new = params[key]
				if config.value != new:
					config.value = params[key]
			db.session.add(config)
		db.session.commit()

	return { "success": 1, "message": "Success!" }
Esempio n. 36
0
def reply_to_ticket():
    params = utils.flat_multi(request.form)

    htid = params.get("htid")
    body = params.get("body")

    _user = user.get_user().first()
    if _user is None:
        raise WebException("User does not exist.")

    reply = TicketReplies(htid, body, _user.uid)
    with app.app_context():
        db.session.add(reply)
        db.session.commit()

    return {"success": 1, "message": ""}
Esempio n. 37
0
def user_session_delete():
    params = utils.flat_multi(request.form)
    sid = params.get("sid")
    if sid is None:
        raise WebException("Please specify which session to delete.")

    with app.app_context():
        _session = LoginTokens.query.filter_by(sid=sid).first()
        _user = get_user().first()
        if _session.uid != _user.uid:
            raise WebException("That's not your token!")
        LoginTokens.query.filter_by(sid=sid).update({"active": False})
        db.session.commit()

    assert (LoginTokens.query.filter_by(sid=sid).first().active == False)

    return {"success": 1, "message": "Deleted."}
Esempio n. 38
0
def create_ticket():
	params = utils.flat_multi(request.form)

	title = params.get("title")
	body = params.get("body")
	username = session.get("username")

	_user = user.get_user().first()
	if _user is None:
		raise WebException("User does not exist.")

	ticket = Tickets(title, body, _user.uid)
	with app.app_context():
		db.session.add(ticket)
		db.session.commit()

	return { "success": 1, "message": "Ticket created." }
Esempio n. 39
0
def team_info():
	logged_in = user.is_logged_in()
	my_team = -1
	in_team = False
	owner = False
	_user = None
	teamdata = { }
	search = { }
	teamname = utils.flat_multi(request.args).get("teamname")
	if teamname:
		search.update({ "teamname_lower": utils.escape_teamname(teamname) })
	if logged_in:
		_user = user.get_user().first()
		if user.in_team(_user):
			my_team = _user.tid
			if "teamname_lower" not in search:
				search.update({ "tid": _user.tid })
				in_team = True
	if bool(search) != False:
		team = get_team(**search).first()
		teamdata = get_team_info(**search)
		if logged_in:
			in_team = teamdata["tid"] == _user.tid
			owner = teamdata["captain"] == _user.uid
		teamdata["in_team"] = in_team
		teamdata["my_team"] = my_team
		if in_team:
			teamdata["is_owner"] = owner
			if owner:
				teamdata["pending_invitations"] = team.get_pending_invitations()
				teamdata["invitation_requests"] = team.get_invitation_requests()
		else:
			if logged_in:
				teamdata["invited"] = team.get_pending_invitations(toid=_user.uid) is not None
				teamdata["requested"] = team.get_invitation_requests(frid=_user.uid) is not None
		teamdata["activity"] = team.get_activity()
	else:
		if logged_in:
			teamdata["invitations"] = _user.get_invitations()
			teamdata["my_team"] = my_team
			teamdata["tid"] = -1
			teamdata["activity"] = []
		else:
			# Non-logged-in user viewing /team page
			raise WebException()
	return { "success": 1, "team": teamdata }
Esempio n. 40
0
def user_session_delete():
	params = utils.flat_multi(request.form)
	sid = params.get("sid")
	if sid is None:
		raise WebException("Please specify which session to delete.")

	with app.app_context():
		_session = LoginTokens.query.filter_by(sid=sid).first()
		_user = get_user().first()
		if _session.uid != _user.uid:
			raise WebException("That's not your token!")
		LoginTokens.query.filter_by(sid=sid).update({ "active": False })
		db.session.commit()

	assert(LoginTokens.query.filter_by(sid=sid).first().active == False)

	return { "success": 1, "message": "Deleted." }
Esempio n. 41
0
def create_ticket():
    params = utils.flat_multi(request.form)

    title = params.get("title")
    body = params.get("body")
    username = session.get("username")

    _user = user.get_user().first()
    if _user is None:
        raise WebException("User does not exist.")

    ticket = Tickets(title, body, _user.uid)
    with app.app_context():
        db.session.add(ticket)
        db.session.commit()

    return {"success": 1, "message": "Ticket created."}
Esempio n. 42
0
def problem_update():
	params = utils.flat_multi(request.form)
	pid = params.get("pid", "")
	title = params.get("title", "")
	category = params.get("category", "")
	description = params.get("description", "")
	hint = params.get("hint", "")
	value = params.get("value", 0)
	bonus = params.get("bonus", 0)
	grader_contents = params.get("grader_contents", "")
	autogen = params.get("autogen", 0)
	try:
		weightmap = json.loads(params.get("weightmap", "{}"))
	except:
		weightmap = {}
	threshold = params.get("threshold", 0)

	problem = Problems.query.filter_by(pid=pid).first()
	if problem:
		problem.pid = title.lower().replace(" ", "-")
		problem.title = title
		problem.category = category
		problem.description = description
		problem.hint = hint
		problem.value = value
		problem.bonus = bonus
		problem.autogen = autogen
		problem.weightmap = weightmap
		problem.threshold = threshold

		if category == "Programming":
			programming.validate_judge(grader_contents)
		else:
			validate_grader(grader_contents, autogen=int(autogen))

		with open(problem.grader, "w") as grader:
			grader.write(grader_contents)
			grader.close()

		db.session.add(problem)
		db.session.commit()
		db.session.close()

		return { "success": 1, "message": "Success!" }
	raise WebException("Problem does not exist!")
Esempio n. 43
0
def team_edit():
	params = utils.flat_multi(request.form)
	_user = user.get_user().first()
	_team = get_team(tid=_user.tid).first()
	if _user.uid != _team.owner:
		raise WebException("You must be the captain of your team to edit information!")

	with app.app_context():
		update = {}
		if params.get("new_teamname") is not None:
			if get_team(teamname_lower=utils.escape_teamname(params["new_teamname"])).first() is not None:
				raise WebException("This team name is taken!")
			update["teamname"] = params["new_teamname"]
			update["teamname_lower"] = utils.escape_teamname(params["new_teamname"])
		if params.get("new_school") is not None:
			update["school"] = params["new_school"]
		_team.update_info(update)

	return { "success": 1 }
Esempio n. 44
0
def problem_add():
	params = utils.flat_multi(request.form)
	title = params.get("title", "")
	category = params.get("category", "")
	description = params.get("description", "")
	hint = params.get("hint", "")
	value = params.get("value", 0)
	grader_contents = params.get("grader_contents", "")
	bonus = params.get("bonus", 0)
	autogen = params.get("autogen", 0)
	try:
		weightmap = json.loads(params.get("weightmap", "{}"))
	except:
		weightmap = {}
	threshold = params.get("threshold", 0)

	try:
		add_problem(title, category, description, value, grader_contents, hint=hint, bonus=bonus, autogen=autogen, threshold=threshold, weightmap=weightmap)
	except Exception, e:
		raise WebException("Error: " + str(e))
Esempio n. 45
0
def team_invite_rescind():
	params = utils.flat_multi(request.form)
	_user = user.get_user().first()
	_team = get_team(tid=_user.tid).first()
	if _user.uid != _team.owner:
		raise WebException("You must be the captain of your team to rescind invitations!")

	uid = params.get("uid")
	if uid is None:
		raise WebException("Please provide a user.")
	invitation = TeamInvitations.query.filter_by(rtype=0, frid=_team.tid, toid=uid).first()
	if invitation is None:
		raise WebException("Invitation doesn't exist.")

	with app.app_context():
		db.session.delete(invitation)
		db.session.commit()
		db.session.close()

	return { "success": 1, "message": "Success!" }
Esempio n. 46
0
def verify_email():
    # Actual verification of email
    if request.method == "GET":
        params = utils.flat_multi(request.args)
        token = params.get("token")
        if token is not None:
            user = Users.query.filter_by(email_token=token).first()
            if user is None:
                raise WebException("Invalid token.")

            user.email_verified = True
            user.email_token = None
            current_session = db.session.object_session(user)
            current_session.add(user)
            current_session.commit()

            return {"success": 1, "message": "Email verified."}
        raise WebException("Invalid token.")
    # Request to verify email
    elif request.method == "POST":
        user = get_user().first()
        if user is None:
            raise WebException("User with that username does not exist.")

        if user.email_verified:
            raise WebException("Email is already verified.")

        token = utils.generate_string(length=64)
        user.email_token = token
        current_session = db.session.object_session(user)
        current_session.add(user)
        current_session.commit()

        try:
            send_verification(user.username, user.email, token)
        except:
            return {"success": 0, "message": "Failed."}
        return {
            "success": 1,
            "message": "Verification email sent to %s" % user.email
        }
Esempio n. 47
0
def team_create():
	params = utils.flat_multi(request.form)
	_user = user.get_user().first()
	if (_user.tid is not None and _user.tid >= 0) or get_team(owner=_user.uid).first() is not None:
		raise WebException("You're already in a team!")

	verify_to_schema(TeamSchema, params)
	teamname = params.get("teamname")
	school = params.get("school")

	team = Teams(teamname, school, _user.uid, _user.utype != 1)
	with app.app_context():
		db.session.add(team)
		db.session.commit()
		Users.query.filter_by(uid=_user.uid).update({ "tid": team.tid })
		team_activity = UserActivity(_user.uid, 1, tid=team.tid)
		db.session.add(team_activity)
		db.session.commit()

		session["tid"] = team.tid
	return { "success": 1, "message": "Success!" }
Esempio n. 48
0
def team_invite_request():
	params = utils.flat_multi(request.form)
	_user = user.get_user().first()
	if user.in_team(_user):
		raise WebException("You're already in a team!")

	tid = params.get("tid")
	_team = get_team(tid=tid).first()
	if _team is None:
		raise WebException("Team not found.")

	if _team.get_invitation_requests(frid=_user.uid) is not None:
		raise WebException("You've already requested to join this team!")

	req = TeamInvitations(1, _user.uid, _team.tid)
	with app.app_context():
		db.session.add(req)
		db.session.commit()
		db.session.close()

	return { "success": 1, "message": "Success!" }
Esempio n. 49
0
def admin_setup():
	global user
	params = utils.flat_multi(request.form)
	if utils.is_setup_complete(): raise WebException("Setup has already been complete.")

	if params.get("verification") != Config.query.filter_by(key="setup_verification").first().value:
		raise WebException("Verification does not match.")

	if params.get("password") != params.get("password_confirm"):
		raise WebException("Passwords do not match.")
	verify_to_schema(user.UserSchema, params)

	name = params.get("name")
	email = params.get("email")
	username = params.get("username")
	password = params.get("password")
	password_confirm = params.get("password_confirm")
	utype = int(params.get("type"))

	setup_vars = [
		Config("ctf_name", params.get("ctf_name")),
		Config("start_time", params.get("start_time")),
		Config("end_time", params.get("end_time")),
		Config("team_size", params.get("team_size")),
		Config("stylesheet", "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"),
		Config("setup_complete", True)
	]

	#  _user = Users(name, username, email, password, utype=utype, admin=True)
	user.register_user(name, username, email, password, utype=utype, admin=True)
	with app.app_context():
		for var in setup_vars:
			db.session.add(var)
			db.session.commit()
			db.session.close()

	logger.log(__name__, "%s registered with %s" % (name.encode("utf-8"), email.encode("utf-8")))
	user.login_user(username, password)

	return { "success": 1, "message": "Success!" }
Esempio n. 50
0
def problem_add():
    params = utils.flat_multi(request.form)
    title = params.get("title")
    category = params.get("category")
    description = params.get("description")
    hint = params.get("hint")
    value = params.get("value")
    grader_contents = params.get("grader_contents")
    bonus = params.get("bonus")
    autogen = params.get("autogen")
    try:
        add_problem(title,
                    category,
                    description,
                    value,
                    grader_contents,
                    hint=hint,
                    bonus=bonus,
                    autogen=autogen)
    except e:
        raise WebException(str(e))
    return {"success": 1, "message": "Success!"}
Esempio n. 51
0
def team_create():
    params = utils.flat_multi(request.form)
    _user = user.get_user().first()
    if (_user.tid is not None and _user.tid >= 0) or get_team(
            owner=_user.uid).first() is not None:
        raise WebException("You're already in a team!")

    verify_to_schema(TeamSchema, params)
    teamname = params.get("teamname")
    school = params.get("school")

    team = Teams(teamname, school, _user.uid, _user.utype != 1)
    with app.app_context():
        db.session.add(team)
        db.session.commit()
        Users.query.filter_by(uid=_user.uid).update({"tid": team.tid})
        team_activity = UserActivity(_user.uid, 1, tid=team.tid)
        db.session.add(team_activity)
        db.session.commit()

        session["tid"] = team.tid
    return {"success": 1, "message": "Success!"}
Esempio n. 52
0
def team_invite_request():
    params = utils.flat_multi(request.form)
    _user = user.get_user().first()
    if user.in_team(_user):
        raise WebException("You're already in a team!")

    tid = params.get("tid")
    _team = get_team(tid=tid).first()
    if _team is None:
        raise WebException("Team not found.")
    if _team.finalized:
        raise WebException("This team is finalized.")

    if _team.get_invitation_requests(frid=_user.uid) is not None:
        raise WebException("You've already requested to join this team!")

    req = TeamInvitations(1, _user.uid, _team.tid)
    with app.app_context():
        db.session.add(req)
        db.session.commit()
        db.session.close()

    return {"success": 1, "message": "Success!"}
Esempio n. 53
0
def team_edit():
    params = utils.flat_multi(request.form)
    _user = user.get_user().first()
    _team = get_team(tid=_user.tid).first()
    if _user.uid != _team.owner:
        raise WebException(
            "You must be the captain of your team to edit information!")
    if _team.finalized:
        raise WebException("This team is finalized.")

    with app.app_context():
        update = {}
        if params.get("new_teamname") is not None:
            if get_team(teamname_lower=params["new_teamname"].lower()).first(
            ) is not None:
                raise WebException("This team name is taken!")
            update["teamname"] = params["new_teamname"]
            update["teamname_lower"] = params["new_teamname"].lower()
        if params.get("new_school") is not None:
            update["school"] = params["new_school"]
        _team.update_info(update)

    return {"success": 1}
Esempio n. 54
0
def user_login():
    params = utils.flat_multi(request.form)

    username = params.get("username")
    password = params.get("password")
    token = params.get("token")

    if username is None or password is None:
        raise WebException("Please fill out all the fields.")

    creds = {"username": username, "password": password}
    _user = get_user(username_lower=username.lower()).first()
    if _user is None:
        raise WebException("This user doesn't exist!")
    if _user.tfa_enabled():
        if token is None:
            raise WebException("Invalid token.")
        creds["token"] = params.get("token")
    result = login_user(**creds)
    if result != True:
        raise WebException("Please check if your credentials are correct.")

    return {"success": 1, "message": "Success!"}
Esempio n. 55
0
def problem_update():
    params = utils.flat_multi(request.form)
    pid = params.get("pid")
    title = params.get("title")
    category = params.get("category")
    description = params.get("description")
    hint = params.get("hint")
    value = params.get("value")
    bonus = params.get("bonus")
    grader_contents = params.get("grader_contents")
    autogen = params.get("autogen")

    problem = Problems.query.filter_by(pid=pid).first()
    if problem:
        problem.title = title
        problem.category = category
        problem.description = description
        problem.hint = hint
        problem.value = value
        problem.bonus = bonus
        problem.autogen = autogen

        if category == "Programming":
            programming.validate_judge(grader_contents)
        else:
            validate_grader(grader_contents, autogen=int(autogen))

        with open(problem.grader, "w") as grader:
            grader.write(grader_contents)
            grader.close()

        db.session.add(problem)
        db.session.commit()

        return {"success": 1, "message": "Success!"}
    raise WebException("Problem does not exist!")
Esempio n. 56
0
def ticket_data():
    opened = []
    closed = []
    _user = user.get_user().first()
    if _user is None:
        raise WebException("User does not exist.")

    params = utils.flat_multi(request.args)
    htid = params.get("htid")

    if htid is not None:
        result = get_ticket(htid=htid).first()
    elif user.is_admin():
        result = get_ticket().all()
    else:
        result = get_ticket(author=_user.uid).all()

    if result is not None:
        if htid is not None:
            tickets = [result]
        else:
            tickets = result

        for ticket in tickets:
            tmp = user.get_user(uid=ticket.author).first()

            if tmp is not None:
                username = tmp.username
                uid = tmp.uid
            else:
                username = ""
                uid = ""

            replies = ticket.get_replies()
            d = {
                "htid":
                ticket.htid,
                "date":
                utils.isoformat(ticket.date),
                "opened":
                ticket.opened,
                "username":
                username,
                "uid":
                uid,
                "title":
                ticket.title,
                "body":
                markdown2.markdown(ticket.body),
                "replies":
                replies,
                "participants":
                list(set([username] + [reply["username"]
                                       for reply in replies])),
                "you": {
                    "username": _user.username,
                    "uid": _user.uid
                }
            }

            if htid is None:
                if d["opened"] == True:
                    opened.append(d)
                else:
                    closed.append(d)
            else:
                data = d
    else:
        data = {}

    if htid is None:
        data = [opened, closed]

    return {"success": 1, "data": data}
Esempio n. 57
0
def user_info():
    logged_in = is_logged_in()
    username = utils.flat_multi(request.args).get("username")
    if username is None:
        if logged_in:
            username = session["username"]
    if username is None:
        raise WebException("No user specified.")
    me = False if not ("username" in session) else username.lower(
    ) == session["username"].lower()
    user = get_user(username_lower=username.lower()).first()
    if user is None:
        raise WebException("User not found.")

    show_email = me if logged_in else False
    user_in_team = in_team(user)
    userdata = {
        "user_found":
        True,
        "name":
        user.name,
        "username":
        user.username,
        "type": ["Student", "Instructor", "Observer"][user.utype - 1],
        "admin":
        user.admin,
        "registertime":
        datetime.datetime.fromtimestamp(user.registertime).isoformat() + "Z",
        "me":
        me,
        "show_email":
        show_email,
        "in_team":
        user_in_team,
        "uid":
        user.uid,
        "activity":
        user.get_activity(),
        "tfa_enabled":
        user.tfa_enabled(),
        "stats":
        user.get_stats()
    }
    if show_email:
        userdata["email"] = user.email
    if user_in_team:
        userdata["team"] = team.get_team_info(tid=user.tid)
    if me:
        userdata["tfa_enabled"] = user.tfa_enabled()
        userdata["email_verified"] = user.email_verified == True
        if not (user_in_team):
            invitations = user.get_invitations()
            userdata["invitations"] = invitations
        session_data = []
        sessions = LoginTokens.query.filter_by(username=user.username,
                                               active=True).all()
        for _session in sessions:
            session_data.append({
                "sid":
                _session.sid,
                "me":
                _session.sid == session["sid"],
                "ip":
                _session.ip,
                "location":
                _session.location,
                "since":
                datetime.datetime.fromtimestamp(_session.issued).isoformat() +
                "Z"
            })
        userdata["sessions"] = session_data
    return {"success": 1, "user": userdata}