import hmac
from CTFd.models import Users, db
from CTFd.plugins.flags import BaseFlag
from CTFd.utils.user import get_current_user, is_admin
from flask import current_app
from sqlalchemy.exc import IntegrityError
from .models import CheatReport
# CTFd serves plugin assets from the plugin's directory
# ("CTFd.plugins.
.flags"): their URL must use its real name.
ASSETS = f"/plugins/{__name__.split('.')[-2]}/assets/"
def flag_owner_id(flag):
"""The user id a personal flag belongs to (its data), or None if invalid."""
try:
return int(flag.data)
except (TypeError, ValueError):
return None
def report_cheater(challenge_id: int, cheater, owner, flag_id: int):
"""Record that ``cheater`` submitted ``owner``'s flag, once."""
already = CheatReport.query.filter_by(
challenge_id=challenge_id, cheater_id=cheater.id, flag_id=flag_id
).first()
if already:
return
db.session.add(CheatReport(challenge_id, cheater.id, owner.id, flag_id))
try:
db.session.commit()
except IntegrityError:
# reported by a concurrent submission meanwhile
db.session.rollback()
return
current_app.logger.warning(
"[CTFd Cheaters] %s (user %s) submitted the flag of %s (user %s) "
"for challenge %s",
cheater.name,
cheater.id,
owner.name,
owner.id,
challenge_id,
)
def _check_owner(flag):
"""Report the current user if the flag belongs to another account."""
user = get_current_user()
# admins testing challenges (e.g. in preview mode) aren't cheating
if user is None or is_admin():
return
owner_id = flag_owner_id(flag)
if owner_id is None or owner_id == user.id:
return
owner = Users.query.filter_by(id=owner_id).first()
# in teams mode the account is the team: sharing within it is fine
if owner is None or owner.account_id == user.account_id:
return
report_cheater(flag.challenge_id, user, owner, flag.id)
class PersonalFlag(BaseFlag):
"""A flag generated for one user (its data holds the user id).
Any user's personal flag is accepted, so a shared flag still solves the
challenge; submitting the flag of another account is reported on the
Cheaters admin page. Use challenges with the "any" flag logic: "all"
would require every user's flag.
"""
name = "personal"
templates = { # Nunjucks templates used for key editing & viewing
"create": ASSETS + "create.html",
"update": ASSETS + "edit.html",
}
@staticmethod
def compare(chal_key_obj, provided):
# exact match in constant time, like CTFd's case-sensitive static flags
saved = (chal_key_obj.content or "").encode()
# an empty flag never matches (not even an empty submission)
if not saved or not hmac.compare_digest(saved, str(provided).encode()):
return False
_check_owner(chal_key_obj)
return True