Compare commits

...
2 Commits
Author SHA1 Message Date
Matte23andClaude Opus 5.5 e54d98498c 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 <noreply@anthropic.com>
2026-11-18 10:21:53 +01:00
Matte23andClaude Opus 5.5 8084b3996a 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 <noreply@anthropic.com>
2026-11-18 10:21:53 +01:00
16 changed files with 654 additions and 111 deletions

No files matched your search

+3
View File
@@ -174,3 +174,6 @@ cython_debug/
# PyPI configuration file
.pypirc
# written by CTFd's test app (make test)
.ctfd_secret_key
+25
View File
@@ -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
+48
View File
@@ -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 <this repository> 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
```
+61 -26
View File
@@ -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/<int:report_id>/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)
+8 -8
View File
@@ -1,14 +1,14 @@
<label>
<div class="form-group">
<label for="personal-flag-content">
Personal<br>
<small>Enter personal flag data</small>
<small>The flag content</small>
</label>
<div class="form-group">
<input type="text" class="form-control" name="content" value="{{ content }}">
<input type="text" class="form-control" id="personal-flag-content" name="content" value="{{ content }}">
</div>
<label>
<small>User id for whom the flag is for</small>
</label>
<div class="form-group">
<input type="text" class="form-control" name="user id" value="{{ data }}">
<label for="personal-flag-owner">
<small>Id of the user this flag belongs to</small>
</label>
<input type="number" min="1" class="form-control" id="personal-flag-owner" name="data" value="{{ data }}" required>
</div>
<input type="hidden" name="type" value="personal">
+8 -8
View File
@@ -1,15 +1,15 @@
<label>
<div class="form-group">
<label for="personal-flag-content">
Personal<br>
<small>Enter personal flag data</small>
<small>The flag content</small>
</label>
<div class="form-group">
<input type="text" class="form-control" name="content" value="{{ content }}">
<input type="text" class="form-control" id="personal-flag-content" name="content" value="{{ content }}">
</div>
<label>
<small>User id for whom the flag is for</small>
</label>
<div class="form-group">
<input type="text" class="form-control" name="user id" value="{{ data }}">
<label for="personal-flag-owner">
<small>Id of the user this flag belongs to</small>
</label>
<input type="number" min="1" class="form-control" id="personal-flag-owner" name="data" value="{{ data }}" required>
</div>
<input type="hidden" name="type" value="personal">
<input type="hidden" name="id" value="{{ id }}">
+3
View File
@@ -0,0 +1,3 @@
-r linting.txt
# same version as CTFd 3.8.9 (development.txt)
pytest==8.4.2
+73 -30
View File
@@ -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.<dir>.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)
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
)
_check_owner(chal_key_obj)
return True
return False
+3
View File
@@ -0,0 +1,3 @@
black==26.10.1
isort==5.13.2
ruff==0.0.260
@@ -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")
+31 -25
View File
@@ -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 "<CheaterTeams User {0} maybe cheated for challenge {1} with the flag {2} belonging to the User {3} at {4} >".format(
self.cheater_id,
self.challenge_id,
self.flag.content,
self.helper_id,
self.date,
return (
f"<CheatReport user {self.cheater_id} submitted the flag {self.flag_id} "
f"of user {self.owner_id} for challenge {self.challenge_id} at {self.date}>"
)
+77
View File
@@ -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()
]
+13
View File
@@ -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
+183
View File
@@ -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()]
+1 -1
View File
@@ -1,6 +1,6 @@
{
"include": ["."],
"extraPaths": ["/home/matteo/Gitted/CTFd"],
"extraPaths": ["../CTFd"],
"reportMissingImports": true,
"reportUnknownVariableType": false,
"reportUnknownMemberType": false
+48 -13
View File
@@ -4,35 +4,70 @@
<div class="jumbotron">
<div class="container">
<h1>Cheat Monitor</h1>
<p class="text-muted mb-0">
Personal flags submitted by an account they don't belong to. The
submission still counts: review the reports and act on the scoreboard.
</p>
</div>
</div>
<div class="container">
<div id="cheat" class="row">
<div class="col-md-12">
{% if reports.items %}
<table class="table table-striped">
<thead>
<tr>
<td scope="col" width="10px"><b>ID</b></td>
<td scope="col"><b>Challenge</b></td>
<td scope="col"><b>Cheat User</b></td>
<td scope="col"><b>Helper User</b></td>
<td scope="col"><b>Flag</b></td>
<td scope="col"><b>Date</b></td>
<th scope="col">ID</th>
<th scope="col">Challenge</th>
<th scope="col">Submitted by</th>
{% if teams_mode %}<th scope="col">Team</th>{% endif %}
<th scope="col">Flag owner</th>
{% if teams_mode %}<th scope="col">Owner's team</th>{% endif %}
<th scope="col">Flag</th>
<th scope="col">Date</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
{% for cheater in cheaters %}
{% for report in reports.items %}
<tr>
<th scope="row" class="text-center">{{ loop.index }}</th>
<td><a href="{{ request.script_root }}/admin/challenges/{{ cheater.challenge.id }}">{{ cheater.challenge.name }}</a></td>
<td><a href="{{ request.script_root }}/admin/users/{{ cheater.cheater.id }}">{{ cheater.cheater.name }}</a></td>
<td><a href="{{ request.script_root }}/admin/users/{{ cheater.helper.id }}">{{ cheater.helper.name }}</a></td>
<td>{{ cheater.flag.content }}</td>
<td>{{cheater.date}}</td>
<th scope="row">{{ report.id }}</th>
<td><a href="{{ url_for('admin.challenges_detail', challenge_id=report.challenge.id) }}">{{ report.challenge.name }}</a></td>
<td><a href="{{ url_for('admin.users_detail', user_id=report.cheater.id) }}">{{ report.cheater.name }}</a></td>
{% if teams_mode %}
<td>{% if report.cheater.team %}<a href="{{ url_for('admin.teams_detail', team_id=report.cheater.team.id) }}">{{ report.cheater.team.name }}</a>{% endif %}</td>
{% endif %}
<td><a href="{{ url_for('admin.users_detail', user_id=report.owner.id) }}">{{ report.owner.name }}</a></td>
{% if teams_mode %}
<td>{% if report.owner.team %}<a href="{{ url_for('admin.teams_detail', team_id=report.owner.team.id) }}">{{ report.owner.team.name }}</a>{% endif %}</td>
{% endif %}
<td><code>{{ report.flag.content }}</code></td>
<td><span data-time="{{ report.date | isoformat }}"></span></td>
<td>
<form method="POST" action="{{ url_for(endpoint + '.dismiss_report', report_id=report.id) }}">
<input type="hidden" name="nonce" value="{{ Session.nonce }}">
<input type="hidden" name="page" value="{{ reports.page }}">
<button type="submit" class="btn btn-sm btn-outline-secondary" title="Dismiss this report">Dismiss</button>
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% if reports.pages > 1 %}
<nav>
<ul class="pagination">
{% for page in range(1, reports.pages + 1) %}
<li class="page-item{{ ' active' if page == reports.page }}">
<a class="page-link" href="{{ url_for(endpoint + '.show_cheaters', page=page) }}">{{ page }}</a>
</li>
{% endfor %}
</ul>
</nav>
{% endif %}
{% else %}
<p class="text-center text-muted">No reports.</p>
{% endif %}
</div>
</div>
</div>