From 8084b3996a57400c7e2b1d2b5f8c0af1dca600e5 Mon Sep 17 00:00:00 2001 From: Matte23 Date: Wed, 18 Nov 2026 10:21:53 +0100 Subject: [PATCH 1/4] fix: Reliable cheat reports and a usable admin side Reports - Sharing within a team is no longer reported: owner and submitter are compared by account (the team in teams mode), not by user. - Admins (e.g. testing in preview mode) are never reported. - A personal flag without a valid owner no longer crashes the submission (int() of its data raised a 500); empty flags never match. - One report per cheater, challenge and flag (unique constraint plus a check before inserting): "all" logic re-checks every earlier submission on each attempt, which created duplicates. Migration 5b1e0c7d9a24 drops existing duplicates and adds the constraint. - Every new report is logged. Matching uses hmac.compare_digest. Flags and helpers - The admin flag forms sent the owner as "user id", which CTFd's flag API ignores: personal flags created by admins had no owner. They now send "data", with labels bound to their inputs. - create_flag_if_missing only considers personal flags, deterministically. Plugin - Migrations run under the plugin's real directory (was "cheaters"); asset paths follow the directory instead of hardcoding it. - Model renamed CheatReport (owner instead of helper); table and column names unchanged. Dates stored in UTC. - Admin page: newest first, paginated, related rows loaded with the page, real report ids, url_for links, team columns in teams mode, local-time dates, and a Dismiss action. - README (install as ctfd_cheaters, "any" logic, API for other plugins); pyrightconfig without an absolute path. Co-Authored-By: Claude Opus 5.5 --- README.md | 48 ++++++++ __init__.py | 87 +++++++++----- assets/create.html | 18 +-- assets/edit.html | 18 +-- flags.py | 107 ++++++++++++------ .../5b1e0c7d9a24_unique_cheat_reports.py | 69 +++++++++++ models.py | 56 +++++---- pyrightconfig.json | 2 +- templates/cheaters.html | 95 +++++++++++----- 9 files changed, 368 insertions(+), 132 deletions(-) create mode 100644 migrations/5b1e0c7d9a24_unique_cheat_reports.py 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 %} -- 2.43.0 From e54d98498c8d04de4a9764a62d9dc7a8d7c7f8c4 Mon Sep 17 00:00:00 2001 From: Matte23 Date: Wed, 18 Nov 2026 10:21:53 +0100 Subject: [PATCH 2/4] test: Test suite against CTFd's own test app, lint tooling - plugin_tests/: 9 tests running the plugin inside CTFd 3.8.9's test app (users and teams mode): own/shared flags, single reports, admins, invalid owners and empty flags, teams, create_flag_if_missing, the admin flag form, the admin page and dismissing. - make venv (uv, Python 3.11), make lint, make format, make test: same tools and versions as ctfd-whale. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 3 + Makefile | 25 +++++ dev-requirements.txt | 3 + linting.txt | 3 + plugin_tests/conftest.py | 77 ++++++++++++++ plugin_tests/pytest.ini | 13 +++ plugin_tests/test_cheaters.py | 183 ++++++++++++++++++++++++++++++++++ 7 files changed, 307 insertions(+) create mode 100644 Makefile create mode 100644 dev-requirements.txt create mode 100644 linting.txt create mode 100644 plugin_tests/conftest.py create mode 100644 plugin_tests/pytest.ini create mode 100644 plugin_tests/test_cheaters.py diff --git a/.gitignore b/.gitignore index 36b13f1..6a2cd71 100644 --- a/.gitignore +++ b/.gitignore @@ -174,3 +174,6 @@ cython_debug/ # PyPI configuration file .pypirc + +# written by CTFd's test app (make test) +.ctfd_secret_key diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..1011135 --- /dev/null +++ b/Makefile @@ -0,0 +1,25 @@ +# Same lint tools and rules as CTFd 3.8.9 (see CTFd's Makefile and linting.txt). +# Setup: make venv (needs uv; Python 3.11 like CTFd's Docker image) +VENV ?= .venv/bin +CTFD_PATH ?= ../CTFd +PYTHON ?= 3.11 + +venv: + uv venv --python $(PYTHON) .venv + uv pip install --python .venv/bin/python -r $(CTFD_PATH)/requirements.txt -r dev-requirements.txt + +lint: + $(VENV)/ruff check --select E,F,W,B,C4,I --ignore E402,E501,E712,B904,B905,I001 --exclude=.venv . + $(VENV)/isort --profile=black --check-only --skip=.venv . + $(VENV)/black --check --diff --exclude=.venv . + +format: + $(VENV)/isort --profile=black --skip=.venv . + $(VENV)/black --exclude=.venv . + +# Runs inside CTFd's own test app, with the plugin loaded from this +# checkout; CTFD_PATH must be a checkout of the CTFd version it targets. +test: + CTFD_PATH=$(CTFD_PATH) $(VENV)/pytest -c plugin_tests/pytest.ini plugin_tests + +.PHONY: venv lint format test diff --git a/dev-requirements.txt b/dev-requirements.txt new file mode 100644 index 0000000..ddc100e --- /dev/null +++ b/dev-requirements.txt @@ -0,0 +1,3 @@ +-r linting.txt +# same version as CTFd 3.8.9 (development.txt) +pytest==8.4.2 diff --git a/linting.txt b/linting.txt new file mode 100644 index 0000000..4253d6f --- /dev/null +++ b/linting.txt @@ -0,0 +1,3 @@ +black==26.10.1 +isort==5.13.2 +ruff==0.0.260 diff --git a/plugin_tests/conftest.py b/plugin_tests/conftest.py new file mode 100644 index 0000000..61e3d26 --- /dev/null +++ b/plugin_tests/conftest.py @@ -0,0 +1,77 @@ +"""Test harness: CTFd's own test app with ctfd-cheaters loaded from this repo. + +CTFd is imported from CTFD_PATH (default: ../CTFd). The test app runs in +CTFd's safe mode (no plugins loaded from CTFd/plugins), and this checkout is +loaded as CTFd.plugins.ctfd_cheaters, the name other plugins import. +""" + +import importlib.util +import os +import sys +from pathlib import Path + +import pytest + +REPO = Path(__file__).resolve().parent.parent +CTFD_PATH = Path(os.environ.get("CTFD_PATH", REPO.parent / "CTFd")).resolve() +PLUGIN_MODULE = "CTFd.plugins.ctfd_cheaters" + +if not (CTFD_PATH / "CTFd" / "__init__.py").exists(): + raise RuntimeError(f"CTFd not found at {CTFD_PATH}: set CTFD_PATH") +sys.path.insert(0, str(CTFD_PATH)) + +import CTFd.plugins # noqa: E402,F401 (parent package of the plugin module) +from tests.helpers import create_ctfd, destroy_ctfd, setup_ctfd # noqa: E402 + + +def _import_plugin(): + """Import the plugin (once). Like CTFd, only inside an app context.""" + if PLUGIN_MODULE in sys.modules: + return sys.modules[PLUGIN_MODULE] + spec = importlib.util.spec_from_file_location( + PLUGIN_MODULE, REPO / "__init__.py", submodule_search_locations=[str(REPO)] + ) + module = importlib.util.module_from_spec(spec) + sys.modules[PLUGIN_MODULE] = module + spec.loader.exec_module(module) + return module + + +def plugin(submodule=None): + return sys.modules[PLUGIN_MODULE + (f".{submodule}" if submodule else "")] + + +def _make_app(user_mode): + app = create_ctfd(setup=False, user_mode=user_mode) + with app.app_context(): + _import_plugin().load(app) + return setup_ctfd(app, user_mode=user_mode) + + +@pytest.fixture +def app(): + app = _make_app("users") + yield app + destroy_ctfd(app) + + +@pytest.fixture +def teams_app(): + app = _make_app("teams") + yield app + destroy_ctfd(app) + + +def submit(client, challenge_id, submission, preview=False): + url = "/api/v1/challenges/attempt" + ("?preview=true" if preview else "") + r = client.post(url, json={"challenge_id": challenge_id, "submission": submission}) + assert r.status_code == 200, r.get_json() + return r.get_json()["data"]["status"] + + +def reports(app): + with app.app_context(): + return [ + (r.cheater_id, r.owner_id, r.flag_id) + for r in plugin("models").CheatReport.query.all() + ] diff --git a/plugin_tests/pytest.ini b/plugin_tests/pytest.ini new file mode 100644 index 0000000..a189cf0 --- /dev/null +++ b/plugin_tests/pytest.ini @@ -0,0 +1,13 @@ +[pytest] +# This directory is the rootdir on purpose: the repo root is the plugin +# package itself (it has an __init__.py), which pytest would otherwise import +# as a test package before any CTFd app exists. The folder isn't called +# "tests" because CTFd's own tests package, whose helpers the suite uses, +# needs that name. Run with: make test +addopts = -p no:cacheprovider +filterwarnings = + ignore::DeprecationWarning + # CTFd's test client uses the "localhost" cookie domain + ignore:'localhost' is not a valid cookie domain:UserWarning + # CTFd's Flags model maps no subclasses: every flag type warns + ignore:Flushing object .* with incompatible polymorphic identity diff --git a/plugin_tests/test_cheaters.py b/plugin_tests/test_cheaters.py new file mode 100644 index 0000000..8ee1998 --- /dev/null +++ b/plugin_tests/test_cheaters.py @@ -0,0 +1,183 @@ +from conftest import plugin, reports, submit +from CTFd.models import Flags, Users, db +from tests.helpers import ( + gen_challenge, + gen_flag, + gen_team, + login_as_user, + register_user, +) + + +def _challenge_with_flags(app, *owners): + """A challenge with one personal flag per owner id; returns (id, {owner: flag}).""" + with app.app_context(): + challenge = gen_challenge(db) + flags = { + owner: gen_flag( + db, + challenge.id, + content=f"flag{{{owner}}}", + type="personal", + data=str(owner), + ).id + for owner in owners + } + return challenge.id, flags + + +def _users(app, *names): + for name in names: + register_user(app, name=name, email=f"{name}@examplectf.com") + with app.app_context(): + return [Users.query.filter_by(name=name).one().id for name in names] + + +def test_own_flag_is_correct_and_not_reported(app): + alice, bob = _users(app, "alice", "bob") + challenge_id, _ = _challenge_with_flags(app, alice, bob) + with login_as_user(app, name="alice") as client: + assert submit(client, challenge_id, f"flag{{{alice}}}") == "correct" + assert reports(app) == [] + + +def test_shared_flag_is_accepted_and_reported_once(app): + alice, bob = _users(app, "alice", "bob") + challenge_id, flags = _challenge_with_flags(app, alice, bob) + with login_as_user(app, name="alice") as client: + assert submit(client, challenge_id, "wrong") == "incorrect" + assert submit(client, challenge_id, f"flag{{{bob}}}") == "correct" + assert reports(app) == [(alice, bob, flags[bob])] + # reporting the same cheat again (e.g. "all" logic re-checks) adds nothing + with app.test_request_context(), login_as_user(app, name="alice"): + cheater = Users.query.get(alice) + owner = Users.query.get(bob) + plugin("flags").report_cheater(challenge_id, cheater, owner, flags[bob]) + assert len(reports(app)) == 1 + + +def test_admins_are_not_reported(app): + (alice,) = _users(app, "alice") + challenge_id, _ = _challenge_with_flags(app, alice) + with login_as_user(app, name="admin") as admin: + assert ( + submit(admin, challenge_id, f"flag{{{alice}}}", preview=True) == "correct" + ) + assert reports(app) == [] + + +def test_invalid_owner_and_empty_flags(app): + (alice,) = _users(app, "alice") + with app.app_context(): + challenge_id = gen_challenge(db).id + db.session.add( + Flags(challenge_id=challenge_id, type="personal", content="flag{x}") + ) + db.session.add( + Flags( + challenge_id=challenge_id, + type="personal", + content="flag{y}", + data="bob", + ) + ) + db.session.add(Flags(challenge_id=challenge_id, type="personal", content="")) + db.session.commit() + with login_as_user(app, name="alice") as client: + # no crash for a flag without (or with an invalid) owner, and no report + assert submit(client, challenge_id, "flag{x}") == "correct" + with login_as_user(app, name="alice") as client: + assert submit(client, challenge_id, "") in ("incorrect", "already_solved") + assert reports(app) == [] + + +def test_teams_mode_only_reports_other_teams(teams_app): + app = teams_app + with app.app_context(): + red = gen_team(db, name="red", email="red@examplectf.com", member_count=2) + blue = gen_team(db, name="blue", email="blue@examplectf.com", member_count=1) + red_a, red_b = (m.id for m in red.members) + blue_a = blue.members[0].id + names = {u.id: u.name for u in Users.query.all()} + challenge_id, flags = _challenge_with_flags(app, red_a, red_b, blue_a) + with login_as_user(app, name=names[red_b]) as client: + # a teammate's flag: shared within the team, not a cheat + assert submit(client, challenge_id, f"flag{{{red_a}}}") == "correct" + assert reports(app) == [] + second = _challenge_with_flags(app, red_a, blue_a)[0] + with login_as_user(app, name=names[blue_a]) as client: + assert submit(client, second, f"flag{{{red_a}}}") == "correct" + with app.app_context(): + assert [ + (r.cheater_id, r.owner_id) for r in plugin("models").CheatReport.query + ] == [(blue_a, red_a)] + + +def test_create_flag_if_missing(app): + alice, bob = _users(app, "alice", "bob") + create = plugin().create_flag_if_missing + with app.app_context(): + challenge_id = gen_challenge(db).id + # a non-personal flag with the same data is never picked up + gen_flag(db, challenge_id, content="static", data=str(alice)) + first = create(challenge_id, alice, "flag{one}") + again = create(challenge_id, alice, "flag{two}") + other = create(challenge_id, bob, "flag{bob}") + assert first == again != other + flag = Flags.query.get(first) + assert (flag.type, flag.content, flag.data) == ( + "personal", + "flag{one}", + str(alice), + ) + + +def test_admin_flag_form_sets_the_owner(app): + (alice,) = _users(app, "alice") + with app.app_context(): + challenge_id = gen_challenge(db).id + with login_as_user(app, name="admin") as admin: + # what the admin form posts (its fields: content, data, type) + r = admin.post( + "/api/v1/flags", + json={ + "challenge": challenge_id, + "content": "flag{a}", + "data": str(alice), + "type": "personal", + }, + ) + assert r.status_code == 200, r.get_json() + assert r.get_json()["data"]["data"] == str(alice) + r = admin.get("/api/v1/flags/types/personal") + templates = r.get_json()["data"]["templates"] + assert templates["create"] == "/plugins/ctfd_cheaters/assets/create.html" + assert admin.get(templates["create"]).status_code == 200 + + +def test_admin_page_and_dismiss(app): + alice, bob = _users(app, "alice", "bob") + challenge_id, _ = _challenge_with_flags(app, alice, bob) + with login_as_user(app, name="alice") as client: + assert submit(client, challenge_id, f"flag{{{bob}}}") == "correct" + [report_id] = _report_ids(app) + with login_as_user(app, name="admin") as admin: + page = admin.get("/admin/cheaters").get_data(as_text=True) + assert "alice" in page and "bob" in page and f"flag{{{bob}}}" in page + with admin.session_transaction() as sess: + nonce = sess["nonce"] + r = admin.post(f"/admin/cheaters/{report_id}/dismiss", data={"nonce": nonce}) + assert r.status_code == 302 + assert "No reports" in admin.get("/admin/cheaters").get_data(as_text=True) + assert reports(app) == [] + + +def test_players_cannot_see_the_admin_page(app): + _users(app, "alice") + with login_as_user(app, name="alice") as client: + assert client.get("/admin/cheaters").status_code in (302, 403) + + +def _report_ids(app): + with app.app_context(): + return [r.id for r in plugin("models").CheatReport.query.all()] -- 2.43.0 From 396c7afb9f7a685eaacecde439f615d56b0e5676 Mon Sep 17 00:00:00 2001 From: Matte23 Date: Wed, 18 Nov 2026 18:31:21 +0100 Subject: [PATCH 3/4] refactor: Drop a redundant sentence from the cheaters page Co-Authored-By: Claude Opus 5.5 --- templates/cheaters.html | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/templates/cheaters.html b/templates/cheaters.html index 1bc22b0..46398fc 100644 --- a/templates/cheaters.html +++ b/templates/cheaters.html @@ -5,8 +5,7 @@

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. + Personal flags submitted by an account they don't belong to.

-- 2.43.0 From a42e7f2823b7e31297e432779cc6265850ee111d Mon Sep 17 00:00:00 2001 From: Matte23 Date: Wed, 18 Nov 2026 18:38:48 +0100 Subject: [PATCH 4/4] fix: Silence CTFd's Flags polymorphic-identity warning on flag creation CTFd's Flags model sets polymorphic_on without mapping any type, so every flag flush warns. Mapping "personal" would break loading the other types. Co-Authored-By: Claude Opus 5.5 --- __init__.py | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/__init__.py b/__init__.py index 44f4eb3..5e4fc23 100644 --- a/__init__.py +++ b/__init__.py @@ -1,3 +1,5 @@ +import warnings + from CTFd.models import Flags, Users, db from CTFd.plugins import ( register_admin_plugin_menu_bar, @@ -8,6 +10,7 @@ from CTFd.plugins.migrations import upgrade from CTFd.utils.config import is_teams_mode from CTFd.utils.decorators import admins_only from flask import Blueprint, redirect, render_template, request, url_for +from sqlalchemy.exc import SAWarning from sqlalchemy.orm import joinedload from .flags import PersonalFlag @@ -41,7 +44,16 @@ def create_flag_if_missing(challenge_id: int, user_id: int, flag_content: str) - data=data, ) db.session.add(flag) - db.session.commit() + # CTFd's Flags model sets polymorphic_on without mapping any type, so + # SQLAlchemy warns on every flag flush (static flags too). Mapping + # "personal" would break loading the other types: ignore it here. + with warnings.catch_warnings(): + warnings.filterwarnings( + "ignore", + message="Flushing object .* with incompatible polymorphic identity", + category=SAWarning, + ) + db.session.commit() return flag.id -- 2.43.0