Лабораторная 7

This commit is contained in:
MacBook
2026-11-24 12:20:21 +03:00
parent 20afc2c790
commit b962fa0d5d
99 changed files with 11329 additions and 107 deletions
+2
View File
@@ -0,0 +1,2 @@
FROM nginx:1.29.1-alpine3.22
RUN apk add --no-cache curl
+4
View File
@@ -0,0 +1,4 @@
FROM python:3.13.16-slim-bookworm@sha256:73aa5faee130c60da030e105ec971ccf57473fbd22ce73bd6fc9ba99a40b838d
COPY infra/security/tls_proxy.py /tls_proxy.py
USER 65532:65532
ENTRYPOINT ["python3","/tls_proxy.py"]
+65
View File
@@ -0,0 +1,65 @@
# Security boundary
TLS roots are generated by the operator in `secrets/operator/ca.key` (never mounted
in services). Each service receives only its leaf directory plus the public CA.
Leaf lifetime: 7 days. Root lifetime: 365 days. Keys are generated, never in Git
or images. `scripts/pki.py` is idempotent; it does not silently replace a CA.
The native backend processes Redis/MinIO/Collector/Prometheus/Loki/Tempo share
only their corresponding TLS-sidecar network namespace (`network_mode:
service:tls-...`). They bind plaintext listeners to 127.0.0.1 on distinct ports.
Only the sidecar binds the network-facing port. No plaintext port is published.
The proxy verifies client CA, expiry, DNS SAN allowlist and serial denylist on
EVERY new connection. It disables tickets and reloads leaf files per connection.
For broker it additionally parses bounded RESP frames, binds AUTH/HELLO username
to the certificate SAN, and restricts consumer XADD to the invalid-envelope DLQ;
Redis independently enforces producer/consumer command/key ACLs.
A connection can stay alive until its finite 75s socket timeout; certificate
rotation restarts the affected caller to drain its old connections. Denylist
checks refer to NEW connections. No claim of revoking already completed actions.
PostgreSQL uses native TLS and verify-full URLs; separate API/worker/dispatcher/
cleanup database roles. Only the operator migration identity owns schema. API
must read password hashes to authenticate; worker cannot read users. S3 policies
separate API staging writes from worker originals/variants writes. MinIO admin
credentials exist only at the server and one-shot operator bootstrap.
OpenBao uses native TLS, non-dev persistent file storage, cert auth bound to exact
leaf certificates and a read-only policy for each KV path. Tokens: TTL60s/max120s.
Services reauthenticate every20s; this is renewal by scoped reauthentication,
not use of a permanent bootstrap token. Revocation replaces exact cert bindings.
If refresh fails, the last granted lease remains valid only until its deadline;
API then returns contract 503 (liveness stays up), workers exit75 and restart
fail-closed until authority recovery. Secrets are loaded only from Bao; no file
or plaintext fallback. Secret rotation restarts only the affected process/pool,
without building an image. Bootstrap and renewal remain explicit operator tasks.
## Operator commands
```sh
sh scripts/start.sh
python3 scripts/bao-operator.py seal
python3 scripts/bao-operator.py unseal
python3 scripts/rotate-db-secret.py
python3 scripts/rotate-leaf.py worker
```
The operator owns `secrets/operator/bao-init.json`, root token and unseal share;
file mode0600 under mode0700 directory. Neither OpenBao nor apps mount this
operator directory. One-share Shamir is a local teaching compromise; production
requires separated custodians / protected auto-unseal. Restart hook explicitly
runs as operator and unseals using LOCAL operator material; it is not server-side
unattended unseal. Keep an offline protected backup; losing it can make Bao data
unrecoverable. Never delete volumes to recover a forgotten unseal key.
App/worker are non-root; read-only root filesystems, no-new-privileges and
cap_drop ALL apply to runtime services. Writable volumes contain state, bounded
tmpfs contains temporary processing data. One-shot volume ownership init uses
only CHOWN, no network; this is the documented exception, not application power.
Docker socket/host network/privileged mode are absent. Operator audit is a profile,
not a production service, and explicitly mounts audit leaf material read-only.
Runtime secret bind files have mode0444 inside mounts so non-root Linux UIDs can read them. The enclosing host secrets directory stays0700; operator CA key/root token/unseal file stay0600 and are never runtime mounts. Each container receives only its own named files/leaf directory.
Redis sessions: отдельный user api ограничен session:*/login:* и GET/SET/DEL/INCR/EXPIRE/EVAL; CONFIG/FLUSHALL/чужие prefixes не разрешены. Operator health/expiry использует отдельную identity.
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
set -eu
export PGPASSWORD="$(cat /run/secrets/postgres_password)"
exec psql -X -v ON_ERROR_STOP=1 -h postgres -U messenger -d messenger -f /bootstrap/db-grants.sql
+10
View File
@@ -0,0 +1,10 @@
ui = false
storage "file" { path = "/bao/data" }
listener "tcp" {
address = "0.0.0.0:8200"
tls_cert_file = "/run/tls/cert.crt"
tls_key_file = "/run/tls/key.key"
tls_client_ca_file = "/run/ca/ca.crt"
tls_min_version = "tls12"
}
api_addr = "https://openbao:8200"
+3
View File
@@ -0,0 +1,3 @@
local all all trust
hostssl all all 0.0.0.0/0 scram-sha-256
hostssl all all ::/0 scram-sha-256
+3
View File
@@ -0,0 +1,3 @@
path "secret/api1" {
capabilities = ["read"]
}
+3
View File
@@ -0,0 +1,3 @@
path "secret/api2" {
capabilities = ["read"]
}
+3
View File
@@ -0,0 +1,3 @@
path "secret/cleanup" {
capabilities = ["read"]
}
+3
View File
@@ -0,0 +1,3 @@
path "secret/dispatcher" {
capabilities = ["read"]
}
+3
View File
@@ -0,0 +1,3 @@
path "secret/migrate" {
capabilities = ["read"]
}
+3
View File
@@ -0,0 +1,3 @@
path "secret/worker" {
capabilities = ["read"]
}
+39
View File
@@ -0,0 +1,39 @@
# Разбор результатов сканирования зависимостей и образов — 23 ноября 2026
Повторный запуск: `python3 scripts/scan.py` после сборки образов. Trivy 0.76.2
проверяет сохранённые Docker-архивы, без доступа к Docker socket. Govulncheck 1.1.4
использует Go 1.26.11 — ту же версию, что и сборка приложения.
Сводка находится в `evidence/scan-summary.json`.
Проверены исполняемый файл приложения, ОС, Python и зависимости образа worker.
Это не проверка каждого инфраструктурного образа и не доказательство полного
отсутствия уязвимостей.
Перед итоговым сканированием обновлены:
- Go 1.26.8 → 1.26.11: исправления X509/TLS/HTTP;
- Python 3.13.7 → 3.13.16, Pillow 12 → 13;
- pgx 5.7.6 → 5.13.0, OpenTelemetry 1.38 → 1.47;
- x/crypto 0.42 → 0.59, x/net 0.43 → 0.63;
- grpc 1.75 → 1.85, jwt 4.5.0 → 4.5.2, compress 1.18 → 1.20.5.
Точные версии и digest закреплены в Dockerfile и зависимостях Go. После обновлений
выполнены регрессионные проверки бизнес-функций и TLS.
| Группа находок | Применимость и принятое решение |
|---|---|
| Уязвимости Go HTTP/TLS/X509, pgx и обработки изображений Pillow в перенесённой версии | Актуальны: эти компоненты обрабатывают сетевые запросы и недоверенные изображения. Установлены исправленные версии, образы пересобраны, тесты повторены. Внутренняя сеть сама по себе не считается исправлением. |
| GO-2026-5264/5381/5662/5710, модуль Prometheus через madmin | Приложение импортирует только `github.com/prometheus/prometheus/model/histogram`; это проверяется командой `go list -deps ./cmd/messenger`. Оно не подключает обработчики remote-read, config и веб-интерфейса Prometheus, не использует Azure OAuth remote-write. Указанный сканером `histogram.init` не доказывает достижимость уязвимых веб-обработчиков. Косвенная зависимость сохранена до совместимого обновления madmin. Этот вывод относится к исполняемому файлу приложения, а не к отдельному контейнеру Prometheus. |
| CVE-2023-45853, zlib/minizip | Описание относится к функции записи ZIP в minizip, а не к используемой распаковке PNG через zlib. Worker декодирует PNG/JPEG и кодирует JPEG/WebP; ZIP не создаётся, minizip не вызывается. Находка пакета Debian сохранена в результатах. |
| CVE-2025-7458, SQLite | Конвейер worker не открывает SQLite и не выполняет SQLite-запросы. Приложение использует PostgreSQL, обработка Pillow принимает PNG/JPEG. Пакет остаётся в базовом образе Python, но в проверяемом сценарии входные данные в SQLite не передаются. |
| certifi внутри pip, GHSA-6q48-6c7w-9gw2 | Во время работы приложение не использует requests/certifi для доверия внешним адресам: клиенты Go и Python явно доверяют локальному CA. Подпроцесс обработки не получает URL. Pip устанавливает закреплённый Pillow при сборке. Обновления базового образа и pip всё равно необходимы; находка не объявляется безопасной для любого использования. |
| Другие находки Debian: mount/PAM/systemd/apt и библиотеки | Применимость зависит от конкретного пути выполнения. Запрещены mount capabilities, повышение привилегий и установка пакетов во время работы; используются non-root, read-only rootfs и ограниченный подпроцесс. Находки высокой важности остаются в сводке. Для промышленного выпуска нужны дальнейшее сокращение/обновление образа и разбор отдельных уведомлений. Учебная изоляция не устраняет сами CVE. |
## Ограничения анализа
Базы сканеров обновляются, поэтому количество находок — снимок на дату проверки,
а не оценка безопасности в баллах. Изоляция уменьшает последствия, но не исправляет
достижимую ошибку нативного декодера.
Оставшиеся находки явно сохранены и объяснены с учётом выполняемых операций.
Полное отсутствие CVE и завершённая промышленная защита не заявляются.
+29
View File
@@ -0,0 +1,29 @@
# Модель угроз — лабораторная 7, оценка 4
**Защищаемые активы:** хеши паролей, Bearer-сессии, права доступа к чатам,
оригиналы/варианты/staging, целостность заданий, сервисные credentials, ключи PKI,
сохранённая телеметрия и состояние OpenBao.
**Участники:** анонимный клиент, авторизованный пользователь вне чата, клиент
с другим сертификатом доверенного CA, неисправный сервис, скомпрометированный
worker в пределах выданной роли и локальный оператор.
Компрометация хоста, root или самого оператора не покрывается этим учебным стендом.
| Конкретная угроза | Механизм защиты | Воспроизводимая отрицательная проверка |
|---|---|---|
| Перехват соединения (MITM) или подмена сервера | TLS с проверкой CA и hostname, без отключения верификации | `make test-security`; неверный hostname в `verify_security` |
| Обход балансировщика и прямой доступ к API | Порты реплик не опубликованы; mTLS и проверка SAN балансировщика; собственный сертификат API разрешён только для health | `verify_tls`: обе реплики отклоняют запросы без сертификата, с чужим CA и посторонним SAN |
| Клиент доверенного CA выдаёт себя за отправителя заданий | Список разрешённых SAN, разделение портов, привязка Redis AUTH и команд к identity, Redis ACL | `verify_tls`: worker не может выполнить XADD в поток заданий; посторонний клиент не допускается к broker |
| Посторонний сервис отправляет поддельную телеметрию | mTLS Collector с разрешёнными SAN, отдельные identities для сбора метрик | `verify_tls`: посторонний клиент не допускается к приёму данных; прямой локальный listener недоступен извне |
| Чтение чужих вложений или подмена пользовательского заголовка | Bearer-сессия, проверка участия в чате в БД, отсутствие публичных объектов S3 | `verify_security`: чужие metadata/content/upload недоступны, X-User-Id не меняет пользователя |
| Исчерпание CPU/RAM массовыми попытками входа | Argon2id 19 MiB/t2/p1; два параллельных хеширования на реплику; общий Redis-лимит 120 запросов/мин и 10 попыток/мин на username | `verify_security`: общий 429/Retry-After; измерение стоимости Argon2id |
| Worker читает секреты API или хеши паролей | Привязка OpenBao к точному сертификату и scoped policy, отдельная роль БД, ограниченные S3-prefixes | `verify_tls`: разрешения/запреты OpenBao; команда worker `security-audit` |
| Утечка или дальнейшее использование старой сервисной identity | Ограниченный срок сертификата/token, запрет старого serial, замена cert-auth binding, перезапуск пула соединений | `verify_lifecycle`: старые пароль и сертификат отклоняются на новых соединениях |
| Sealed OpenBao приводит к бессрочному использованию старых credentials | Срок lease; после истечения API возвращает 503, worker завершается; сетевые таймауты ограничены | `verify_lifecycle`: seal → истечение lease и 503 → восстановление после unseal |
| Вредоносное изображение исчерпывает ресурсы | Лимиты 10 MiB/40 млн пикселей, подпроцесс 1 GiB с таймаутом, worker CPU1/RAM1536 MiB/tmpfs128 MiB | `verify_variants` и проверки восстановления pipeline |
| Секреты попадают в логи или трассы | Безопасные поля событий, отсутствие SQL-аргументов/заголовков/тела запроса, шаблоны маршрутов в labels | `verify_observability`: поиск специально заданных секретных значений и проверка labels |
Не заявляется защита от злонамеренного оператора хоста, полной потери компьютера
или неограниченная доступность при массовой атаке на login. Общий лимит входа
осознанно ограничивает доступность авторизации ради ограничения дорогой работы.
+83
View File
@@ -0,0 +1,83 @@
"""Bounded mTLS TCP proxy. The backend shares this network namespace and
binds only loopback. Certificate chain AND DNS SAN role are mandatory.
Each new connection reloads leaf and denylist: no session resumption cache.
"""
import os, socket, ssl, threading, time, json
from pathlib import Path
ROLE=os.environ['PROXY_ROLE']
ALLOWED=set(os.environ['ALLOWED_IDENTITIES'].split(','))
PORTS=[tuple(map(int,p.split(':'))) for p in os.environ['PORT_MAP'].split(',')]
PER_PORT=json.loads(os.environ.get("PORT_IDENTITIES","{}"))
SLOTS=threading.BoundedSemaphore(64)
def serve(conn,upstream,port):
try:
conn.settimeout(5)
ctx=ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER);ctx.minimum_version=ssl.TLSVersion.TLSv1_2
ctx.load_cert_chain('/run/tls/cert.crt','/run/tls/key.key');ctx.load_verify_locations('/run/ca/ca.crt');ctx.verify_mode=ssl.CERT_REQUIRED
ctx.options |= ssl.OP_NO_TICKET
with ctx.wrap_socket(conn,server_side=True) as client:
cert=client.getpeercert();names={v for k,v in cert.get('subjectAltName',[]) if k=='DNS'}
revoked=Path('/run/ca/revoked-serials').read_text().lower().split()
if not names.intersection(set(PER_PORT.get(str(port),list(ALLOWED)))) or cert.get('serialNumber','').lower().lstrip('0') in [s.lstrip('0') for s in revoked]:return
principal=next(iter(names.intersection(set(PER_PORT.get(str(port),list(ALLOWED))))))
with socket.create_connection(('127.0.0.1',upstream),timeout=3) as backend:
client.settimeout(75);backend.settimeout(75)
# Two blocking directions; finite socket timeouts, bounded connections.
def copy(a,b):
try:
while True:
data=a.recv(32768)
if not data:break
b.sendall(data)
except (OSError,ssl.SSLError):pass
finally:
try:b.shutdown(socket.SHUT_WR)
except OSError:pass
def redis_commands():
try:
stream=client.makefile('rb')
while True:
header=stream.readline(128)
if not header:break
if not header.startswith(b'*'):break
count=int(header[1:]);args=[];wire=bytearray(header)
if not 1<=count<=64:break
for _ in range(count):
size=stream.readline(128)
if not size.startswith(b'$'):raise ValueError('invalid RESP')
n=int(size[1:])
if not 0<=n<=1048576:raise ValueError('oversized command')
value=stream.read(n+2)
if len(value)!=n+2:raise ValueError('truncated RESP')
args.append(value[:-2]);wire.extend(size);wire.extend(value)
op=args[0].lower()
allowed={b'ping',b'hello',b'auth',b'client'}
if principal=='worker':allowed|={b'xgroup',b'xautoclaim',b'xreadgroup',b'xack',b'xdel',b'xadd'}
if principal=='dispatcher':allowed|={b'xadd'}
if principal!='operator':
if op not in allowed:break
if op==b'auth' and (len(args)!=3 or args[1].decode()!=principal):break
if op==b'hello' and b'auth' in [a.lower() for a in args]:
i=[a.lower() for a in args].index(b'auth')
if args[i+1].decode()!=principal:break
if op==b'xadd':
expected=b'attachment.invalid.dlq' if principal=='worker' else b'attachment.jobs.v1'
if len(args)<2 or args[1]!=expected:break
backend.sendall(wire)
except (OSError,ValueError,IndexError,UnicodeError):pass
finally:
try:backend.shutdown(socket.SHUT_WR)
except OSError:pass
t=threading.Thread(target=redis_commands if ROLE=='broker' else copy,args=() if ROLE=='broker' else (client,backend),daemon=True)
t.start();copy(backend,client);t.join(timeout=1)
except (OSError,ssl.SSLError):conn.close()
finally:SLOTS.release()
def listen(port,upstream):
with socket.socket() as s:
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1);s.bind(('0.0.0.0',port));s.listen(32)
while True:
conn,_=s.accept()
if not SLOTS.acquire(blocking=False):conn.close();continue
threading.Thread(target=serve,args=(conn,upstream,port),daemon=True).start()
for port,upstream in PORTS:threading.Thread(target=listen,args=(port,upstream),daemon=True).start()
while True:time.sleep(3600)