fix: закрыть уязвимости (CSRF, rate limit, секреты, CSV-injection, LIKE-экранирование)
This commit is contained in:
+7
-2
@@ -1,2 +1,7 @@
|
|||||||
SECRET_KEY=replace-with-a-long-random-string
|
# Обязательные переменные. Без них приложение не запустится.
|
||||||
ADMIN_PASSWORD=replace-with-a-private-admin-password
|
SECRET_KEY=сгенерируйте-случайную-строку-50-символов
|
||||||
|
ADMIN_PASSWORD=надёжный-пароль-админки
|
||||||
|
|
||||||
|
# Необязательные
|
||||||
|
# FLASK_DEBUG=1 # только для локальной разработки
|
||||||
|
# COOKIE_SECURE=1 # включить при работе по HTTPS
|
||||||
|
|||||||
@@ -8,6 +8,9 @@ from hmac import compare_digest
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from flask import Flask, flash, make_response, redirect, render_template, request, session, url_for
|
from flask import Flask, flash, make_response, redirect, render_template, request, session, url_for
|
||||||
|
from flask_limiter import Limiter
|
||||||
|
from flask_limiter.util import get_remote_address
|
||||||
|
from flask_wtf import CSRFProtect
|
||||||
|
|
||||||
|
|
||||||
BASE_DIR = Path(__file__).resolve().parent
|
BASE_DIR = Path(__file__).resolve().parent
|
||||||
@@ -29,9 +32,21 @@ REQUEST_STATUSES = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
app = Flask(__name__)
|
app = Flask(__name__)
|
||||||
app.config["SECRET_KEY"] = os.getenv("SECRET_KEY", "change-this-secret-key")
|
app.config["SECRET_KEY"] = os.environ.get("SECRET_KEY")
|
||||||
|
if not app.config["SECRET_KEY"]:
|
||||||
|
raise RuntimeError("SECRET_KEY не задан. Установите переменную окружения SECRET_KEY.")
|
||||||
app.config["SESSION_COOKIE_HTTPONLY"] = True
|
app.config["SESSION_COOKIE_HTTPONLY"] = True
|
||||||
app.config["SESSION_COOKIE_SAMESITE"] = "Lax"
|
app.config["SESSION_COOKIE_SAMESITE"] = "Lax"
|
||||||
|
app.config["SESSION_COOKIE_SECURE"] = os.environ.get("COOKIE_SECURE", "0") == "1"
|
||||||
|
|
||||||
|
csrf = CSRFProtect(app)
|
||||||
|
|
||||||
|
limiter = Limiter(
|
||||||
|
get_remote_address,
|
||||||
|
app=app,
|
||||||
|
default_limits=["200 per hour"],
|
||||||
|
storage_uri="memory://",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def get_connection():
|
def get_connection():
|
||||||
@@ -88,6 +103,7 @@ def index():
|
|||||||
|
|
||||||
|
|
||||||
@app.post("/submit")
|
@app.post("/submit")
|
||||||
|
@limiter.limit("10 per minute")
|
||||||
def submit_request():
|
def submit_request():
|
||||||
name = request.form.get("name", "").strip()
|
name = request.form.get("name", "").strip()
|
||||||
contact = request.form.get("contact", "").strip()
|
contact = request.form.get("contact", "").strip()
|
||||||
@@ -172,8 +188,12 @@ def build_request_query(filters):
|
|||||||
conditions.append("subject = ?")
|
conditions.append("subject = ?")
|
||||||
parameters.append(filters["subject"])
|
parameters.append(filters["subject"])
|
||||||
if filters["q"]:
|
if filters["q"]:
|
||||||
conditions.append("(name LIKE ? OR contact LIKE ? OR message LIKE ? OR admin_note LIKE ?)")
|
escaped = filters["q"].replace("%", "\\%").replace("_", "\\_")
|
||||||
search_pattern = f"%{filters['q']}%"
|
search_pattern = f"%{escaped}%"
|
||||||
|
conditions.append(
|
||||||
|
"(name LIKE ? ESCAPE '\\' OR contact LIKE ? ESCAPE '\\' "
|
||||||
|
"OR message LIKE ? ESCAPE '\\' OR admin_note LIKE ? ESCAPE '\\')"
|
||||||
|
)
|
||||||
parameters.extend([search_pattern] * 4)
|
parameters.extend([search_pattern] * 4)
|
||||||
|
|
||||||
where_clause = f"WHERE {' AND '.join(conditions)}" if conditions else ""
|
where_clause = f"WHERE {' AND '.join(conditions)}" if conditions else ""
|
||||||
@@ -210,13 +230,16 @@ def fetch_stats(connection):
|
|||||||
|
|
||||||
|
|
||||||
@app.route("/admin/login", methods=["GET", "POST"])
|
@app.route("/admin/login", methods=["GET", "POST"])
|
||||||
|
@limiter.limit("10 per minute")
|
||||||
def admin_login():
|
def admin_login():
|
||||||
if session.get("is_admin"):
|
if session.get("is_admin"):
|
||||||
return redirect(url_for("admin_dashboard"))
|
return redirect(url_for("admin_dashboard"))
|
||||||
|
|
||||||
if request.method == "POST":
|
if request.method == "POST":
|
||||||
password = request.form.get("password", "")
|
password = request.form.get("password", "")
|
||||||
admin_password = os.getenv("ADMIN_PASSWORD", "admin123")
|
admin_password = os.environ.get("ADMIN_PASSWORD")
|
||||||
|
if not admin_password:
|
||||||
|
raise RuntimeError("ADMIN_PASSWORD не задан. Установите переменную окружения.")
|
||||||
|
|
||||||
if compare_digest(password, admin_password):
|
if compare_digest(password, admin_password):
|
||||||
session.clear()
|
session.clear()
|
||||||
@@ -288,6 +311,13 @@ def admin_delete_request(request_id):
|
|||||||
return redirect(url_for("admin_dashboard"))
|
return redirect(url_for("admin_dashboard"))
|
||||||
|
|
||||||
|
|
||||||
|
def csv_safe(value):
|
||||||
|
"""Защита от CSV-инъекции: значения с формулами экранируются апострофом."""
|
||||||
|
if value and value[0] in ("=", "+", "-", "@", "\t", "\r"):
|
||||||
|
return "'" + value
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
@app.get("/admin/export.csv")
|
@app.get("/admin/export.csv")
|
||||||
@admin_required
|
@admin_required
|
||||||
def admin_export():
|
def admin_export():
|
||||||
@@ -317,15 +347,15 @@ def admin_export():
|
|||||||
writer.writerow(
|
writer.writerow(
|
||||||
[
|
[
|
||||||
consultation["id"],
|
consultation["id"],
|
||||||
consultation["name"],
|
csv_safe(consultation["name"]),
|
||||||
consultation["contact"],
|
csv_safe(consultation["contact"]),
|
||||||
consultation["subject"],
|
consultation["subject"],
|
||||||
consultation["exam"],
|
consultation["exam"],
|
||||||
consultation["format"],
|
consultation["format"],
|
||||||
consultation["preferred_time"],
|
consultation["preferred_time"],
|
||||||
REQUEST_STATUSES.get(consultation["status"], consultation["status"]),
|
REQUEST_STATUSES.get(consultation["status"], consultation["status"]),
|
||||||
consultation["message"] or "",
|
csv_safe(consultation["message"] or ""),
|
||||||
consultation["admin_note"] or "",
|
csv_safe(consultation["admin_note"] or ""),
|
||||||
consultation["created_at"],
|
consultation["created_at"],
|
||||||
consultation["updated_at"] or "",
|
consultation["updated_at"] or "",
|
||||||
]
|
]
|
||||||
@@ -349,4 +379,4 @@ init_database()
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
app.run(debug=True)
|
app.run(debug=os.environ.get("FLASK_DEBUG") == "1")
|
||||||
|
|||||||
@@ -1 +1,3 @@
|
|||||||
Flask>=3.0,<4.0
|
Flask>=3.0,<4.0
|
||||||
|
Flask-WTF>=1.2,<2.0
|
||||||
|
Flask-Limiter>=3.5,<4.0
|
||||||
|
|||||||
@@ -81,6 +81,7 @@
|
|||||||
{% if consultation["message"] %}<p class="request-message"><span>Комментарий</span>{{ consultation["message"] }}</p>{% endif %}
|
{% if consultation["message"] %}<p class="request-message"><span>Комментарий</span>{{ consultation["message"] }}</p>{% endif %}
|
||||||
<div class="request-actions">
|
<div class="request-actions">
|
||||||
<form class="request-status-form" action="{{ url_for('admin_update_status', request_id=consultation["id"]) }}" method="post">
|
<form class="request-status-form" action="{{ url_for('admin_update_status', request_id=consultation["id"]) }}" method="post">
|
||||||
|
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||||
<label for="status-{{ consultation["id"] }}">Статус</label>
|
<label for="status-{{ consultation["id"] }}">Статус</label>
|
||||||
<select id="status-{{ consultation["id"] }}" name="status">{% for status_key, status_label in statuses.items() %}<option value="{{ status_key }}" {% if consultation["status"] == status_key %}selected{% endif %}>{{ status_label }}</option>{% endfor %}</select>
|
<select id="status-{{ consultation["id"] }}" name="status">{% for status_key, status_label in statuses.items() %}<option value="{{ status_key }}" {% if consultation["status"] == status_key %}selected{% endif %}>{{ status_label }}</option>{% endfor %}</select>
|
||||||
<button class="mini-button" type="submit">Сохранить</button>
|
<button class="mini-button" type="submit">Сохранить</button>
|
||||||
@@ -88,11 +89,13 @@
|
|||||||
<details class="request-note" {% if consultation["admin_note"] %}open{% endif %}>
|
<details class="request-note" {% if consultation["admin_note"] %}open{% endif %}>
|
||||||
<summary>{% if consultation["admin_note"] %}Изменить заметку{% else %}Добавить заметку{% endif %} <span>+</span></summary>
|
<summary>{% if consultation["admin_note"] %}Изменить заметку{% else %}Добавить заметку{% endif %} <span>+</span></summary>
|
||||||
<form action="{{ url_for('admin_update_note', request_id=consultation["id"]) }}" method="post">
|
<form action="{{ url_for('admin_update_note', request_id=consultation["id"]) }}" method="post">
|
||||||
|
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||||
<textarea name="admin_note" rows="2" maxlength="2000" placeholder="Например: перезвонить вечером...">{{ consultation["admin_note"] }}</textarea>
|
<textarea name="admin_note" rows="2" maxlength="2000" placeholder="Например: перезвонить вечером...">{{ consultation["admin_note"] }}</textarea>
|
||||||
<button class="mini-button" type="submit">Сохранить заметку</button>
|
<button class="mini-button" type="submit">Сохранить заметку</button>
|
||||||
</form>
|
</form>
|
||||||
</details>
|
</details>
|
||||||
<form class="request-delete-form" action="{{ url_for('admin_delete_request', request_id=consultation["id"]) }}" method="post" data-confirm="Удалить эту заявку? Восстановить её будет нельзя.">
|
<form class="request-delete-form" action="{{ url_for('admin_delete_request', request_id=consultation["id"]) }}" method="post" data-confirm="Удалить эту заявку? Восстановить её будет нельзя.">
|
||||||
|
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||||
<button class="delete-button" type="submit">Удалить</button>
|
<button class="delete-button" type="submit">Удалить</button>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -25,6 +25,7 @@
|
|||||||
{% endif %}
|
{% endif %}
|
||||||
{% endwith %}
|
{% endwith %}
|
||||||
<form action="{{ url_for('admin_login') }}" method="post" class="admin-login-form">
|
<form action="{{ url_for('admin_login') }}" method="post" class="admin-login-form">
|
||||||
|
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||||
<label for="password">Пароль администратора</label>
|
<label for="password">Пароль администратора</label>
|
||||||
<input id="password" type="password" name="password" placeholder="Введите пароль" autocomplete="current-password" required autofocus>
|
<input id="password" type="password" name="password" placeholder="Введите пароль" autocomplete="current-password" required autofocus>
|
||||||
<button class="button button-primary form-button" type="submit">Войти в панель <span>↗</span></button>
|
<button class="button button-primary form-button" type="submit">Войти в панель <span>↗</span></button>
|
||||||
|
|||||||
@@ -132,6 +132,7 @@
|
|||||||
{% endif %}
|
{% endif %}
|
||||||
{% endwith %}
|
{% endwith %}
|
||||||
<form action="{{ url_for('submit_request') }}" method="post">
|
<form action="{{ url_for('submit_request') }}" method="post">
|
||||||
|
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||||
<div class="form-row">
|
<div class="form-row">
|
||||||
<label>Ваше имя <span>*</span><input type="text" name="name" placeholder="Например, Мария" required></label>
|
<label>Ваше имя <span>*</span><input type="text" name="name" placeholder="Например, Мария" required></label>
|
||||||
<label>Как связаться <span>*</span><input type="text" name="contact" placeholder="Телефон или Telegram" required></label>
|
<label>Как связаться <span>*</span><input type="text" name="contact" placeholder="Телефон или Telegram" required></label>
|
||||||
|
|||||||
Reference in New Issue
Block a user