diff --git a/README.md b/README.md index d16a42d..4e122c6 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,50 @@ # ctfd-cheaters +A CTFd plugin that detects flag sharing through **personal flags**: flags +generated for one user (for example by [ctfd-whale](https://github.com/frankli0324/ctfd-whale) +for each user's instance). + +- Adds the `personal` flag type. Its data is the id of the user the flag + belongs to. +- Any user's personal flag is accepted, so a shared flag still solves the + challenge. When an account submits a personal flag that belongs to + another account, the cheat is recorded once and logged. +- In teams mode, sharing a flag within a team is not reported. Admins + (e.g. testing challenges in preview mode) are never reported. +- **Cheaters** in the admin menu lists the reports, with their challenge, + users, teams, flag and date; reports can be dismissed. + +## Requirements + +- CTFd 3.8.9 (the version this plugin targets). +- Challenges with personal flags must use the **any** flag logic: "all" + would require every user's flag. + +## Installation + +Install it as `CTFd/plugins/ctfd_cheaters` (with an underscore): other +plugins import it as `CTFd.plugins.ctfd_cheaters`, and its assets are +served from that directory. + +```bash +git clone CTFd/CTFd/plugins/ctfd_cheaters +``` + +## For other plugins + +```python +from CTFd.plugins.ctfd_cheaters import create_flag_if_missing + +flag_id = create_flag_if_missing(challenge_id=..., user_id=..., flag_content="flag{...}") +``` + +returns the id of the user's personal flag for the challenge, creating it +with `flag_content` if the user has none yet. + +## Development + +```bash +make venv # uv, Python 3.11 like CTFd's Docker image; CTFD_PATH=../CTFd +make lint +make test # runs inside CTFd's own test app +``` diff --git a/__init__.py b/__init__.py index bbce1e0..44f4eb3 100644 --- a/__init__.py +++ b/__init__.py @@ -1,55 +1,90 @@ -import os - -from CTFd.plugins import register_admin_plugin_menu_bar, register_plugin_assets_directory -from CTFd.plugins.migrations import upgrade +from CTFd.models import Flags, Users, db +from CTFd.plugins import ( + register_admin_plugin_menu_bar, + register_plugin_assets_directory, +) from CTFd.plugins.flags import FLAG_CLASSES +from CTFd.plugins.migrations import upgrade +from CTFd.utils.config import is_teams_mode from CTFd.utils.decorators import admins_only -from CTFd.models import Flags, db -from flask import Blueprint, render_template, request +from flask import Blueprint, redirect, render_template, request, url_for +from sqlalchemy.orm import joinedload -from .models import CheaterTeams -from .flags import PersonalFlag, report_cheater +from .flags import PersonalFlag +from .models import CheatReport -PLUGIN_PATH = os.path.dirname(__file__) +# The plugin's directory: CTFd keys migrations and serves assets by it. Other +# plugins import this one as CTFd.plugins.ctfd_cheaters, so install it there. +PLUGIN_NAME = __name__.split(".")[-1] +REPORTS_PER_PAGE = 50 -directory_name = PLUGIN_PATH.split(os.sep)[-1] # Get the directory name of this file - -bp = Blueprint(directory_name, __name__, template_folder="templates") +bp = Blueprint(PLUGIN_NAME, __name__, template_folder="templates") -def create_flag_if_missing(challenge_id: int, user_id: int, flag_content: str): - user_id_str = str(user_id) - flag = Flags.query.filter_by(challenge_id=challenge_id, data=user_id_str).first() +def create_flag_if_missing(challenge_id: int, user_id: int, flag_content: str) -> int: + """Id of the user's personal flag for the challenge. + Created with ``flag_content`` if the user has none yet; an existing flag + is kept as it is. Used by ctfd-whale to give each user their own flag. + """ + data = str(user_id) + flag = ( + Flags.query.filter_by(challenge_id=challenge_id, type="personal", data=data) + .order_by(Flags.id) + .first() + ) if flag is None: - new_flag = Flags( + flag = Flags( challenge_id=challenge_id, type="personal", content=flag_content, - data=user_id_str, + data=data, ) - db.session.add(new_flag) + db.session.add(flag) db.session.commit() - return new_flag.id - return flag.id -@bp.route("/admin/cheaters", methods=["GET"]) +@bp.route("/admin/cheaters") @admins_only def show_cheaters(): - if request.method == "GET": - cheaters = CheaterTeams.query.all() - return render_template("cheaters.html", cheaters=cheaters) + page = max(request.args.get("page", 1, type=int) or 1, 1) + reports = ( + CheatReport.query.options( + joinedload(CheatReport.challenge), + joinedload(CheatReport.cheater).joinedload(Users.team), + joinedload(CheatReport.owner).joinedload(Users.team), + joinedload(CheatReport.flag), + ) + .order_by(CheatReport.date.desc(), CheatReport.id.desc()) + .paginate(page=page, per_page=REPORTS_PER_PAGE, error_out=False) + ) + return render_template( + "cheaters.html", + reports=reports, + teams_mode=is_teams_mode(), + endpoint=PLUGIN_NAME, + ) + + +@bp.route("/admin/cheaters//dismiss", methods=["POST"]) +@admins_only +def dismiss_report(report_id): + CheatReport.query.filter_by(id=report_id).delete() + db.session.commit() + page = request.form.get("page", 1, type=int) + return redirect(url_for(f"{PLUGIN_NAME}.show_cheaters", page=page)) def load(app): + # create_all() creates missing tables; the migrations bring existing + # tables up to date (CTFd skips them on SQLite and only runs create_all) app.db.create_all() - upgrade(plugin_name="cheaters") + upgrade(plugin_name=PLUGIN_NAME) FLAG_CLASSES["personal"] = PersonalFlag - register_plugin_assets_directory(app, base_path="/plugins/ctfd_cheaters/assets/") + register_plugin_assets_directory(app, base_path=f"/plugins/{PLUGIN_NAME}/assets/") register_admin_plugin_menu_bar(title="Cheaters", route="/admin/cheaters") app.register_blueprint(bp) diff --git a/assets/create.html b/assets/create.html index f2b981d..fa1e47e 100644 --- a/assets/create.html +++ b/assets/create.html @@ -1,14 +1,14 @@ -
- + +
-
- + +
diff --git a/assets/edit.html b/assets/edit.html index d41d3db..4285e77 100644 --- a/assets/edit.html +++ b/assets/edit.html @@ -1,15 +1,15 @@ -
- + +
-
- + +
diff --git a/flags.py b/flags.py index bc3cb85..ee845b9 100644 --- a/flags.py +++ b/flags.py @@ -1,45 +1,88 @@ -from CTFd.models import db +import hmac + +from CTFd.models import Users, db from CTFd.plugins.flags import BaseFlag -from CTFd.utils.user import get_current_user +from CTFd.utils.user import get_current_user, is_admin +from flask import current_app +from sqlalchemy.exc import IntegrityError -from .models import CheaterTeams +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 report_cheater(challenge_id: int, cheater_id: int, helper_id: int, flag_id: int): - cheater = CheaterTeams(challenge_id, cheater_id, helper_id, flag_id) - db.session.add(cheater) - db.session.commit() +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): - name: str = "personal" + """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": "/plugins/ctfd_cheaters/assets/create.html", - "update": "/plugins/ctfd_cheaters/assets/edit.html", + "create": ASSETS + "create.html", + "update": ASSETS + "edit.html", } @staticmethod def compare(chal_key_obj, provided): - saved = chal_key_obj.content - user_id = chal_key_obj.data - - if len(saved) != len(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 - result = 0 - - for x, y in zip(saved, provided): - result |= ord(x) ^ ord(y) - - if result == 0: - # If the flag is correct, we need to check if the team is the one associated with the flag - curr_user_id = get_current_user().id - - if int(user_id) != int(curr_user_id): - # Caught a cheater! - report_cheater( - chal_key_obj.challenge_id, curr_user_id, user_id, chal_key_obj.id - ) - - return True - - return False + _check_owner(chal_key_obj) + return True diff --git a/migrations/5b1e0c7d9a24_unique_cheat_reports.py b/migrations/5b1e0c7d9a24_unique_cheat_reports.py new file mode 100644 index 0000000..ad35fd2 --- /dev/null +++ b/migrations/5b1e0c7d9a24_unique_cheat_reports.py @@ -0,0 +1,69 @@ +"""One cheat report per cheater, challenge and flag + +The same cheat used to be reported once per submission, and repeatedly +with the "all" flag logic, which re-checks earlier submissions. Drop the +duplicates (keeping the oldest report) and add a unique constraint. + +Revision ID: 5b1e0c7d9a24 +Revises: +Create Date: 2026-11-18 + +""" + +import sqlalchemy as sa +from CTFd.plugins.migrations import get_all_tables + +revision = "5b1e0c7d9a24" +down_revision = None +branch_labels = None +depends_on = None + +TABLE = "cheater_teams" +CONSTRAINT = "uq_cheater_teams_report" +COLUMNS = ["challenge_id", "cheater_id", "flag_id"] + + +def _has_unique(op): + """Created unnamed by db.create_all() on fresh installs: match on columns. + + MySQL reports unique constraints as indexes. + """ + inspector = sa.inspect(op.get_bind()) + for uc in inspector.get_unique_constraints(TABLE): + if sorted(uc["column_names"]) == sorted(COLUMNS): + return True + for index in inspector.get_indexes(TABLE): + if index.get("unique") and sorted(index["column_names"]) == sorted(COLUMNS): + return True + return False + + +def upgrade(op=None): + if TABLE not in get_all_tables(op) or _has_unique(op): + return + conn = op.get_bind() + duplicates = conn.execute( + sa.text( + f"SELECT challenge_id, cheater_id, flag_id, MIN(id) FROM {TABLE} " + "GROUP BY challenge_id, cheater_id, flag_id HAVING COUNT(*) > 1" + ) + ).fetchall() + for challenge_id, cheater_id, flag_id, keep_id in duplicates: + conn.execute( + sa.text( + f"DELETE FROM {TABLE} WHERE challenge_id = :c AND cheater_id = :u " + "AND flag_id = :f AND id != :keep" + ), + {"c": challenge_id, "u": cheater_id, "f": flag_id, "keep": keep_id}, + ) + op.create_unique_constraint(CONSTRAINT, TABLE, COLUMNS) + + +def downgrade(op=None): + if TABLE not in get_all_tables(op): + return + names = { + uc["name"] for uc in sa.inspect(op.get_bind()).get_unique_constraints(TABLE) + } + if CONSTRAINT in names: + op.drop_constraint(CONSTRAINT, TABLE, type_="unique") diff --git a/models.py b/models.py index f7115cf..5d3c7e7 100644 --- a/models.py +++ b/models.py @@ -1,45 +1,51 @@ +from datetime import datetime + from CTFd.models import db -class CheaterTeams(db.Model): +class CheatReport(db.Model): + """A user submitted a personal flag that belongs to another account.""" + + # table and column names kept from older versions (CheaterTeams/helper) + __tablename__ = "cheater_teams" + __table_args__ = ( + # one report per cheater, challenge and leaked flag, however many + # times the flag is submitted or re-checked + db.UniqueConstraint( + "challenge_id", "cheater_id", "flag_id", name="uq_cheater_teams_report" + ), + ) + id = db.Column(db.Integer, primary_key=True) challenge_id = db.Column( db.Integer, db.ForeignKey("challenges.id", ondelete="CASCADE") ) + # who submitted the flag cheater_id = db.Column(db.Integer, db.ForeignKey("users.id", ondelete="CASCADE")) - helper_id = db.Column(db.Integer, db.ForeignKey("users.id", ondelete="CASCADE")) + # whom the flag belongs to (who leaked it) + owner_id = db.Column( + "helper_id", db.Integer, db.ForeignKey("users.id", ondelete="CASCADE") + ) flag_id = db.Column(db.Integer, db.ForeignKey("flags.id", ondelete="CASCADE")) - date = db.Column(db.DateTime, default=db.func.current_timestamp()) - - # Relationships - cheater = db.relationship( - "Users", foreign_keys="CheaterTeams.cheater_id", lazy="select" - ) - helper = db.relationship( - "Users", foreign_keys="CheaterTeams.helper_id", lazy="select" - ) - flag = db.relationship("Flags", foreign_keys="CheaterTeams.flag_id", lazy="select") + # UTC, like CTFd's own timestamps + date = db.Column(db.DateTime, default=datetime.utcnow) + cheater = db.relationship("Users", foreign_keys=[cheater_id], lazy="select") + owner = db.relationship("Users", foreign_keys=[owner_id], lazy="select") + flag = db.relationship("Flags", foreign_keys=[flag_id], lazy="select") challenge = db.relationship( - "Challenges", - foreign_keys="CheaterTeams.challenge_id", - lazy="select", + "Challenges", foreign_keys=[challenge_id], lazy="select" ) - def __init__( - self, challenge_id: int, cheater_id: int, helper_id: int, flag_id: int - ): + def __init__(self, challenge_id: int, cheater_id: int, owner_id: int, flag_id: int): self.challenge_id = challenge_id self.cheater_id = cheater_id - self.helper_id = helper_id + self.owner_id = owner_id self.flag_id = flag_id def __repr__(self): - return "".format( - self.cheater_id, - self.challenge_id, - self.flag.content, - self.helper_id, - self.date, + return ( + f"" ) diff --git a/pyrightconfig.json b/pyrightconfig.json index 76f14d6..c17bffd 100644 --- a/pyrightconfig.json +++ b/pyrightconfig.json @@ -1,6 +1,6 @@ { "include": ["."], - "extraPaths": ["/home/matteo/Gitted/CTFd"], + "extraPaths": ["../CTFd"], "reportMissingImports": true, "reportUnknownVariableType": false, "reportUnknownMemberType": false diff --git a/templates/cheaters.html b/templates/cheaters.html index e5ebedc..1bc22b0 100644 --- a/templates/cheaters.html +++ b/templates/cheaters.html @@ -4,36 +4,71 @@

Cheat Monitor

+

+ Personal flags submitted by an account they don't belong to. The + submission still counts: review the reports and act on the scoreboard. +

+
+
+
+
+
+ {% if reports.items %} + + + + + + + {% if teams_mode %}{% endif %} + + {% if teams_mode %}{% endif %} + + + + + + + {% for report in reports.items %} + + + + + {% if teams_mode %} + + {% endif %} + + {% if teams_mode %} + + {% endif %} + + + + + {% endfor %} + +
IDChallengeSubmitted byTeamFlag ownerOwner's teamFlagDate
{{ report.id }}{{ report.challenge.name }}{{ report.cheater.name }}{% if report.cheater.team %}{{ report.cheater.team.name }}{% endif %}{{ report.owner.name }}{% if report.owner.team %}{{ report.owner.team.name }}{% endif %}{{ report.flag.content }} +
+ + + +
+
+ {% if reports.pages > 1 %} + + {% endif %} + {% else %} +

No reports.

+ {% endif %} +
-
-
-
- - - - - - - - - - - - - {% for cheater in cheaters %} - - - - - - - - - {% endfor %} - -
IDChallengeCheat UserHelper UserFlagDate
{{ loop.index }}{{ cheater.challenge.name }}{{ cheater.cheater.name }}{{ cheater.helper.name }}{{ cheater.flag.content }}{{cheater.date}}
-
-
-
{% endblock %}