forked from mtusi2026/mtusi2026lab7
feat: completed tasks for grade 4
This commit is contained in:
+72
-10
@@ -1,7 +1,8 @@
|
||||
"""Сквозные проверки уровня 3 для запущенного HTTPS-стенда."""
|
||||
"""Сквозные проверки защиты для запущенного HTTPS-стенда."""
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
@@ -64,15 +65,42 @@ asyncio.run(probe())
|
||||
"""
|
||||
|
||||
|
||||
ROOTFS_PROBE = """
|
||||
from os import ST_RDONLY, statvfs
|
||||
from tempfile import TemporaryFile
|
||||
|
||||
assert statvfs("/app").f_flag & ST_RDONLY
|
||||
with TemporaryFile(dir="/tmp") as temporary:
|
||||
temporary.write(b"tmpfs probe")
|
||||
"""
|
||||
|
||||
API_BROKER_PROBE = """
|
||||
import asyncio
|
||||
from app.core.jobs import JobSettings
|
||||
from app.storage.broker import connect_broker
|
||||
|
||||
|
||||
async def probe():
|
||||
async with await connect_broker(JobSettings()) as connection:
|
||||
assert not connection.is_closed
|
||||
|
||||
|
||||
asyncio.run(probe())
|
||||
"""
|
||||
|
||||
|
||||
def probe_deployment(project: ComposeProject) -> None:
|
||||
services = project.config["services"]
|
||||
for name in ("api", "worker"):
|
||||
service = services[name]
|
||||
assert not service.get("ports")
|
||||
assert "ALL" in service["cap_drop"]
|
||||
assert "ALL" in service["cap_drop"] and service["read_only"]
|
||||
assert "no-new-privileges:true" in service["security_opt"]
|
||||
assert service["tmpfs"]
|
||||
assert service["deploy"]["resources"]["limits"]["memory"]
|
||||
uid = project.run("exec", "-T", name, "id", "-u")
|
||||
assert int(uid) > 0
|
||||
project.run("exec", "-T", name, "python", "-c", ROOTFS_PROBE)
|
||||
for service in services.values():
|
||||
assert not service.get("privileged") and service.get("network_mode") != "host"
|
||||
assert all(mount["target"] != "/var/run/docker.sock"
|
||||
@@ -104,6 +132,22 @@ def probe_mtls(project: ComposeProject) -> None:
|
||||
print(output)
|
||||
|
||||
|
||||
def audit_dependencies(project: ComposeProject) -> None:
|
||||
command = ["run", "--rm", "--network", project.name + "_default",
|
||||
"--network", project.name + "_objects",
|
||||
"-v", f"{ROOT / 'scripts/audit_tls.py'}:/app/audit_tls.py:ro",
|
||||
"-v", f"{TLS / 'ca.crt'}:/certificates/ca.crt:ro"]
|
||||
for role in ("otel-api", "otel-worker", "otel-publisher", "otel-wrong-role",
|
||||
"otel-reader", "otel-writer", "otel-scraper", "api-broker",
|
||||
"attachment-worker", "attachment-publisher", "broker-wrong-role", "foreign-client"):
|
||||
for extension in ("crt", "key"):
|
||||
name = f"{role}.{extension}"
|
||||
command.extend(("-v", f"{TLS / name}:/certificates/{name}:ro"))
|
||||
project.run("exec", "-T", "api", "python", "-c", API_BROKER_PROBE)
|
||||
image = project.config["services"]["api"]["image"]
|
||||
print(project.docker(*command, image, "python", "-m", "audit_tls"))
|
||||
|
||||
|
||||
def probe_bao(port: int) -> None:
|
||||
def call(context, path, *, token=None, data=None):
|
||||
headers = {"Content-Type": "application/json"}
|
||||
@@ -178,19 +222,28 @@ def probe_http(base: str, project: ComposeProject) -> None:
|
||||
time.sleep(0.1)
|
||||
client.call("GET", "/api/v1/users/me", 401, actor=outsider)
|
||||
|
||||
basic = "Basic " + base64.b64encode(b"unknown:wrong").decode()
|
||||
basic = "Basic " + base64.b64encode(b"unknown:synthetic-password").decode()
|
||||
login = base + "/api/v1/auth/sessions"
|
||||
for _ in range(25):
|
||||
|
||||
def login_attempt(_):
|
||||
request = Request(login, data=b"", headers={"Authorization": basic})
|
||||
try:
|
||||
urlopen(request, context=tls, timeout=5)
|
||||
except HTTPError as error:
|
||||
if error.code == 429:
|
||||
assert int(error.headers["Retry-After"]) > 0
|
||||
break
|
||||
assert error.code == 401
|
||||
else:
|
||||
raise AssertionError("Лимит входа не сработал")
|
||||
return error.code, error.headers.get("X-Instance-Id")
|
||||
raise AssertionError("Неизвестный пользователь получил сессию")
|
||||
|
||||
started = time.monotonic()
|
||||
with ThreadPoolExecutor(max_workers=12) as pool:
|
||||
results = list(pool.map(login_attempt, range(25)))
|
||||
statuses = [status for status, _ in results]
|
||||
replicas = {instance for status, instance in results if status == 401 and instance}
|
||||
assert set(statuses) == {401, 429} and len(replicas) >= 2, (statuses, len(replicas))
|
||||
print(f"PASS: login burst 25 за {time.monotonic() - started:.2f} с, "
|
||||
f"{statuses.count(401)} проверок на {len(replicas)} репликах, "
|
||||
f"{statuses.count(429)} ограничений")
|
||||
|
||||
try:
|
||||
urlopen(Request(login, data=b"x" * 17000), context=tls, timeout=5)
|
||||
@@ -203,8 +256,10 @@ def probe_http(base: str, project: ComposeProject) -> None:
|
||||
|
||||
def measure_argon2(project: ComposeProject) -> None:
|
||||
probe = """
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from resource import RUSAGE_SELF, getrusage
|
||||
from statistics import median
|
||||
from time import perf_counter
|
||||
from time import perf_counter, process_time
|
||||
|
||||
from app.core.security import _hash_password_sync, _verify_password_sync
|
||||
|
||||
@@ -216,7 +271,13 @@ for _ in range(15):
|
||||
started = perf_counter()
|
||||
assert _verify_password_sync(password, encoded)
|
||||
timings.append((perf_counter() - started) * 1000)
|
||||
print(f"PASS: Argon2id, медиана проверки {median(timings):.1f} мс (15 попыток)")
|
||||
wall, cpu = perf_counter(), process_time()
|
||||
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||
assert all(pool.map(lambda _: _verify_password_sync(password, encoded), range(24)))
|
||||
wall, cpu = perf_counter() - wall, process_time() - cpu
|
||||
print(f"PASS: Argon2id, медиана {median(timings):.1f} мс, 24 проверки на 2 потоках "
|
||||
f"за {wall:.2f} с, CPU {cpu / 24 * 1000:.1f} мс/проверку, "
|
||||
f"пиковый RSS {getrusage(RUSAGE_SELF).ru_maxrss / 1024:.1f} MiB")
|
||||
"""
|
||||
print(project.run("exec", "-T", "api", "python", "-c", probe))
|
||||
|
||||
@@ -229,6 +290,7 @@ def main() -> None:
|
||||
project = ComposeProject()
|
||||
probe_deployment(project)
|
||||
probe_mtls(project)
|
||||
audit_dependencies(project)
|
||||
probe_bao(args.bao_port)
|
||||
probe_http(args.base_url, project)
|
||||
measure_argon2(project)
|
||||
|
||||
Reference in New Issue
Block a user