Fix/review findings #1

Merged
Matte23 merged 4 commits from fix/review-findings into main 2026-11-18 20:51:39 +00:00
9 changed files with 347 additions and 111 deletions
Showing only changes of commit 8084b3996a - Show all commits

No files matched your search

+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 }}">
+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
@@ -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}>"
)
+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>